@forgeax/engine-ecs 0.1.26 → 0.1.28

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/README.md +94 -35
  2. package/dist/__tests__/world-read.unit.test.d.ts +2 -0
  3. package/dist/__tests__/world-read.unit.test.d.ts.map +1 -0
  4. package/dist/commands.d.ts +2 -0
  5. package/dist/commands.d.ts.map +1 -1
  6. package/dist/index.mjs +3471 -4263
  7. package/dist/index.mjs.map +1 -1
  8. package/dist/internal.d.ts +2 -3
  9. package/dist/internal.d.ts.map +1 -1
  10. package/dist/internal.mjs +3 -333
  11. package/dist/internal.mjs.map +1 -1
  12. package/dist/projection/index.mjs.map +1 -1
  13. package/dist/shared.mjs.map +1 -1
  14. package/dist/world-entity-lifecycle.d.ts +3 -14
  15. package/dist/world-entity-lifecycle.d.ts.map +1 -1
  16. package/dist/world-internal.d.ts +65 -5
  17. package/dist/world-internal.d.ts.map +1 -1
  18. package/dist/world-read.d.ts +16 -0
  19. package/dist/world-read.d.ts.map +1 -0
  20. package/dist/world-read.mjs +8 -0
  21. package/dist/world-read.mjs.map +1 -0
  22. package/dist/world-scheduling.d.ts +0 -4
  23. package/dist/world-scheduling.d.ts.map +1 -1
  24. package/dist/world-storage-primitives.d.ts +26 -0
  25. package/dist/world-storage-primitives.d.ts.map +1 -0
  26. package/dist/world.d.ts +352 -157
  27. package/dist/world.d.ts.map +1 -1
  28. package/package.json +8 -4
  29. package/src/__tests__/command-buffer.test.ts +29 -3
  30. package/src/__tests__/hierarchy.unit.test.ts +3 -3
  31. package/src/__tests__/world-health.contract.test.ts +195 -2
  32. package/src/__tests__/world-read.unit.test.ts +30 -0
  33. package/src/commands.ts +22 -9
  34. package/src/internal.ts +5 -3
  35. package/src/world-entity-lifecycle.ts +23 -252
  36. package/src/world-internal-augmentation.d.ts +11 -0
  37. package/src/world-internal.ts +114 -63
  38. package/src/world-read.ts +38 -0
  39. package/src/world-scheduling.ts +0 -26
  40. package/src/world-storage-primitives.ts +179 -0
  41. package/src/world.ts +2590 -509
  42. package/dist/world-component-access.d.ts +0 -311
  43. package/dist/world-component-access.d.ts.map +0 -1
  44. package/dist/world-component-storage.d.ts +0 -298
  45. package/dist/world-component-storage.d.ts.map +0 -1
  46. package/dist/world-core.d.ts +0 -39
  47. package/dist/world-core.d.ts.map +0 -1
  48. package/src/world-component-access.ts +0 -1769
  49. package/src/world-component-storage.ts +0 -1264
  50. package/src/world-core.ts +0 -74
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/component-schema.ts","../src/errors/query-and-component-errors.ts","../src/errors/relationship-errors.ts","../src/errors/sprite-and-shared-errors.ts","../src/errors/validation-errors.ts","../src/world-internal.ts","../src/execution/shared-kernel.ts","../src/errors.ts","../src/component.ts","../src/entity.ts","../src/plugin-service.ts","../src/relationship-index.ts","../src/schedule-token.ts","../src/time.ts","../src/entity-handle.ts","../src/internal.ts","../src/storage/archetype.ts","../src/storage/column.ts","../src/storage/table.ts","../src/storage/archetype-graph.ts","../src/storage/change-detection.ts","../src/query/derived-range-writer.ts","../src/query/query.ts","../src/resource.ts","../src/component-default-fallback.ts","../src/commands.ts","../src/schedule.ts","../src/component-value-validate.ts","../src/world-component-storage.ts","../src/world-component-access.ts","../src/buffer-pool.ts","../src/shared-ref-store.ts","../src/storage/structural-evidence.ts","../src/unique-ref-store.ts","../src/world-core.ts","../src/world-entity-lifecycle.ts","../src/world-scheduling.ts","../src/world.ts","../src/index.ts"],"names":["roles","resourceName","tableRow","INITIAL_CAPACITY","metaKey","scalarType","componentId","target","err","ok","relationshipSource","targetRecord","component","unwrapHandle","HAS_TRANSFER","id","buffer","view","BUILTIN_BASE","MAX_SLOT","pack","toShared","isRetiredSlot","toUnique","handleSlot","handleGeneration","componentNames","systems"],"mappings":";;;;;;AAmCA,IAAM,kBAAA,mBAAqB,MAAA,CAAO,GAAA,CAAI,+BAA+B,CAAA;AAIrE,IAAM,aAAA,GAAgB,UAAA;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5B;;;ACr1CA,IACE,CAAC,iCAAgC,IACjC,uBAAA,CAAwB,WAAW,CAAA,IACnC,uBAAA,CAAwB,CAAC,CAAA,KAAM,CAAA,EAC/B;AACA,EAAA,MAAM,IAAI,KAAA;AAAA,IACR,CAAA,mFAAA,EACyB,uBAAA,CAAwB,IAAA,CAAK,IAAI,CAAC,CAAA,gMAAA;AAAA,GAG7D;AACF","file":"index.mjs","sourcesContent":["import type { Component, FieldReflection, SchemaFieldType } from './component';\n\n/** The complete storage placement vocabulary owned by ECS schema. */\nexport type ComponentStorageKind = 'table' | 'sparse';\n\n/** The stable public facts needed to describe a component schema offline. */\nexport interface ComponentSchemaDefinition {\n readonly name: string;\n readonly fields: Readonly<Record<string, SchemaFieldType>>;\n readonly storage: ComponentStorageKind;\n}\n\n/**\n * Serialization facts owned beside schema registration, not carried by the\n * public component token. Queries and storage only need the token's schema\n * vocabulary; domain validation and lifecycle belong to their owners.\n */\nexport interface ComponentPolicy {\n readonly transient: boolean;\n readonly meta: Record<string, unknown>;\n /** Components that are materialized whenever this component is added. */\n readonly requires: readonly Component[];\n}\n\n/** Immutable schema reflection plus non-token policy projection. */\nexport interface ComponentDefinition {\n readonly fields: Readonly<Record<string, FieldReflection>>;\n readonly defaults: Readonly<Record<string, unknown>> | undefined;\n readonly policy: ComponentPolicy;\n}\n\n// Component tokens can cross independently bundled ECS entry points. Share\n// the owner registry through globalThis rather than attaching a hidden symbol\n// to each token; `Reflect.ownKeys(token)` must remain exactly the three public\n// facts name/fields/storage.\nconst COMPONENT_REGISTRY = Symbol.for('forgeax.ecs.componentRegistry');\ninterface ComponentRegistry {\n readonly definitions: WeakMap<object, ComponentDefinition>;\n}\nconst globalSymbols = globalThis as typeof globalThis & { [key: symbol]: unknown };\nconst definitions =\n (globalSymbols[COMPONENT_REGISTRY] as ComponentRegistry | undefined) ??\n (() => {\n const registry: ComponentRegistry = { definitions: new WeakMap<object, ComponentDefinition>() };\n globalSymbols[COMPONENT_REGISTRY] = registry;\n return registry;\n })();\n\nexport function registerComponentDefinition(\n component: Component,\n definition: ComponentDefinition,\n): void {\n definitions.definitions.set(component, definition);\n}\n\n/** Read the definition-time schema/policy projection for a component token. */\nexport function componentDefinition(component: Component): ComponentDefinition {\n const definition = definitions.definitions.get(component);\n if (definition === undefined) {\n throw new Error(`Component definition missing for '${component.name}'.`);\n }\n return definition;\n}\n\n/** Read the generic structural requirements declared by one component. */\nexport function componentRequirements(component: Component): readonly Component[] {\n // Keep invalid/foreign tokens on the ordinary preflight error path. The\n // expansion helper runs before validation, so it must not turn a structured\n // `component-not-defined` Result into an uncaught registry exception.\n return definitions.definitions.get(component)?.policy.requires ?? [];\n}\n\ntype ComponentDataLike = {\n readonly component: Component;\n readonly data: Partial<Record<string, unknown>>;\n};\n\n/**\n * Expand component requirements once at the structural boundary.\n *\n * Explicit component data wins and is never duplicated. Requirements are\n * appended in declaration order, and the same identity set also terminates a\n * malformed dependency cycle without a per-frame scan.\n */\nexport function expandComponentRequirements<T extends ComponentDataLike>(\n componentDatas: readonly T[],\n): T[] {\n let hasRequirements = false;\n for (const entry of componentDatas) {\n if (componentRequirements(entry.component).length !== 0) {\n hasRequirements = true;\n break;\n }\n }\n // Most structural operations use components without dependencies. Preserve\n // that path without copying or allocating a Set; callers only consume the\n // returned list and never mutate it.\n if (!hasRequirements) return componentDatas as T[];\n\n const expanded = [...componentDatas];\n const seen = new Set<Component>(expanded.map((entry) => entry.component));\n for (let index = 0; index < expanded.length; index++) {\n const component = expanded[index]?.component;\n if (component === undefined) continue;\n for (const required of componentRequirements(component)) {\n if (seen.has(required)) continue;\n seen.add(required);\n expanded.push({ component: required, data: {} } as T);\n }\n }\n return expanded;\n}\n\n/**\n * Freeze a schema value recursively. Component descriptors are authored data,\n * so nested defaults and enum label maps must not become mutation channels.\n */\nexport function deepFreeze<T>(value: T): Readonly<T> {\n if (value === null || (typeof value !== 'object' && typeof value !== 'function')) {\n return value as Readonly<T>;\n }\n // Non-empty TypedArrays reject Object.freeze and their indexed elements\n // remain writable even when the wrapper is frozen. Treat binary views as\n // immutable leaf projections; the authored descriptor around them is still\n // recursively frozen by this function.\n if (ArrayBuffer.isView(value) || value instanceof ArrayBuffer) {\n return value as Readonly<T>;\n }\n const object = value as object;\n for (const key of Reflect.ownKeys(object)) {\n const child = (object as Record<PropertyKey, unknown>)[key];\n if (child !== null && (typeof child === 'object' || typeof child === 'function')) {\n deepFreeze(child);\n }\n }\n return Object.freeze(value) as Readonly<T>;\n}\n\nexport function assertComponentStorage(value: string): asserts value is ComponentStorageKind {\n if (value !== 'table' && value !== 'sparse') {\n throw new Error(`Unsupported component storage '${value}'. Expected 'table' or 'sparse'.`);\n }\n}\n","/**\n * Returned via `Result.err` from `world.removeComponent` when the caller tries\n * to remove an essential (undeletable) component\n * (feat-20260602-archetype-stores-full-packed-entity M1 / w3, plan-strategy\n * D-3). The only essential component today is the id=0 `Entity` component: every\n * archetype carries it unconditionally as the row's own packed handle, so\n * removing it is structurally meaningless. The code name is deliberately\n * generic (`remove-essential-component`, not entity-specific) so a future second\n * essential component reuses it without a rename.\n *\n * `.code = 'remove-essential-component'`\n * `.detail = { componentName }`\n * `.hint` — names the essential component + states it cannot be removed.\n */\nexport class RemoveEssentialComponentError extends Error {\n override readonly name = 'RemoveEssentialComponentError';\n readonly code = 'remove-essential-component' as const;\n readonly hint: string;\n readonly expected: string;\n readonly detail: { readonly componentName: string };\n\n constructor(componentName: string) {\n const hint = `Component \"${componentName}\" is essential (every entity carries it unconditionally) and cannot be removed. Despawn the entity instead if you want to retire it.`;\n const expected = 'non-essential component';\n super(\n `removeComponent: essential component cannot be removed.\\n` +\n ` code: remove-essential-component\\n` +\n ` component: ${componentName}\\n` +\n ` expected: ${expected}\\n` +\n ` hint: ${hint}`,\n );\n this.hint = hint;\n this.expected = expected;\n this.detail = { componentName };\n }\n}\n\n/**\n * Returned via the `Result` err branch when `instantiate` encounters a\n * SceneAsset entity whose `components` map references a component name that was\n * never passed to `defineComponent`.\n *\n * `.code = 'component-not-defined'`\n * `.detail.name` — the offending component name.\n *\n * Promoting this to a class (rather than a bare object literal) keeps the\n * scene-instantiate failure surface inside the `EcsError` class union, so the\n * documented two-level narrow `cause instanceof EcsError` actually matches it\n * (docs/feedbacks/2026-06-03 §6.2 Tier 4.2). `expected` / `hint` accept\n * per-call overrides because the parent-passthrough (ChildOf) site needs a\n * distinct message from the generic entity-component site.\n */\nexport class ComponentNotDefinedError extends Error {\n override readonly name = 'ComponentNotDefinedError';\n readonly code = 'component-not-defined' as const;\n readonly hint: string;\n readonly expected: string;\n readonly detail: { readonly name: string };\n\n constructor(componentName: string, opts?: { expected?: string; hint?: string }) {\n const expected = opts?.expected ?? `component '${componentName}' defined before instantiate`;\n const hint =\n opts?.hint ??\n `define the component via defineComponent('${componentName}', ...) before instantiating this SceneAsset`;\n super(\n `instantiate: component not defined.\\n` +\n ` code: component-not-defined\\n` +\n ` component: ${componentName}\\n` +\n ` expected: ${expected}\\n` +\n ` hint: ${hint}`,\n );\n this.hint = hint;\n this.expected = expected;\n this.detail = { name: componentName };\n }\n}\n\n/**\n * Returned via `Result.err` from `world.spawn` / `world.addComponent` /\n * `world.instantiateScene` / `Commands.spawn` when the caller-supplied\n * data payload carries a key that is not declared in the target component's\n * schema. The pre-fix behaviour silently dropped unknown keys inside\n * `fillComponentDefaults` (which walked schema keys, never raw keys), so a\n * typo like `MeshRenderer { material: h }` (singular legacy field name; the\n * current schema has `materials: array<...>`) produced an empty-defaults row\n * + an invisible / mid-grey entity downstream. Surfacing the typo at the\n * spawn boundary collapses a class of \"renders wrong, looks like a graphics\n * bug\" reports into a single explicit error.\n *\n * `.code = 'spawn-data-unknown-field'`\n * `.detail = { component, field, knownFields }`\n * `.hint` — names the offending field and lists the schema's known fields.\n */\nexport class SpawnDataUnknownFieldError extends Error {\n override readonly name = 'SpawnDataUnknownFieldError';\n readonly code = 'spawn-data-unknown-field' as const;\n readonly hint: string;\n readonly expected: string;\n readonly detail: {\n readonly component: string;\n readonly field: string;\n readonly knownFields: readonly string[];\n };\n\n constructor(componentName: string, fieldName: string, knownFields: readonly string[]) {\n const sortedKnown = [...knownFields].sort();\n const expected = `field name in {${sortedKnown.join(', ')}}`;\n const hint =\n `'${fieldName}' is not a schema field of '${componentName}'. ` +\n `Known fields: ${sortedKnown.join(', ')}. ` +\n `Check for a typo or a stale single-vs-plural rename (e.g. 'material' vs 'materials').`;\n super(\n `${componentName}: spawn data carries unknown field.\\n` +\n ` code: spawn-data-unknown-field\\n` +\n ` component: ${componentName}\\n` +\n ` field: ${fieldName}\\n` +\n ` expected: ${expected}\\n` +\n ` hint: ${hint}`,\n );\n this.hint = hint;\n this.expected = expected;\n this.detail = { component: componentName, field: fieldName, knownFields: sortedKnown };\n }\n}\nexport type QuerySpanUnavailableReason =\n | 'optional-data'\n | 'sparse-component'\n | 'relationship-component';\n\nexport class QueryDescriptorConflictError extends Error {\n override readonly name = 'QueryDescriptorConflictError';\n readonly code = 'query-descriptor-conflict' as const;\n readonly expected = 'each component occupies one descriptor role';\n readonly hint: string;\n readonly detail: { readonly componentName: string; readonly roles: readonly string[] };\n\n constructor(componentName: string, roles: readonly string[]) {\n const hint = `Remove ${componentName} from all but one of: ${roles.join(', ')}.`;\n super(`Query descriptor roles conflict for ${componentName}.\\n hint: ${hint}`);\n this.hint = hint;\n this.detail = { componentName, roles };\n }\n}\n\nexport class QueryDataRequiresFieldsError extends Error {\n override readonly name = 'QueryDataRequiresFieldsError';\n readonly code = 'query-data-requires-fields' as const;\n readonly expected = 'a component with at least one data field';\n readonly hint: string;\n readonly detail: { readonly componentName: string };\n\n constructor(componentName: string) {\n const hint = `Move tag ${componentName} to with or without.`;\n super(`Query data access requires fields on ${componentName}.\\n hint: ${hint}`);\n this.hint = hint;\n this.detail = { componentName };\n }\n}\n\nexport class QuerySpanUnavailableError extends Error {\n override readonly name = 'QuerySpanUnavailableError';\n readonly code = 'query-span-unavailable' as const;\n readonly expected = 'a descriptor whose rows form contiguous table ranges';\n readonly hint = 'Use row iteration or split the query.';\n readonly detail: { readonly reason: QuerySpanUnavailableReason };\n\n constructor(reason: QuerySpanUnavailableReason) {\n super(`Query spans are unavailable: ${reason}.\\n hint: Use row iteration or split the query.`);\n this.detail = { reason };\n }\n}\n\nexport class QueryIterationInvalidatedError extends Error {\n override readonly name = 'QueryIterationInvalidatedError';\n readonly code = 'query-iteration-invalidated' as const;\n readonly expected: string;\n readonly hint = 'Use deferred Commands for structural mutation, then restart iteration.';\n readonly detail: {\n readonly expectedStructureEpoch: number;\n readonly actualStructureEpoch: number;\n };\n\n constructor(expectedStructureEpoch: number, actualStructureEpoch: number) {\n const expected = `structure epoch ${expectedStructureEpoch}`;\n super(\n `Query iteration was invalidated by structure epoch ${actualStructureEpoch}.\\n hint: ${'Use deferred Commands for structural mutation, then restart iteration.'}`,\n );\n this.expected = expected;\n this.detail = { expectedStructureEpoch, actualStructureEpoch };\n }\n}\n\nexport class QueryIterationActiveError extends Error {\n override readonly name = 'QueryIterationActiveError';\n readonly code = 'query-iteration-active' as const;\n readonly expected = 'one active iterator per Query';\n readonly hint = 'Complete the active iterator or create an independent Query.';\n readonly detail = {};\n\n constructor() {\n super('Query already has an active iterator.\\n hint: Complete it before iterating again.');\n }\n}\n","// ────────────────────────────────────────────────────────────────────────────\n// feat-20260531-ecs-relationship-abstraction-bidirectional-sync M2 — closed-\n// union evolution +4 (plan-strategy D-5). Adds 4 `relationship-*` kebab codes\n// (27 -> 31, add-only minor per AGENTS.md Error model evolution contract):\n//\n// - relationship-self-cycle (cycle / ancestor walk hit)\n// - relationship-mirror-component-not-registered (defineComponent gate a)\n// - relationship-mirror-field-type-mismatch (defineComponent gate b)\n// - relationship-detach-mismatch (removeChild parent arg mismatch)\n//\n// `relationship-exclusive-violation` is intentionally NOT a member: exclusive\n// re-add is an automatic reparent (a success path, D-1 style), not an error.\n// Every detail object is a discriminated payload narrowed via EcsErrorDetail.\n// ────────────────────────────────────────────────────────────────────────────\n\n/**\n * Returned via `Result.err` from `world.addChild` / `world.reparent` (M3) when\n * a hierarchy write would form a cycle — either the child is its own parent\n * (self-loop) or the proposed parent is already a descendant of the child\n * (ancestor-walk hit). The `.detail` carries both the offending child entity\n * and the ancestor entity that closed the cycle so AI users can locate the\n * loop without re-walking the graph.\n *\n * `.code = 'relationship-self-cycle'`\n * `.detail = { component, entity, ancestor }`\n * `.hint` — names the child + ancestor that would close the cycle.\n */\nexport class RelationshipSelfCycleError extends Error {\n override readonly name = 'RelationshipSelfCycleError';\n readonly code = 'relationship-self-cycle' as const;\n readonly hint: string;\n readonly expected: string;\n readonly detail: {\n readonly component: string;\n readonly entity: number;\n readonly ancestor: number;\n };\n\n constructor(component: string, entity: number, ancestor: number) {\n const hint = `Linking entity ${entity} via \"${component}\" would close a cycle through ancestor ${ancestor}. Reparent to an entity that is not a descendant of ${entity}.`;\n const expected = 'acyclic parent chain';\n super(\n `relationship: cycle detected.\\n` +\n ` code: relationship-self-cycle\\n` +\n ` component: ${component}\\n` +\n ` entity: ${entity}\\n` +\n ` ancestor: ${ancestor}\\n` +\n ` expected: ${expected}\\n` +\n ` hint: ${hint}`,\n );\n this.hint = hint;\n this.expected = expected;\n this.detail = { component, entity, ancestor };\n }\n}\n\n/**\n * Thrown by `defineComponent` (feat-20260602 M2) when a component declares a\n * `relationship.mirror` naming a component that has not yet been defined\n * (AC-09). AI users defineComponent the mirror before the holder (mirror-then-\n * holder order).\n *\n * The `.code` literal `relationship-mirror-component-not-registered` is kept\n * unchanged across the M2 migration (deliberate terminology trade-off:\n * external `.code` stability over wording precision); only the `.hint` text\n * drops the register/registered phrasing in favour of defineComponent ordering\n * guidance.\n *\n * `.code = 'relationship-mirror-component-not-registered'`\n * `.detail = { component, mirror }`\n * `.hint` — names the holder + the undefined mirror component.\n */\nexport class RelationshipMirrorComponentNotRegisteredError extends Error {\n override readonly name = 'RelationshipMirrorComponentNotRegisteredError';\n readonly code = 'relationship-mirror-component-not-registered' as const;\n readonly hint: string;\n readonly expected: string;\n readonly detail: { readonly component: string; readonly mirror: string };\n\n constructor(component: string, mirror: string) {\n const hint = `Component \"${component}\" declares relationship.mirror = \"${mirror}\", but \"${mirror}\" has not been defined yet. defineComponent the mirror component before the holder (define them in mirror-then-holder order).`;\n const expected = `mirror component \"${mirror}\" registered`;\n super(\n `relationship: mirror component not registered.\\n` +\n ` code: relationship-mirror-component-not-registered\\n` +\n ` component: ${component}\\n` +\n ` mirror: ${mirror}\\n` +\n ` expected: ${expected}\\n` +\n ` hint: ${hint}`,\n );\n this.hint = hint;\n this.expected = expected;\n this.detail = { component, mirror };\n }\n}\n\n/**\n * Thrown by `defineComponent` (feat-20260602 M2) when the\n * `relationship.field` on the mirror component is missing or its schema type\n * is not the only legal back-reference storage shape `array<entity>`\n * (AC-11 b). AI users declare the mirror field as `'array<entity>'`.\n *\n * `.code = 'relationship-mirror-field-type-mismatch'`\n * `.detail = { component, mirror, field, actualType }`\n * `.hint` — names the holder + mirror field + the type observed.\n */\nexport class RelationshipMirrorFieldTypeMismatchError extends Error {\n override readonly name = 'RelationshipMirrorFieldTypeMismatchError';\n readonly code = 'relationship-mirror-field-type-mismatch' as const;\n readonly hint: string;\n readonly expected: string;\n readonly detail: {\n readonly component: string;\n readonly mirror: string;\n readonly field: string;\n readonly actualType: string;\n };\n\n constructor(component: string, mirror: string, field: string, actualType: string) {\n const hint = `Component \"${component}\" mirror \"${mirror}\".${field} has type \"${actualType}\"; the reverse-list field must be declared as 'array<entity>'.`;\n const expected = \"mirror field type === 'array<entity>'\";\n super(\n `relationship: mirror field type mismatch.\\n` +\n ` code: relationship-mirror-field-type-mismatch\\n` +\n ` component: ${component}\\n` +\n ` mirror: ${mirror}\\n` +\n ` field: ${field}\\n` +\n ` actualType: ${actualType}\\n` +\n ` expected: ${expected}\\n` +\n ` hint: ${hint}`,\n );\n this.hint = hint;\n this.expected = expected;\n this.detail = { component, mirror, field, actualType };\n }\n}\n\n/**\n * Returned via `Result.err` from `world.removeChild` (M3) when the `parent`\n * argument does not match the child's current relationship parent (the child\n * lacks the relationship component, or it points at a different parent). The\n * `.detail` carries the expected (argument) parent + the actual current parent\n * so AI users can reconcile their model.\n *\n * `.code = 'relationship-detach-mismatch'`\n * `.detail = { component, child, expectedParent, actualParent }`\n * `actualParent === ENTITY_NULL_RAW` (0) signals the child has no relationship.\n * `.hint` — names the child + the parent mismatch.\n */\nexport class RelationshipDetachMismatchError extends Error {\n override readonly name = 'RelationshipDetachMismatchError';\n readonly code = 'relationship-detach-mismatch' as const;\n readonly hint: string;\n readonly expected: string;\n readonly detail: {\n readonly component: string;\n readonly child: number;\n readonly expectedParent: number;\n readonly actualParent: number;\n };\n\n constructor(component: string, child: number, expectedParent: number, actualParent: number) {\n const hint = `removeChild(${expectedParent}, ${child}) via \"${component}\": child's current parent is ${actualParent}, not ${expectedParent}. Detach from the actual parent or re-read the current relationship.`;\n const expected = `child's \"${component}\" parent === ${expectedParent}`;\n super(\n `relationship: detach parent mismatch.\\n` +\n ` code: relationship-detach-mismatch\\n` +\n ` component: ${component}\\n` +\n ` child: ${child}\\n` +\n ` expectedParent: ${expectedParent}\\n` +\n ` actualParent: ${actualParent}\\n` +\n ` expected: ${expected}\\n` +\n ` hint: ${hint}`,\n );\n this.hint = hint;\n this.expected = expected;\n this.detail = { component, child, expectedParent, actualParent };\n }\n}\n\n/** Returned when callers attempt to mutate an engine-maintained target list. */\nexport class RelationshipTargetReadonlyError extends Error {\n override readonly name = 'RelationshipTargetReadonlyError';\n readonly code = 'component-field-invalid-value' as const;\n readonly expected = 'relationship source mutation';\n readonly hint: string;\n readonly detail: {\n readonly component: string;\n readonly operation: string;\n };\n\n constructor(component: string, operation: string) {\n const hint = `Component \"${component}\" is an engine-maintained relationship target. Mutate its source component instead of ${operation}.`;\n super(`[RelationshipTargetReadonlyError component-field-invalid-value] ${hint}`);\n this.hint = hint;\n this.detail = { component, operation };\n }\n}\n","/**\n * feat-20260713-mount-override-component-add-and-shared-ref-round M2 / w9 —\n * `.code = 'shared-field-invalid-value'`.\n *\n * A `shared<T>` scalar / `array<shared<T>>` element must be a resolved numeric\n * Handle. A raw GUID string / `{ guid }` / `{ kind }` object (the\n * pre-resolution shape a sidecar hands an AI user) used to be silently coerced\n * to the all-zero sentinel by the column packer / scalar write path, so a\n * mis-bound reference read back as `0` / `[0,0,0,0]` and rendered blank with no\n * error. `validateComponentDataKeys` only checks key NAMES, not value types;\n * this error closes the value-type gap at all three write entries\n * (spawn / addComponent / set). `.detail.field` + `.detail.fieldType` name the\n * offending field; `.detail.index` locates the array element (undefined for the\n * scalar form).\n *\n * `.detail = { component, field, fieldType, actualValue, index? }`\n * `.hint` — names the field and points at `AssetRegistry.load + allocSharedRef`.\n */\nexport class SharedFieldInvalidValueError extends Error {\n override readonly name = 'SharedFieldInvalidValueError';\n readonly code = 'shared-field-invalid-value' as const;\n readonly hint: string;\n readonly expected: string;\n readonly detail: {\n readonly component: string;\n readonly field: string;\n readonly fieldType: string;\n readonly actualValue: unknown;\n readonly index?: number;\n };\n\n constructor(\n componentName: string,\n fieldName: string,\n fieldType: string,\n actualValue: unknown,\n index?: number,\n ) {\n const at = index === undefined ? '' : `[${index}]`;\n const expected = `a resolved numeric Handle for shared field '${fieldName}${at}'`;\n const hint =\n `'${fieldName}${at}' on '${componentName}' is a ${fieldType} reference; ` +\n `got ${typeof actualValue} (${JSON.stringify(actualValue)}). ` +\n `Resolve the GUID to a handle first: AssetRegistry.load(guid, kind) then allocSharedRef(...), ` +\n `and bind the returned numeric handle — not the raw GUID / sidecar object.`;\n super(\n `${componentName}.${fieldName}${at}: shared field bound to a non-handle value.\\n` +\n ` code: shared-field-invalid-value\\n` +\n ` component: ${componentName}\\n` +\n ` field: ${fieldName}${at}\\n` +\n ` fieldType: ${fieldType}\\n` +\n ` expected: ${expected}\\n` +\n ` hint: ${hint}`,\n );\n this.hint = hint;\n this.expected = expected;\n this.detail =\n index === undefined\n ? { component: componentName, field: fieldName, fieldType, actualValue }\n : { component: componentName, field: fieldName, fieldType, actualValue, index };\n }\n}\n\n// ────────────────────────────────────────────────────────────────────────────\n// feat-20260625-sprite-instances-and-tilemap-terrain-static-batch M1 / w2 —\n// closed-union evolution +3 for the SpriteInstances primitive + tilemap\n// terrain static-batch path. AGENTS.md §Error model evolution contract: minor\n// (add member only).\n//\n// All 3 codes are DECLARED here (M1) but FIRED at the render-system-extract\n// QueryRow loop (M3 w13) — plan-strategy D-6 \"fail-fast at the render\n// domain entry, not at ECS spawn-time (avoids reverse dep ECS -> AssetRegistry\n// to look up MaterialAsset.shadingModel)\". M1 carries class declarations only;\n// the `_routeError` call sites land in M3.\n//\n// Three codes, three failure shapes:\n// - 'sprite-instances-count-mismatch' — transforms.length / 16 !==\n// regions.length / 4 (stride contract; cf. instance-transforms-stride-\n// mismatch which guards Instances stride 16).\n// - 'sprite-instances-requires-sprite-shader' — the entity's MaterialAsset's\n// first pass shader is not 'forgeax::sprite' (extract-time check; AI users\n// using SpriteInstances must pick a sprite-shaded material).\n// - 'sprite-instances-mutually-exclusive-with-instances' — the same entity\n// carries both Instances + SpriteInstances (the two primitives are peers;\n// SpriteInstances supersedes Instances when per-instance UV region is\n// needed).\n//\n// .hint follows charter P3: each contains the literal repair step AI users\n// can paste back into spawn code (transforms/regions stride math; shading\n// model field write; component removal).\n// ────────────────────────────────────────────────────────────────────────────\n\n/**\n * Thrown / returned via Layer-3 error route when `SpriteInstances.transforms`\n * (stride 16 — column-major mat4 per instance) and `SpriteInstances.regions`\n * (stride 4 — per-instance UV vec4) instance counts disagree at render-system-\n * extract entry.\n *\n * `.code = 'sprite-instances-count-mismatch'`\n * `.detail = { transformsLength, regionsLength, expectedStride: { transforms: 16, regions: 4 } }`\n * `.hint` — instructs the AI user to enforce\n * `transforms.length / 16 === regions.length / 4`.\n */\nexport class SpriteInstancesCountMismatchError extends Error {\n override readonly name = 'SpriteInstancesCountMismatchError';\n readonly code = 'sprite-instances-count-mismatch' as const;\n readonly hint: string;\n readonly expected: string;\n readonly detail: {\n readonly code: 'sprite-instances-count-mismatch';\n readonly transformsLength: number;\n readonly regionsLength: number;\n readonly expectedStride: { readonly transforms: 16; readonly regions: 4 };\n };\n\n constructor(transformsLength: number, regionsLength: number) {\n const hint =\n 'SpriteInstances.transforms (stride 16) and SpriteInstances.regions (stride 4) ' +\n 'must describe the same instance count: ensure transforms.length / 16 === regions.length / 4 ' +\n 'at the spawn / set site (resize both arrays together).';\n const expected = 'transforms.length / 16 === regions.length / 4';\n super(\n `SpriteInstances: per-instance count mismatch between transforms and regions.\\n` +\n ` code: sprite-instances-count-mismatch\\n` +\n ` transformsLength: ${transformsLength} (count = ${transformsLength / 16})\\n` +\n ` regionsLength: ${regionsLength} (count = ${regionsLength / 4})\\n` +\n ` expected: ${expected}\\n` +\n ` hint: ${hint}`,\n );\n this.hint = hint;\n this.expected = expected;\n this.detail = {\n code: 'sprite-instances-count-mismatch',\n transformsLength,\n regionsLength,\n expectedStride: { transforms: 16, regions: 4 },\n };\n }\n}\n\n/**\n * Thrown / returned via Layer-3 error route when an entity carrying\n * `SpriteInstances` references a MaterialAsset whose first pass shader is not\n * `'forgeax::sprite'`. Detected at render-system-extract entry (M3 w13).\n *\n * `.code = 'sprite-instances-requires-sprite-shader'`\n * `.detail = { entityId, observedMaterialShaderId }`\n * `.hint` — instructs the AI user to bind a MaterialAsset whose first pass\n * `shader` is `'forgeax::sprite'` or `'forgeax::sprite-lit'`.\n *\n * feat-20260624-sprite-lit-shading-model-pure-2d-lighting M1' / t6:\n * sprite-lit walks the same per-instance UV region vertex path as sprite\n * (VsOut byte-identical, paramSchema mirror); both shader ids are accepted.\n */\nexport class SpriteInstancesRequiresSpriteShaderError extends Error {\n override readonly name = 'SpriteInstancesRequiresSpriteShaderError';\n readonly code = 'sprite-instances-requires-sprite-shader' as const;\n readonly hint: string;\n readonly expected: string;\n readonly detail: {\n readonly code: 'sprite-instances-requires-sprite-shader';\n readonly entityId: number;\n readonly observedMaterialShaderId: string;\n };\n\n constructor(entityId: number, observedMaterialShaderId: string) {\n const hint =\n \"bind a MaterialAsset whose first pass `shader` is 'forgeax::sprite' \" +\n \"or 'forgeax::sprite-lit' to this entity's MeshRenderer (SpriteInstances \" +\n 'requires a sprite-family shader so the per-instance UV region is consumed ' +\n 'by the sprite vertex shader path).';\n const expected =\n \"MaterialAsset.passes[0].shader === 'forgeax::sprite' || 'forgeax::sprite-lit'\";\n super(\n `SpriteInstances: entity ${entityId} requires a sprite-shaded MaterialAsset.\\n` +\n ` code: sprite-instances-requires-sprite-shader\\n` +\n ` entityId: ${entityId}\\n` +\n ` observedMaterialShaderId: ${observedMaterialShaderId}\\n` +\n ` expected: ${expected}\\n` +\n ` hint: ${hint}`,\n );\n this.hint = hint;\n this.expected = expected;\n this.detail = {\n code: 'sprite-instances-requires-sprite-shader',\n entityId,\n observedMaterialShaderId,\n };\n }\n}\n\n/**\n * Thrown / returned via Layer-3 error route when the same entity carries both\n * `Instances` (3D per-instance mat4) and `SpriteInstances` (2D per-instance\n * mat4 + UV region). The two primitives are peers — pick one. Detected at\n * render-system-extract entry (M3 w13).\n *\n * `.code = 'sprite-instances-mutually-exclusive-with-instances'`\n * `.detail = { entityId }`\n * `.hint` — instructs the AI user to remove one of the two components.\n */\nexport class SpriteInstancesMutuallyExclusiveWithInstancesError extends Error {\n override readonly name = 'SpriteInstancesMutuallyExclusiveWithInstancesError';\n readonly code = 'sprite-instances-mutually-exclusive-with-instances' as const;\n readonly hint: string;\n readonly expected: string;\n readonly detail: {\n readonly code: 'sprite-instances-mutually-exclusive-with-instances';\n readonly entityId: number;\n };\n\n constructor(entityId: number) {\n const hint =\n 'remove Instances or replace with SpriteInstances; SpriteInstances supersedes ' +\n 'Instances when per-instance region is needed.';\n const expected = 'entity carries Instances XOR SpriteInstances (not both)';\n super(\n `SpriteInstances: entity ${entityId} carries both Instances and SpriteInstances.\\n` +\n ` code: sprite-instances-mutually-exclusive-with-instances\\n` +\n ` entityId: ${entityId}\\n` +\n ` expected: ${expected}\\n` +\n ` hint: ${hint}`,\n );\n this.hint = hint;\n this.expected = expected;\n this.detail = {\n code: 'sprite-instances-mutually-exclusive-with-instances',\n entityId,\n };\n }\n}\n","import type { Component, ComponentSchema, FieldReflection } from '../component';\nimport { componentDefinition } from '../component-schema';\n\nexport class TimeDeltaInvalidError extends Error {\n override readonly name = 'TimeDeltaInvalidError';\n readonly code = 'time-delta-invalid' as const;\n readonly expected = 'a finite delta greater than or equal to 0';\n readonly hint = 'Call world.update(deltaSeconds) with a finite non-negative delta.';\n readonly detail: { readonly received: number };\n\n constructor(received: number) {\n super(\n `Invalid world.update delta: ${received}.\\n expected: a finite delta greater than or equal to 0\\n hint: Call world.update(deltaSeconds) with a finite non-negative delta.`,\n );\n this.detail = { received };\n }\n}\n\nexport class TimeConfigInvalidError extends Error {\n override readonly name = 'TimeConfigInvalidError';\n readonly code = 'time-config-invalid' as const;\n readonly expected: string;\n readonly hint = 'Increase maxDeltaSeconds or decrease maxStepsPerUpdate or fixedDeltaSeconds.';\n readonly detail: {\n readonly fixedDeltaSeconds: number;\n readonly maxStepsPerUpdate: number;\n readonly maxDeltaSeconds: number;\n };\n\n constructor(detail: TimeConfigInvalidError['detail']) {\n const expected = 'maxDeltaSeconds >= (maxStepsPerUpdate + 1) * fixedDeltaSeconds';\n super(\n `Invalid World time policy.\\n expected: ${expected}\\n hint: Increase maxDeltaSeconds or decrease maxStepsPerUpdate or fixedDeltaSeconds.`,\n );\n this.expected = expected;\n this.detail = detail;\n }\n}\n\nexport class ScheduleScopeMismatchError extends Error {\n override readonly name = 'ScheduleScopeMismatchError';\n readonly code = 'schedule-scope-mismatch' as const;\n readonly expected: string;\n readonly hint: string;\n readonly detail: {\n readonly sourceSchedule: string;\n readonly targetSchedule: string;\n readonly reference?: string;\n };\n\n constructor(sourceSchedule: string, targetSchedule: string, reference?: string) {\n const expected = `a reference owned by ${sourceSchedule}`;\n const hint = `The referenced item belongs to ${targetSchedule}; register and order it in ${sourceSchedule}.`;\n super(`Schedule scope mismatch.\\n expected: ${expected}\\n hint: ${hint}`);\n this.expected = expected;\n this.hint = hint;\n this.detail = { sourceSchedule, targetSchedule, ...(reference ? { reference } : {}) };\n }\n}\n\n/**\n * Returned when a closed enum field receives a value outside its reflected\n * labels. The write owner runs this before any archetype or column mutation.\n */\nexport class ComponentFieldInvalidValueError extends Error {\n override readonly name = 'ComponentFieldInvalidValueError';\n readonly code = 'component-field-invalid-value' as const;\n readonly hint: string;\n readonly expected: string;\n readonly detail: {\n readonly entity: number | undefined;\n readonly component: string;\n readonly field: string;\n readonly received: unknown;\n readonly allowedValues: Readonly<Record<string, number>>;\n };\n\n constructor(\n entity: number | undefined,\n component: string,\n field: string,\n received: unknown,\n allowedValues: Readonly<Record<string, number>>,\n ) {\n const entries = Object.entries(allowedValues)\n .map(([label, value]) => `${label}=${value}`)\n .join(', ');\n const expected = `${component}.${field} in { ${entries} }`;\n const hint = `Set ${component}.${field} to one of the reflected enum values: ${entries}`;\n super(\n `${component}.${field} received an invalid enum value.\\n` +\n ` code: component-field-invalid-value\\n` +\n ` component: ${component}\\n` +\n ` field: ${field}\\n` +\n ` received: ${String(received)}\\n` +\n ` expected: ${expected}\\n` +\n ` hint: ${hint}`,\n );\n this.hint = hint;\n this.expected = expected;\n this.detail = { entity, component, field, received, allowedValues };\n }\n}\n\nexport class ComponentNumericValueInvalidError extends Error {\n override readonly name = 'ComponentNumericValueInvalidError';\n readonly code = 'component-numeric-value-invalid' as const;\n readonly expected = 'a numeric value other than NaN';\n readonly hint: string;\n readonly detail: {\n readonly entity: number | undefined;\n readonly component: string;\n readonly field: string;\n readonly received: number;\n readonly index?: number;\n };\n\n constructor(\n entity: number | undefined,\n component: string,\n field: string,\n received: number,\n index?: number,\n ) {\n const location =\n index === undefined ? `${component}.${field}` : `${component}.${field}[${index}]`;\n const hint = `Replace NaN at ${location} with an authored numeric value; Number.POSITIVE_INFINITY remains valid where the component domain permits it.`;\n super(\n `${location} received NaN.\\n` +\n ` code: component-numeric-value-invalid\\n` +\n ` expected: a numeric value other than NaN\\n` +\n ` hint: ${hint}`,\n );\n this.hint = hint;\n this.detail = {\n entity,\n component,\n field,\n received,\n ...(index === undefined ? {} : { index }),\n };\n }\n}\n\nconst NUMERIC_FIELD_TYPES = new Set(['f32', 'f64', 'i32', 'u32', 'i16', 'u16', 'i8', 'u8', 'enum']);\n\nexport function validateNumericFieldValues<S extends ComponentSchema>(\n component: Component<string, S>,\n raw: Partial<Record<string, unknown>> | undefined,\n entity?: number,\n): ComponentNumericValueInvalidError | null {\n if (raw === undefined) return null;\n const fields = componentDefinition(component).fields as Readonly<Record<string, FieldReflection>>;\n const rawValues = raw as Record<string, unknown>;\n for (const fieldName of Object.keys(rawValues)) {\n const reflection = fields[fieldName];\n if (reflection === undefined) continue;\n const value = rawValues[fieldName];\n if (NUMERIC_FIELD_TYPES.has(reflection.type)) {\n if (typeof value === 'number' && Number.isNaN(value)) {\n return new ComponentNumericValueInvalidError(entity, component.name, fieldName, value);\n }\n continue;\n }\n if (\n reflection.arrayMeta === undefined ||\n !NUMERIC_FIELD_TYPES.has(reflection.arrayMeta.elementType)\n ) {\n continue;\n }\n const length =\n Array.isArray(value) || ArrayBuffer.isView(value)\n ? (value as { readonly length?: number }).length\n : undefined;\n if (length === undefined) continue;\n const values = value as ArrayLike<unknown>;\n for (let index = 0; index < length; index++) {\n const received = values[index];\n if (typeof received === 'number' && Number.isNaN(received)) {\n return new ComponentNumericValueInvalidError(\n entity,\n component.name,\n fieldName,\n received,\n index,\n );\n }\n }\n }\n return null;\n}\n\n/**\n * Returned before an ECS write when a managed `array<T>` field receives a\n * value that the storage boundary cannot interpret as an array payload. The\n * old column writer treated arbitrary objects as an empty payload, which\n * silently changed the row while retaining no evidence of the caller error.\n */\nexport class ManagedArrayInvalidValueError extends Error {\n override readonly name = 'ManagedArrayInvalidValueError';\n readonly code = 'managed-array-invalid-value' as const;\n readonly expected = 'an Array or TypedArray payload (or null/undefined to clear it)';\n readonly hint: string;\n readonly detail: {\n readonly component: string;\n readonly field: string;\n readonly fieldType: string;\n readonly actualValue: unknown;\n };\n\n constructor(componentName: string, fieldName: string, fieldType: string, actualValue: unknown) {\n const hint =\n `Set ${componentName}.${fieldName} to a plain array or TypedArray matching ` +\n `${fieldType}; use null or undefined to clear the managed value.`;\n super(\n `${componentName}.${fieldName}: managed array received an invalid value.\\n` +\n ` code: managed-array-invalid-value\\n` +\n ` fieldType: ${fieldType}\\n` +\n ` expected: an Array or TypedArray payload (or null/undefined to clear it)\\n` +\n ` hint: ${hint}`,\n );\n this.hint = hint;\n this.detail = { component: componentName, field: fieldName, fieldType, actualValue };\n }\n}\n\n/**\n * Validate the closed enum fields present in a write payload. Enums without\n * labels remain open numeric fields for compatibility with existing schemas.\n */\nexport function validateEnumFieldValues<S extends ComponentSchema>(\n component: Component<string, S>,\n raw: Partial<Record<string, unknown>> | undefined,\n entity?: number,\n): ComponentFieldInvalidValueError | null {\n if (raw === undefined) return null;\n const fields = componentDefinition(component).fields as Readonly<Record<string, FieldReflection>>;\n const rawValues = raw as Record<string, unknown>;\n for (const fieldName of Object.keys(rawValues)) {\n const reflection = fields[fieldName];\n if (reflection?.type !== 'enum' || reflection.labels === undefined) continue;\n const value = rawValues[fieldName];\n const allowedValues = Object.values(reflection.labels);\n if (typeof value !== 'number' || !Number.isInteger(value) || !allowedValues.includes(value)) {\n return new ComponentFieldInvalidValueError(\n entity,\n component.name,\n fieldName,\n value,\n reflection.labels,\n );\n }\n }\n return null;\n}\n\n// ────────────────────────────────────────────────────────────────────────────\n// feat-20260519-light-casters-point-spot-pbr w2 — closed-union evolution +1.\n//\n// Adds 1 new member 'spawn-light-invalid-bounds' to EcsErrorCode (23 -> 24).\n// AGENTS.md section Error model evolution contract: minor (add member only).\n// Triggered by PointLight / SpotLight spawn-time payload validation\n// (plan-strategy D-S3 a). detail.field three-branch\n// ('range' | 'innerOuter' | 'outerNinety') keeps the four bound-violation\n// shapes under one error code so callers narrow first on `.code` then on\n// `.detail.field` (charter P3 progressive disclosure).\n// ────────────────────────────────────────────────────────────────────────────\n\n/**\n * Returned via `Result.err` from `world.spawn` when a PointLight or SpotLight\n * payload field is out of the documented bound. Four bound violations share\n * one `.code` and discriminate via `.detail.field`:\n *\n * - `range` — PointLight / SpotLight `range < 0` or `Number.isNaN(range)`.\n * Use `Number.POSITIVE_INFINITY` for an unlimited range or a non-negative\n * meter value.\n * - `innerOuter` — SpotLight `outerConeDeg <= innerConeDeg`. Inner cone is\n * the saturated bright region; outer cone is the falloff edge.\n * - `outerNinety` — SpotLight `outerConeDeg > 90`. KHR_lights_punctual upper\n * bound. A spot light cone wider than 90 degrees becomes a point light;\n * use PointLight instead.\n * - `direction` — DirectionalLight / SpotLight `direction` is missing or a\n * zero vector `[0, 0, 0]`. Direction has no default (there is no universal\n * default direction): omitting it lands the array layer-3 all-zero, which is\n * the same illegal state as an explicit zero vector. Supply a non-zero\n * direction (feat-20260709 M2 / D-1, add-only union member).\n *\n * `.code = 'spawn-light-invalid-bounds'`\n * `.detail.field` is derived from `keyof typeof SPAWN_LIGHT_INVALID_BOUNDS_POLICY`;\n * `.detail.got` is `number | readonly number[]`.\n * `.hint` — names the offending field plus the valid replacement form.\n */\nconst SPAWN_LIGHT_INVALID_BOUNDS_POLICY = {\n intensity: {\n expected: 'intensity is finite and >= 0',\n hint: (componentName: string, got: number | readonly number[]) =>\n `${componentName}.intensity must be a finite non-negative number (got ${got})`,\n },\n color: {\n expected: 'color is a finite non-negative [r, g, b] vector',\n hint: (componentName: string, got: number | readonly number[]) =>\n `${componentName}.color must contain three finite non-negative channels (got ${JSON.stringify(got)})`,\n },\n width: {\n expected: 'width is finite and > 0',\n hint: (componentName: string, got: number | readonly number[]) =>\n `${componentName}.width must be a finite positive meter value (got ${got})`,\n },\n height: {\n expected: 'height is finite and > 0',\n hint: (componentName: string, got: number | readonly number[]) =>\n `${componentName}.height must be a finite positive meter value (got ${got})`,\n },\n irradiance: {\n expected: 'irradiance is a finite 27-value SH vector',\n hint: (componentName: string, got: number | readonly number[]) =>\n `${componentName}.irradiance must contain 27 finite SH values (got ${JSON.stringify(got)})`,\n },\n radius: {\n expected: 'radius is finite and >= R_MIN',\n hint: (componentName: string, got: number | readonly number[]) =>\n `${componentName}.radius must be a finite value >= R_MIN (got ${got})`,\n },\n range: {\n expected: 'range >= 0 or Number.POSITIVE_INFINITY',\n hint: (componentName: string, got: number | readonly number[]) =>\n `${componentName}.range = ${got} is invalid; use Number.POSITIVE_INFINITY for unlimited range, or a non-negative meter value`,\n },\n innerOuter: {\n expected: 'outerConeDeg > innerConeDeg',\n hint: (componentName: string, got: number | readonly number[]) =>\n `${componentName}.outerConeDeg <= innerConeDeg (got ${got}); inner cone is the saturated bright region, outer cone is the falloff edge; outerConeDeg > innerConeDeg required`,\n },\n outerNinety: {\n expected: 'outerConeDeg <= 90 (KHR_lights_punctual upper bound)',\n hint: (componentName: string, got: number | readonly number[]) =>\n `${componentName}.outerConeDeg = ${got} > 90; a spot light cone wider than 90 degrees becomes a point light; use PointLight instead`,\n },\n direction: {\n expected: 'direction is a non-zero [x, y, z] vector',\n hint: (componentName: string, got: number | readonly number[]) =>\n `${componentName}.direction is missing or a zero vector (got ${JSON.stringify(got)}); direction has no default, provide a non-zero direction, e.g. [-0.5, -1, -0.3]`,\n },\n} satisfies Record<\n string,\n {\n readonly expected: string;\n readonly hint: (componentName: string, got: number | readonly number[]) => string;\n }\n>;\n\nexport class SpawnLightInvalidBoundsError extends Error {\n override readonly name = 'SpawnLightInvalidBoundsError';\n readonly code = 'spawn-light-invalid-bounds' as const;\n readonly hint: string;\n readonly expected: string;\n readonly detail: {\n readonly field: keyof typeof SPAWN_LIGHT_INVALID_BOUNDS_POLICY;\n readonly got: number | readonly number[];\n };\n\n constructor(\n componentName: string,\n field: keyof typeof SPAWN_LIGHT_INVALID_BOUNDS_POLICY,\n got: number | readonly number[],\n ) {\n const policy = SPAWN_LIGHT_INVALID_BOUNDS_POLICY[field];\n const hint = policy.hint(componentName, got);\n const expectedStr = policy.expected;\n super(\n `${componentName}: spawn payload bound violation.\\n` +\n ` code: spawn-light-invalid-bounds\\n` +\n ` component: ${componentName}\\n` +\n ` field: ${field}\\n` +\n ` got: ${got}\\n` +\n ` expected: ${expectedStr}\\n` +\n ` hint: ${hint}`,\n );\n this.hint = hint;\n this.expected = expectedStr;\n this.detail = { field, got };\n }\n}\n\n/**\n * Returned via `Result.err` from resource-setter helpers (e.g.\n * `setTransparentSortConfig`) when a numeric payload field violates the\n * closed bound declared by the resource contract. The first consumer is\n * `TransparentSortConfig.mode ∈ {0, 1, 2}` (plan-strategy D-4); future\n * resource validators with the same shape reuse this code by routing\n * through `.detail.receivedKey` to disambiguate which resource validator\n * surfaced the failure.\n *\n * Closed-set kebab code consistent with `spawn-light-invalid-bounds`\n * (feat-20260519 / w2); AI users consume via `switch (err.code)` exhaustive\n * narrows + `err.detail.receivedMode` (or `err.detail.receivedKey` /\n * `err.expected`) property access — never string-parse the message.\n *\n * `.code = 'resource-invalid-value'`\n * `.detail = { receivedMode: number; receivedKey?: string }`\n * `.hint` — direct copy-paste recovery (e.g. \"0=layer-z, 1=layer-y,\n * 2=layer-yz\" for the sort-config case).\n * `.expected` — the bound contract literal (e.g. \"mode ∈ {0, 1, 2}\").\n *\n * @reuses RhiError structured shape — same `.code / .expected / .hint /\n * .detail` quadruple AI users consume across rhi + ecs.\n */\nexport class ResourceInvalidValueError extends Error {\n override readonly name = 'ResourceInvalidValueError';\n readonly code = 'resource-invalid-value' as const;\n readonly hint: string;\n readonly expected: string;\n readonly detail: { readonly receivedMode: number; readonly receivedKey?: string };\n\n constructor(\n expected: string,\n hint: string,\n detail: { readonly receivedMode: number; readonly receivedKey?: string },\n ) {\n const keyClause = detail.receivedKey === undefined ? '' : ` key: ${detail.receivedKey}\\n`;\n super(\n `resource: invalid value.\\n` +\n ` code: resource-invalid-value\\n` +\n keyClause +\n ` receivedMode: ${detail.receivedMode}\\n` +\n ` expected: ${expected}\\n` +\n ` hint: ${hint}`,\n );\n this.hint = hint;\n this.expected = expected;\n this.detail = detail;\n }\n}\n\n// ────────────────────────────────────────────────────────────────────────────\n// feat-20260521-sprite-atlas-animation M1 T-05 — closed-union evolution +1.\n//\n// Adds 1 new member 'sprite-animation-invalid' to EcsErrorCode (25 -> 26).\n// AGENTS.md §Error model evolution contract: minor (add member only).\n// Same-shape add-only mirror of SpawnLightInvalidBoundsError (feat-20260519\n// w2 line 736-776) and ResourceInvalidValueError (feat-20260520 w13 line\n// 862) — the kebab `'<noun>-invalid-...'` series keeps `switch (err.code)`\n// exhaustive narrows visually consistent (charter P4 consistent abstraction;\n// research F-7 candidate A).\n//\n// Triggered by `spriteAnimationTickSystem` (packages/runtime/src/systems/\n// sprite-animation-tick.ts, landed in M4 T-23) when an entity's\n// `SpriteAnimation` row violates one of two runtime invariants:\n//\n// - field='regions-length' -> `regions.length !== frameCount * 4`\n// - field='frame-duration' -> `frameDuration <= 0`\n//\n// `.detail.field` two-branch (charter P3: AI users branch once on\n// `err.code` and once on `err.detail.field` to reach the recovery hint\n// without parsing the message). Plan-strategy section 2 D-1 binds the\n// detail field shape; M4 T-19 / T-20 / T-21 cover the runtime fail-fast\n// paths end-to-end.\n// ────────────────────────────────────────────────────────────────────────────\n\n/**\n * Returned via `Result.err` from `spriteAnimationTickSystem` (M4 T-23) when\n * an entity's `SpriteAnimation` row violates a runtime invariant.\n * Two invariants share one `.code` and discriminate via `.detail.field`:\n *\n * - `regions-length` — `SpriteAnimation.regions.length !== frameCount * 4`.\n * `regions` packs `[uMin, vMin, uW, vH]` per frame so the length must be\n * exactly `frameCount * 4`. Detail carries the offending `regionsLength`\n * alongside the declared `frameCount` so the hint can spell the exact\n * delta in callsite-friendly numbers.\n * - `frame-duration` — `SpriteAnimation.frameDuration <= 0` (covers both\n * `frameDuration === 0` and `frameDuration < 0`; T-21 binds the negative\n * case to the same arm so AI users handle both via a single\n * `if (err.detail.field === 'frame-duration')` branch — charter P4\n * consistent abstraction).\n *\n * `.code = 'sprite-animation-invalid'`\n * `.detail = { field: 'regions-length', regionsLength, frameCount } |\n * { field: 'frame-duration', frameDuration }`\n *\n * Two top-level detail variants give each `.field` branch its own\n * required sub-field shape so AI users get strong narrowing inside\n * `switch (err.detail.field)` without optional sub-fields bleeding\n * across branches (mirrors `SpawnLightInvalidBoundsError`'s shared\n * `got: number` shape but adapted because regions-length /\n * frame-duration carry different sub-field counts).\n *\n * `.hint` — names the offending invariant plus the valid replacement form.\n */\nexport class SpriteAnimationInvalidError extends Error {\n override readonly name = 'SpriteAnimationInvalidError';\n readonly code = 'sprite-animation-invalid' as const;\n readonly hint: string;\n readonly expected: string;\n readonly detail:\n | {\n readonly field: 'regions-length';\n readonly regionsLength: number;\n readonly frameCount: number;\n }\n | {\n readonly field: 'frame-duration';\n readonly frameDuration: number;\n };\n\n private static resolvePolicy(detail: SpriteAnimationInvalidError['detail']): {\n readonly expected: string;\n readonly hint: string;\n } {\n switch (detail.field) {\n case 'regions-length':\n return {\n expected: 'SpriteAnimation.regions.length === frameCount * 4',\n hint: `SpriteAnimation.regions.length = ${detail.regionsLength} does not match frameCount * 4 = ${detail.frameCount * 4}; pack 4 floats [uMin, vMin, uW, vH] per frame (see <name>.atlas.meta.json sidecar 'regions' map)`,\n };\n case 'frame-duration':\n return {\n expected: 'SpriteAnimation.frameDuration > 0',\n hint: `SpriteAnimation.frameDuration = ${detail.frameDuration} is invalid; use a positive seconds-per-frame value (e.g. 0.1 = 10 fps)`,\n };\n }\n }\n\n constructor(detail: SpriteAnimationInvalidError['detail']) {\n const policy = SpriteAnimationInvalidError.resolvePolicy(detail);\n super(\n `SpriteAnimation: invariant violated.\\n` +\n ` code: sprite-animation-invalid\\n` +\n ` field: ${detail.field}\\n` +\n ` expected: ${policy.expected}\\n` +\n ` hint: ${policy.hint}`,\n );\n this.hint = policy.hint;\n this.expected = policy.expected;\n this.detail = detail;\n }\n}\n","/**\n * ECS package-internal World seam.\n *\n * This module is intentionally not re-exported by the package entry points.\n * It keeps implementation access out of World's discoverable API while\n * retaining direct bound calls for the hot query and structural paths.\n */\n// Bundled ECS entry points (`index` and `projection`) each include this module\n// in their own closure. A plain Symbol() therefore gives World and projection\n// different property keys at runtime even though their source imports agree.\n// The registry is package-private by convention: no root/advanced export\n// exposes this key, while Symbol.for keeps source/dist and split bundles on\n// one identity.\nexport const worldInternal: unique symbol = Symbol.for(\n 'forgeax.ecs.worldInternal',\n) as unknown as typeof worldInternal;\n\ntype InternalName =\n | 'addComponentCore'\n | 'allocateIndex'\n | 'allocatePendingEntity'\n | 'cancelPendingEntity'\n | 'despawnCore'\n | 'getArrayView'\n | 'getArrayLength'\n | 'getArrayElement'\n | 'getFieldValue'\n | 'getBufferPool'\n | 'getClockWriter'\n | 'getComponentChange'\n | 'getComponentMutationEpoch'\n | 'getComponentMutationEpochs'\n | 'getEntityArchetype'\n | 'getFixedAccumulator'\n | 'getFreeIndices'\n | 'getGraph'\n | 'getMutationEpoch'\n | 'getQueryRow'\n | 'getRecords'\n | 'getRelationshipEpoch'\n | 'getRelationshipTargetEntities'\n | 'getResources'\n | 'getSchedule'\n | 'getSchedules'\n | 'getSharedRefs'\n | 'getStructureEpoch'\n | 'getStructuralEvidence'\n | 'getUniqueRefs'\n | 'lookupAlive'\n | 'markComponentAdded'\n | 'markComponentChanged'\n | 'markComponentRangeChanged'\n | 'markComponentsAdded'\n | 'markStructureChanged'\n | 'materializePendingEntity'\n | 'nextMutationEpoch'\n | 'poisonExecution'\n | 'publishDerivedRange'\n | 'prepareRelationshipInsert'\n | 'preflightComponentData'\n | 'readRow'\n | 'recordStructuralEvidence'\n | 'recordIsLive'\n | 'relationshipOnInsert'\n | 'relationshipOnRemove'\n | 'releaseManagedRefsOnRow'\n | 'releaseRelationshipPreparation'\n | 'removeComponentCore'\n | 'routeError'\n | 'restoreMutationEpoch'\n | 'setFixedAccumulator'\n | 'setQueryRow'\n | 'spawnCore'\n | 'writeEntitySelf'\n | 'writeRow';\n\nexport type WorldInternal = {\n // biome-ignore lint/suspicious/noExplicitAny: this closed package-internal seam preserves each method's existing inferred result type.\n readonly [K in InternalName]: (...args: any[]) => any;\n};\n","import type { Component, SchemaFieldType } from '../component';\nimport { componentId, componentSchema } from '../component';\nimport type { QueryDescriptor, QuerySpan } from '../query/query';\nimport type { SystemHandle } from '../schedule';\nimport { worldInternal } from '../world-internal';\n\nexport const SHARED_KERNEL_EXECUTOR_RESOURCE_KEY = 'SharedKernelExecutor';\n\nexport interface KernelDispatchResult {\n readonly mode: 'forced-inline' | 'shared';\n readonly dispatched: number;\n readonly completed: number;\n readonly waitMs: number;\n}\n\nexport interface KernelDispatchFailure {\n readonly cause: unknown;\n readonly dispatched: number;\n readonly completed: number;\n readonly partialWrite: boolean;\n}\n\nexport interface KernelDispatchSpan {\n readonly queryIndex: number;\n readonly span: QuerySpan;\n}\n\nexport interface SharedKernelExecutor {\n warmup?(kernel: SharedKernelDispatch): void;\n execute(\n kernel: SharedKernelDispatch,\n spans: readonly KernelDispatchSpan[],\n ): KernelDispatchResult | KernelDispatchFailure;\n}\n\nexport function isKernelDispatchFailure(\n value: KernelDispatchResult | KernelDispatchFailure,\n): value is KernelDispatchFailure {\n return 'cause' in value;\n}\n\nexport const SHARED_KERNEL_ELIGIBILITY_REASONS = [\n 'callback-not-module-function',\n 'dom-access',\n 'missing-access-declaration',\n 'descriptor-conflict',\n 'object-field',\n 'span-unavailable',\n] as const;\nexport type SharedKernelEligibilityReason = (typeof SHARED_KERNEL_ELIGIBILITY_REASONS)[number];\n\nexport type WorldExecutionHealth = 'healthy' | 'poisoned';\n\nexport interface WorldExecutionFault {\n readonly code: 'shared-kernel-failed';\n readonly kernelName: string;\n readonly cause: unknown;\n readonly partialWrite: boolean;\n readonly retryable: false;\n}\n\nexport interface WorldExecutionState {\n readonly identity: string;\n readonly health: WorldExecutionHealth;\n readonly fault: WorldExecutionFault | null;\n}\n\nlet nextWorldIdentity = 1;\n\nexport function createWorldIdentity(): string {\n const identity = `world-${nextWorldIdentity}`;\n nextWorldIdentity += 1;\n return identity;\n}\n\nexport function healthyWorldExecutionState(identity: string): WorldExecutionState {\n return Object.freeze({ identity, health: 'healthy', fault: null });\n}\n\nexport function poisonedWorldExecutionState(\n identity: string,\n fault: WorldExecutionFault,\n): WorldExecutionState {\n return Object.freeze({ identity, health: 'poisoned', fault: Object.freeze(fault) });\n}\n\nexport interface SharedKernelDefinition<Qs extends readonly QueryDescriptor[]> {\n readonly name: string;\n readonly queries: Qs;\n readonly run: (spans: readonly QuerySpan[]) => void;\n readonly minimumRows?: number;\n readonly before?: readonly (string | import('../schedule-token').ScheduleToken)[];\n readonly after?: readonly (string | import('../schedule-token').ScheduleToken)[];\n}\n\nexport interface SharedKernelDispatch<\n Qs extends readonly QueryDescriptor[] = readonly QueryDescriptor[],\n> {\n readonly kind: 'shared-kernel';\n readonly moduleUrl: string;\n readonly name: string;\n readonly minimumRows: number;\n readonly queries: Qs;\n readonly run: (spans: readonly QuerySpan[]) => void;\n}\n\nexport interface SharedKernelHandle<\n Qs extends readonly QueryDescriptor[] = readonly QueryDescriptor[],\n> extends SystemHandle<Qs>,\n SharedKernelDispatch<Qs> {}\n\nexport class SharedKernelEligibilityError extends Error {\n readonly code = 'shared-kernel-ineligible' as const;\n readonly expected =\n 'a module-loadable named kernel with one or more numeric QuerySpan read/write declarations';\n readonly hint =\n 'export a named function from the kernel module and use only dense numeric QuerySpan columns';\n readonly detail: { readonly kernelName: string; readonly reason: SharedKernelEligibilityReason };\n\n constructor(kernelName: string, reason: SharedKernelEligibilityReason) {\n super(`Shared kernel \"${kernelName}\" is ineligible: ${reason}.`);\n this.name = 'SharedKernelEligibilityError';\n this.detail = { kernelName, reason };\n }\n}\n\nexport class SharedKernelFailureError extends Error {\n readonly code = 'shared-kernel-failed' as const;\n readonly expected = 'every dispatched shard completes without a possible partial write';\n readonly hint =\n 'do not retry this World; inspect detail.cause and rebuild with a new World identity';\n readonly detail: {\n readonly kernelName: string;\n readonly worldIdentity: string;\n readonly cause: unknown;\n readonly partialWrite: boolean;\n readonly retryable: false;\n };\n\n constructor(kernelName: string, worldIdentity: string, cause: unknown, partialWrite: boolean) {\n super(`Shared kernel \"${kernelName}\" failed; World ${worldIdentity} is poisoned.`);\n this.name = 'SharedKernelFailureError';\n this.detail = { kernelName, worldIdentity, cause, partialWrite, retryable: false };\n }\n}\n\nexport class WorldPoisonedError extends Error {\n readonly code = 'world-poisoned' as const;\n readonly expected = 'World health is healthy before update';\n readonly hint = 'stop scheduling this World and explicitly bootstrap a new World identity';\n readonly detail: { readonly worldIdentity: string; readonly fault: unknown };\n\n constructor(worldIdentity: string, fault: unknown) {\n super(`World ${worldIdentity} is poisoned and cannot update.`);\n this.name = 'WorldPoisonedError';\n this.detail = { worldIdentity, fault };\n }\n}\n\nconst NUMERIC_FIELDS = new Set<SchemaFieldType>([\n 'f32',\n 'f64',\n 'i32',\n 'u32',\n 'i16',\n 'u16',\n 'i8',\n 'u8',\n 'bool',\n 'enum',\n 'ref',\n 'entity',\n]);\n\nfunction components(descriptor: QueryDescriptor): readonly Component[] {\n return [\n ...(descriptor.read ?? []),\n ...(descriptor.write ?? []),\n ...(descriptor.optional ?? []),\n ...(descriptor.with ?? []),\n ...(descriptor.without ?? []),\n ...(descriptor.changed ?? []),\n ...(descriptor.added ?? []),\n ];\n}\n\nfunction descriptorReason(descriptor: QueryDescriptor): SharedKernelEligibilityReason | undefined {\n if ((descriptor.read?.length ?? 0) + (descriptor.write?.length ?? 0) === 0) {\n return 'missing-access-declaration';\n }\n if (\n (descriptor.optional?.length ?? 0) > 0 ||\n (descriptor.changed?.length ?? 0) > 0 ||\n (descriptor.added?.length ?? 0) > 0\n ) {\n return 'span-unavailable';\n }\n const seen = new Set<number>();\n for (const component of components(descriptor)) {\n if (seen.has(componentId(component))) return 'descriptor-conflict';\n seen.add(componentId(component));\n if (component.storage === 'sparse') return 'span-unavailable';\n if (Object.values(componentSchema(component)).some((field) => !NUMERIC_FIELDS.has(field))) {\n return 'object-field';\n }\n }\n return undefined;\n}\n\nexport function sharedKernelEligibility(\n moduleUrl: string,\n definition: SharedKernelDefinition<readonly QueryDescriptor[]>,\n): SharedKernelEligibilityReason | undefined {\n try {\n new URL(moduleUrl);\n } catch {\n return 'callback-not-module-function';\n }\n const source = Function.prototype.toString.call(definition.run);\n if (definition.run.name.length === 0 || source.includes('=>')) {\n return 'callback-not-module-function';\n }\n if (/\\b(?:document|window|globalThis|HTMLElement|GPUDevice|AudioContext)\\b/u.test(source)) {\n return 'dom-access';\n }\n for (const query of definition.queries) {\n const reason = descriptorReason(query);\n if (reason !== undefined) return reason;\n }\n return undefined;\n}\n\nexport function defineSharedKernel<const Qs extends readonly QueryDescriptor[]>(\n moduleUrl: string,\n definition: SharedKernelDefinition<Qs>,\n): SharedKernelHandle<Qs> {\n const reason = sharedKernelEligibility(moduleUrl, definition);\n if (reason !== undefined) throw new SharedKernelEligibilityError(definition.name, reason);\n\n const handle: SharedKernelHandle<Qs> = Object.freeze({\n kind: 'shared-kernel' as const,\n moduleUrl,\n name: definition.name,\n queries: definition.queries,\n minimumRows: definition.minimumRows ?? 16_384,\n run: definition.run,\n ...(definition.before !== undefined ? { before: definition.before } : {}),\n ...(definition.after !== undefined ? { after: definition.after } : {}),\n fn: (world: import('../world').World, queries: Parameters<SystemHandle<Qs>['fn']>[1]) => {\n const dispatchSpans: KernelDispatchSpan[] = [];\n for (const [queryIndex, query] of queries.entries()) {\n const result = query.spans();\n if (!result.ok) throw new SharedKernelEligibilityError(definition.name, 'span-unavailable');\n for (const span of result.value) dispatchSpans.push({ queryIndex, span });\n }\n const spans = dispatchSpans.map((entry) => entry.span);\n const totalRows = spans.reduce((sum, span) => sum + span.length, 0);\n try {\n if (\n totalRows < (definition.minimumRows ?? 16_384) ||\n !world.hasResource(SHARED_KERNEL_EXECUTOR_RESOURCE_KEY)\n ) {\n definition.run(spans);\n return;\n }\n const executor = world.getResource<SharedKernelExecutor>(\n SHARED_KERNEL_EXECUTOR_RESOURCE_KEY,\n );\n const result = executor.execute(handle, dispatchSpans);\n if (isKernelDispatchFailure(result)) {\n if (!result.partialWrite) {\n definition.run(spans);\n return;\n }\n world[worldInternal].poisonExecution({\n code: 'shared-kernel-failed',\n kernelName: definition.name,\n cause: result.cause,\n partialWrite: result.partialWrite,\n retryable: false,\n });\n throw new SharedKernelFailureError(\n definition.name,\n world.execution.identity,\n result.cause,\n result.partialWrite,\n );\n }\n } catch (cause) {\n if (world.execution.health !== 'poisoned') {\n world[worldInternal].poisonExecution({\n code: 'shared-kernel-failed',\n kernelName: definition.name,\n cause,\n partialWrite: true,\n retryable: false,\n });\n }\n if (cause instanceof SharedKernelFailureError) throw cause;\n throw new SharedKernelFailureError(definition.name, world.execution.identity, cause, true);\n }\n },\n });\n return handle;\n}\n\nexport type SharedFieldView =\n | Float32Array\n | Float64Array\n | Int32Array\n | Uint32Array\n | Int16Array\n | Uint16Array\n | Int8Array\n | Uint8Array;\n\nexport interface SharedSpanBinding {\n readonly entities: Readonly<Uint32Array>;\n readonly length: number;\n readonly read: Readonly<Record<string, Readonly<Record<string, SharedFieldView>>>>;\n readonly write: Readonly<Record<string, Readonly<Record<string, SharedFieldView>>>>;\n}\n\nfunction sliceFields(\n fields: Readonly<Record<string, SharedFieldView>>,\n start: number,\n end: number,\n): Readonly<Record<string, SharedFieldView>> {\n return Object.fromEntries(\n Object.entries(fields).map(([name, view]) => [name, view.subarray(start, end)]),\n );\n}\n\nexport function bindSharedSpan(\n kernel: SharedKernelDispatch,\n span: QuerySpan,\n queryIndex: number,\n): SharedSpanBinding {\n const descriptor = kernel.queries[queryIndex];\n if (descriptor === undefined) throw new Error(`Missing query descriptor ${queryIndex}.`);\n const read = Object.fromEntries(\n (descriptor.read ?? []).map((component) => [\n component.name,\n span.get(component) as unknown as Record<string, SharedFieldView>,\n ]),\n );\n const write = Object.fromEntries(\n (descriptor.write ?? []).map((component) => [\n component.name,\n span.mut(component) as unknown as Record<string, SharedFieldView>,\n ]),\n );\n return { entities: span.entities, length: span.length, read, write };\n}\n\nexport function splitSharedSpan(\n binding: SharedSpanBinding,\n shardCount: number,\n): readonly SharedSpanBinding[] {\n if (binding.length === 0 || shardCount <= 0) return [];\n const count = Math.min(binding.length, shardCount);\n const shards: SharedSpanBinding[] = [];\n for (let index = 0; index < count; index += 1) {\n const start = Math.floor((binding.length * index) / count);\n const end = Math.floor((binding.length * (index + 1)) / count);\n shards.push({\n entities: binding.entities.subarray(start, end),\n length: end - start,\n read: Object.fromEntries(\n Object.entries(binding.read).map(([component, fields]) => [\n component,\n sliceFields(fields, start, end),\n ]),\n ),\n write: Object.fromEntries(\n Object.entries(binding.write).map(([component, fields]) => [\n component,\n sliceFields(fields, start, end),\n ]),\n ),\n });\n }\n return shards;\n}\n\nexport function isSharedSpan(binding: SharedSpanBinding): boolean {\n if (typeof SharedArrayBuffer === 'undefined') return false;\n if (!(binding.entities.buffer instanceof SharedArrayBuffer)) return false;\n return [...Object.values(binding.read), ...Object.values(binding.write)].every((fields) =>\n Object.values(fields).every((view) => view.buffer instanceof SharedArrayBuffer),\n );\n}\n","// @forgeax/engine-ecs — typed error class collection.\n//\n// Typed error classes covering all boundary conditions. Each follows progressive\n// disclosure format: one-line summary → context fields → hint fix suggestion.\n// Each exposes a `.hint` readonly property for programmatic extraction.\n\nimport type { QuerySpanUnavailableReason } from './errors/query-and-component-errors';\n\n// ────────────────────────────────────────────────────────────────────────────\n// Re-exports from split error sub-files (w3-b — package cohesion split)\n// ────────────────────────────────────────────────────────────────────────────\n\nexport {\n ComponentNotDefinedError,\n QueryDataRequiresFieldsError,\n QueryDescriptorConflictError,\n QueryIterationActiveError,\n QueryIterationInvalidatedError,\n QuerySpanUnavailableError,\n type QuerySpanUnavailableReason,\n RemoveEssentialComponentError,\n SpawnDataUnknownFieldError,\n} from './errors/query-and-component-errors';\n\nexport {\n RelationshipDetachMismatchError,\n RelationshipMirrorComponentNotRegisteredError,\n RelationshipMirrorFieldTypeMismatchError,\n RelationshipSelfCycleError,\n RelationshipTargetReadonlyError,\n} from './errors/relationship-errors';\nexport {\n SharedFieldInvalidValueError,\n SpriteInstancesCountMismatchError,\n SpriteInstancesMutuallyExclusiveWithInstancesError,\n SpriteInstancesRequiresSpriteShaderError,\n} from './errors/sprite-and-shared-errors';\nexport {\n ComponentFieldInvalidValueError,\n ComponentNumericValueInvalidError,\n ManagedArrayInvalidValueError,\n ResourceInvalidValueError,\n ScheduleScopeMismatchError,\n SpawnLightInvalidBoundsError,\n SpriteAnimationInvalidError,\n TimeConfigInvalidError,\n TimeDeltaInvalidError,\n validateEnumFieldValues,\n validateNumericFieldValues,\n} from './errors/validation-errors';\n\nexport {\n SharedKernelEligibilityError,\n SharedKernelFailureError,\n WorldPoisonedError,\n} from './execution/shared-kernel';\n\n/**\n * Thrown when an attempt is made to encode an entity index that does not fit\n * in 24 bits (i.e. >= 2^24 = 16_777_216).\n *\n * `.code = 'entity-index-overflow'`\n * `.hint` — suggests reducing entity count or investigating leaks.\n */\nexport class EntityIndexOverflowError extends RangeError {\n override readonly name = 'EntityIndexOverflowError';\n readonly code = 'entity-index-overflow' as const;\n readonly hint: string;\n\n constructor(index: number) {\n const hint =\n 'Entity index exceeds 24-bit max (16777215). Reduce simultaneous entity count or investigate entity leaks.';\n super(\n `Entity index ${index} exceeds 24-bit max (16777215).\\n` +\n ` index: ${index}\\n` +\n ` hint: ${hint}`,\n );\n this.hint = hint;\n }\n}\n\n/**\n * Thrown when `defineComponent` is given a field type that is not in the\n * supported scalar field type set.\n *\n * `.code = 'schema-unsupported-field'`\n * `.hint` — lists all supported scalar field types.\n */\nexport class SchemaUnsupportedFieldError extends Error {\n override readonly name = 'SchemaUnsupportedFieldError';\n readonly code = 'schema-unsupported-field' as const;\n readonly hint: string;\n\n constructor(fieldName: string, fieldType: string) {\n let hint = 'Supported types: f32 / f64 / i32 / u32 / i16 / u16 / i8 / u8 / bool / enum / ref.';\n // feat-20260614 M1 / M5: explicit migration hints for the two\n // retired schema-vocab keyword families. Both renames preserve brand\n // and storage layout (u32 column); only the keyword + dispatch arm\n // changed. AI users hitting either literal land directly on the new\n // keyword instead of grepping for the rename note (charter F1\n // single-entry indexability).\n if (fieldType.startsWith('handle<') && fieldType.endsWith('>')) {\n const tag = fieldType.slice(7, -1);\n hint = `'handle<${tag}>' was removed in feat-20260614 M5; use 'shared<${tag}>' instead. The brand and storage layout are unchanged; only the keyword + write-barrier dispatch (SharedRefStore retain/release) is new.`;\n } else if (fieldType.startsWith('ref<') && fieldType.endsWith('>')) {\n const tag = fieldType.slice(4, -1);\n hint = `'ref<${tag}>' was renamed in feat-20260614 M1; use 'unique<${tag}>' instead. The brand and storage layout are unchanged; the dispatch still routes through UniqueRefStore (single-holder direct release).`;\n }\n super(\n `Schema field \"${fieldName}\" has unsupported type \"${fieldType}\".\\n` +\n ` field: ${fieldName}\\n` +\n ` type: ${fieldType}\\n` +\n ` hint: ${hint}`,\n );\n this.hint = hint;\n }\n}\n\nexport class SparseStorageRequiresTagError extends Error {\n override readonly name = 'SparseStorageRequiresTagError';\n readonly code = 'sparse-storage-requires-tag' as const;\n readonly expected = 'sparse components have an empty schema and no relationship metadata';\n readonly hint = 'remove all fields and relationship metadata, or use storage: table';\n readonly detail: { readonly componentName: string };\n\n constructor(componentName: string) {\n super(\n `Sparse component \"${componentName}\" must be a zero-field, non-relationship tag.\\n` +\n ` component: ${componentName}\\n` +\n ` hint: remove all fields and relationship metadata, or use storage: table`,\n );\n this.detail = { componentName };\n }\n}\n\n/**\n * Thrown (or returned via the `Result` err branch — `r.ok === false`, `r.error`)\n * when get/set/addComponent/removeComponent is called on an entity that has\n * been despawned (stale handle).\n *\n * `.code = 'stale-entity'`\n * `.hint` — includes operation name, expected/actual generation, and component name.\n * Enhanced fields: `.component`, `.operation`, `.expectedGeneration`, `.actualGeneration`.\n */\nexport class StaleEntityError extends Error {\n override readonly name = 'StaleEntityError';\n readonly code = 'stale-entity' as const;\n readonly hint: string;\n\n /** Component name involved in the operation (undefined when the operation does not target a specific component). */\n readonly component: string | undefined;\n /** The component-level operation that triggered this error (e.g. 'get' / 'set' / 'add' / 'remove'). Entity-level operations like `despawn` are not surfaced here — see `EntityHandle` lifecycle errors. */\n readonly operation: string | undefined;\n /** The generation the caller expected (from the entity handle). */\n readonly expectedGeneration: number | undefined;\n /**\n * The actual generation found in the entity pool. `-1` is the sentinel\n * value for entities never allocated (slot was never occupied), as opposed\n * to allocated-then-despawned entities which carry a real (incremented)\n * generation number.\n */\n readonly actualGeneration: number | undefined;\n\n constructor(\n entityId: number,\n index: number,\n generation: number,\n enhanced?: {\n component?: string;\n operation: string;\n expectedGeneration: number;\n actualGeneration: number;\n },\n ) {\n const hint = enhanced\n ? `Entity was despawned. Operation \"${enhanced.operation}\" on entity ${entityId}` +\n (enhanced.component ? ` (component: ${enhanced.component})` : '') +\n ` expected generation ${enhanced.expectedGeneration}, found ${enhanced.actualGeneration}.` +\n ' Check entity lifecycle before access.'\n : 'Entity was despawned. Check entity lifecycle before access.';\n super(\n `Operation on stale entity handle.\\n` +\n ` entity: ${entityId} (index=${index}, generation=${generation})\\n` +\n (enhanced ? ` operation: ${enhanced.operation}\\n` : '') +\n (enhanced?.component ? ` component: ${enhanced.component}\\n` : '') +\n ` hint: ${hint}`,\n );\n this.hint = hint;\n this.component = enhanced?.component;\n this.operation = enhanced?.operation;\n this.expectedGeneration = enhanced?.expectedGeneration;\n this.actualGeneration = enhanced?.actualGeneration;\n }\n}\n\n/**\n * Returned via the `Result` err branch (`r.ok === false`, `r.error`) when\n * addComponent tries to add a component that the entity already possesses.\n *\n * `.code = 'component-already-present'`\n * `.hint` — suggests using `set()` to update values instead.\n */\nexport class ComponentAlreadyPresentError extends Error {\n override readonly name = 'ComponentAlreadyPresentError';\n readonly code = 'component-already-present' as const;\n readonly hint: string;\n\n constructor(entityId: number, componentName: string) {\n const hint = 'Entity already has this component. Use set() to update values.';\n super(\n `Entity ${entityId} already has component \"${componentName}\".\\n` +\n ` entity: ${entityId}\\n` +\n ` component: ${componentName}\\n` +\n ` hint: ${hint}`,\n );\n this.hint = hint;\n }\n}\n\n/**\n * Returned via the `Result` err branch (`r.ok === false`, `r.error`) when\n * removeComponent / set is called for a component the entity does not possess.\n *\n * `.code = 'component-not-present'`\n * `.hint` — suggests checking with query or inspect().\n */\nexport class ComponentNotPresentError extends Error {\n override readonly name = 'ComponentNotPresentError';\n readonly code = 'component-not-present' as const;\n readonly hint: string;\n\n constructor(entityId: number, componentName: string) {\n const hint = 'Entity does not have this component. Check with query or inspect().';\n super(\n `Entity ${entityId} does not have component \"${componentName}\".\\n` +\n ` entity: ${entityId}\\n` +\n ` component: ${componentName}\\n` +\n ` hint: ${hint}`,\n );\n this.hint = hint;\n }\n}\n\n/**\n * Thrown when DAG Schedule detects a cyclic dependency among systems.\n *\n * `.code = 'cyclic-dependency'`\n * `.hint` — includes the cycle path and suggests removing one constraint.\n * `.detail` — `{ code: 'cyclic-dependency'; cycle: readonly string[] }` contains the\n * structured cycle path for programmatic consumption.\n */\nexport class CyclicDependencyError extends Error {\n override readonly name = 'CyclicDependencyError';\n readonly code = 'cyclic-dependency' as const;\n readonly expected = 'the schedule dependency graph is acyclic';\n readonly hint: string;\n /** Structured cycle path — programmatic consumers read this, not the message. */\n readonly detail: { readonly code: 'cyclic-dependency'; readonly cycle: readonly string[] };\n\n constructor(cycle: readonly string[]) {\n const cycleStr = cycle.join(' -> ');\n const hint = `Cycle path: ${cycleStr}. Remove one ordering constraint to break the cycle.`;\n super(`DAG Schedule has a cyclic dependency.\\n cycle: ${cycleStr}\\n hint: ${hint}`);\n this.hint = hint;\n this.detail = { code: 'cyclic-dependency' as const, cycle };\n }\n}\n\n/**\n * Returned via `Result.err` from `world.addSystems`\n * when a SystemSet token fails local structural validation.\n *\n * The sole public invalid-token error type (D-2a). Covers all rejection\n * scenarios: plain-object cast, unregistered name, stale token after\n * overwrite, and cross-realm copies.\n *\n * `.code = 'system-set-not-registered'`\n * `.expected` — the name of the unregistered token.\n * `.hint` — suggests passing the current token to the owning World schedule.\n * `.detail` — `{ code, name, registered }` where `registered` is a deterministic snapshot\n * of the current World-local schedule keys.\n */\nexport class SystemSetNotRegisteredError extends Error {\n override readonly name = 'SystemSetNotRegisteredError';\n readonly code = 'system-set-not-registered' as const;\n /** The name carried by the rejected token. */\n readonly expected: string;\n readonly hint: string;\n /** Deterministic snapshot of the current World-local schedule for repair. */\n readonly detail: {\n readonly code: 'system-set-not-registered';\n readonly name: string;\n readonly registered: readonly string[];\n };\n\n constructor(name: string, registered: readonly string[]) {\n const hint =\n `SystemSet \"${name}\" is not valid for the current World schedule. ` +\n `Pass a non-empty SystemSet token owned by this World schedule.`;\n const message =\n `SystemSet \"${name}\" is not registered.\\n` +\n ` expected: ${name}\\n` +\n ` registered: [${registered.join(', ')}]\\n` +\n ` hint: ${hint}`;\n super(message);\n this.expected = name;\n this.hint = hint;\n this.detail = { code: 'system-set-not-registered' as const, name, registered };\n }\n}\n\n/**\n * Factory for {@link SystemSetNotRegisteredError}. Consumed by\n * {@link validateSystemSetTokens} (w4) and the two mutation entry points.\n */\nexport function systemSetNotRegistered(\n name: string,\n registered: readonly string[],\n): SystemSetNotRegisteredError {\n return new SystemSetNotRegisteredError(name, registered);\n}\n\n/**\n * Closed-set ScheduleMutationError code union (M2 — plan-strategy D-3).\n *\n * Schedule add-only API (`removeSystem` / `replaceSystem`) returns\n * `Result<void, ScheduleMutationError>` carrying one of these codes. The\n * `@forgeax/engine-remote` layer (M3) bridges these strings to JSON-RPC\n * `RemoteErrorCode` 1:1 — keeping ECS free of console / wire dependencies.\n *\n * - `system-before-unknown` — name argument does not match any registered system.\n * - `system-name-conflict` — reserved for the M3 inject path; surfaced from\n * schedule when callers inject a name that already exists.\n * - `cyclic-injection` — schedule build detected a cycle introduced by\n * the mutation; carries the cycle path in `.detail.cycle`.\n */\nexport type ScheduleMutationErrorCode = 'system-before-unknown';\n\nexport interface ScheduleMutationErrorDetail {\n readonly cycle?: readonly string[];\n readonly candidates?: readonly string[];\n}\n\n/**\n * Returned via `Result.err` from `world.removeSystem` / `world.replaceSystem`.\n *\n * `.code` is the closed-set string SSOT consumed by the M3 console bridge;\n * `.hint` carries an AI-friendly self-repair suggestion; `.detail` is the\n * discriminated payload (cycle path for `cyclic-injection`, candidate list\n * for `system-before-unknown`).\n */\nexport class ScheduleMutationError extends Error {\n override readonly name = 'ScheduleMutationError';\n readonly code: ScheduleMutationErrorCode;\n readonly hint: string;\n readonly detail: ScheduleMutationErrorDetail;\n\n constructor(\n code: ScheduleMutationErrorCode,\n message: string,\n hint: string,\n detail: ScheduleMutationErrorDetail = {},\n ) {\n super(`${message}\\n code: ${code}\\n hint: ${hint}`);\n this.code = code;\n this.hint = hint;\n this.detail = detail;\n }\n}\n\n/**\n * Thrown when getResource is called with a key that does not exist.\n *\n * `.code = 'resource-not-found'`\n * `.hint` — suggests using `world.insertResource()` first.\n */\nexport class ResourceNotFoundError extends Error {\n override readonly name = 'ResourceNotFoundError';\n readonly code = 'resource-not-found' as const;\n readonly hint: string;\n\n constructor(key: string) {\n const hint = `Resource \"${key}\" not found. Insert with world.insertResource() first.`;\n super(`Resource \"${key}\" not found.\\n` + ` key: ${key}\\n` + ` hint: ${hint}`);\n this.hint = hint;\n }\n}\n\nexport class ChangeEpochExhaustedError extends Error {\n override readonly name = 'ChangeEpochExhaustedError';\n readonly code = 'change-epoch-exhausted' as const;\n readonly expected = 'mutationEpoch < Number.MAX_SAFE_INTEGER';\n readonly hint = 'Rebuild the World before performing another mutation.';\n readonly detail: { readonly epoch: number };\n\n constructor(epoch: number) {\n super(`World mutation epoch is exhausted at ${epoch}.\\n hint: Rebuild the World.`);\n this.detail = { epoch };\n }\n}\n\nexport class DerivedRangeOutOfBoundsError extends Error {\n override readonly name = 'DerivedRangeOutOfBoundsError';\n readonly code = 'derived-range-out-of-bounds' as const;\n readonly expected = 'a non-negative span-relative range with start + count <= span.length';\n readonly hint =\n 'check start and count against the QuerySpan length, then retry without changing World state';\n readonly detail: { readonly start: number; readonly count: number; readonly spanLength: number };\n\n constructor(start: number, count: number, spanLength: number) {\n super(`Derived range [${start}, ${start + count}) exceeds QuerySpan length ${spanLength}.`);\n this.detail = { start, count, spanLength };\n }\n}\n\n/**\n * Thrown when insertResource/removeResource is called on a World-owned\n * protected resource (Time or FixedTime).\n *\n * `.code = 'resource-protected'`\n * `.hint` — suggests using `world.update(delta)` or reading the resource.\n * `.expected` — the resource name that was rejected.\n */\nexport class ProtectedResourceError extends Error {\n override readonly name = 'ProtectedResourceError';\n readonly code = 'resource-protected' as const;\n readonly hint: string;\n readonly expected: string;\n\n constructor(resourceName: string, operation: 'insert' | 'remove') {\n const hint =\n operation === 'insert'\n ? `\"${resourceName}\" is a World-owned protected resource. It is advanced by world.update(delta); read it via world.getResource(${resourceName}).`\n : `\"${resourceName}\" is a World-owned protected resource. It is owned by the World scheduler and cannot be removed.`;\n const expected = `a user-owned resource key (not ${resourceName})`;\n super(\n `Protected resource \"${resourceName}\" cannot be ${operation}ed.\\n` +\n ` code: resource-protected\\n` +\n ` resource: ${resourceName}\\n` +\n ` expected: ${expected}\\n` +\n ` hint: ${hint}`,\n );\n this.hint = hint;\n this.expected = expected;\n }\n}\n\n// ────────────────────────────────────────────────────────────────────────────\n// w5 — managed-* closed-union extension (M0).\n//\n// Four error classes covering the managed-* family:\n//\n// managed-* : UniqueRefStore + BufferPool runtime fail-fast.\n// Returned via Result.err from M1 / M2 storage paths.\n//\n// `.code` uses lowercase-kebab literals consistent with `ScheduleMutationErrorCode`\n// (the prior closed-set convention). The 9 legacy errors keep their\n// SCREAMING_SNAKE_CASE codes — codes are append-only per the evolution contract.\n// `EcsErrorCode` (declared at the foot of this file) merges all literal codes\n// into one closed union; downstream `switch (err.code)` is exhaustive.\n//\n// Every detail object is a discriminated payload — narrowed per `.code` via\n// `EcsErrorDetail` (also at foot of file).\n// ────────────────────────────────────────────────────────────────────────────\n\n/**\n * Thrown / returned via `Result.err` when UniqueRefStore.alloc encounters a\n * slot whose refcount has already dropped to zero (sentinel for a released\n * slot reused without re-init).\n *\n * `.code = 'unique-ref-released'`\n * `.detail = { handle, target }`\n * `.hint` — recommends checking handle lifetime against owner despawn.\n */\nexport class UniqueRefReleasedError extends Error {\n override readonly name = 'UniqueRefReleasedError';\n readonly code = 'unique-ref-released' as const;\n readonly hint: string;\n readonly expected: string;\n readonly detail: { readonly handle: number; readonly target: string };\n\n constructor(handle: number, target: string) {\n const hint = `Handle ${handle} (target ${target}) was released before this access. Re-acquire via the producing system or re-spawn the asset before reading.`;\n const expected = 'live (refcount >= 1) managed handle';\n super(\n `UniqueRefStore: handle is already released.\\n` +\n ` code: unique-ref-released\\n` +\n ` handle: ${handle}\\n` +\n ` target: ${target}\\n` +\n ` expected: ${expected}\\n` +\n ` hint: ${hint}`,\n );\n this.hint = hint;\n this.expected = expected;\n this.detail = { handle, target };\n }\n}\n\n/**\n * Thrown / returned via `Result.err` when UniqueRefStore.release is called on\n * a handle whose refcount is already zero (double-free).\n *\n * `.code = 'unique-ref-double-release'`\n * `.detail = { handle, target }`\n * `.hint` — recommends auditing the release-loop entry points (set / removeComponent / despawn).\n */\nexport class UniqueRefDoubleReleaseError extends Error {\n override readonly name = 'UniqueRefDoubleReleaseError';\n readonly code = 'unique-ref-double-release' as const;\n readonly hint: string;\n readonly expected: string;\n readonly detail: { readonly handle: number; readonly target: string };\n\n constructor(handle: number, target: string) {\n const hint = `Handle ${handle} (target ${target}) was released twice. Only one of {despawn / removeComponent / set} should release a managed handle per lifecycle.`;\n const expected = 'first release of a managed handle (refcount transition 1 -> 0)';\n super(\n `UniqueRefStore: double release on handle.\\n` +\n ` code: unique-ref-double-release\\n` +\n ` handle: ${handle}\\n` +\n ` target: ${target}\\n` +\n ` expected: ${expected}\\n` +\n ` hint: ${hint}`,\n );\n this.hint = hint;\n this.expected = expected;\n this.detail = { handle, target };\n }\n}\n\n// ────────────────────────────────────────────────────────────────────────────\n// feat-20260614-ecs-shared-component-and-unique-rename M3 — SharedRefStore\n// closed-union extension (+2). Mirrors the UniqueRef* pair — `'shared-ref-released'`\n// covers resolve-after-release / retain-after-release; `'shared-ref-double-release'`\n// covers release-when-rc-already-zero. Both are Result.err returns (not throws);\n// AI users branch on `.code` and read `.detail.handle` for the offending slot.\n//\n// Detail field shape mirrors UniqueRef* with one addition (`rc`) so AI users\n// debugging a double-release see the exact rc transition that surfaced the\n// failure (charter P3 progressive disclosure). Empty `target` handled the\n// same way as UniqueRef* — runtime-erased phantom, surfaced as '<unknown>'.\n// ────────────────────────────────────────────────────────────────────────────\n\n/**\n * Thrown / returned via `Result.err` when SharedRefStore.resolve / .retain is\n * called on a handle whose refcount has already dropped to zero (slot released).\n *\n * `.code = 'shared-ref-released'`\n * `.detail = { handle, target }`\n * `.hint` — recommends checking handle lifetime against owner / consumer release.\n */\nexport class SharedRefReleasedError extends Error {\n override readonly name = 'SharedRefReleasedError';\n readonly code = 'shared-ref-released' as const;\n readonly hint: string;\n readonly expected: string;\n readonly detail: { readonly handle: number; readonly target: string };\n\n constructor(handle: number, target: string) {\n const hint = `Handle ${handle} (target ${target}) was released (refcount reached 0). Re-acquire via the producing system or re-spawn the asset before reading.`;\n const expected = 'live (refcount >= 1) shared handle';\n super(\n `SharedRefStore: handle is already released.\\n` +\n ` code: shared-ref-released\\n` +\n ` handle: ${handle}\\n` +\n ` target: ${target}\\n` +\n ` expected: ${expected}\\n` +\n ` hint: ${hint}`,\n );\n this.hint = hint;\n this.expected = expected;\n this.detail = { handle, target };\n }\n}\n\n/**\n * Thrown / returned via `Result.err` when SharedRefStore.release is called on\n * a handle whose refcount is already zero (double-release). Distinct from the\n * UniqueRef family because shared release is rc--, not direct slot drop —\n * AI users debug this by reading `.detail.rc` (always 0 here) alongside the\n * payload-presence signal.\n *\n * `.code = 'shared-ref-double-release'`\n * `.detail = { handle, target, rc }`\n * `.hint` — recommends auditing the producer / consumer release pairs.\n */\nexport class SharedRefDoubleReleaseError extends Error {\n override readonly name = 'SharedRefDoubleReleaseError';\n readonly code = 'shared-ref-double-release' as const;\n readonly hint: string;\n readonly expected: string;\n readonly detail: { readonly handle: number; readonly target: string; readonly rc: number };\n\n constructor(handle: number, target: string, rc: number) {\n const hint = `Handle ${handle} (target ${target}) released with rc=${rc}. Each shared handle must have a matching alloc/retain for every release; audit the producer / consumer release pairs.`;\n const expected = 'rc >= 1 before release';\n super(\n `SharedRefStore: double release on handle.\\n` +\n ` code: shared-ref-double-release\\n` +\n ` handle: ${handle}\\n` +\n ` target: ${target}\\n` +\n ` rc: ${rc}\\n` +\n ` expected: ${expected}\\n` +\n ` hint: ${hint}`,\n );\n this.hint = hint;\n this.expected = expected;\n this.detail = { handle, target, rc };\n }\n}\n\n/** Raised before SharedRefStore mutates slot state for a nullish payload. */\nexport class SharedRefPayloadInvalidError extends Error {\n override readonly name = 'SharedRefPayloadInvalidError';\n readonly code = 'shared-ref-payload-invalid' as const;\n readonly expected = 'a non-null, non-undefined shared payload';\n readonly hint = 'Allocate a concrete payload and let its owning effect dispose it.';\n readonly detail: { readonly target: string; readonly actual: 'null' | 'undefined' };\n\n constructor(target: string, actual: 'null' | 'undefined') {\n super(`SharedRefStore: ${actual} payload is not a valid shared reference for ${target}.`);\n this.detail = { target, actual };\n }\n}\n\n/**\n * Returned via `Result.err` when a builtin-tier slot (`slot < BUILTIN_BASE`)\n * is passed to SharedRefStore.alloc / retain / release / resolve\n * (feat-20260614 M6 D-15). The SharedRefStore manages ONLY user-tier slots\n * (`>= BUILTIN_BASE`); builtin asset payloads are process-static and owned by\n * the package that authored their builtin handle, never reference-counted by\n * this World store.\n *\n * `.code = 'builtin-slot-not-owned'`\n * `.detail = { slot }`\n * `.hint` — points the caller back to the builtin handle owner.\n */\nexport class BuiltinSlotNotOwnedError extends Error {\n override readonly name = 'BuiltinSlotNotOwnedError';\n readonly code = 'builtin-slot-not-owned' as const;\n readonly hint: string;\n readonly expected: string;\n readonly detail: { readonly slot: number };\n\n constructor(slot: number) {\n const hint = `Slot ${slot} is a builtin-tier handle (< BUILTIN_BASE). World.sharedRefs manages only user-tier handles (>= BUILTIN_BASE). Obtain the builtin payload from the package that authored the handle; builtin payloads are process-static and never reference-counted by this World.`;\n const expected = 'user-tier slot (>= BUILTIN_BASE)';\n super(\n `SharedRefStore: builtin slot is not owned by this store.\\n` +\n ` code: builtin-slot-not-owned\\n` +\n ` slot: ${slot}\\n` +\n ` expected: ${expected}\\n` +\n ` hint: ${hint}`,\n );\n this.hint = hint;\n this.expected = expected;\n this.detail = { slot };\n }\n}\n\n// ────────────────────────────────────────────────────────────────────────────\n// feat-20260623-asset-handle-generation M4 — stale error classes (+2).\n//\n// Two error classes covering gen-based staleness detection in SharedRefStore\n// and UniqueRefStore. Distinguish from the existing `*-ref-released` codes\n// (slot empty / never allocated) — `*-ref-stale` means the slot has been\n// released AND re-allocated, so the caller's handle generation no longer\n// matches the store's current generation. AI users pick different recovery\n// strategies: released -> re-load the asset; stale -> re-acquire the handle\n// from AssetRegistry (charter P3 explicit failure, two semantics two\n// recovery paths).\n//\n// `.detail` carries { slot, expectedGeneration, actualGeneration } aligned\n// with StaleEntityError field names (AC-11). Codes are add-only minor\n// members of EcsErrorCode (AC-10) and detail shapes extend EcsErrorDetail\n// discriminator.\n// ────────────────────────────────────────────────────────────────────────────\n\n/**\n * Returned via `Result.err` when SharedRefStore.resolve / .retain / .release\n * is called with a handle whose generation no longer matches the store's\n * current generation for that slot — the slot was released and re-allocated\n * to a different payload. Distinct from `'shared-ref-released'` (slot empty,\n * never re-allocated): stale means the slot IS live but belongs to a newer\n * allocation.\n *\n * `.code = 'shared-ref-stale'`\n * `.detail = { slot, expectedGeneration, actualGeneration }`\n * `.hint` — recommends re-acquiring the handle from AssetRegistry.\n */\nexport class SharedRefStaleError extends Error {\n override readonly name = 'SharedRefStaleError';\n readonly code = 'shared-ref-stale' as const;\n readonly hint: string;\n readonly expected: string;\n readonly detail: {\n readonly slot: number;\n readonly expectedGeneration: number;\n readonly actualGeneration: number;\n };\n\n constructor(slot: number, expectedGeneration: number, actualGeneration: number) {\n const hint = `Handle for slot ${slot} is stale: expected generation ${expectedGeneration}, but the store has generation ${actualGeneration} (slot was released and re-allocated). Re-acquire the handle from AssetRegistry.`;\n const expected = `generation === ${actualGeneration} (current store generation)`;\n super(\n `SharedRefStore: stale handle.\\n` +\n ` code: shared-ref-stale\\n` +\n ` slot: ${slot}\\n` +\n ` expectedGeneration: ${expectedGeneration}\\n` +\n ` actualGeneration: ${actualGeneration}\\n` +\n ` expected: ${expected}\\n` +\n ` hint: ${hint}`,\n );\n this.hint = hint;\n this.expected = expected;\n this.detail = { slot, expectedGeneration, actualGeneration };\n }\n}\n\n/**\n * Returned via `Result.err` when UniqueRefStore.resolve / .release is\n * called with a handle whose generation no longer matches the store's\n * current generation for that slot — the slot was released and re-allocated.\n * Distinct from `'unique-ref-released'` (slot empty). UniqueRefStore has\n * no retain method; the stale surface is resolve + release only.\n *\n * `.code = 'unique-ref-stale'`\n * `.detail = { slot, expectedGeneration, actualGeneration }`\n * `.hint` — recommends re-acquiring the handle from the producing system.\n */\nexport class UniqueRefStaleError extends Error {\n override readonly name = 'UniqueRefStaleError';\n readonly code = 'unique-ref-stale' as const;\n readonly hint: string;\n readonly expected: string;\n readonly detail: {\n readonly slot: number;\n readonly expectedGeneration: number;\n readonly actualGeneration: number;\n };\n\n constructor(slot: number, expectedGeneration: number, actualGeneration: number) {\n const hint = `Handle for slot ${slot} is stale: expected generation ${expectedGeneration}, but the store has generation ${actualGeneration} (slot was released and re-allocated). Re-acquire the handle via the producing system or re-spawn the asset.`;\n const expected = `generation === ${actualGeneration} (current store generation)`;\n super(\n `UniqueRefStore: stale handle.\\n` +\n ` code: unique-ref-stale\\n` +\n ` slot: ${slot}\\n` +\n ` expectedGeneration: ${expectedGeneration}\\n` +\n ` actualGeneration: ${actualGeneration}\\n` +\n ` expected: ${expected}\\n` +\n ` hint: ${hint}`,\n );\n this.hint = hint;\n this.expected = expected;\n this.detail = { slot, expectedGeneration, actualGeneration };\n }\n}\n\n/**\n * Thrown / returned via `Result.err` when BufferPool indexing reads or writes\n * an offset outside the slot's `[0, size)` byte range. Triggers are limited\n * to the `buffer:<N>` and managed-array-element-buffer paths; the\n * `'string'` schema vocab no longer routes through this code (collapsed onto\n * the managed-ref dispatch by feat-20260515-string-managed-collapse — JS\n * string capacity is bounded by the host runtime, not by BufferPool buckets).\n *\n * `.code = 'managed-buffer-out-of-bounds'`\n * `.detail = { index, size }`\n * `.hint` — points at the field's `'buffer'` / `buffer<N>` schema declaration.\n */\nexport class ManagedBufferOutOfBoundsError extends RangeError {\n override readonly name = 'ManagedBufferOutOfBoundsError';\n readonly code = 'managed-buffer-out-of-bounds' as const;\n readonly hint: string;\n readonly expected: string;\n readonly detail: { readonly index: number; readonly size: number };\n\n constructor(index: number, size: number) {\n const hint = `Index ${index} is outside [0, ${size}). Check the field's 'buffer' / 'buffer<N>' declaration matches the access pattern.`;\n const expected = `index in [0, ${size})`;\n super(\n `BufferPool: index out of bounds.\\n` +\n ` code: managed-buffer-out-of-bounds\\n` +\n ` index: ${index}\\n` +\n ` size: ${size}\\n` +\n ` expected: ${expected}\\n` +\n ` hint: ${hint}`,\n );\n this.hint = hint;\n this.expected = expected;\n this.detail = { index, size };\n }\n}\n\n/**\n * Thrown / returned via `Result.err` when BufferPool resize is asked to shrink\n * a slot below its current allocated size — the pool only grows.\n *\n * `.code = 'managed-buffer-shrink-not-supported'`\n * `.detail = { requested, current }`\n * `.hint` — directs callers to allocate a fresh slot if a smaller buffer is needed.\n */\nexport class ManagedBufferShrinkNotSupportedError extends Error {\n override readonly name = 'ManagedBufferShrinkNotSupportedError';\n readonly code = 'managed-buffer-shrink-not-supported' as const;\n readonly hint: string;\n readonly expected: string;\n readonly detail: { readonly requested: number; readonly current: number };\n\n constructor(requested: number, current: number) {\n const hint = `BufferPool only grows. Requested ${requested} bytes < current ${current}; allocate a fresh slot if a smaller buffer is required.`;\n const expected = `requested >= ${current}`;\n super(\n `BufferPool: shrink not supported.\\n` +\n ` code: managed-buffer-shrink-not-supported\\n` +\n ` requested: ${requested}\\n` +\n ` current: ${current}\\n` +\n ` expected: ${expected}\\n` +\n ` hint: ${hint}`,\n );\n this.hint = hint;\n this.expected = expected;\n this.detail = { requested, current };\n }\n}\n\n// ────────────────────────────────────────────────────────────────────────────\n// feat-20260515-buffer-array-vocab-collapse w11 — closed-union evolution.\n//\n// 4 managed-array-* error classes deleted (replaced by the 4 collapsed-vocab\n// codes below); ManagedArrayElementTypeNotAllowedError preserved (still\n// surfaced from defineComponent's schema parser).\n//\n// 2 surviving error classes:\n// - FixedSizeMismatchError ('fixed-size-mismatch')\n// - InstanceTransformsStrideMismatchError ('instance-transforms-stride-mismatch')\n//\n// Naming-prefix orthogonality (plan-strategy §2.5):\n// fixed- element-type or capacity contract violations on fixed shape\n// array- operation failures (pop on empty) on the array vocab keyword\n// instance- GPU-render component-specific stride contract (Instances.transforms)\n//\n// The array element-wise facade was removed; only write-shape and render\n// stride errors remain on this boundary. The\n// `instance-transforms-stride-mismatch` member is the plan-strategy §2.4\n// evolution surfaced from `packages/runtime/src/render-system-extract.ts`\n// defensive entry (consumed by w15 in M3, but the error class lives here so\n// the EcsErrorCode union closure is owned by ECS — RhiError is not extended\n// per plan-strategy §2.4 decision).\n// ────────────────────────────────────────────────────────────────────────────\n\n/**\n * Returned via `Result.err` from `world.set` when a `buffer<N>` field is\n * written with a `Uint8Array` whose `byteLength` does not equal the\n * schema-declared fixed size `N`. AI users resize their payload to exactly\n * `N` bytes (zero-pad or truncate at the producer) before calling `world.set`.\n *\n * `.code = 'fixed-size-mismatch'`\n * `.detail = { expected, actual }`\n * `.hint` — points at the producer's payload sizing.\n */\nexport class FixedSizeMismatchError extends Error {\n override readonly name = 'FixedSizeMismatchError';\n readonly code = 'fixed-size-mismatch' as const;\n readonly hint: string;\n readonly expected: string;\n readonly detail: { readonly expected: number; readonly actual: number };\n\n constructor(fieldName: string, expected: number, actual: number) {\n const hint = `buffer<${expected}> set with byteLength ${actual} (expected ${expected}); resize your Uint8Array to exactly ${expected} bytes before world.set`;\n const expectedStr = `byteLength === ${expected}`;\n super(\n `buffer<N>: fixed-size mismatch.\\n` +\n ` code: fixed-size-mismatch\\n` +\n ` field: ${fieldName}\\n` +\n ` expected: ${expected}\\n` +\n ` actual: ${actual}\\n` +\n ` hint: ${hint}`,\n );\n this.hint = hint;\n this.expected = expectedStr;\n this.detail = { expected, actual };\n }\n}\n\n/**\n * Surfaced via the Layer-3 ErrorHandler from\n * `packages/runtime/src/render-system-extract.ts` defensive entry when an\n * `Instances.transforms` array<f32> length violates the column-major mat4\n * stride contract (`length % 16 === 0`). Locates the failure adjacent to the\n * extract pipeline rather than at GPU upload (plan-strategy §2.4 D-P2 +\n * §8.3 hint SSOT).\n *\n * `.code = 'instance-transforms-stride-mismatch'`\n * `.detail = { actualLength, expectedStride: 16 }`\n * `.hint` — names the stride invariant + the call sites to audit.\n */\nexport class InstanceTransformsStrideMismatchError extends Error {\n override readonly name = 'InstanceTransformsStrideMismatchError';\n readonly code = 'instance-transforms-stride-mismatch' as const;\n readonly hint: string;\n readonly expected: string;\n readonly detail: { readonly actualLength: number; readonly expectedStride: 16 };\n\n constructor(actualLength: number) {\n const hint = `Instances.transforms length ${actualLength} violates stride 16 (mat4); ensure transforms.length % 16 === 0 before render frame; verify world.set / world.push call sites`;\n const expectedStr = 'actualLength % 16 === 0';\n super(\n `Instances.transforms: stride mismatch.\\n` +\n ` code: instance-transforms-stride-mismatch\\n` +\n ` actualLength: ${actualLength}\\n` +\n ` expectedStride: 16\\n` +\n ` hint: ${hint}`,\n );\n this.hint = hint;\n this.expected = expectedStr;\n this.detail = { actualLength, expectedStride: 16 };\n }\n}\n\n/**\n * Thrown by `defineComponent` when an `array<T>` / `array<T,N>` schema field\n * carries an element type outside the legal whitelist (scalars + entity).\n * Forms like `array<ref<X>>` / `array<handle<X>>` / `array<buffer:N>` /\n * `array<array<...>>` are rejected (AC-03 runtime fail-safe). The TS layer\n * blocks these forms at compile time; this error is the runtime backstop for\n * `as unknown as SchemaFieldType` casts.\n *\n * `.code = 'managed-array-element-type-not-allowed'`\n * `.detail = { fieldName, elementType, hint }`\n * `.hint` — lists the whitelist of legal element types.\n */\nexport class ManagedArrayElementTypeNotAllowedError extends Error {\n override readonly name = 'ManagedArrayElementTypeNotAllowedError';\n readonly code = 'managed-array-element-type-not-allowed' as const;\n readonly hint: string;\n readonly expected: string;\n readonly detail: {\n readonly fieldName: string;\n readonly elementType: string;\n readonly hint: string;\n };\n\n constructor(fieldName: string, elementType: string) {\n const hint = `array<T> element type must be a scalar (f32/f64/i32/u32/i16/u16/i8/u8/bool/enum/ref) or entity. ref<X> / handle<X> / buffer:N / nested array<...> are forbidden on field \"${fieldName}\".`;\n const expected = 'element type in {scalar | entity}';\n super(\n `managed-array: element type not allowed.\\n` +\n ` code: managed-array-element-type-not-allowed\\n` +\n ` field: ${fieldName}\\n` +\n ` elementType: ${elementType}\\n` +\n ` expected: ${expected}\\n` +\n ` hint: ${hint}`,\n );\n this.hint = hint;\n this.expected = expected;\n this.detail = { fieldName, elementType, hint };\n }\n}\n\n// ────────────────────────────────────────────────────────────────────────────\n// EcsErrorCode closed union (w5)\n//\n// Merges every `.code` literal across the EcsError family. Downstream\n// `switch (err.code)` blocks become exhaustive; `assertNever(code)` catches\n// any future code addition without a matching case at compile time.\n//\n// Order is grouped (legacy SCREAMING_SNAKE first, then closed-set kebab) but\n// not load-bearing — TS unions are unordered.\n// ────────────────────────────────────────────────────────────────────────────\n\n/** Closed union of every `.code` literal carried by EcsError instances. */\nexport type EcsErrorCode =\n // Legacy SCREAMING_SNAKE codes (7, carried unchanged; the two\n // registration codes COMPONENT_ALREADY_REGISTERED / COMPONENT_NOT_REGISTERED\n // were dropped by feat-20260602 along with the per-World register concept).\n | 'stale-entity'\n | 'component-already-present'\n | 'component-not-present'\n | 'cyclic-dependency'\n | 'resource-not-found'\n // ECS time and schedule-scope errors (M2 w16, approved 43 -> 46 baseline; verify hotfix +1 → 47).\n | 'time-delta-invalid'\n | 'time-config-invalid'\n | 'schedule-scope-mismatch'\n // ScheduleMutationError closed-set kebab code.\n | ScheduleMutationErrorCode\n // w5 managed-* kebab codes (4).\n | 'unique-ref-released'\n | 'unique-ref-double-release'\n // feat-20260614-ecs-shared-component-and-unique-rename M3 — SharedRefStore\n // closed-union extension (+2). `'shared-ref-released'` covers resolve / retain\n // on rc=0; `'shared-ref-double-release'` covers release on rc=0.\n | 'shared-ref-released'\n | 'shared-ref-double-release'\n | 'shared-ref-payload-invalid'\n // feat-20260614-ecs-shared-component-and-unique-rename M6 D-15 (+1).\n // SharedRefStore manages ONLY user-tier slots (>= BUILTIN_BASE); a builtin\n // slot (< BUILTIN_BASE) passed to alloc/retain/release/resolve is a caller\n // error -> `'builtin-slot-not-owned'` (the authoring package owns the payload).\n | 'builtin-slot-not-owned'\n // feat-20260623-asset-handle-generation M4 — stale error codes (+2).\n // `'shared-ref-stale'` / `'unique-ref-stale'` cover gen mismatch on resolve /\n // retain / release after slot re-allocation. Add-only minor per AGENTS.md\n // Error model evolution contract; distinct from the existing `*-ref-released`\n // codes (slot empty vs slot re-allocated).\n | 'shared-ref-stale'\n | 'unique-ref-stale'\n | 'managed-buffer-out-of-bounds'\n | 'managed-buffer-shrink-not-supported'\n // managed-array-* kebab codes — surviving member from feat-20260514;\n // the other 4 (`managed-array-{index-out-of-bounds, pop-empty,\n // shrink-not-supported, stride-mismatch}`) were dropped by\n // feat-20260515-buffer-array-vocab-collapse w11 in favour of the 4 new\n // collapsed-vocab codes below. Kept here because `defineComponent`'s schema\n // parser still surfaces it for illegal `array<...>` element types.\n // feat-20260515-buffer-array-vocab-collapse w11 collapsed-vocab codes (4,\n // plan-strategy §2.4 + §2.5 four-prefix taxonomy).\n | 'fixed-size-mismatch'\n // feat-20260519-light-casters-point-spot-pbr w2 — PointLight / SpotLight\n // spawn-time payload bound violation (plan-strategy D-S3 a). 23 -> 24\n // minor evolution per AGENTS.md Error model evolution contract.\n // feat-20260520-2d-sprite-layer-mvp M-2 w13 — resource-setter bound\n // validation (plan-strategy D-4). 25 -> 26 minor evolution; first\n // consumer is `setTransparentSortConfig` (mode ∈ {0, 1, 2}).\n // feat-20260521-sprite-atlas-animation M1 T-05 — spriteAnimationTickSystem\n // runtime invariant violation (plan-strategy D-1). 26 -> 27 minor evolution\n // per AGENTS.md §Error model evolution contract; same-shape mirror of\n // 'spawn-light-invalid-bounds' (feat-20260519 w2) and 'resource-invalid-\n // value' (feat-20260520 w13) — the `<noun>-invalid-...` kebab series keeps\n // switch (err.code) narrows visually consistent for AI users (charter P4).\n // feat-20260531-ecs-relationship-abstraction-bidirectional-sync M2 —\n // relationship bidirectional sync + defineComponent relationship validation +\n // addChild/reparent cycle detection + removeChild detach guard\n // (plan-strategy D-5). 27 -> 31 minor evolution per AGENTS.md Error model\n // evolution contract. `relationship-exclusive-violation` is NOT a member:\n // exclusive re-add is an automatic reparent (success path), not an error.\n | 'relationship-self-cycle'\n | 'relationship-detach-mismatch'\n // feat-20260602-drop-component-registration w16-a — scene instantiate\n // fail-fast when a SceneAsset entity names a component that was never defined\n // via defineComponent (the per-World register concept was dropped; a\n // component becomes globally usable the moment defineComponent runs). 30 ->\n // 31 minor evolution per AGENTS.md Error model evolution contract. Replaces\n // the deleted COMPONENT_NOT_REGISTERED code at the scene-instance producer\n // sites (research Finding 5 missed these 3 producers; human escalation-\n // response authorized this scope-amendment).\n // feat-20260602-archetype-stores-full-packed-entity M1 / w3 — removeComponent\n // rejection when the target is an essential (undeletable) component. The only\n // essential component is the id=0 `Entity` (plan-strategy D-3). Net +1 minor\n // evolution per AGENTS.md §Error model evolution contract.\n | 'remove-essential-component'\n // feat-20260608-scene-nesting-ecs-fication M1 / w9 — setSceneOverride\n // type-mismatch fail-fast (plan-strategy D-9). 30 -> 31 minor evolution per\n // AGENTS.md §Error model evolution contract. Surfaced from\n // `world.setSceneOverride(root, member, comp, field, value)` when `value`'s\n // runtime type does not match the per-component schema field type (the\n // override apply path never silently coerces — value writes are typed at the\n // ECS layer; requirements §Edge cases table last row, reviewer Issue 1).\n // bug-20260615-spawn-data-unknown-field-fail-fast — spawn / addComponent /\n // SceneAsset.instantiate / Commands.spawn fail-fast when the caller-supplied\n // payload carries a key that is not declared in the component schema. Pre-\n // fix the unknown key was silently dropped by `fillComponentDefaults`\n // (which iterated only over schema keys), routing typos like\n // `MeshRenderer { material }` (singular legacy name) into the empty-default\n // path and producing invisible / mid-grey entities downstream. AI users\n // narrow on `.code` then read `.detail.field` for the offending key and\n // `.detail.knownFields` for the valid field whitelist.\n | 'spawn-data-unknown-field'\n // feat-20260625-sprite-instances-and-tilemap-terrain-static-batch M1 / w2 —\n // SpriteInstances primitive + tilemap terrain static-batch path. Three\n // codes declared together; fire path lands in M3 w13 at the\n // render-system-extract QueryRow loop. Minor evolution +3 per\n // AGENTS.md §Error model evolution contract; plan-strategy D-6 keeps the\n // detection in the render domain (not the ECS spawn path) to avoid an\n // ECS -> AssetRegistry reverse dep for the shader-id lookup.\n // feat-20260713-mount-override-component-add-and-shared-ref-round M2 / w9 —\n // P3 shared-field value gate. A `shared<T>` scalar or `array<shared<T>>`\n // element must be a resolved numeric Handle; a raw GUID string / `{ guid }` /\n // `{ kind }` object (the pre-resolution shape an AI user gets from a sidecar)\n // was silently coerced to the all-zero sentinel by the column packer\n // (`typed[i] = typeof val === 'number' ? val : 0`) / scalar write, so a\n // mis-bound reference read back as `0` / `[0,0,0,0]` and rendered blank with\n // no error. `validateComponentDataKeys` only checks key names, not value\n // types — this code closes the value-type gap at all three write entries\n // (spawn / addComponent / set). AI users resolve a GUID via\n // `AssetRegistry.load(guid, kind) + allocSharedRef` first; passing the raw GUID now fails fast.\n // Minor evolution +1 per AGENTS.md §Error model evolution contract.\n | 'shared-field-invalid-value'\n // feat-20260714-bevy-style-system-sets M1 / w3 — sole invalid-SystemSet\n // error code. Surfaced from world.addSystems when a\n // token fails identity validation (brand bypass + registry identity check).\n // Minor evolution +1 per AGENTS.md §Error model evolution contract.\n | 'system-set-not-registered'\n // Closed enum field writes fail before archetype or column mutation.\n | 'component-field-invalid-value'\n | 'component-numeric-value-invalid'\n | 'managed-array-invalid-value'\n | 'shared-kernel-ineligible'\n | 'shared-kernel-failed'\n | 'world-poisoned'\n // World.update terminal failures. These remain in the same closed union as\n // structural errors so consumers never need a second error discriminator.\n | 'command-failed'\n | 'system-failed';\n\n/**\n * Discriminated `.detail` payload per `.code`.\n *\n * Narrowed via `switch (err.code)` against `EcsErrorCode`. Empty-detail entries\n * (legacy errors without `.detail`) are intentionally omitted from this map —\n * only the w5 family + `cyclic-injection` carry structured payloads today.\n */\nexport type EcsErrorDetail =\n | {\n readonly code: 'shared-kernel-ineligible';\n readonly kernelName: string;\n readonly reason: string;\n }\n | {\n readonly code: 'shared-kernel-failed';\n readonly kernelName: string;\n readonly worldIdentity: string;\n readonly cause: unknown;\n readonly partialWrite: boolean;\n readonly retryable: false;\n }\n | { readonly code: 'world-poisoned'; readonly worldIdentity: string; readonly fault: unknown }\n | { readonly code: 'sparse-storage-requires-tag'; readonly componentName: string }\n | {\n readonly code: 'query-descriptor-conflict';\n readonly componentName: string;\n readonly roles: readonly string[];\n }\n | { readonly code: 'query-data-requires-fields'; readonly componentName: string }\n | { readonly code: 'query-span-unavailable'; readonly reason: QuerySpanUnavailableReason }\n | {\n readonly code: 'query-iteration-invalidated';\n readonly expectedStructureEpoch: number;\n readonly actualStructureEpoch: number;\n }\n | { readonly code: 'query-iteration-active' }\n | { readonly code: 'change-epoch-exhausted'; readonly epoch: number }\n | { readonly code: 'unique-ref-released'; readonly handle: number; readonly target: string }\n | {\n readonly code: 'unique-ref-double-release';\n readonly handle: number;\n readonly target: string;\n }\n // feat-20260614 M3 — SharedRefStore detail variants (+2).\n | { readonly code: 'shared-ref-released'; readonly handle: number; readonly target: string }\n | {\n readonly code: 'shared-ref-double-release';\n readonly handle: number;\n readonly target: string;\n readonly rc: number;\n }\n | {\n readonly code: 'shared-ref-payload-invalid';\n readonly target: string;\n readonly actual: 'null' | 'undefined';\n }\n // feat-20260614 M6 D-15 — builtin-slot fail-fast detail variant (+1).\n | { readonly code: 'builtin-slot-not-owned'; readonly slot: number }\n // feat-20260623-asset-handle-generation M4 — stale error detail variants (+2).\n | {\n readonly code: 'shared-ref-stale';\n readonly slot: number;\n readonly expectedGeneration: number;\n readonly actualGeneration: number;\n }\n | {\n readonly code: 'unique-ref-stale';\n readonly slot: number;\n readonly expectedGeneration: number;\n readonly actualGeneration: number;\n }\n | { readonly code: 'managed-buffer-out-of-bounds'; readonly index: number; readonly size: number }\n | {\n readonly code: 'managed-buffer-shrink-not-supported';\n readonly requested: number;\n readonly current: number;\n }\n // feat-20260514 surviving managed-array-* discriminated detail variant (1).\n | {\n readonly code: 'managed-array-element-type-not-allowed';\n readonly fieldName: string;\n readonly elementType: string;\n readonly hint: string;\n }\n // feat-20260515-buffer-array-vocab-collapse w11 collapsed-vocab detail\n // variants (4). Per-code field names are SSOT-anchored at AC-07 + plan-\n // strategy §2.4 §detail-list (NOT renamed for \"consistency\" — name follows\n // semantics).\n | {\n readonly code: 'fixed-size-mismatch';\n readonly expected: number;\n readonly actual: number;\n }\n | {\n readonly code: 'instance-transforms-stride-mismatch';\n readonly actualLength: number;\n readonly expectedStride: 16;\n }\n // feat-20260519-light-casters-point-spot-pbr w2 — light and local probe\n // spawn-time payload bound violation (plan-strategy D-S3 a). detail.field\n // names the validated scalar or RGB payload while one code keeps the\n // recovery surface closed; AI users narrow on `.detail.field` after the\n // outer `switch (err.code)` to pick the specific recovery hint.\n | {\n readonly code: 'spawn-light-invalid-bounds';\n readonly field:\n | 'direction'\n | 'intensity'\n | 'color'\n | 'width'\n | 'height'\n | 'irradiance'\n | 'radius'\n | 'range'\n | 'innerOuter'\n | 'outerNinety';\n readonly got: number | readonly number[];\n }\n // feat-20260520-2d-sprite-layer-mvp M-2 w13 — resource-setter bound\n // violation (plan-strategy D-4). receivedMode carries the rejected\n // payload number; receivedKey is optional so future resource\n // validators can share the same code while disambiguating which\n // resource produced the failure.\n | {\n readonly code: 'resource-invalid-value';\n readonly receivedMode: number;\n readonly receivedKey?: string;\n }\n // feat-20260521-sprite-atlas-animation M1 T-05 — sprite-animation tick\n // runtime invariant violation (plan-strategy D-1 + section 5 AC-09).\n // detail.field two-branch keeps the regions-length / frame-duration\n // invariants under one code; AI users narrow on `.detail.field` after\n // the outer `switch (err.code)` to pick the specific recovery hint\n // (charter P3 + P4). Two top-level variants give each `.field` branch\n // its own required sub-field shape so AI users get strong narrowing\n // inside `switch (err.detail.field)` without optional sub-fields\n // bleeding across branches.\n | {\n readonly code: 'sprite-animation-invalid';\n readonly field: 'regions-length';\n readonly regionsLength: number;\n readonly frameCount: number;\n }\n | {\n readonly code: 'sprite-animation-invalid';\n readonly field: 'frame-duration';\n readonly frameDuration: number;\n }\n // feat-20260531-ecs-relationship-abstraction-bidirectional-sync M2 — the 4\n // relationship-* discriminated detail variants (plan-strategy D-5). Each\n // carries the component name + the entities involved so AI users narrow on\n // `.code` then read `.detail` to locate the offending relationship surface.\n | {\n readonly code: 'relationship-self-cycle';\n readonly component: string;\n readonly entity: number;\n readonly ancestor: number;\n }\n | {\n readonly code: 'relationship-mirror-component-not-registered';\n readonly component: string;\n readonly mirror: string;\n }\n | {\n readonly code: 'relationship-mirror-field-type-mismatch';\n readonly component: string;\n readonly mirror: string;\n readonly field: string;\n readonly actualType: string;\n }\n | {\n readonly code: 'relationship-detach-mismatch';\n readonly component: string;\n readonly child: number;\n readonly expectedParent: number;\n readonly actualParent: number;\n }\n // feat-20260602-drop-component-registration w16-a — scene instantiate\n // unknown-component fail-fast (30 -> 31). `.detail.name` carries the\n // component name that was never defined via defineComponent.\n | {\n readonly code: 'component-not-defined';\n readonly name: string;\n }\n // feat-20260602-archetype-stores-full-packed-entity M1 / w3 — removeComponent\n // essential-component rejection. `.detail.componentName` carries the essential\n // component name (the id=0 `Entity`).\n | {\n readonly code: 'remove-essential-component';\n readonly componentName: string;\n }\n // feat-20260608-scene-nesting-ecs-fication M1 / w9 — setSceneOverride\n // value-type rejection (plan-strategy D-9; requirements §Edge cases last\n // row + reviewer Issue 1). `.detail.comp` / `.detail.field` locate the\n // override target; `.detail.expectedType` carries the schema-declared\n // type literal (e.g. 'f32', 'bool', 'string'); `.detail.actualType`\n // carries the runtime `typeof value` (typed `unknown` because the\n // override write is not coerced — fail-fast surfaces the mismatch).\n | {\n readonly code: 'scene-override-type-mismatch';\n readonly comp: string;\n readonly field: string;\n readonly expectedType: string;\n readonly actualType: unknown;\n }\n // bug-20260615-spawn-data-unknown-field-fail-fast — spawn-data unknown-key\n // fail-fast. `.detail.component` names the schema's component, `.detail.field`\n // is the offending raw key, `.detail.knownFields` is the schema's full field\n // whitelist (sorted, used by AI users / hint formatters to surface \"did you\n // mean\" suggestions without round-tripping to the schema).\n | {\n readonly code: 'spawn-data-unknown-field';\n readonly component: string;\n readonly field: string;\n readonly knownFields: readonly string[];\n }\n // feat-20260625-sprite-instances-and-tilemap-terrain-static-batch M1 / w2 —\n // 3 discriminated detail variants for the SpriteInstances primitive\n // (declared in M1, fired at render-system-extract entry in M3).\n | {\n readonly code: 'sprite-instances-count-mismatch';\n readonly transformsLength: number;\n readonly regionsLength: number;\n readonly expectedStride: { readonly transforms: 16; readonly regions: 4 };\n }\n | {\n readonly code: 'sprite-instances-requires-sprite-shader';\n readonly entityId: number;\n readonly observedMaterialShaderId: string;\n }\n | {\n readonly code: 'sprite-instances-mutually-exclusive-with-instances';\n readonly entityId: number;\n }\n // feat-20260713-mount-override-component-add-and-shared-ref-round M2 / w9 —\n // shared-field value gate. `.detail.component` / `.detail.field` locate the\n // shared reference field; `.detail.fieldType` is the schema-declared type\n // literal (`shared<T>` scalar or `array<shared<T>>`); `.detail.actualValue`\n // is the offending non-handle value (typed `unknown` — a raw GUID string /\n // `{ guid }` / `{ kind }` object is not coerced, the fail-fast surfaces it);\n // `.detail.index` is the array element index for the array form (undefined for\n // the scalar form). AI users read `.detail.field` + `.detail.fieldType` to see\n // which reference needs `AssetRegistry.load(guid, kind) + allocSharedRef` before binding.\n | {\n readonly code: 'shared-field-invalid-value';\n readonly component: string;\n readonly field: string;\n readonly fieldType: string;\n readonly actualValue: unknown;\n readonly index?: number;\n }\n // feat-20260714-bevy-style-system-sets M1 / w3 — invalid-SystemSet detail.\n // `.detail.name` is the rejected token name; `.detail.registered` is a\n // deterministic snapshot of the current registry keys.\n | {\n readonly code: 'system-set-not-registered';\n readonly name: string;\n readonly registered: readonly string[];\n }\n | {\n readonly code: 'component-field-invalid-value';\n readonly entity: number | undefined;\n readonly component: string;\n readonly field: string;\n readonly received: unknown;\n readonly allowedValues: Readonly<Record<string, number>>;\n }\n | {\n readonly code: 'component-numeric-value-invalid';\n readonly entity: number | undefined;\n readonly component: string;\n readonly field: string;\n readonly received: number;\n readonly index?: number;\n }\n | {\n readonly code: 'managed-array-invalid-value';\n readonly component: string;\n readonly field: string;\n readonly fieldType: string;\n readonly actualValue: unknown;\n }\n // feat-20260714-bevy-style-system-sets M2 / w12 — structured cyclic-dependency\n // detail. `.detail.cycle` is the ordered cycle path array; consumers read\n // this instead of parsing the message string.\n | {\n readonly code: 'cyclic-dependency';\n readonly cycle: readonly string[];\n }\n | {\n readonly code: 'command-failed';\n readonly systemName: string;\n readonly schedule: string;\n readonly commandIndex: number;\n readonly commandKind: CommandKind;\n readonly cause: unknown;\n }\n | {\n readonly code: 'system-failed';\n readonly systemName: string;\n readonly schedule: string;\n readonly cause: unknown;\n readonly lastCommittedCommand: CommandCommitEvidence | null;\n };\n\n/**\n * Layer-3 error envelope routed through managed-storage callbacks. Callers\n * narrow `detail` through the source-owned `EcsErrorDetail` union.\n */\nexport interface ManagedArrayErrorEnvelope {\n readonly code: EcsErrorCode;\n readonly hint: string;\n readonly expected: string;\n readonly detail: unknown;\n}\n\nexport type CommandKind = 'spawn' | 'despawn' | 'addComponent' | 'removeComponent';\n\nexport interface CommandCommitEvidence {\n readonly index: number;\n readonly kind: CommandKind;\n}\n\n/** Expected command preflight failure, with the exact batch location. */\nexport class CommandFailedError extends Error {\n override readonly name = 'CommandFailedError';\n readonly code = 'command-failed' as const;\n readonly expected = 'all deferred commands pass preflight before commit';\n readonly hint =\n 'Inspect detail.cause, repair the command at detail.commandIndex, and run the World again.';\n override readonly cause: unknown;\n readonly detail: {\n readonly systemName: string;\n readonly schedule: string;\n readonly commandIndex: number;\n readonly commandKind: CommandKind;\n readonly cause: unknown;\n };\n\n constructor(\n systemName: string,\n schedule: string,\n commandIndex: number,\n commandKind: CommandKind,\n cause: unknown,\n ) {\n super(\n `Deferred command failed before commit in ${schedule}/${systemName} ` +\n `at command ${commandIndex} (${commandKind}).`,\n );\n this.cause = cause;\n this.detail = { systemName, schedule, commandIndex, commandKind, cause };\n }\n}\n\n/** Unknown system failure. The World is poisoned because row writes may exist. */\nexport class SystemFailedError extends Error {\n override readonly name = 'SystemFailedError';\n readonly code = 'system-failed' as const;\n readonly expected = 'a system completes without throwing or returning a failed Result';\n readonly hint =\n 'Inspect detail.cause, stop using this poisoned World, and rebuild it from the owning App.';\n override readonly cause: unknown;\n readonly detail: {\n readonly systemName: string;\n readonly schedule: string;\n readonly cause: unknown;\n readonly lastCommittedCommand: CommandCommitEvidence | null;\n };\n\n constructor(\n systemName: string,\n schedule: string,\n cause: unknown,\n lastCommittedCommand: CommandCommitEvidence | null = null,\n ) {\n super(`System ${schedule}/${systemName} failed; World is poisoned.`);\n this.cause = cause;\n this.detail = { systemName, schedule, cause, lastCommittedCommand };\n }\n}\n","// @forgeax/engine-ecs — Component schema + opaque token.\n//\n// `defineComponent(name, fields, options?)` returns a frozen token carrying\n// only the three runtime facts needed by callers:\n// - `.name`: component name string\n// - `.fields`: frozen field descriptors (the schema SSOT)\n// - `.storage`: table or sparse placement\n// Numeric identity, flat schema projections, and default maps live in the ECS\n// owner tables below rather than on the public token.\n//\n// ComponentId is used by archetype storage, bitmask matching, and edges cache.\n\nimport { err, type Handle, ok, type Result } from '@forgeax/engine-types';\nimport {\n assertComponentStorage,\n deepFreeze,\n registerComponentDefinition,\n} from './component-schema';\nimport type { EntityHandle } from './entity-handle';\nimport {\n ManagedArrayElementTypeNotAllowedError,\n SchemaUnsupportedFieldError,\n SparseStorageRequiresTagError,\n} from './errors';\nimport type { ManagedColumnReader } from './storage/column';\n\n// The internal package subpath reuses this owner module so the source budget\n// does not grow a second forwarding module. Root exports remain curated in\n// index.ts; this re-export is only reached through `@forgeax/engine-ecs/internal`.\nexport { componentDefinition } from './component-schema';\n\n// ────────────────────────────────────────────────────────────────────────────\n// Field types — schema vocab keywords (AC-01).\n//\n// Two-tier vocabulary:\n//\n// 1. Legacy scalar set: 11 keywords backed by TypedArray storage. Concrete\n// byte-sizes + TypedArray constructors are internal constants consumed by\n// `scalarRow()` to build TYPE_METADATA rows (see M4 §FIELD_SIZE_BYTES / VIEW_CTORS).\n//\n// 2. Schema-vocab keywords: 7 template-literal patterns expressing\n// ECS-managed types whose storage is owned by separate subsystems:\n// * `buffer:<bytes>` — fixed-byte managed Uint8Array, stored by BufferPool\n// * `ref<T>` — managed Handle<T,'unique'>, released by UniqueRefStore\n// * `shared<T>` — rc-tracked Handle<T,'shared'>, lifecycle owned by SharedRefStore\n// * `entity` — Entity reference (Entity | null)\n// * `string` — utf-8 string payload, allocated as a managed handle via UniqueRefStore\n// * `array<T,N>` — fixed-capacity typed view; elements inline in stride-N column (feat-20260602)\n// * `array<T>` — variable-capacity typed view over BufferPool slot bytes\n//\n// The retired `array<entity>` predecessor (closed out by this feat) is no\n// longer a valid schema field type — the union has narrowed it out.\n// ────────────────────────────────────────────────────────────────────────────\n\n/** Bytes per element for each scalar field type. */\nconst FIELD_SIZE_BYTES = {\n f32: 4,\n f64: 8,\n i32: 4,\n u32: 4,\n i16: 2,\n u16: 2,\n i8: 1,\n u8: 1,\n bool: 1,\n enum: 4,\n ref: 4,\n} as const;\n\n/** Numeric scalar field types backed by TypedArray storage (legacy tier). */\nexport type ScalarFieldType = keyof typeof FIELD_SIZE_BYTES;\n\n/**\n * Legal element-type whitelist for the `array<T,N>` / `array<T>` vocab\n * keywords (AC-03). T must be a scalar field type, `entity`, or a\n * `shared\\<X\\>` template with a non-empty tag; reference / buffer / nested\n * array element types are forbidden (OOS-08 / OOS-03).\n *\n * feat-20260614 M5 / w23: the historical `handle\\<X\\>` element family was\n * deleted in favor of `shared\\<X\\>` (rc-tracked, lifecycle owned by\n * SharedRefStore). The `MANAGED_ARRAY_ELEMENT_TYPES` Set remains\n * static-scalar + entity only (D-8); dynamic `shared\\<X\\>` templates are\n * validated by `isValidArrayElementType` at parse time.\n *\n * Legal: every member of `ScalarFieldType` plus `entity` plus\n * `shared\\<X\\>` (non-empty tag). The `ref` legacy scalar keyword (a u32\n * column placeholder) is in the whitelist; the parametric `unique<T>` /\n * `shared<T>` scalars are rejected as array element types by AC-03.\n */\nexport type ManagedArrayElementType = ScalarFieldType | 'entity' | `shared<${string}>`;\n\n/**\n * Schema-vocab keywords beyond the legacy scalar tier (AC-01).\n *\n * Each pattern is a template-literal type so a literal schema like\n * `{ mat: 'unique<MaterialAsset>' }` types the value as\n * `Handle<'MaterialAsset','unique'>` end-to-end. Runtime acceptance is\n * gated by the internal `isSchemaVocabKeyword` check — the SSOT for parser fail-fast.\n *\n * The legacy `'buffer:<N>'` literal is retired one-cut by\n * feat-20260515-buffer-array-vocab-collapse w4: replaced by the\n * angle-bracket generic shapes `'buffer'` (variable byte slot) and\n * `'buffer<N>'` (fixed byte slot). With `'array<T>'` / `'array<T, N>'` they\n * form a 4-keyword closed surface across two orthogonal axes (element-type\n * x capacity contract).\n */\nexport type SchemaVocabKeyword =\n | 'string'\n | 'buffer'\n | `buffer<${number}>`\n | `unique<${string}>`\n | `shared<${string}>`\n | 'entity'\n | `array<${ManagedArrayElementType}, ${number}>`\n | `array<${ManagedArrayElementType}>`;\n\n/**\n * Closed union of every keyword `defineComponent` accepts for a schema field.\n * Combines the legacy scalar tier with the schema-vocab tier.\n *\n * `ComponentSchema` is keyed against this union; `defineComponent` rejects\n * any field value not satisfying it (compile-time) or matching it\n * (runtime).\n */\nexport type SchemaFieldType = ScalarFieldType | SchemaVocabKeyword;\n\n/**\n * Producer-owned semantic shape tags for authoring/schema consumers.\n *\n * The ECS storage vocabulary remains the source of truth for bytes and\n * runtime values. These tags capture the semantic shape that storage alone\n * cannot express (for example an optional entity reference or a nested\n * unique payload). The tag is deliberately closed so downstream consumers\n * can exhaustively handle the representative field-shape vocabulary without\n * creating a second component registry.\n */\nexport type FieldShapeKind =\n | 'scalar'\n | 'boolean'\n | 'enum'\n | 'vector'\n | 'quaternion'\n | 'optional'\n | 'nested'\n | 'array'\n | 'asset-ref';\n\n/**\n * Normalize any field-type keyword to its TYPE_METADATA key.\n *\n * The 11 legacy scalars round-trip their own key. The 6 vocab families normalize\n * their parametric shapes to the family key:\n * - `unique<T>` / `shared<T>` — strip `<T>` → `'ref'` / `'shared'`\n * - `buffer<N>` — strip `<N>` → `'buffer'`\n * - `array<T>` / `array<T,N>` — strip `<...>` → `'array'`\n * - `entity` / `string` / `buffer` are identity.\n *\n * Returns `null` for an unrecognised keyword so callers can skip column\n * allocation (same semantics as the retired `storageFieldType`).\n */\nexport function fieldTypeToMetaKey(fieldType: string): string | null {\n if (fieldType === 'entity' || fieldType === 'string' || fieldType === 'buffer') {\n return fieldType;\n }\n if (fieldType.startsWith('unique<') && fieldType.endsWith('>')) return 'ref';\n if (fieldType.startsWith('shared<') && fieldType.endsWith('>')) return 'shared';\n if (fieldType.startsWith('buffer<') && fieldType.endsWith('>')) return 'buffer';\n if (fieldType.startsWith('array<') && fieldType.endsWith('>')) return 'array';\n // Legacy scalar — the 11 types are keys in TYPE_METADATA.\n if (TYPE_METADATA[fieldType] !== undefined) return fieldType;\n return null;\n}\n\n/**\n * `true` when the schema field type is a managed-store slot - i.e. should be\n * routed through `UniqueRefStore` (or `SharedRefStore` for `'shared<T>'`)\n * for alloc / resolve / release. Derived from TYPE_METADATA[].isManaged\n * column (feat-20260611-ecs-storage-naming-ssot D-3).\n *\n * Naming note (D-6 whitelist): `managed = ECS-tracked`. The prefix here is\n * about column-side lifecycle ownership (the ECS releases the slot on\n * despawn / overwrite), not the retired `'managed' | 'unmanaged'` Handle\n * brand. Both `'unique<T>'` and `'shared<T>'` schema fields satisfy\n * `isManagedField` because both are ECS-tracked; the dispatcher in\n * `releaseManagedFieldOnRow` picks the right store per field type.\n */\nexport function isManagedField(fieldType: string): boolean {\n return TYPE_METADATA[fieldTypeToMetaKey(fieldType) ?? '']?.isManaged ?? false;\n}\n\n/**\n * `true` when the schema field type is a managed-buffer slot - i.e. should be\n * released by the M2 BufferPool release loop. Derived from\n * TYPE_METADATA[].isBuffer column (feat-20260611-ecs-storage-naming-ssot D-3/D-4).\n *\n * D-4 semantic widening accepted: `buffer<abc>` resolves to metaKey 'buffer'\n * (isBuffer=true) while the old regex-based impl rejected the non-integer N.\n * This is a dead path — `defineComponent` rejects `buffer<abc>` via\n * `isSchemaVocabKeyword` before the predicate fires.\n *\n * Naming note (D-6 whitelist): `managed = ECS-tracked`. Same semantic as\n * `isManagedField` — the variable `'buffer'` keyword is one whose\n * BufferPool slot the ECS releases at despawn / overwrite time.\n */\nexport function isManagedBufferField(fieldType: string): boolean {\n return TYPE_METADATA[fieldTypeToMetaKey(fieldType) ?? '']?.isBuffer ?? false;\n}\n\n/**\n * `true` when the schema field type is the single-entity reference keyword\n * `'entity'`. Derived from TYPE_METADATA[].isEntityRef column\n * (feat-20260611-ecs-storage-naming-ssot D-3).\n */\nexport function isEntityField(fieldType: string): boolean {\n return TYPE_METADATA[fieldTypeToMetaKey(fieldType) ?? '']?.isEntityRef ?? false;\n}\n\n/**\n * `true` when the schema field type is an `array<T,N>` / `array<T>` vocab\n * keyword. Derived from TYPE_METADATA[].isArray column\n * (feat-20260611-ecs-storage-naming-ssot D-3).\n *\n * Naming note (D-6 whitelist): `managed = ECS-tracked`. Variable\n * `array<T>` storage routes through BufferPool (slot lifecycle owned by\n * the ECS); fixed `array<T,N>` is inline stride-N and has no separate\n * slot to release, but both share this predicate as they share the\n * `'array'` meta key.\n */\nexport function isManagedArrayField(fieldType: string): boolean {\n return TYPE_METADATA[fieldTypeToMetaKey(fieldType) ?? '']?.isArray ?? false;\n}\n\n/**\n * Set of legal element types for the `array<T,N>` / `array<T>` keywords\n * (AC-03). Runtime mirror of `ManagedArrayElementType`.\n *\n * Naming note (D-6 whitelist): `MANAGED_ARRAY_ELEMENT_TYPES` keeps the\n * `MANAGED` prefix because `managed = ECS-tracked` here — the Set is the\n * static-whitelist arm of `isValidArrayElementType`, which gates which\n * element types the ECS array dispatch knows how to retain / release.\n * The `'shared<X>'` template family rides the `startsWith('shared<')`\n * special case (D-8) rather than living in this Set.\n */\nexport const MANAGED_ARRAY_ELEMENT_TYPES: ReadonlySet<ManagedArrayElementType> =\n new Set<ManagedArrayElementType>([\n 'f32',\n 'f64',\n 'i32',\n 'u32',\n 'i16',\n 'u16',\n 'i8',\n 'u8',\n 'bool',\n 'enum',\n 'ref',\n 'entity',\n ]);\n\n/**\n * Return `true` when `elementType` is a legal array element type\n * (static-whitelist scalar | entity, or a `shared\\<X\\>` template with a\n * non-empty tag). The empty-tag form `shared\\<\\>` is rejected\n * (plan-strategy §2 D-1 / R-NEW-1).\n *\n * @internal\n */\nfunction isValidArrayElementType(elementType: string): elementType is ManagedArrayElementType {\n if (MANAGED_ARRAY_ELEMENT_TYPES.has(elementType as ManagedArrayElementType)) return true;\n // feat-20260614 D-8: `shared<X>` is a legal element-type via the\n // startsWith special case; `MANAGED_ARRAY_ELEMENT_TYPES` Set deliberately\n // does NOT carry a `'shared'` entry (D-8 keeps the static-whitelist Set\n // free of the new family; runtime validation through the special case\n // here pairs with the independent `'shared'` TYPE_METADATA row that\n // routes element retain/release semantics in M4).\n if (elementType.startsWith('shared<') && elementType.endsWith('>') && elementType.length > 9)\n return true;\n return false;\n}\n\n/**\n * Parse an `array<T,N>` / `array<T>` schema string into its element type and\n * optional fixed length. Returns `null` if the string is not a managed-array\n * keyword or its element type is not in the whitelist (AC-03 runtime\n * fail-safe).\n *\n * Examples:\n * parseManagedArraySchema('array<entity>') => { elementType: 'entity', length: undefined }\n * parseManagedArraySchema('array<f32, 16>') => { elementType: 'f32', length: 16 }\n * parseManagedArraySchema('array<shared<MaterialAsset>>') => { elementType: 'shared<MaterialAsset>', length: undefined }\n * parseManagedArraySchema('array<shared<>>') => null (empty tag rejection)\n * parseManagedArraySchema('array<unique<X>>') => null (illegal element)\n * parseManagedArraySchema('array<array<f32,4>>') => null (nested rejected)\n *\n * Naming note (D-6 whitelist): `parseManagedArraySchema` keeps the\n * `Managed` infix because `managed = ECS-tracked` — every legal output\n * shape this parser returns is one whose lifecycle the ECS knows how to\n * retain / release on overwrite, despawn, or archetype migration.\n */\nexport function parseManagedArraySchema(\n fieldType: string,\n): { readonly elementType: ManagedArrayElementType; readonly length: number | undefined } | null {\n if (!fieldType.startsWith('array<') || !fieldType.endsWith('>')) return null;\n const inner = fieldType.slice(6, -1);\n const commaIdx = inner.indexOf(',');\n if (commaIdx === -1) {\n // Variable-capacity: inner must be a bare element-type keyword or\n // handle<X> template.\n if (!isValidArrayElementType(inner)) return null;\n return { elementType: inner as ManagedArrayElementType, length: undefined };\n }\n // Fixed-capacity: split at first comma; element-type before, integer length\n // after. Reject any further '<' / ':' / ',' to keep the form unambiguous.\n const head = inner.slice(0, commaIdx).trim();\n const tail = inner.slice(commaIdx + 1).trim();\n if (!isValidArrayElementType(head)) return null;\n if (!/^[1-9]\\d*$/.test(tail)) return null;\n return { elementType: head as ManagedArrayElementType, length: Number.parseInt(tail, 10) };\n}\n\n/**\n * Parse the byte count out of a `buffer<N>` schema keyword. Returns NaN if\n * the input does not match the keyword pattern - callers that already gated\n * via `isManagedBufferField` get a guaranteed-positive integer for the\n * fixed-byte form. The bare `'buffer'` keyword (variable byte capacity)\n * returns NaN and callers must check `fieldType === 'buffer'` separately.\n */\nexport function bufferFieldByteLength(fieldType: string): number {\n if (!fieldType.startsWith('buffer<') || !fieldType.endsWith('>')) return Number.NaN;\n const tail = fieldType.slice(7, -1);\n if (!/^[1-9]\\d*$/.test(tail)) return Number.NaN;\n return Number.parseInt(tail, 10);\n}\n\n/**\n * Runtime check for a schema-vocab keyword (the tier-2 surface).\n *\n * Pure-function regex match — kept off the hot path; only invoked by\n * `defineComponent` once per field at registration time. The match patterns\n * are the runtime mirror of `SchemaVocabKeyword` template literals.\n *\n * - `'string'` is exact-match (bare literal, no `<>`).\n * - `'buffer'` is exact-match (variable-byte capacity).\n * - `buffer<N>` requires `N` to be a positive base-10 integer (`/^[1-9]\\d*$/`).\n * Forms like `buffer<abc>` / `buffer<0>` / `buffer<>` are rejected.\n * - `unique<T>` / `shared<T>` require a non-empty target tag (`/^\\w+$/`).\n * - `entity` is exact-match.\n * - `array<T,N>` / `array<T>` accept only the whitelist element types\n * (`MANAGED_ARRAY_ELEMENT_TYPES`); illegal inner types fall through and\n * the caller surfaces `managed-array-element-type-not-allowed`.\n */\nexport function isSchemaVocabKeyword(s: string): s is SchemaVocabKeyword {\n if (s === 'string') return true;\n if (s === 'entity') return true;\n if (s === 'buffer') return true;\n if (s.startsWith('buffer<') && s.endsWith('>')) {\n const tail = s.slice(7, -1);\n return /^[1-9]\\d*$/.test(tail);\n }\n if (s.startsWith('unique<') && s.endsWith('>')) {\n return /^\\w+$/.test(s.slice(7, -1));\n }\n if (s.startsWith('shared<') && s.endsWith('>')) {\n return /^\\w+$/.test(s.slice(7, -1));\n }\n if (s.startsWith('array<') && s.endsWith('>')) {\n return parseManagedArraySchema(s) !== null;\n }\n return false;\n}\n\n/**\n * JS value-shape per managed-array element type. `entity` maps to `Entity`\n * (branded number), every scalar maps to `number` (bool is stored as a 0/1\n * byte and read back as 0 or 1).\n */\nexport type ManagedArrayElementValue<T extends ManagedArrayElementType> = T extends 'entity'\n ? EntityHandle\n : number;\n\n/**\n * Maps each field-type keyword to the JS value type read/written by it.\n *\n * Tier-1 (legacy scalars) widens to `boolean | number`; tier-2 (schema-vocab)\n * resolves to the corresponding handle / entity / buffer / array / string\n * shape via the `infer T` template-literal extraction pattern. Conditional\n * types resolve top-down --- the `'string'` arm sits BEFORE the array<...> /\n * `buffer<N>` arms so the precise literal wins template-literal resolution\n * (R-P5: prevents `'string'` from being shadowed by a wider template-literal\n * pattern). The fixed-capacity `array<T,N>` arm matches before the\n * variable-capacity `array<T>` arm by the same rule.\n *\n * The 4 buffer/array keywords (`'buffer'` / `'buffer<N>'` / `'array<T>'` /\n * `'array<T, N>'`) all resolve directly to a concrete TypedArray (or\n * Uint8Array for the byte-only buffer family). At the public `world.get`\n * boundary, a relationship-target `array<entity>` is a detached `Uint32Array`\n * snapshot. Other public array fields retain their existing transient live\n * TypedArray alias: fixed `buffer<N>` / `array<T,N>` values alias the inline\n * column buffer (feat-20260602), while variable `buffer` / `array<T>` values\n * alias the BufferPool slot bytes. Internal `readRow`, `_getArrayView`, and\n * `materializeArrayView` paths always use the live zero-copy alias. Mutation\n * flows through `world.set` / `world.push` / `world.pop`, not direct\n * assignment to a returned TypedArray.\n *\n * The `'string'` arm resolves to a native JS `string` (D-R1 / AC-13): the\n * dispatch routes the column u32 through `UniqueRefStore.resolve(handle)`\n * which returns the immutable string payload by reference.\n */\nexport type FieldValueType<T extends SchemaFieldType> = T extends 'bool'\n ? boolean\n : T extends 'entity'\n ? EntityHandle | null\n : T extends 'string'\n ? string\n : T extends 'buffer'\n ? Uint8Array\n : T extends `buffer<${number}>`\n ? Uint8Array\n : T extends `array<shared<${infer Target}>, ${number}>`\n ? readonly Handle<Target, 'shared'>[]\n : T extends `array<shared<${infer Target}>>`\n ? readonly Handle<Target, 'shared'>[]\n : T extends `array<${infer Elem extends ManagedArrayElementType}, ${number}>`\n ? TypedArrayFor<Elem extends 'entity' ? 'u32' : Elem>\n : T extends `array<${infer Elem extends ManagedArrayElementType}>`\n ? TypedArrayFor<Elem extends 'entity' ? 'u32' : Elem>\n : T extends `unique<${infer Target}>`\n ? Handle<Target, 'unique'>\n : T extends `shared<${infer Target}>`\n ? Handle<Target, 'shared'>\n : T extends ScalarFieldType\n ? number\n : never;\n\n/**\n * Input-side counterpart of {@link FieldValueType} for write paths\n * (`world.spawn` / `world.addComponent` / `world.set`).\n *\n * Asymmetric on `array<scalar, N>` / `array<scalar>` ONLY: the read side\n * surfaces zero-copy `Float32Array` / `Uint32Array` / etc views; the write\n * side ALSO accepts `readonly number[]` because writeArrayField copies bytes\n * verbatim from either shape (TypedArray subarray() OR per-element pack via\n * DataView). Plain literals like `times: [0.5]` reach the same code path\n * with no Float32Array wrapper boilerplate at the call site, and short\n * prefixes pad the row tail with zero (writeArrayField D-3 contract).\n *\n * Asymmetric on `buffer` / `buffer<N>`: the read side returns `Uint8Array`,\n * but the write side accepts any `AllowSharedBufferSource` (Float32Array /\n * ArrayBuffer / Uint8Array / any TypedArray). The ECS buffer-write ingestion\n * point (`World.writeRow` / `World.set`) normalizes any view to `Uint8Array`\n * over its raw bytes before storing (feat-20260621 V2 / AC-A4). This lets AI\n * users write typed param payloads directly, e.g.\n * `world.set(e, PostProcessParams, { data: Float32Array.of(exposure,0,0,0) })`,\n * without manual byte-reinterpret boilerplate at the call site.\n *\n * Every other arm matches FieldValueType verbatim (no widening): handles\n * are already arrays-of-handle, scalars stay number, etc.\n */\nexport type FieldInputType<T extends SchemaFieldType> = T extends 'bool'\n ? boolean\n : T extends 'entity'\n ? EntityHandle | null\n : T extends 'string'\n ? string\n : T extends 'buffer'\n ? AllowSharedBufferSource\n : T extends `buffer<${number}>`\n ? AllowSharedBufferSource\n : T extends `array<shared<${infer Target}>, ${number}>`\n ? readonly Handle<Target, 'shared'>[]\n : T extends `array<shared<${infer Target}>>`\n ? readonly Handle<Target, 'shared'>[]\n : T extends `array<${infer Elem extends ManagedArrayElementType}, ${number}>`\n ? TypedArrayFor<Elem extends 'entity' ? 'u32' : Elem> | readonly number[]\n : T extends `array<${infer Elem extends ManagedArrayElementType}>`\n ? TypedArrayFor<Elem extends 'entity' ? 'u32' : Elem> | readonly number[]\n : T extends `unique<${infer Target}>`\n ? Handle<Target, 'unique'>\n : T extends `shared<${infer Target}>`\n ? Handle<Target, 'shared'>\n : T extends ScalarFieldType\n ? number\n : never;\n\n/**\n * Maps a SchemaFieldType to its zero-copy query-column view type.\n *\n * Three storage shapes share the keyword space:\n *\n * 1. Scalar / fixed-inline columns -- the column buffer is the data, written\n * in place. The bundle entry is a concrete writable TypedArray of the\n * correct ctor (`f32` -> `Float32Array`, `'buffer<N>'` -> `Uint8Array`,\n * `'array<T,N>'` -> the T-typed array). Direct index assignment is\n * fine -- the column owns the bytes.\n *\n * 2. `shared\\<X\\>` (rc-tracked AssetRegistry reference) -- the column carries\n * a u32 handle id; SharedRefStore owns the rc lifecycle. The bundle\n * entry is a `ManagedColumnReader<T>` (D-4 / D-7) -- read-only, walk\n * via `.get(i)`. Consumers route through `assets.get(handle)` to\n * materialise the asset payload.\n *\n * 3. The 4 managed-vocab keywords -- `'string'` / `` `ref<T>` `` / variable\n * `'buffer'` / variable `` `array<T>` `` -- the column carries a u32 slot\n * id; the payload lives in `UniqueRefStore` / `BufferPool`. The bundle\n * entry is a `ManagedColumnReader<T>` (D-4 / D-7) -- read-only by\n * construction, no index signature. Mutation MUST flow through the\n * public dispatch (`world.set` / `world.push` / `world.allocUniqueRef`).\n *\n * The `extends SchemaFieldType` upper bound matches `ComponentSchema[K]`\n * so query bundle types do not have to pre-filter.\n */\nexport type TypedArrayFor<T extends SchemaFieldType> = T extends 'f32'\n ? Float32Array\n : T extends 'f64'\n ? Float64Array\n : T extends 'i32'\n ? Int32Array\n : T extends 'u32' | 'enum' | 'ref' | 'entity'\n ? Uint32Array\n : T extends 'i16'\n ? Int16Array\n : T extends 'u16'\n ? Uint16Array\n : T extends 'i8'\n ? Int8Array\n : T extends 'u8' | 'bool'\n ? Uint8Array\n : T extends 'string'\n ? ManagedColumnReader<'string'>\n : T extends `unique<${string}>`\n ? ManagedColumnReader<T>\n : T extends `shared<${string}>`\n ? ManagedColumnReader<T>\n : T extends 'buffer'\n ? ManagedColumnReader<'buffer'>\n : T extends `buffer<${number}>`\n ? Uint8Array\n : T extends `array<${infer Elem extends ManagedArrayElementType}, ${number}>`\n ? TypedArrayFor<\n Elem extends 'entity' | `shared<${string}>` ? 'u32' : Elem\n >\n : T extends `array<${string}>`\n ? ManagedColumnReader<T>\n : never;\n\n/**\n * Relationship metadata (feat-20260531 M2 / plan-strategy D-5). Declares this\n * component as the holder side of a Bevy-style bidirectional relationship: the\n * holder carries a single `entity` field (the target), and the engine mirrors\n * the reverse reference into `mirror`.`field` (an `array<entity>` on the target\n * entity) at add / remove / despawn time.\n *\n * - `mirror` — the mirror component's string NAME (not a type reference, so\n * `engine-ecs` never imports the mirror component type; AC-29). The mirror\n * component is a derived runtime view rebuilt by the relationship owner, so\n * it MUST declare `transient: true` — otherwise scene collect serializes it\n * and `instantiateScene` double-writes (serialized copy + owner rebuild).\n * - `field` — the `array<entity>` field on the mirror component that holds the\n * reverse list. Validated to be exactly `'array<entity>'` at `defineComponent` time.\n * - `exclusive` — when `true`, re-adding the holder component with a new target\n * auto-reparents (clears the old mirror entry, then appends the new one)\n * instead of returning `ComponentAlreadyPresentError` (AC-12).\n * - `linkedSpawn` — when `true`, despawning the target recursively despawns the\n * holders in its mirror list. Default `false` (D-1): despawn only prunes the\n * mirror entry, the holder entity survives.\n */\n/** A schema is a record of field-name → field-type keyword. */\nexport type ComponentSchema = Record<string, SchemaFieldType>;\n\n/** Derive the JS value-shape from a schema (read side; zero-copy views). */\nexport type ShapeOf<S extends ComponentSchema> = {\n [K in keyof S]: FieldValueType<S[K]>;\n};\n\n/**\n * Derive the input-side value-shape from a schema (write side; widens\n * `array<scalar>` to also accept `readonly number[]` plus the strict\n * TypedArray view). Used by `world.spawn` / `world.addComponent` /\n * `world.set` `data` so AI users can write `times: [0.5]` instead of the\n * `new Float32Array([0.5])` boilerplate. writeArrayField walks both shapes\n * via the same byte-copy path so runtime semantics are identical.\n */\nexport type InputShapeOf<S extends ComponentSchema> = {\n [K in keyof S]: FieldInputType<S[K]>;\n};\n\n// ────────────────────────────────────────────────────────────────────────────\n// ComponentId\n// ────────────────────────────────────────────────────────────────────────────\n\n/**\n * Numeric identity is an ECS-owner fact, not component authoring data. Keep it\n * out of the token's own enumerable surface so reflection sees only\n * `name`/`fields`/`storage`.\n */\n/** Component owner identity shared by independently bundled ECS entry points. */\nconst COMPONENT_OWNER_REGISTRY = Symbol.for('forgeax.ecs.componentOwnerRegistry');\ninterface ComponentOwnerRegistry {\n nextId: number;\n readonly ids: WeakMap<object, ComponentId>;\n readonly schemas: WeakMap<object, Readonly<Record<string, SchemaFieldType>>>;\n}\nconst ownerSymbols = globalThis as typeof globalThis & { [key: symbol]: unknown };\nconst ownerRegistry =\n (ownerSymbols[COMPONENT_OWNER_REGISTRY] as ComponentOwnerRegistry | undefined) ??\n (() => {\n const registry: ComponentOwnerRegistry = {\n nextId: 1,\n ids: new WeakMap<object, ComponentId>(),\n schemas: new WeakMap<object, Readonly<Record<string, SchemaFieldType>>>(),\n };\n ownerSymbols[COMPONENT_OWNER_REGISTRY] = registry;\n return registry;\n })();\n\nlet entityDefinitionSeen = false;\nlet componentDefinedBeforeEntity = false;\n\n/** @internal Barrel-only check for the id=0 Entity import-order invariant. */\nexport function isComponentDefinitionOrderValid(): boolean {\n return !componentDefinedBeforeEntity;\n}\n\n/** @internal Read the owner-assigned identity for storage/archetype code. */\nexport function componentId(component: Component): ComponentId {\n const id = ownerRegistry.ids.get(component);\n if (id === undefined) throw new Error(`Component identity missing for '${component.name}'.`);\n return id;\n}\n\n/** @internal Derive the flat type map from the fields SSOT. */\nexport function componentSchema<const C extends Component>(component: C): Readonly<SchemaOf<C>> {\n const schema = ownerRegistry.schemas.get(component);\n if (schema === undefined) throw new Error(`Component schema missing for '${component.name}'.`);\n return schema as Readonly<SchemaOf<C>>;\n}\n\n/** Numeric identifier for a component type, used by bitmask matching and archetype edges. */\nexport type ComponentId = number;\nexport type ComponentStorage = 'table' | 'sparse';\n\n// ────────────────────────────────────────────────────────────────────────────\n// Token\n// ────────────────────────────────────────────────────────────────────────────\n\ndeclare const __componentBrand: unique symbol;\n\n/**\n * Opaque component token. Carries the component name `N` as a string-literal\n * type parameter (lifted from the `defineComponent` call site via `<const N>`)\n * and the schema-shape `S` as a phantom brand so `world.get(e, Comp)` can\n * return `Result<ShapeOf<S>, EcsError>` precisely.\n *\n * The `N` parameter defaults to `string` to keep existing single-parameter\n * `Component<S>` annotations source-compatible. When inferred from a\n * `defineComponent('Position', ...)` call, `N` is the literal `'Position'`,\n * which lets query row/span mapped types resolve `{ [K in N]: ... }` to a\n * concrete keyed object instead of a degraded index signature (KD-1).\n */\nexport interface Component<N extends string = string, S extends ComponentSchema = ComponentSchema> {\n readonly name: N;\n /** The one schema projection: type, default, and enum labels per field. */\n readonly fields: Readonly<Record<keyof S & string, FieldReflection>>;\n readonly storage: ComponentStorage;\n readonly [__componentBrand]: ShapeOf<S>;\n}\n\n// ────────────────────────────────────────────────────────────────────────────\n// TypedArray constructors — internal; consumed by `scalarRow()` to build\n// TYPE_METADATA rows (feat-20260602 M4, w12).\n// ────────────────────────────────────────────────────────────────────────────\n\n/** TypedArray constructor for each scalar field type. */\nconst VIEW_CTORS: Readonly<\n Record<\n ScalarFieldType,\n | Float32ArrayConstructor\n | Float64ArrayConstructor\n | Int32ArrayConstructor\n | Uint32ArrayConstructor\n | Int16ArrayConstructor\n | Uint16ArrayConstructor\n | Int8ArrayConstructor\n | Uint8ArrayConstructor\n >\n> = {\n f32: Float32Array,\n f64: Float64Array,\n i32: Int32Array,\n u32: Uint32Array,\n i16: Int16Array,\n u16: Uint16Array,\n i8: Int8Array,\n u8: Uint8Array,\n bool: Uint8Array,\n enum: Uint32Array,\n ref: Uint32Array,\n};\n\n// ────────────────────────────────────────────────────────────────────────────\n// TYPE_METADATA — global per-type metadata table (feat-20260602 M1 / D-A6)\n//\n// Converges the 12 scattered type-intrinsic structures (3 tables + 9\n// predicate / tool functions) into a single per-type authoritative table.\n// Exports FIELD_SIZE_BYTES / VIEW_CTORS / isSchemaVocabKeyword /\n// managedArrayElementBytes / SUPPORTED_FIELD_TYPES / storageFieldType were\n// deleted M4 (w12); internal FIELD_SIZE_BYTES + VIEW_CTORS constants remain as\n// build inputs for scalarRow(). All former consumers now read TYPE_METADATA:\n// storage routing via fieldTypeToMetaKey() + TYPE_METADATA[key].storage,\n// scalar checks via TYPE_METADATA[key]?.isScalar.\n//\n// Mixed key granularity (D-5): the 11 scalars are keyed by their concrete\n// type (`f32` ... `ref`); the 6 vocab families are keyed by family (`entity`\n// / `string` / `buffer` / `ref` / `handle` / `array`). The `array` row's T/N\n// parameters are NOT table columns — they are parsed per-field into\n// `arrayMeta` (see FieldDescriptor below). The vocab `ref` family row and\n// the scalar `ref` row share the `'ref'` key intentionally: the scalar is a\n// u32 column placeholder and the vocab `ref<T>` form maps to the same\n// managed-ref storage, so one row carries both (isScalar + isManaged both\n// true). tweak-20260612-ecs-concept-compression dropped redundant columns:\n// `isVocabKeyword` (zero production consumers), the per-vocab managed-\n// ref predicate column (100% duplicate of `isManaged`), and the YAGNI\n// `fixedByteLength` placeholder;\n// `isLegacyScalar` was renamed `isScalar` (the \"legacy\" prefix labelled the\n// historical M2-introduction tense; the 11 scalars are first-class).\n// ────────────────────────────────────────────────────────────────────────────\n\n/**\n * One row of the global type-metadata table. Carries the type-intrinsic\n * properties a field type has regardless of which component declares it.\n *\n * - `byteSize` — element byte width for the column-storage scalar; `undefined`\n * for families whose storage byte size is not a fixed per-type constant\n * (variable buffer / array slot ids are u32-stored, surfaced via `storage`).\n * - `viewCtor` — TypedArray constructor for the column storage; `undefined`\n * for families without a direct TypedArray column.\n * - `storage` — the column-storage scalar type this field routes to (every\n * vocab family stores a u32 slot id / handle).\n * - `isScalar` — member of the 11 concrete scalar types\n * (`f32`/`f64`/`i32`/`u32`/`i16`/`u16`/`i8`/`u8`/`bool`/`enum`/`ref`).\n * - `isManaged` — routed through `UniqueRefStore` (string / ref<T>).\n * - `isBuffer` — a `buffer` / `buffer<N>` managed-byte slot.\n * - `isEntityRef` — the single-entity `entity` reference keyword.\n * - `isArray` — an `array<T>` / `array<T,N>` keyword.\n */\nexport interface TypeMetadataRow {\n readonly byteSize: number | undefined;\n readonly viewCtor:\n | Float32ArrayConstructor\n | Float64ArrayConstructor\n | Int32ArrayConstructor\n | Uint32ArrayConstructor\n | Int16ArrayConstructor\n | Uint16ArrayConstructor\n | Int8ArrayConstructor\n | Uint8ArrayConstructor\n | undefined;\n readonly storage: ScalarFieldType;\n readonly isScalar: boolean;\n readonly isManaged: boolean;\n readonly isBuffer: boolean;\n readonly isEntityRef: boolean;\n readonly isArray: boolean;\n}\n\n/** Build a scalar row from the concrete scalar type. */\nfunction scalarRow(t: ScalarFieldType): TypeMetadataRow {\n return {\n byteSize: FIELD_SIZE_BYTES[t],\n viewCtor: VIEW_CTORS[t],\n storage: t,\n isScalar: true,\n // The scalar `ref` shares its key with the vocab `ref<T>` family; mark\n // it as managed so the single row covers both.\n isManaged: t === 'ref',\n isBuffer: false,\n isEntityRef: false,\n isArray: false,\n };\n}\n\n/**\n * Global per-type metadata table. Keyed by concrete scalar type (11) plus\n * vocab family (6 — `entity` / `string` / `buffer` / `ref` / `handle` /\n * `array`). The `ref` key is shared by the legacy scalar and the vocab family\n * (see header). Every vocab family stores a u32 slot id / handle.\n *\n * Built once at module load; frozen so downstream consumers (column.ts /\n * archetype.ts / world.ts, migrated M2) read a stable single source.\n */\nexport const TYPE_METADATA: Readonly<Record<string, TypeMetadataRow>> = Object.freeze({\n f32: scalarRow('f32'),\n f64: scalarRow('f64'),\n i32: scalarRow('i32'),\n u32: scalarRow('u32'),\n i16: scalarRow('i16'),\n u16: scalarRow('u16'),\n i8: scalarRow('i8'),\n u8: scalarRow('u8'),\n bool: scalarRow('bool'),\n enum: scalarRow('enum'),\n ref: scalarRow('ref'),\n entity: {\n byteSize: 4,\n viewCtor: Uint32Array,\n storage: 'u32',\n isScalar: false,\n isManaged: false,\n isBuffer: false,\n isEntityRef: true,\n isArray: false,\n },\n string: {\n byteSize: 4,\n viewCtor: Uint32Array,\n storage: 'u32',\n isScalar: false,\n isManaged: true,\n isBuffer: false,\n isEntityRef: false,\n isArray: false,\n },\n buffer: {\n byteSize: 4,\n viewCtor: Uint32Array,\n storage: 'u32',\n isScalar: false,\n isManaged: false,\n isBuffer: true,\n isEntityRef: false,\n isArray: false,\n },\n // feat-20260614-ecs-shared-component-and-unique-rename M3 (plan-strategy\n // D-3): independent `'shared'` row, NOT a reuse of the `'ref'` (post-M2:\n // `'unique<T>'` family) row. `isManaged: true` so write-barrier dispatch\n // routes shared<T> fields through release on despawn / removeComponent /\n // set-overwrite, but the M4 sub-dispatch in releaseManagedFieldOnRow will\n // separate shared (rc--) from unique (direct slot drop) using the\n // fieldType.startsWith('shared<') predicate. Keeping the meta key\n // independent preserves the \"meta key = release semantics\" invariant\n // (architecture-principles.md #1 SSOT).\n shared: {\n byteSize: 4,\n viewCtor: Uint32Array,\n storage: 'u32',\n isScalar: false,\n isManaged: true,\n isBuffer: false,\n isEntityRef: false,\n isArray: false,\n },\n array: {\n byteSize: 4,\n viewCtor: Uint32Array,\n storage: 'u32',\n isScalar: false,\n isManaged: false,\n isBuffer: false,\n isEntityRef: false,\n isArray: true,\n },\n});\n\n// ────────────────────────────────────────────────────────────────────────────\n// FieldDescriptor — input field-descriptor object + per-field reflection\n// (feat-20260602 M1 / D-A1 / D-A3)\n// ────────────────────────────────────────────────────────────────────────────\n\n/**\n * Pre-parsed `array<T>` / `array<T,N>` reflection. Bare length sentinel\n * (D-A1 user ruling): `length` present => fixed-capacity, `length === undefined`\n * => variable-capacity. No `isVariable` / `kind` field — both are losslessly\n * derivable from `length` presence (architecture-principles.md #2 Derive). This\n * is exactly the existing `parseManagedArraySchema` return shape (zero shape\n * change).\n */\nexport interface ArrayMeta {\n readonly elementType: ManagedArrayElementType;\n readonly length?: number;\n}\n\n/**\n * Input field-descriptor object (D-A3). The second `defineComponent` argument\n * may declare each field either as a bare type keyword (legacy flat form,\n * still accepted through M2; migrated repo-wide in M3) or as a descriptor\n * object aggregating `type` + `default` + semantic `shape` + field-level\n * `meta`.\n *\n * - `type` — the schema field-type keyword (a parametrized string such as\n * `'array<f32,3>'` / `'unique<MaterialAsset>'` is used verbatim, D-A2).\n * - `default` — layer-2 default value; retained in the field reflection row.\n * - `shape` — producer-owned semantic shape tag for schema consumers; it does\n * not change ECS storage or runtime value semantics.\n * - `meta` — field-level open namespace; aggregated into `component.meta`. The\n * infra gives no key special meaning (open map, OOS-1).\n * - `transient` — when `true`, scene collect skips this field (D-5). Same word,\n * same meaning as the component-level `transient` flag, with granularity sunk\n * to the field level: a field that is derived/reconstructable (e.g. a resolved\n * world mat4) is excluded from serialization while its component's persisted\n * fields still round-trip. Absent (the common case) means the field is\n * serialized.\n * - `labels` — for an `enum` field ONLY: the label→numeric-value map (e.g.\n * `{ static: 0, dynamic: 1, kinematic: 2 }`). An `enum` field stores a bare\n * `u32` variant index; the human-readable names historically lived in a\n * SEPARATE per-package const map (`RigidBodyTypeValue`) + comment table, so no\n * schema consumer could read them and the two could drift. Declaring `labels`\n * attaches that map to the field itself (SSOT-adjacent): it is aggregated into\n * `component.fields[field].labels` and surfaced by reflection consumers (the\n * editor's `describeComponent`, inspector UIs, validation hints) so a\n * docs-only user learns the legal variants + their integers from the schema\n * alone. Pass the EXISTING `*Value` const map here (Derive, don't Duplicate —\n * one object, two consumers). Absent for non-enum fields / enums that opt out.\n */\nexport interface FieldDescriptor<T extends SchemaFieldType = SchemaFieldType> {\n readonly type: T;\n readonly default?: FieldValueType<T>;\n /** Semantic authoring shape; storage still follows `type`. */\n readonly shape?: FieldShapeKind;\n readonly meta?: Readonly<Record<string, unknown>>;\n readonly transient?: boolean;\n readonly labels?: Readonly<Record<string, number>>;\n}\n\n/**\n * Per-field reflection produced at registration time and read off\n * `component.fields[fieldName]` (D-A3). Carries the pre-parsed facts: the\n * field `type`, its `default` (if any), semantic `shape` (if declared), — for\n * `array<...>` fields only — the pre-parsed `arrayMeta` (parse happens once at\n * registration, AC-03c), and the field-level `transient` flag (D-5) when\n * declared.\n *\n * `transient` mirrors the component-level `Component.transient` (same word,\n * same meaning): scene collect skips a `transient` field just as it skips a\n * `transient` component. Granularity is sunk to the field level so a component\n * can persist most of its fields while excluding a derived/reconstructable one\n * (e.g. `GlobalTransform.world`). Absent means the field participates in\n * serialization.\n */\nexport interface FieldReflection {\n readonly type: SchemaFieldType;\n readonly default?: unknown;\n /** Producer-declared semantic shape, when storage type alone is insufficient. */\n readonly shape?: FieldShapeKind;\n readonly arrayMeta?: ArrayMeta;\n readonly transient?: boolean;\n /**\n * For an `enum` field: the label→numeric-value map declared on the field\n * descriptor (see `FieldDescriptor.labels`). Lets a schema consumer resolve a\n * variant name ↔ its stored `u32` index without a separate const map. Absent\n * for non-enum fields / enums that did not declare labels.\n */\n readonly labels?: Readonly<Record<string, number>>;\n}\n\n/**\n * One input field-spec value: either the bare type keyword (legacy flat form)\n * or a field-descriptor object. Accepting both keeps the ~44 flat-string\n * call-sites + ~55 test files green through M1/M2 while the field-descriptor\n * form is migrated in repo-wide in M3 (D-A7 / D-A8 shrink the migration\n * surface to the input side only).\n */\nexport type FieldSpec<T extends SchemaFieldType = SchemaFieldType> = T | FieldDescriptor<T>;\n\n/** An input field-spec map: field-name -> bare keyword | field-descriptor. */\nexport type FieldsInput = Record<string, FieldSpec>;\n\n/**\n * Project an input field-spec map down to its flat `ComponentSchema` shape\n * (field-name -> type keyword). A bare-keyword spec maps to itself (identity,\n * so existing flat-string call-sites infer exactly as before); a descriptor\n * spec maps to its `type`. This keeps `Component<N, SchemaOf<F>>` driving every\n * downstream type (ShapeOf / query row/span projection / TypedArrayFor) unchanged.\n */\nexport type SchemaOf<F extends FieldsInput | Component> =\n F extends Component<string, infer S>\n ? S\n : F extends FieldsInput\n ? {\n [K in keyof F]: F[K] extends FieldDescriptor<infer T>\n ? T\n : F[K] extends SchemaFieldType\n ? F[K]\n : never;\n }\n : never;\n\n// ────────────────────────────────────────────────────────────────────────────\n// defineComponent\n// ────────────────────────────────────────────────────────────────────────────\n\n/** Optional configuration for `defineComponent` (w4, M3 consumer; w21 layer-2 defaults). */\nexport interface DefineComponentOptions {\n readonly storage?: ComponentStorage;\n /**\n * When `true`, the component is skipped by scene collect\n * (rootsToSceneAsset). The component stays in archetype columns and\n * participates normally in queries / world.get at runtime.\n *\n * Default: `false`. Mirror targets of relationship components should\n * declare `transient: true` so they are not serialized (their state is\n * rebuilt by the mirror hook after instantiateScene).\n */\n readonly transient?: boolean;\n /**\n * Components materialized automatically when this component is added.\n * Explicit data for a required component wins; the ECS appends only missing\n * identities at the spawn/add boundary, never from a frame system.\n */\n readonly requires?: readonly Component[];\n /**\n * Component-level open metadata namespace. Entries are copied into\n * `Component.meta` at registration; the ECS core assigns no meaning to any\n * key. Component-level entries win over field-level entries with the same\n * key, and consumers may extend the mutable map after registration.\n */\n readonly meta?: Readonly<Record<string, unknown>>;\n}\n\n/**\n * Extract the bare field-type keyword from a field-spec (bare keyword | field-\n * descriptor object), fail-fast if a descriptor object is missing its `type`.\n * The throw carries the field name + expected shape (charter P3 / OOS-6: this\n * is a programmer error caught at registration time, no new EcsErrorCode).\n */\nfunction fieldSpecType(fieldName: string, spec: FieldSpec): SchemaFieldType {\n if (typeof spec === 'string') return spec as SchemaFieldType;\n const t = (spec as FieldDescriptor).type;\n if (typeof t !== 'string') {\n throw new SchemaUnsupportedFieldError(\n fieldName,\n `<field-descriptor missing 'type'> (expected { type, default?, meta? })`,\n );\n }\n return t as SchemaFieldType;\n}\n\n/**\n * Define a component. Returns a frozen opaque token with exactly three runtime\n * facts: `.name`, `.fields`, and `.storage`. Numeric identity, flat schema,\n * and defaults are owner projections held outside the token.\n *\n * The second argument accepts each field either as a bare type keyword\n * ('f32', 'array<entity>', ...) or as a field-descriptor object\n * `{ type, default?, meta? }` (D-A3). The single `FieldsInput` overload\n * handles both forms — bare keywords are identity through `SchemaOf<F>`.\n *\n * The `<const N>` modifier lifts `name` to its string-literal type so the\n * returned `Component<N, SchemaOf<S>>` drives precise key-based mapped types\n * downstream (for example QueryRow and QuerySpan projections). At runtime `name` is a plain\n * string.\n *\n * Schema-field validation accepts both the legacy scalar tier\n * (`ScalarFieldType`, 11 keywords) and the schema-vocab tier\n * (`SchemaVocabKeyword`, 8 patterns including `array<T,N>` / `array<T>` /\n * `buffer` / `buffer<N>`). Mismatched values raise\n * `SchemaUnsupportedFieldError`. Illegal `array<...>` element types\n * (e.g. `array<ref<X>>`) raise `ManagedArrayElementTypeNotAllowedError`\n * (AC-03 runtime fail-safe).\n *\n * Relationship roles are declared through `defineRelationship`; component\n * definitions contain only schema vocabulary and no mirror metadata.\n *\n * @throws SchemaUnsupportedFieldError for any field type not in the supported\n * set, or a field-descriptor object missing its `type`.\n * @throws ManagedArrayElementTypeNotAllowedError when an `array<...>`\n * keyword carries an illegal element type.\n * @throws RelationshipMirrorComponentNotRegisteredError when\n * `relationship.mirror` names a component not yet defined.\n * @throws RelationshipMirrorFieldTypeMismatchError when the mirror's\n * `relationship.field` is missing or not typed `'array<entity>'`.\n */\n// Single signature post-M4 (w12) — bare-keyword field specs are valid\n// FieldSpec<T> values (identity through SchemaOf<F>), so flat-string schemas\n// work without a separate overload. tweak-20260612-ecs-concept-compression\n// dropped the redundant byte-identical overload declaration.\nexport function defineComponent<const N extends string, const S extends FieldsInput>(\n name: N,\n fields: S,\n options?: DefineComponentOptions,\n): Component<N, SchemaOf<S>> {\n const storage = options?.storage ?? 'table';\n assertComponentStorage(storage);\n if (storage === 'sparse' && Object.keys(fields).length !== 0) {\n throw new SparseStorageRequiresTagError(name);\n }\n const schema: Record<string, SchemaFieldType> = {};\n const reflectedFields: Record<string, FieldReflection> = {};\n const collectedMeta: Record<string, unknown> = {};\n const collectedDefaults: Record<string, unknown> = {};\n\n for (const fieldName of Object.keys(fields)) {\n const spec = fields[fieldName] as FieldSpec;\n const fieldType = fieldSpecType(fieldName, spec);\n\n // Validate the field type — same fail-fast as before, now over the\n // normalized keyword.\n let arrayMeta: ArrayMeta | undefined;\n if (TYPE_METADATA[fieldType]?.isScalar === true) {\n // legacy scalar — ok\n } else if (fieldType === 'string') {\n // string vocab — ok\n } else if (fieldType.startsWith('array<') && fieldType.endsWith('>')) {\n const parsed = parseManagedArraySchema(fieldType);\n if (parsed === null) {\n const elementType = fieldType.slice(6, -1);\n throw new ManagedArrayElementTypeNotAllowedError(fieldName, elementType);\n }\n // Pre-parse once at registration (AC-03c): array fields cache arrayMeta.\n // Bare length sentinel {elementType, length?} (D-A1): drop `length` when\n // variable so the row is byte-identical to the parse return shape.\n arrayMeta = deepFreeze(\n parsed.length === undefined\n ? { elementType: parsed.elementType }\n : { elementType: parsed.elementType, length: parsed.length },\n );\n } else if (!isSchemaVocabKeyword(fieldType)) {\n throw new SchemaUnsupportedFieldError(fieldName, fieldType);\n }\n\n schema[fieldName] = fieldType;\n\n // Per-field reflection row — only attach arrayMeta / default when present\n // (exactOptionalPropertyTypes: never set an explicit `undefined`).\n const row: {\n type: string;\n default?: unknown;\n shape?: FieldShapeKind;\n arrayMeta?: ArrayMeta;\n transient?: boolean;\n labels?: Readonly<Record<string, number>>;\n } = {\n type: fieldType,\n };\n if (typeof spec !== 'string') {\n const desc = spec as FieldDescriptor;\n if ('default' in desc) {\n row.default = desc.default;\n collectedDefaults[fieldName] = desc.default;\n }\n if (desc.shape !== undefined) row.shape = desc.shape;\n if (desc.meta !== undefined) {\n Object.assign(collectedMeta, desc.meta);\n }\n // exactOptionalPropertyTypes: only attach `transient` when declared.\n if (desc.transient !== undefined) row.transient = desc.transient;\n // enum label→value map (see FieldDescriptor.labels). Frozen so the\n // reflected row exposes a stable read-only map. Only enum fields declare it.\n if (desc.labels !== undefined) row.labels = deepFreeze({ ...desc.labels });\n }\n if (arrayMeta !== undefined) row.arrayMeta = arrayMeta;\n reflectedFields[fieldName] = Object.freeze(row) as FieldReflection;\n }\n\n if (name === 'Entity') {\n entityDefinitionSeen = true;\n } else if (!entityDefinitionSeen) {\n componentDefinedBeforeEntity = true;\n }\n const id = name === 'Entity' ? 0 : ownerRegistry.nextId++;\n\n // Derived defaults projection (D-A8): pure from `fields[k].default`.\n // No longer merged with a removed `options.defaults` input — strict single-entry\n // means the only way to set a layer-2 default is through the field descriptor.\n const frozenDefaults =\n Object.keys(collectedDefaults).length === 0\n ? undefined\n : (deepFreeze(collectedDefaults) as Readonly<Partial<ShapeOf<SchemaOf<S>>>>);\n\n // Keep the component token immutable while leaving its open metadata map\n // extensible for higher-level consumers after registration.\n if (options?.meta !== undefined) {\n Object.assign(collectedMeta, options.meta);\n }\n const frozenSchema = deepFreeze(schema);\n const frozenFields = deepFreeze(reflectedFields);\n const meta = collectedMeta;\n const token = Object.freeze({ name, fields: frozenFields, storage }) as Component<N, SchemaOf<S>>;\n ownerRegistry.ids.set(token, id);\n ownerRegistry.schemas.set(token, frozenSchema);\n registerComponentDefinition(token, {\n fields: frozenFields,\n defaults: frozenDefaults,\n policy: {\n transient: options?.transient ?? false,\n meta,\n requires: Object.freeze([...(options?.requires ?? [])]),\n },\n });\n return Object.freeze(token);\n}\n\nexport class ComponentInUseError extends Error {\n override readonly name = 'ComponentInUseError';\n readonly code = 'component-in-use' as const;\n readonly expected = 'the component to have no live entity or scheduled-system references';\n readonly hint =\n 'Remove owning systems and component values before disposing the registration lease.';\n readonly detail: { readonly componentName: string };\n\n constructor(componentName: string) {\n super(`Component ${componentName} is still in use.`);\n this.detail = { componentName };\n }\n}\n\nexport class ComponentNameConflictError extends Error {\n override readonly name = 'ComponentNameConflictError';\n readonly code = 'component-name-conflict' as const;\n readonly expected = 'one component token per name in a World';\n readonly hint =\n 'Use the token already registered in this World or choose a distinct component name.';\n readonly detail: { readonly componentName: string };\n\n constructor(componentName: string) {\n super(`Component ${componentName} is already registered with a different token.`);\n this.detail = { componentName };\n }\n}\n\nexport type ComponentCatalogError = ComponentInUseError | ComponentNameConflictError;\n\nexport interface ComponentLease {\n readonly component: Component;\n dispose(): Result<void, ComponentInUseError>;\n}\n\ninterface ComponentRegistration {\n readonly component: Component;\n owners: number;\n}\n\n/** World-local discovery and ownership boundary for plugin-installed component vocabulary. */\nexport class ComponentCatalog {\n private readonly registrations = new Map<string, ComponentRegistration>();\n\n constructor(private readonly inUse: (component: Component) => boolean) {}\n\n register(component: Component): Result<ComponentLease, ComponentNameConflictError> {\n const current = this.registrations.get(component.name);\n if (current !== undefined && current.component !== component) {\n return err(new ComponentNameConflictError(component.name));\n }\n if (current === undefined) {\n this.registrations.set(component.name, { component, owners: 1 });\n } else {\n current.owners += 1;\n }\n\n let active = true;\n return ok({\n component,\n dispose: () => {\n if (!active) return ok(undefined);\n const registration = this.registrations.get(component.name);\n if (registration === undefined || registration.component !== component) {\n active = false;\n return ok(undefined);\n }\n if (registration.owners > 1) {\n registration.owners -= 1;\n active = false;\n return ok(undefined);\n }\n if (this.inUse(component)) return err(new ComponentInUseError(component.name));\n this.registrations.delete(component.name);\n active = false;\n return ok(undefined);\n },\n });\n }\n\n resolve(name: string): Component | undefined {\n return this.registrations.get(name)?.component;\n }\n\n entries(): ReadonlyMap<string, Component> {\n return new Map(\n [...this.registrations].map(([name, registration]) => [name, registration.component]),\n );\n }\n}\n","// @forgeax/engine-ecs - Entity component (feat-20260602-archetype-stores-full-packed-entity M1 / w1).\n//\n// Entity identity is modelled as a real id=0 ECS component `Entity`, whose sole\n// field `self` stores the full 32-bit packed entity handle (generation << 24 |\n// index). Every archetype carries this column unconditionally (it is essential\n// and cannot be removed), so an entity's own handle is read through the exact\n// same query / read path as Transform / MeshRenderer columns:\n//\n// const query = world.query({ read: [Transform] }).unwrap();\n// for (const row of query) row.entity;\n// world.get(e, Entity).unwrap().self === e\n//\n// This retires the \"entity is an archetype side-array + three-step rebuild\"\n// implementation detail (index slot -> generation lookup -> encodeEntity) in\n// favour of a single uniform column read.\n//\n// id=0 structural guarantee: `Entity` MUST be the first `defineComponent`\n// evaluated in the process so the owner identity assigns it 0. The package\n// barrel (packages/ecs/src/index.ts) force-evaluates this module before any\n// other component-defining module and asserts the invariant fail-fast.\n// See plan-strategy D-1 / D-6b (LP-1): the hard-coded 0 + barrel forced\n// registration + startup throw is the locked design; no UECS-style runtime\n// token lookup is introduced (the hot-path archetype column key stays a numeric\n// owner-assigned component identity).\n//\n// charter mapping: P4 (consistent abstraction -- reading the entity handle is\n// reading any other column) + P3 (id=0 drift surfaces as a structured startup\n// throw, never a silent runtime mis-id) + P1 (single top-level import surface).\n\nimport type { ComponentId } from './component';\nimport { componentId, defineComponent } from './component';\n\n/**\n * The id=0 essential `Entity` component. Its single `self` field carries the\n * full packed entity handle for the row it sits on (written at spawn time).\n *\n * Naming convention (feat-20260611-ecs-storage-naming-ssot):\n *\n * - Value-space `Entity` (this const) is the id=0 component token. It is\n * looked up by name (`'Entity'`) at component-registration time and used\n * as a value (`world.spawn`, `world.get(entity, Entity)`).\n * - Type-space `EntityHandle` (the branded number, exported from `../entity`)\n * is the row-identifier handle type. It is used in `: EntityHandle`\n * annotations.\n *\n * The two no longer share a name -- the prior intentional coexistence (a\n * single `Entity` symbol carrying both meanings via TS namespace merging) was\n * dropped because two-roles-one-name created repeated AI-user confusion when\n * reading `: Entity` annotations (is this the handle or the token?). The id=0\n * component token's name (the literal string `'Entity'`) is preserved for\n * runtime stability; only the type-space alias was renamed.\n *\n * @example Read an entity's own handle through a query:\n * const query = world.query({ read: [Transform] }).unwrap();\n * for (const row of query) {\n * const handle = row.entity;\n * }\n *\n * @example Use `world.get` as a general liveness probe:\n * const r = world.get(e, Entity);\n * if (!r.ok) { // r.error.code === 'stale-entity' for a despawned handle\n * }\n */\nexport const Entity = defineComponent('Entity', {\n // Layer-2 default is never observed: `world.spawn` always overwrites `self`\n // with the freshly encoded handle for the row. `null` is the type-correct\n // \"no handle yet\" placeholder (`'entity'` decodes to `EntityHandle | null`).\n self: { type: 'entity', default: null },\n});\n\n/**\n * Marks an entity as disabled.\n *\n * Queries exclude this tag by default. Add `Disabled` to a query's `with`\n * tuple when the query must inspect or re-enable disabled entities.\n */\nexport const Disabled = defineComponent('Disabled', {});\n\n/**\n * SSOT for component ids that are essential to every archetype. Every archetype\n * carries the columns named by these ids unconditionally (they cannot be added\n * or removed via `addComponent` / `removeComponent`). Currently only `Entity`\n * is essential -- the row-identity column that lets every entity read its own\n * packed handle (`world.get(e, Entity).self === e`) through the same column\n * path as any other component (feat-20260602 / charter P4).\n *\n * Frozen so consumers cannot mutate the SSOT. The barrel\n * (`packages/ecs/src/index.ts`) re-exports this constant so the AI-facing\n * `import { ESSENTIAL_COMPONENT_IDS } from '@forgeax/engine-ecs'` works.\n *\n * Physical location is `packages/ecs/src/entity.ts` -- the module that owns\n * the `defineComponent('Entity', ...)` call, so reading the owner identity\n * immediately after registration is well-defined. tweak-20260612-ecs-concept-\n * compression lifted this file back from the historical `components/entity.ts`\n * after `entity-handle.ts` freed up the `entity.ts` slot.\n */\nexport const ESSENTIAL_COMPONENT_IDS: ReadonlyArray<ComponentId> = Object.freeze([\n componentId(Entity),\n]);\n\n/**\n * Fold the essential component ids (currently `[componentId(Entity)]`) into a caller-\n * supplied id list. Returns a NEW array; never mutates the input.\n *\n * - If `ids` already contains every essential id, returns a deduped copy\n * (idempotent under repeated folding).\n * - Otherwise, returns `[...essential, ...ids]` with duplicates of the\n * essential ids removed.\n *\n * The empty input maps to `[componentId(Entity)]` -- the bare-archetype shape that a\n * `world.spawn()` (no components) materialises.\n *\n * Single SSOT consumed by both `archetypeKey` (string-key fold) and\n * `createArchetype` (column-build fold) so the two sites can never disagree\n * on which ids are essential. Hot-path correctness is on `createArchetype`'s\n * side: misalignment between key and columns silently drops fields.\n *\n * @example\n * foldEssentials([2, 5, 7]) // [componentId(Entity), 2, 5, 7]\n * foldEssentials([componentId(Entity), 2, 5]) // [componentId(Entity), 2, 5]\n * foldEssentials([componentId(Entity), componentId(Entity)]) // [componentId(Entity)]\n * foldEssentials([]) // [componentId(Entity)]\n */\nexport function foldEssentials(ids: ReadonlyArray<ComponentId>): ComponentId[] {\n const seen = new Set<ComponentId>();\n const out: ComponentId[] = [];\n for (const essential of ESSENTIAL_COMPONENT_IDS) {\n if (!seen.has(essential)) {\n seen.add(essential);\n out.push(essential);\n }\n }\n for (const id of ids) {\n if (!seen.has(id)) {\n seen.add(id);\n out.push(id);\n }\n }\n return out;\n}\n","import { Context, type Plugin } from '@forgeax/engine-plugin';\n\nimport type { World } from './world';\n\ndeclare module '@forgeax/engine-plugin' {\n interface EngineContextServices {\n world: World;\n }\n}\n\nexport function worldPlugin(world: World): Plugin {\n return {\n name: 'world',\n provide: 'world',\n apply(ctx) {\n ctx.provide('world', world);\n },\n };\n}\n\n/** Create one Cordis realm whose root service is the ECS World. */\nexport async function createWorldContext(\n world: World,\n plugins: readonly Plugin[] = [],\n): Promise<Context> {\n const ctx = new Context();\n try {\n await ctx.plugin(worldPlugin(world));\n for (const plugin of plugins) await ctx.plugin(plugin);\n return ctx;\n } catch (error) {\n await ctx.fiber.dispose();\n throw error;\n }\n}\n","import {\n type Component,\n type ComponentSchema,\n defineComponent,\n type FieldsInput,\n} from './component';\nimport type { EntityHandle } from './entity-handle';\n\ndeclare const relationshipTargetBrand: unique symbol;\n\n/** A relationship target is a read projection, never a structural-write token. */\nexport type RelationshipTargetComponent<C extends Component = Component> = C & {\n readonly [relationshipTargetBrand]: true;\n};\n\n/** The two immutable roles produced by one relationship declaration. */\nexport interface RelationshipDefinition {\n readonly source: Component<string, ComponentSchema>;\n readonly target: RelationshipTargetComponent<Component<string, ComponentSchema>>;\n}\n\nexport interface RelationshipOptions {\n readonly sourceName: string;\n readonly sourceField: string;\n readonly targetName: string;\n readonly targetField: string;\n /**\n * Components materialized with the writable source side. This is the\n * relationship equivalent of `defineComponent(..., { requires })`: the\n * dependency is resolved once at the structural boundary, never by a frame\n * system. It applies only to the source; the reverse target remains an\n * engine-owned projection.\n */\n readonly sourceRequires?: readonly Component[];\n readonly exclusive?: boolean;\n readonly linkedSpawn?: boolean;\n /** Allow a source to point at its own holder (e.g. self-animated entities). */\n readonly allowSelf?: boolean;\n}\n\nexport type RelationshipRole =\n | {\n readonly kind: 'source';\n readonly target: Component<string, ComponentSchema>;\n readonly sourceField: string;\n readonly targetField: string;\n readonly exclusive: boolean;\n readonly linkedSpawn: boolean;\n readonly allowSelf: boolean;\n }\n | {\n readonly kind: 'target';\n readonly source: Component<string, ComponentSchema>;\n readonly sourceField: string;\n readonly targetField: string;\n };\n\nconst roles = new WeakMap<Component, RelationshipRole>();\n\n/**\n * Declare both sides of a relationship in one closed operation. The source is\n * the only writable relationship component; its target is a materialized,\n * engine-maintained reverse list.\n */\nexport function defineRelationship<\n const S extends string,\n const SF extends string,\n const T extends string,\n const TF extends string,\n>(\n options: RelationshipOptions & {\n readonly sourceName: S;\n readonly sourceField: SF;\n readonly targetName: T;\n readonly targetField: TF;\n },\n): {\n readonly source: Component<S, { [K in SF]: 'entity' }>;\n readonly target: RelationshipTargetComponent<Component<T, { [K in TF]: 'array<entity>' }>>;\n} {\n const targetFields: FieldsInput = {\n [options.targetField]: { type: 'array<entity>', transient: true },\n };\n const target = defineComponent(options.targetName, targetFields);\n const sourceFields: FieldsInput = { [options.sourceField]: { type: 'entity' } };\n const source = defineComponent(\n options.sourceName,\n sourceFields,\n options.sourceRequires === undefined ? undefined : { requires: options.sourceRequires },\n );\n\n roles.set(source, {\n kind: 'source',\n target,\n sourceField: options.sourceField,\n targetField: options.targetField,\n exclusive: options.exclusive ?? true,\n linkedSpawn: options.linkedSpawn ?? false,\n allowSelf: options.allowSelf ?? false,\n });\n roles.set(target, {\n kind: 'target',\n source,\n sourceField: options.sourceField,\n targetField: options.targetField,\n });\n return { source: source as never, target: target as never };\n}\n\nexport function relationshipRole(component: Component): RelationshipRole | undefined {\n return roles.get(component);\n}\n\n/** Return the materialized target token owned by a source relationship. */\nexport function relationshipMirror(component: Component): Component | undefined {\n const role = roles.get(component);\n return role?.kind === 'source' ? role.target : undefined;\n}\n\n/** Return the source token owned by a materialized relationship target. */\nexport function relationshipSource(component: Component): Component | undefined {\n const role = roles.get(component);\n return role?.kind === 'target' ? role.source : undefined;\n}\n\nexport function isRelationshipTarget(component: Component): boolean {\n return roles.get(component)?.kind === 'target';\n}\n\n/**\n * Backpointer index for the materialized reverse lists stored by World.\n * The target component array is the one authoritative read list; this index\n * stores only source-to-target locations for O(1) swap-remove bookkeeping.\n */\nexport class RelationshipIndex {\n private readonly slots = new Map<number, { target: number; slot: number }>();\n private epochValue = 0;\n\n get epoch(): number {\n return this.epochValue;\n }\n\n attach(source: EntityHandle, target: EntityHandle, slot: number): number {\n this.slots.set(source as number, { target: target as number, slot });\n this.epochValue++;\n return slot;\n }\n\n detach(source: EntityHandle): boolean {\n if (!this.slots.delete(source as number)) return false;\n this.epochValue++;\n return true;\n }\n\n reparent(source: EntityHandle, target: EntityHandle, slot: number): number {\n return this.attach(source, target, slot);\n }\n\n slotOf(source: EntityHandle): number | undefined {\n return this.slots.get(source as number)?.slot;\n }\n\n targetOf(source: EntityHandle): EntityHandle | undefined {\n return this.slots.get(source as number)?.target as EntityHandle | undefined;\n }\n\n /** Bind the source that swap-remove moved into `slot`. */\n updateSlot(source: EntityHandle, target: EntityHandle, slot: number): void {\n const location = this.slots.get(source as number);\n if (location === undefined) return;\n location.target = target as number;\n location.slot = slot;\n this.epochValue++;\n }\n\n /** Cold recovery path only: rebuild from R source records. */\n recover(records: Iterable<readonly [EntityHandle, EntityHandle]>): void {\n this.slots.clear();\n const nextSlots = new Map<number, number>();\n for (const [source, target] of records) {\n const slot = nextSlots.get(target as number) ?? 0;\n nextSlots.set(target as number, slot + 1);\n this.attach(source, target, slot);\n }\n this.epochValue++;\n }\n}\n","/**\n * Nominal label for one of the World-owned schedules.\n *\n * Worlds expose the built-in tokens below. A token is both a registration\n * scope and, for FixedUpdate, the intrinsic Update ordering anchor.\n */\nexport interface ScheduleToken {\n readonly name: string;\n}\n\nexport type ScheduleName = 'Update' | 'FixedUpdate';\n\nfunction createScheduleToken(name: ScheduleName): ScheduleToken {\n // The Engine Worker loads its runtime and an execution bootstrap as separate\n // Vite bundles. Keep the two built-in tokens physically shared across those\n // bundles so a plugin's `Update` reference still addresses the owning World\n // schedule instead of becoming an accidental cross-scope edge.\n const registry = globalThis as typeof globalThis & {\n readonly [key: symbol]: ScheduleToken | undefined;\n };\n const key = Symbol.for(`forgeax.ecs.schedule-token.${name}`);\n const existing = registry[key];\n if (existing !== undefined) return existing;\n const token = Object.freeze({ name });\n Object.defineProperty(registry, key, {\n configurable: false,\n enumerable: false,\n value: token,\n writable: false,\n });\n return token;\n}\n\n/** Variable-rate World schedule. */\nexport const Update = createScheduleToken('Update');\n/** Fixed-rate World schedule and the intrinsic Update ordering anchor. */\nexport const FixedUpdate = createScheduleToken('FixedUpdate');\nexport function isScheduleToken(value: unknown): value is ScheduleToken {\n return value === Update || value === FixedUpdate;\n}\n","export interface TimeResource {\n readonly delta: number;\n readonly elapsed: number;\n readonly maxDeltaSeconds: number;\n}\n\nexport interface FixedTimeResource {\n readonly delta: number;\n readonly maxStepsPerUpdate: number;\n readonly tick: number;\n /** Seconds accumulated toward the next fixed update. */\n readonly overstep: number;\n readonly droppedSeconds: number;\n readonly droppedUpdates: number;\n}\n\nexport type MutableTimeResource = { -readonly [K in keyof TimeResource]: TimeResource[K] };\nexport type MutableFixedTimeResource = {\n -readonly [K in keyof FixedTimeResource]: FixedTimeResource[K];\n};\n\n/** Scheduler-only mutable clock capability; World never exposes this publicly. */\nexport interface ClockWriter {\n readonly time: MutableTimeResource;\n readonly fixed: MutableFixedTimeResource;\n}\n\nexport interface WorldClock {\n readonly time: TimeResource;\n readonly fixed: FixedTimeResource;\n readonly writer: ClockWriter;\n}\n\ninterface ResourceToken<T> {\n readonly name: string;\n readonly __resourceType?: T;\n}\n\nexport type ResourceValue<Key> = Key extends ResourceToken<infer Value> ? Value : never;\n\nexport interface TimePolicy {\n readonly fixedDeltaSeconds?: number;\n readonly maxStepsPerUpdate?: number;\n readonly maxDeltaSeconds?: number;\n}\n\nexport interface WorldOptions {\n readonly time?: TimePolicy;\n /** SAB-backed dense numeric columns for a SharedKernel-capable Engine Realm. */\n readonly storage?: 'local' | 'shared';\n}\n\n/** World-owned variable-rate clock resource key. */\nexport const Time = Object.freeze({ name: 'Time' }) as ResourceToken<TimeResource> & TimeResource;\n/** World-owned fixed-rate clock, policy, and catch-up metric resource key. */\nexport const FixedTime = Object.freeze({ name: 'FixedTime' }) as ResourceToken<FixedTimeResource> &\n FixedTimeResource;\n\nexport const TIME_RESOURCE_KEY = Time.name;\nexport const FIXED_TIME_RESOURCE_KEY = FixedTime.name;\n\nexport const DEFAULT_TIME_POLICY: Required<TimePolicy> = {\n fixedDeltaSeconds: 1 / 60,\n maxStepsPerUpdate: 4,\n maxDeltaSeconds: 0.1,\n};\n\nexport function createTimeResource(policy: Required<TimePolicy>): TimeResource {\n return { delta: 0, elapsed: 0, maxDeltaSeconds: policy.maxDeltaSeconds };\n}\n\nexport function createFixedTimeResource(policy: Required<TimePolicy>): FixedTimeResource {\n return {\n delta: policy.fixedDeltaSeconds,\n maxStepsPerUpdate: policy.maxStepsPerUpdate,\n tick: 0,\n overstep: 0,\n droppedSeconds: 0,\n droppedUpdates: 0,\n };\n}\n\nexport function createWorldClock(policy: Required<TimePolicy>): WorldClock {\n const time = createTimeResource(policy) as MutableTimeResource;\n const fixed = createFixedTimeResource(policy) as MutableFixedTimeResource;\n const timeView: TimeResource = Object.freeze({\n get delta() {\n return time.delta;\n },\n get elapsed() {\n return time.elapsed;\n },\n get maxDeltaSeconds() {\n return time.maxDeltaSeconds;\n },\n });\n const fixedView: FixedTimeResource = Object.freeze({\n get delta() {\n return fixed.delta;\n },\n get maxStepsPerUpdate() {\n return fixed.maxStepsPerUpdate;\n },\n get tick() {\n return fixed.tick;\n },\n get overstep() {\n return fixed.overstep;\n },\n get droppedSeconds() {\n return fixed.droppedSeconds;\n },\n get droppedUpdates() {\n return fixed.droppedUpdates;\n },\n });\n return {\n time: timeView,\n fixed: fixedView,\n writer: { time, fixed },\n };\n}\n","// @forgeax/engine-ecs — Entity handle.\n//\n// Encoding: u32 = (generation << 24) | (index & 0xFFFFFF)\n// - index: 24 bits — supports up to 16_777_215 simultaneous entities.\n// - generation: 8 bits — retirement when gen exceeds 255 (gen 255 usable);\n// index permanently retired when bumped generation would reach 256.\n//\n// Key difference from @forgeax/engine-ecs: generation does NOT wrap 255 → 0.\n// When generation would exceed 255 (256), the index is permanently retired\n// from the free list to prevent handle aliasing (D-08).\n//\n// feat-20260623-asset-handle-generation M2 / w4: encodeEntity/decodeEntity/\n// entityIndex/entityGeneration are now thin wrappers over the shared gen-slot\n// codec in @forgeax/engine-types (pack / unpackSlot / unpackGen). The\n// `EntityIndexOverflowError` throw and `ENTITY_NULL_RAW` sentinel stay in ecs\n// (D-1). Constants re-export codec values for backward-compatible names.\n\nimport { MAX_GEN, MAX_SLOT, pack, unpackGen, unpackSlot } from '@forgeax/engine-types';\nimport { EntityIndexOverflowError } from './errors';\n\n/**\n * Branded `number` representing an Entity handle. Stored as a JS `number` but\n * holds the u32 bit pattern (generation << 24) | index.\n *\n * The phantom `__entity` brand prevents accidental mixing with other numbers.\n *\n * Naming: the type-space alias is `EntityHandle` (the branded number that\n * identifies a row). The same-named value-space `Entity` re-exported from the\n * package barrel is the id=0 component token (see `./entity`).\n */\nexport type EntityHandle = number & { readonly __entity: unique symbol };\n\n/** Maximum representable entity index (2^24 - 1 = 16_777_215). Re-exports codec MAX_SLOT. */\nexport const ENTITY_MAX_INDEX = MAX_SLOT;\n\n/** Maximum representable generation (2^8 - 1 = 255). Re-exports codec MAX_GEN. */\nexport const ENTITY_MAX_GENERATION = MAX_GEN;\n\n/**\n * Sentinel u32 value reserved for the \"null entity\" slot in `entity`-typed\n * component fields.\n *\n * The encoding `(gen << 24) | index` yields `0xFFFFFFFF` only at the very\n * last valid (gen=255, index=0xFFFFFF) entity, which retires permanently on\n * its first despawn (D-08). Carving out this single bit pattern as the null\n * sentinel costs at most one slot at the far edge of the entity space.\n *\n * Stored u32 column reads compare against `ENTITY_NULL_RAW` first; the\n * column-level `Entity | null` decode lives in `world.readRow`.\n *\n * Scene-as-World-Blueprint anchor (feat-20260514 w12, R-8 lockdown):\n * This module (`packages/ecs/src/entity.ts`) is the canonical export site\n * for the entity null sentinel. Downstream consumers (M2 instantiate\n * layer 3 fallback for `'entity'`-typed component fields, w22) must import\n * from the package barrel:\n *\n * import { ENTITY_NULL_RAW } from '@forgeax/engine-ecs'\n *\n * The raw `0xFFFFFFFF` literal MUST NOT be duplicated at consumer sites\n * (charter proposition 1: SSOT lives here). The decoded JS-side value is\n * `null` (returned by `world.get(e, C).<entityField>`). Layer 3 default\n * for `'entity'` keyword fields stores `ENTITY_NULL_RAW` into the u32\n * column, which decodes back to `null` on read. ecs-managed-buffer feat\n * export verification (w12 grep): see `packages/ecs/src/index.ts` line\n * re-exporting this constant alongside `ENTITY_MAX_GENERATION /\n * ENTITY_MAX_INDEX`. No add-only fallback re-export is required at this\n * time.\n */\nexport const ENTITY_NULL_RAW = 0xffffffff;\n\n/**\n * Encode (index, generation) into a u32 entity handle.\n *\n * Delegates to shared codec `pack(index, generation)` after ecs-specific\n * overflow validation. The `>>> 0` anti-ToInt32 guard is inherited from the\n * codec (D-7 hard constraint).\n *\n * @throws EntityIndexOverflowError when `index > ENTITY_MAX_INDEX` or `index < 0`.\n */\nexport function encodeEntity(index: number, generation: number): EntityHandle {\n if (index < 0 || index > ENTITY_MAX_INDEX) {\n throw new EntityIndexOverflowError(index);\n }\n return pack(index, generation) as EntityHandle;\n}\n\n/** Decode a u32 entity handle into its (index, generation) pair via shared codec. */\nexport function decodeEntity(entity: EntityHandle): { index: number; generation: number } {\n const e = entity as unknown as number;\n return {\n index: unpackSlot(e),\n generation: unpackGen(e),\n };\n}\n\n/** Extract just the index slot from an entity handle via shared codec. */\nexport function entityIndex(entity: EntityHandle): number {\n return unpackSlot(entity as unknown as number);\n}\n\n/** Extract just the generation slot from an entity handle via shared codec. */\nexport function entityGeneration(entity: EntityHandle): number {\n return unpackGen(entity as unknown as number);\n}\n","// @forgeax/engine-ecs/internal — package-owner seams that are intentionally\n// absent from the public ECS barrel.\n//\n// This entry keeps the existing component-owner imports stable and adds the\n// typed symbol used by scene propagation. A symbol avoids putting a derived\n// writer method on the discoverable Query contract while still letting the\n// owning package share the exact query implementation without a private path\n// import or an untyped cast at each consumer.\n\nexport * from './component';\nexport type { WorldInternal } from './world-internal';\nexport { worldInternal } from './world-internal';\n\nimport type { Result } from '@forgeax/engine-types';\nimport type { Component } from './component';\nimport type { QuerySpanUnavailableError } from './errors';\nimport type { DerivedRangeWriter } from './query/derived-range-writer';\nimport type { Query } from './query/query';\n\n/** Internal identity for the ECS-owned derived range writer accessor. */\nexport const DERIVED_WRITER: unique symbol = Symbol.for(\n 'forgeax.ecs.query.derivedWriter',\n) as unknown as typeof DERIVED_WRITER;\n\ntype DerivedWriterQuery<\n R extends readonly Component[],\n W extends readonly Component[],\n O extends readonly Component[],\n> = Query<R, W, O> & {\n readonly [DERIVED_WRITER]: <C extends W[number]>(\n component: C,\n ) => Result<DerivedRangeWriter<R[number], C>, QuerySpanUnavailableError>;\n};\n\n/**\n * Resolve the ECS-owned derived writer through its internal symbol seam.\n * Consumers of this module retain the component/query type relationship while\n * the public Query and QuerySpan surfaces remain read/write-only contracts.\n */\nexport function getDerivedWriter<\n R extends readonly Component[],\n W extends readonly Component[],\n O extends readonly Component[],\n C extends W[number],\n>(\n query: Query<R, W, O>,\n component: C,\n): Result<DerivedRangeWriter<R[number], C>, QuerySpanUnavailableError> {\n const internalQuery = query as DerivedWriterQuery<R, W, O>;\n return internalQuery[DERIVED_WRITER](component);\n}\n\nexport type {\n DerivedColumnBinding,\n DerivedRangeCursor,\n DerivedRangeRowCommit,\n DerivedRangeRowProbe,\n DerivedRangeWriter,\n} from './query/derived-range-writer';\n","import type { Component, ComponentId } from '../component';\nimport { componentId } from '../component';\nimport { foldEssentials } from '../entity';\nimport type { TableId } from './table';\n\nconst INITIAL_CAPACITY = 64;\n\nexport type ArchetypeId = number;\n\nexport interface Archetype {\n readonly id: ArchetypeId;\n readonly key: string;\n readonly components: ReadonlyArray<Component>;\n readonly tableId: TableId;\n rows: Uint32Array;\n size: number;\n capacity: number;\n addEdges: Map<ComponentId, ArchetypeId>;\n removeEdges: Map<ComponentId, ArchetypeId>;\n}\n\nexport function archetypeKey(componentIds: ReadonlyArray<ComponentId>): string {\n return [...foldEssentials(componentIds)].sort((a, b) => a - b).join('+');\n}\n\nexport function createArchetype(\n components: ReadonlyArray<Component>,\n id: ArchetypeId,\n tableId: TableId,\n): Archetype {\n const byId = new Map<ComponentId, Component>();\n for (const component of components) byId.set(componentId(component), component);\n const sorted = [...byId.values()].sort((a, b) => componentId(a) - componentId(b));\n return {\n id,\n key: archetypeKey(sorted.map((component) => componentId(component))),\n components: sorted,\n tableId,\n rows: new Uint32Array(INITIAL_CAPACITY),\n size: 0,\n capacity: INITIAL_CAPACITY,\n addEdges: new Map(),\n removeEdges: new Map(),\n };\n}\n\nexport function appendArchetypeRow(archetype: Archetype, tableRow: number): number {\n if (archetype.size === archetype.capacity) growArchetype(archetype, archetype.capacity * 2);\n const row = archetype.size;\n archetype.rows[row] = tableRow;\n archetype.size = row + 1;\n return row;\n}\n\nexport function removeArchetypeRow(\n archetype: Archetype,\n row: number,\n): { movedTableRow: number; newRow: number } | null {\n const lastRow = archetype.size - 1;\n if (row === lastRow) {\n archetype.size = lastRow;\n return null;\n }\n const movedTableRow = archetype.rows[lastRow] ?? 0;\n archetype.rows[row] = movedTableRow;\n archetype.size = lastRow;\n return { movedTableRow, newRow: row };\n}\n\nexport function growArchetype(archetype: Archetype, targetCapacity: number): void {\n let capacity = archetype.capacity;\n while (capacity < targetCapacity) capacity *= 2;\n if (capacity === archetype.capacity) return;\n const rows = new Uint32Array(capacity);\n rows.set(archetype.rows);\n archetype.rows = rows;\n archetype.capacity = capacity;\n}\n","// @forgeax/engine-ecs — per-field independent buffer column storage (D-01).\n//\n// Each component field gets its own ArrayBuffer/SharedArrayBuffer + TypedArray view.\n// This enables independent per-column transfer() expansion and\n// supports dynamic column add/remove during archetype migration.\n//\n// `array<T>` (variable-capacity) fields take TWO columns in archetype layout\n// (D-3): the primary u32 column carries the BufferPool slot id; a sidecar\n// column carries the live element count, named `<fieldName>:count` and\n// keyed by `arrayCountColumnName(fieldName)`. `array<T,N>` (fixed-capacity)\n// fields (feat-20260602) take a SINGLE inline stride-N column (arity = N) --\n// no BufferPool slot id, no sidecar count column. The elements live\n// contiguously per row. `buffer<N>` likewise takes a single stride-N u8\n// column. Variable `buffer` still uses a u32 BufferPool slot id column.\n// Capacity is never stored as an independent column: for variable-capacity\n// fields it is derived from `BufferPool.view(slotId).byteLength /\n// elementBytes`; for fixed-capacity fields the schema-declared N is the\n// capacity.\n\nimport { type ComponentSchema, type ScalarFieldType, TYPE_METADATA } from '../component';\n\n// ────────────────────────────────────────────────────────────────────────────\n// ManagedColumnReader — read-only view onto a managed-vocab column\n// (feat-20260614 M4 / D-4 / AC-08 / AC-09 / AC-10)\n// ────────────────────────────────────────────────────────────────────────────\n\n/**\n * Read-only access shape for the 4 managed-vocab column keywords --\n * `'string'` / `` `ref<T>` `` / variable `'buffer'` / variable `` `array<T>` ``.\n *\n * The column carries u32 slot ids (`UniqueRefStore` / `BufferPool`); direct\n * index assignment would corrupt the slot table. The reader exposes\n * `.length` + `.get(i): number` so consumers can walk row indices and\n * retrieve slot ids, then route through the public dispatch (`world.set`,\n * `world.push`, `world.allocUniqueRef`, etc.) for any mutation.\n *\n * Phantom brand `__managed` (D-7 / requirements-decisions q2): the\n * double-underscore + semantic-word pattern matches `Handle.__handle`. The\n * brand is a structural-typing safety net; the class name already\n * disambiguates against `Uint32Array` / `Uint8Array` / fixed inline views.\n *\n * Intentionally minimal -- no iterator, no `toArray`, no `slice`. Adding\n * those invites a \"cache the slot ids, mutate later\" anti-pattern that\n * silently desyncs from the live column on the next archetype migration\n * (charter P4 / plan-strategy §8.4).\n */\nexport interface ManagedColumnReader<T extends string> {\n readonly length: number;\n get(i: number): number;\n readonly __managed: T;\n}\n\n/**\n * Sidecar column name for the live `count` of an `array<T>` (variable-\n * capacity) field. Format `<fieldName>:count` keeps the suffix outside the\n * legal user-facing schema name space (the colon is forbidden in user\n * field names by convention) so the archetype Map can carry both columns\n * under one `Map<fieldName, Column>` keyed namespace without collision\n * (D-3 double-column allocation in M1 / w7).\n */\nexport function arrayCountColumnName(fieldName: string): string {\n return `${fieldName}:count`;\n}\n\n// ────────────────────────────────────────────────────────────────────────────\n// Column: one field's storage\n// ────────────────────────────────────────────────────────────────────────────\n\n/** TypedArray view types used by columns. */\nexport type FieldView =\n | Float32Array\n | Float64Array\n | Int32Array\n | Uint32Array\n | Int16Array\n | Uint16Array\n | Int8Array\n | Uint8Array;\n\ntype FieldViewConstructor = new (buffer: ArrayBufferLike) => FieldView;\n\nfunction createFieldView(\n Ctor: NonNullable<(typeof TYPE_METADATA)[string]['viewCtor']>,\n buffer: ArrayBufferLike,\n): FieldView {\n return new (Ctor as FieldViewConstructor)(buffer);\n}\n\nfunction isSharedBuffer(buffer: ArrayBufferLike): buffer is SharedArrayBuffer {\n return typeof SharedArrayBuffer !== 'undefined' && buffer instanceof SharedArrayBuffer;\n}\n\n/** A single column: one field's ArrayBuffer + TypedArray view. */\nexport interface Column {\n buffer: ArrayBuffer | SharedArrayBuffer;\n view: FieldView;\n capacity: number;\n fieldType: ScalarFieldType;\n /**\n * Number of elements per row (stride). Scalar and variable-capacity columns\n * default to 1 (one u32 slot id or one scalar value per row). Fixed-capacity\n * `array<T,N>` / `buffer<N>` inline columns (feat-20260602) have arity = N.\n *\n * For inline columns, the TypedArray view returned by `col.view.subarray()`\n * aliases the column buffer directly. The view is transient: `growColumn`\n * detaches the old `ArrayBuffer` via `transfer()`, so callers must re-fetch\n * the view after any structural change. See `packages/ecs/README.md`\n * Transient view contract section.\n */\n arity: number;\n}\n\n/**\n * Create a column for a single field with given capacity.\n *\n * @param fieldType - scalar storage type for the column view ctor\n * @param capacity - number of rows\n * @param arity - elements per row (stride); default 1 for scalar/variable columns\n */\nexport function createColumn(\n fieldType: ScalarFieldType,\n capacity: number,\n arity = 1,\n shared = false,\n): Column {\n const meta = TYPE_METADATA[fieldType];\n if (!meta) throw new Error(`Missing TYPE_METADATA entry for scalar field type ${fieldType}`);\n const bytesPerElement =\n // biome-ignore lint/style/noNonNullAssertion: ScalarFieldType rows always carry a byteSize\n meta.byteSize!;\n const buffer = shared\n ? new SharedArrayBuffer(bytesPerElement * capacity * arity)\n : new ArrayBuffer(bytesPerElement * capacity * arity);\n // biome-ignore lint/style/noNonNullAssertion: ScalarFieldType rows always carry a viewCtor\n const Ctor = meta.viewCtor!;\n const view = createFieldView(Ctor, buffer);\n return { buffer, view, capacity, fieldType, arity };\n}\n\n/**\n * Module-level cache for `ArrayBuffer.prototype.transfer` support (O-1).\n * Checked once at import time; avoids per-call feature detection overhead.\n *\n * Note: `transfer()` is ES2024. We use runtime feature detection + type cast\n * so that tsconfig does not need `lib: [\"es2024\"]`.\n */\nexport const HAS_TRANSFER: boolean =\n typeof (ArrayBuffer.prototype as { transfer?: unknown }).transfer === 'function';\n\n/**\n * Grow a column to a new capacity, preserving existing data.\n * Returns a new Column; the old column is not modified.\n *\n * When the runtime supports `ArrayBuffer.transfer()` (ES2024, Node 22+,\n * modern browsers), uses zero-copy buffer transfer. Otherwise falls back\n * to `new ArrayBuffer` + `Uint8Array.set` copy.\n *\n * Both paths produce data-equivalent results (O-1 acceptance criterion).\n */\nexport function growColumn(col: Column, newCapacity: number): Column {\n const meta = TYPE_METADATA[col.fieldType];\n if (!meta) throw new Error(`Missing TYPE_METADATA entry for scalar field type ${col.fieldType}`);\n const bytesPerElement =\n // biome-ignore lint/style/noNonNullAssertion: ScalarFieldType rows always carry a byteSize\n meta.byteSize!;\n const newByteLength = bytesPerElement * newCapacity * col.arity;\n // biome-ignore lint/style/noNonNullAssertion: ScalarFieldType rows always carry a viewCtor\n const Ctor = meta.viewCtor!;\n\n let buffer: ArrayBuffer | SharedArrayBuffer;\n if (isSharedBuffer(col.buffer)) {\n buffer = new SharedArrayBuffer(newByteLength);\n new Uint8Array(buffer).set(new Uint8Array(col.buffer));\n } else if (HAS_TRANSFER) {\n // Zero-copy path: transfer() resizes the underlying buffer in-place\n // and detaches the source. The old column's buffer becomes detached,\n // but we return a new Column object so callers never touch the old one.\n buffer = (col.buffer as unknown as { transfer(newByteLength: number): ArrayBuffer }).transfer(\n newByteLength,\n );\n } /* istanbul ignore next -- fallback for runtimes without ES2024 transfer() */ else {\n // Fallback path: allocate new buffer + byte-level copy.\n buffer = new ArrayBuffer(newByteLength);\n new Uint8Array(buffer).set(new Uint8Array(col.buffer));\n }\n\n const view = createFieldView(Ctor, buffer);\n return { buffer, view, capacity: newCapacity, fieldType: col.fieldType, arity: col.arity };\n}\n\n// ────────────────────────────────────────────────────────────────────────────\n// Buffer-write input normalization (feat-20260621 V2 / AC-A4)\n// ────────────────────────────────────────────────────────────────────────────\n\n/**\n * Normalize a `'buffer'` / `'buffer<N>'` write payload to a `Uint8Array` view\n * over its raw bytes. The write surface (`FieldInputType<'buffer'>`) accepts\n * any `AllowSharedBufferSource` (Float32Array / ArrayBuffer / Uint8Array / any\n * TypedArray); the column store and read side speak `Uint8Array` only. This is\n * the single ingestion point that bridges the two — a strict superset of the\n * prior Uint8Array-only behavior (an existing `Uint8Array` caller round-trips\n * through `new Uint8Array(buffer, byteOffset, byteLength)`, same bytes, same\n * length), so existing callers see zero behavior change.\n *\n * Returns `null` for non-buffer-source inputs (e.g. a forced cast feeding a\n * number) so callers keep their existing \"no-op / alloc(0)\" branch for raw\n * that is not a real buffer view.\n */\nexport function normalizeBufferWrite(raw: unknown): Uint8Array | null {\n if (raw instanceof Uint8Array) {\n return raw;\n }\n if (ArrayBuffer.isView(raw)) {\n return new Uint8Array(raw.buffer, raw.byteOffset, raw.byteLength);\n }\n if (raw instanceof ArrayBuffer) {\n return new Uint8Array(raw);\n }\n if (typeof SharedArrayBuffer !== 'undefined' && raw instanceof SharedArrayBuffer) {\n return new Uint8Array(raw);\n }\n return null;\n}\n\n// ────────────────────────────────────────────────────────────────────────────\n// Hot/cold classification\n// ────────────────────────────────────────────────────────────────────────────\n\n/**\n * Determine if a schema is \"hot\" (all fields are scalar → TypedArray SoA).\n * Returns true if all fields are in the scalar field type set.\n * Empty schema (tag component) returns true by convention (vacuously true).\n *\n * Schema-vocab keywords (`buffer:<N>` / `ref<T>` / `handle<T>` / `entity` /\n * `array<T,N>` / `array<T>`) are explicitly cold — their storage is owned by\n * separate subsystems (UniqueRefStore / BufferPool), not the column SoA path. The keyword check uses an unsafe narrowing because\n * `SchemaFieldType` is wider than the set's `ScalarFieldType` element type;\n * the `has` test is the runtime gate.\n */\nexport function isHotSchema(schema: ComponentSchema): boolean {\n for (const fieldType of Object.values(schema)) {\n if (!TYPE_METADATA[fieldType]?.isScalar) {\n return false;\n }\n }\n return true;\n}\n","import {\n bufferFieldByteLength,\n type Component,\n type ComponentId,\n componentId,\n componentSchema,\n fieldTypeToMetaKey,\n isManagedBufferField,\n parseManagedArraySchema,\n type ScalarFieldType,\n TYPE_METADATA,\n} from '../component';\nimport { Entity, foldEssentials } from '../entity';\nimport type { EntityHandle } from '../entity-handle';\nimport {\n type ComponentEpochColumns,\n copyComponentEpoch,\n createComponentEpochColumns,\n growComponentEpochColumns,\n} from './change-detection';\nimport { arrayCountColumnName, type Column, createColumn, growColumn } from './column';\n\nconst INITIAL_CAPACITY = 64;\n\nexport type TableId = number;\n\nexport interface TableComponentStorage {\n readonly component: Component;\n fields: Map<string, Column>;\n epochs: ComponentEpochColumns;\n}\n\nexport interface Table {\n readonly id: TableId;\n readonly key: string;\n readonly components: ReadonlyArray<Component>;\n storage: Map<ComponentId, TableComponentStorage>;\n size: number;\n capacity: number;\n version: number;\n}\n\nexport function tableKey(componentIds: ReadonlyArray<ComponentId>): string {\n return [...foldEssentials(componentIds)].sort((a, b) => a - b).join('+');\n}\n\nexport function canonicalComponents(components: ReadonlyArray<Component>): Component[] {\n const byId = new Map<ComponentId, Component>();\n byId.set(componentId(Entity), Entity as unknown as Component);\n for (const component of components) byId.set(componentId(component), component);\n return [...byId.values()].sort((a, b) => componentId(a) - componentId(b));\n}\n\nexport function createTable(\n components: ReadonlyArray<Component>,\n id: TableId,\n shared = false,\n): Table {\n const sortedComponents = canonicalComponents(components);\n const capacity = INITIAL_CAPACITY;\n const storage = new Map<ComponentId, TableComponentStorage>();\n for (const component of sortedComponents) {\n const fields = new Map<string, Column>();\n for (const [fieldName, fieldType] of Object.entries(componentSchema(component))) {\n const arrayMeta = parseManagedArraySchema(fieldType);\n if (arrayMeta !== null && arrayMeta.length !== undefined) {\n const metaKey = fieldTypeToMetaKey(arrayMeta.elementType);\n const scalarType: ScalarFieldType | null =\n metaKey === null ? null : (TYPE_METADATA[metaKey]?.storage ?? null);\n if (scalarType !== null) {\n fields.set(fieldName, createColumn(scalarType, capacity, arrayMeta.length, shared));\n }\n continue;\n }\n if (isManagedBufferField(fieldType) && fieldType !== 'buffer') {\n fields.set(\n fieldName,\n createColumn('u8', capacity, bufferFieldByteLength(fieldType), shared),\n );\n continue;\n }\n const metaKey = fieldTypeToMetaKey(fieldType);\n const scalarType: ScalarFieldType | null =\n metaKey === null ? null : (TYPE_METADATA[metaKey]?.storage ?? null);\n if (scalarType === null) continue;\n fields.set(fieldName, createColumn(scalarType, capacity, 1, shared));\n if (arrayMeta !== null && arrayMeta.length === undefined) {\n fields.set(arrayCountColumnName(fieldName), createColumn('u32', capacity, 1, shared));\n }\n }\n storage.set(componentId(component), {\n component,\n fields,\n epochs: createComponentEpochColumns(capacity),\n });\n }\n return {\n id,\n key: tableKey(sortedComponents.map((component) => componentId(component))),\n components: sortedComponents,\n storage,\n size: 0,\n capacity,\n version: 0,\n };\n}\n\nexport function appendTableRow(table: Table, entity: EntityHandle): number {\n if (table.size === table.capacity) growTable(table, table.capacity * 2);\n const row = table.size;\n const self = table.storage.get(componentId(Entity))?.fields.get('self');\n if (self !== undefined) self.view[row] = entity as number;\n table.size = row + 1;\n return row;\n}\n\nexport function removeTableRow(\n table: Table,\n row: number,\n): { movedEntity: EntityHandle; newRow: number } | null {\n const lastRow = table.size - 1;\n if (row === lastRow) {\n table.size = lastRow;\n return null;\n }\n const movedEntity = (table.storage.get(componentId(Entity))?.fields.get('self')?.view[lastRow] ??\n 0) as EntityHandle;\n for (const componentStorage of table.storage.values()) {\n for (const column of componentStorage.fields.values()) {\n const arity = column.arity;\n column.view.set(column.view.subarray(lastRow * arity, lastRow * arity + arity), row * arity);\n }\n copyComponentEpoch(componentStorage.epochs, lastRow, componentStorage.epochs, row);\n }\n table.size = lastRow;\n return { movedEntity, newRow: row };\n}\n\nexport function growTable(table: Table, targetCapacity: number): void {\n let capacity = table.capacity;\n while (capacity < targetCapacity) capacity *= 2;\n if (capacity === table.capacity) return;\n for (const componentStorage of table.storage.values()) {\n const fields = new Map<string, Column>();\n for (const [fieldName, column] of componentStorage.fields) {\n fields.set(fieldName, growColumn(column, capacity));\n }\n componentStorage.fields = fields;\n componentStorage.epochs = growComponentEpochColumns(componentStorage.epochs, capacity);\n }\n table.capacity = capacity;\n table.version += 1;\n}\n","// @forgeax/engine-ecs — ArchetypeGraph: manages archetype creation and edge caching.\n//\n// O(1) archetype migration lookup via cached edges (D-02 / Finding 2).\n// Global `generation` counter incremented on each new archetype creation\n// (ArchetypeGeneration for query cache incremental update).\n\nimport type { Component, ComponentId } from '../component';\nimport * as componentOwner from '../component';\nimport { type Archetype, type ArchetypeId, archetypeKey, createArchetype } from './archetype';\nimport { createSparseTagSet, type SparseTagSet } from './change-detection';\nimport { canonicalComponents, createTable, type Table, type TableId, tableKey } from './table';\n\n/**\n * The ArchetypeGraph owns all archetypes and their edge caches.\n *\n * `archetypes` is the SSOT: a dense array indexed by `ArchetypeId` (the id is\n * allocated as the next array slot, so `archetypes[id].id === id`).\n * `dedupByKey` is a derived index `key → ArchetypeId` used only at archetype\n * creation to dedupe; consumers always read through `archetypes[id]`\n * (architecture-principles.md §1 SSOT, §2 Derive — replaces the historical\n * `byKey: Map<string, Archetype>` / `byId: Archetype[]` pair which carried two\n * full Archetype refs per row).\n */\nexport interface ArchetypeGraph {\n /** SSOT: dense array indexed by `ArchetypeId` (id == array slot). */\n archetypes: Archetype[];\n /** Derived dedup index: canonical-key string → ArchetypeId. */\n dedupByKey: Map<string, ArchetypeId>;\n /** Global generation counter. Incremented on each new archetype. */\n generation: number;\n tables: Table[];\n tableDedupByKey: Map<string, TableId>;\n tableGeneration: number;\n sparseTags: Map<ComponentId, SparseTagSet>;\n readonly shared: boolean;\n}\n\n/**\n * Create a fresh ArchetypeGraph.\n */\nexport function createArchetypeGraph(shared = false): ArchetypeGraph {\n return {\n archetypes: [],\n dedupByKey: new Map(),\n generation: 0,\n tables: [],\n tableDedupByKey: new Map(),\n tableGeneration: 0,\n sparseTags: new Map(),\n shared,\n };\n}\n\nexport function getTable(graph: ArchetypeGraph, id: TableId): Table {\n const table = graph.tables[id];\n if (table === undefined) throw new Error(`Table ${id} does not exist.`);\n return table;\n}\n\nexport function getOrCreateTable(\n graph: ArchetypeGraph,\n components: ReadonlyArray<Component>,\n): Table {\n const tableComponents = canonicalComponents(\n components.filter((component) => component.storage === 'table'),\n );\n const key = tableKey(tableComponents.map((component) => componentOwner.componentId(component)));\n const existingId = graph.tableDedupByKey.get(key);\n if (existingId !== undefined) return getTable(graph, existingId);\n const table = createTable(tableComponents, graph.tables.length, graph.shared);\n graph.tables.push(table);\n graph.tableDedupByKey.set(key, table.id);\n graph.tableGeneration += 1;\n return table;\n}\n\nexport function getOrCreateSparseTagSet(graph: ArchetypeGraph, component: Component): SparseTagSet {\n const current = graph.sparseTags.get(componentOwner.componentId(component));\n if (current !== undefined) return current;\n const set = createSparseTagSet(component);\n graph.sparseTags.set(componentOwner.componentId(component), set);\n return set;\n}\n\n/**\n * Get or create an archetype for the given component set.\n * ComponentIds are sorted to produce a canonical key.\n */\nexport function getOrCreateArchetype(\n graph: ArchetypeGraph,\n componentIds: ReadonlyArray<ComponentId>,\n components: ReadonlyArray<Component>,\n): Archetype {\n const key = archetypeKey(componentIds);\n const existingId = graph.dedupByKey.get(key);\n if (existingId !== undefined) {\n // biome-ignore lint/style/noNonNullAssertion: dedupByKey only ever holds ids that were pushed into archetypes[].\n return graph.archetypes[existingId]!;\n }\n\n const fullComponents = canonicalComponents(components);\n const table = getOrCreateTable(graph, fullComponents);\n const archId = graph.archetypes.length;\n const arch = createArchetype(fullComponents, archId, table.id);\n graph.archetypes.push(arch);\n graph.dedupByKey.set(key, archId);\n graph.generation += 1;\n return arch;\n}\n\n/**\n * Get the target archetype after adding `componentId` to `src`.\n * Caches the edge for O(1) subsequent lookups.\n */\nexport function getAddEdge(\n graph: ArchetypeGraph,\n src: Archetype,\n componentId: ComponentId,\n component: Component,\n): Archetype {\n const cached = src.addEdges.get(componentId);\n if (cached !== undefined) {\n const target = graph.archetypes[cached];\n if (target) {\n return target;\n }\n }\n\n // Compute target archetype: src components + new component.\n const newIds = [...src.components.map((c) => componentOwner.componentId(c)), componentId];\n const newComponents = [...src.components, component];\n const target = getOrCreateArchetype(graph, newIds, newComponents);\n src.addEdges.set(componentId, target.id);\n return target;\n}\n\n/**\n * Get the target archetype after removing `componentId` from `src`.\n * Caches the edge for O(1) subsequent lookups.\n *\n * Component list is derived from `src.components.filter(c => componentOwner.componentId(c) !== componentId)`\n * (no separate componentRegistry — feat-20260611 AC-09).\n */\nexport function getRemoveEdge(\n graph: ArchetypeGraph,\n src: Archetype,\n componentId: ComponentId,\n): Archetype {\n const cached = src.removeEdges.get(componentId);\n if (cached !== undefined) {\n const target = graph.archetypes[cached];\n if (target) {\n return target;\n }\n }\n\n // Compute target archetype: src components minus removed component.\n // Derive componentIds from src.components (single-field Archetype).\n const newIds = src.components\n .map((c) => componentOwner.componentId(c))\n .filter((id) => id !== componentId);\n const newComponents = src.components.filter((c) => componentOwner.componentId(c) !== componentId);\n const target = getOrCreateArchetype(graph, newIds, newComponents);\n src.removeEdges.set(componentId, target.id);\n return target;\n}\n","// @forgeax/engine-ecs — per-entity and per-resource change ticks.\n\nimport type { Component } from '../component';\nimport * as componentOwner from '../component';\nimport { type EntityHandle, entityIndex } from '../entity-handle';\n\nimport type { ArchetypeGraph } from './archetype-graph';\nimport { getOrCreateSparseTagSet } from './archetype-graph';\n\nconst INITIAL_SPARSE_CAPACITY = 64;\n\nexport interface ComponentEpochColumns {\n added: Float64Array;\n changed: Float64Array;\n}\n\nexport function createComponentEpochColumns(capacity: number): ComponentEpochColumns {\n return { added: new Float64Array(capacity), changed: new Float64Array(capacity) };\n}\n\nexport function growComponentEpochColumns(\n columns: ComponentEpochColumns,\n capacity: number,\n): ComponentEpochColumns {\n const added = new Float64Array(capacity);\n const changed = new Float64Array(capacity);\n added.set(columns.added);\n changed.set(columns.changed);\n return { added, changed };\n}\n\nexport function copyComponentEpoch(\n source: ComponentEpochColumns,\n sourceRow: number,\n target: ComponentEpochColumns,\n targetRow: number,\n): void {\n target.added[targetRow] = source.added[sourceRow] ?? 0;\n target.changed[targetRow] = source.changed[sourceRow] ?? 0;\n}\n\nexport interface SparseTagSet {\n readonly component: Component;\n sparse: Int32Array;\n dense: Uint32Array;\n added: Float64Array;\n changed: Float64Array;\n size: number;\n}\n\nexport function createSparseTagSet(component: Component): SparseTagSet {\n const sparse = new Int32Array(INITIAL_SPARSE_CAPACITY);\n sparse.fill(-1);\n return {\n component,\n sparse,\n dense: new Uint32Array(INITIAL_SPARSE_CAPACITY),\n added: new Float64Array(INITIAL_SPARSE_CAPACITY),\n changed: new Float64Array(INITIAL_SPARSE_CAPACITY),\n size: 0,\n };\n}\n\nexport function sparseTagIndex(set: SparseTagSet, entity: EntityHandle): number {\n const denseIndex = set.sparse[entityIndex(entity)] ?? -1;\n return denseIndex >= 0 && set.dense[denseIndex] === (entity as number) ? denseIndex : -1;\n}\n\nexport function sparseTagHas(set: SparseTagSet, entity: EntityHandle): boolean {\n return sparseTagIndex(set, entity) >= 0;\n}\n\nexport function insertSparseTag(set: SparseTagSet, entity: EntityHandle, epoch: number): number {\n const present = sparseTagIndex(set, entity);\n if (present >= 0) {\n set.changed[present] = epoch;\n return present;\n }\n growSparseSlots(set, entityIndex(entity) + 1);\n if (set.size === set.dense.length) growSparseDense(set, set.size + 1);\n const denseIndex = set.size;\n set.dense[denseIndex] = entity as number;\n set.added[denseIndex] = epoch;\n set.changed[denseIndex] = epoch;\n set.sparse[entityIndex(entity)] = denseIndex;\n set.size += 1;\n return denseIndex;\n}\n\nexport function removeSparseTag(set: SparseTagSet, entity: EntityHandle): boolean {\n const denseIndex = sparseTagIndex(set, entity);\n if (denseIndex < 0) return false;\n const lastIndex = set.size - 1;\n set.sparse[entityIndex(entity)] = -1;\n if (denseIndex !== lastIndex) {\n const movedEntity = set.dense[lastIndex] as EntityHandle;\n set.dense[denseIndex] = movedEntity as number;\n set.added[denseIndex] = set.added[lastIndex] ?? 0;\n set.changed[denseIndex] = set.changed[lastIndex] ?? 0;\n set.sparse[entityIndex(movedEntity)] = denseIndex;\n }\n set.size = lastIndex;\n return true;\n}\n\nfunction growSparseSlots(set: SparseTagSet, targetCapacity: number): void {\n if (targetCapacity <= set.sparse.length) return;\n let capacity = set.sparse.length;\n while (capacity < targetCapacity) capacity *= 2;\n const sparse = new Int32Array(capacity);\n sparse.fill(-1);\n sparse.set(set.sparse);\n set.sparse = sparse;\n}\n\nfunction growSparseDense(set: SparseTagSet, targetCapacity: number): void {\n let capacity = set.dense.length;\n while (capacity < targetCapacity) capacity *= 2;\n const dense = new Uint32Array(capacity);\n dense.set(set.dense);\n set.dense = dense;\n const added = new Float64Array(capacity);\n added.set(set.added);\n set.added = added;\n const changed = new Float64Array(capacity);\n changed.set(set.changed);\n set.changed = changed;\n}\n\nexport interface ChangeTicks {\n added: number;\n changed: number;\n}\n\nexport const NEVER_CHANGED_TICK = -1;\n\nexport function createChangeTicks(tick: number): ChangeTicks {\n return { added: tick, changed: tick };\n}\n\ninterface EntityLocation {\n readonly archetypeId: number;\n readonly archetypeRow: number;\n}\n\nexport function readComponentChange(\n graph: ArchetypeGraph,\n location: EntityLocation,\n entity: EntityHandle,\n componentId: number,\n): ChangeTicks | undefined {\n const sparseSet = graph.sparseTags.get(componentId);\n if (sparseSet !== undefined) {\n const denseIndex = sparseTagIndex(sparseSet, entity);\n if (denseIndex < 0) return undefined;\n return {\n added: sparseSet.added[denseIndex] ?? 0,\n changed: sparseSet.changed[denseIndex] ?? 0,\n };\n }\n const archetype = graph.archetypes[location.archetypeId];\n if (archetype === undefined) return undefined;\n const epochs = graph.tables[archetype.tableId]?.storage.get(componentId)?.epochs;\n if (epochs === undefined) return undefined;\n const tableRow = archetype.rows[location.archetypeRow] ?? -1;\n return {\n added: epochs.added[tableRow] ?? 0,\n changed: epochs.changed[tableRow] ?? 0,\n };\n}\n\nexport function markComponentsAdded(\n graph: ArchetypeGraph,\n location: EntityLocation,\n entity: EntityHandle,\n componentIds: readonly number[],\n epoch: number,\n): void {\n const archetype = graph.archetypes[location.archetypeId];\n const table = archetype === undefined ? undefined : graph.tables[archetype.tableId];\n const tableRow = archetype?.rows[location.archetypeRow] ?? -1;\n for (const componentId of componentIds) {\n const component = archetype?.components.find(\n (candidate) => componentOwner.componentId(candidate) === componentId,\n );\n if (component?.storage === 'sparse') {\n insertSparseTag(getOrCreateSparseTagSet(graph, component), entity, epoch);\n continue;\n }\n const epochs = table?.storage.get(componentId)?.epochs;\n if (epochs === undefined) continue;\n epochs.added[tableRow] = epoch;\n epochs.changed[tableRow] = epoch;\n }\n}\n\nexport function markComponentChanged(\n graph: ArchetypeGraph,\n location: EntityLocation,\n entity: EntityHandle,\n componentId: number,\n epoch: () => number,\n): void {\n const sparseSet = graph.sparseTags.get(componentId);\n if (sparseSet !== undefined) {\n const denseIndex = sparseTagIndex(sparseSet, entity);\n if (denseIndex >= 0) sparseSet.changed[denseIndex] = epoch();\n return;\n }\n const archetype = graph.archetypes[location.archetypeId];\n if (archetype === undefined) return;\n const epochs = graph.tables[archetype.tableId]?.storage.get(componentId)?.epochs;\n if (epochs === undefined) return;\n const tableRow = archetype.rows[location.archetypeRow] ?? -1;\n epochs.changed[tableRow] = epoch();\n}\n","import { err, ok, type Result } from '@forgeax/engine-types';\nimport type { Component } from '../component';\nimport * as componentOwner from '../component';\nimport { componentId } from '../component';\nimport { Entity } from '../entity';\nimport type { EntityHandle } from '../entity-handle';\nimport {\n DerivedRangeOutOfBoundsError,\n SharedKernelFailureError,\n WorldPoisonedError,\n} from '../errors';\nimport type { Table } from '../storage/table';\nimport type { EcsError, World } from '../world';\nimport { worldInternal } from '../world-internal';\nimport type { MutableColumnShape, ReadonlyColumnShape } from './query';\n\n/** Package-internal whole-column storage owned by one dense query table. */\nexport interface DerivedColumnBinding<R extends Component, C extends Component> {\n /** Physical table identity for package-internal projection consumers. */\n readonly tableId: number;\n /** Whole entity column; every dense table carries the essential Entity row. */\n readonly entities: Readonly<Uint32Array>;\n readonly read: ReadonlyColumnShape<R>;\n readonly write: MutableColumnShape<C>;\n readonly rowCapacity: number;\n}\n\n/** Reusable identity cursor for O(1) dense-table lookup without a row facade. */\nexport interface DerivedRangeCursor {\n bindingIndex: number;\n row: number;\n}\n\nexport type DerivedRangeKernel<R extends Component, C extends Component> = (\n binding: DerivedColumnBinding<R, C>,\n base: number,\n start: number,\n count: number,\n context: unknown,\n) => void;\n\n/** Package-internal row probe used when the probe already has the derived value in scratch storage. */\nexport type DerivedRangeRowProbe<R extends Component, C extends Component> = (\n binding: DerivedColumnBinding<R, C>,\n row: number,\n context: unknown,\n) => boolean;\n\n/** Package-internal commit for a value prepared by a preceding row probe. */\nexport type DerivedRangeRowCommit<R extends Component, C extends Component> = (\n binding: DerivedColumnBinding<R, C>,\n row: number,\n context: unknown,\n) => void;\n\ninterface DerivedRangeBindingSource {\n readonly structureEpoch: () => number;\n readonly tables: () => readonly Table[];\n readonly readComponents: readonly Component[];\n readonly writeComponents: readonly Component[];\n}\n\nexport interface DerivedRangeAllocationTrace {\n subarrayCalls: number;\n shapeAllocations: number;\n closureAllocations: number;\n columnWindowAllocations: number;\n rowFacadeAllocations: number;\n proxyAllocations: number;\n rangeCacheAllocations: number;\n bindingRebuilds: number;\n}\n\nlet allocationTrace: DerivedRangeAllocationTrace | undefined;\n\nexport function beginDerivedRangeAllocationTrace(): void {\n allocationTrace = {\n subarrayCalls: 0,\n shapeAllocations: 0,\n closureAllocations: 0,\n columnWindowAllocations: 0,\n rowFacadeAllocations: 0,\n proxyAllocations: 0,\n rangeCacheAllocations: 0,\n bindingRebuilds: 0,\n };\n}\n\nexport function endDerivedRangeAllocationTrace(): DerivedRangeAllocationTrace {\n const trace = allocationTrace;\n allocationTrace = undefined;\n return (\n trace ?? {\n subarrayCalls: 0,\n shapeAllocations: 0,\n closureAllocations: 0,\n columnWindowAllocations: 0,\n rowFacadeAllocations: 0,\n proxyAllocations: 0,\n rangeCacheAllocations: 0,\n bindingRebuilds: 0,\n }\n );\n}\n\nfunction countAllocation(name: keyof DerivedRangeAllocationTrace): void {\n const trace = allocationTrace;\n if (trace !== undefined) trace[name] += 1;\n}\n\nexport interface DerivedRangeWriter<R extends Component, C extends Component> {\n readonly bindings: readonly DerivedColumnBinding<R, C>[];\n /** Locate a live entity in its bound table and return its physical row. */\n locateEntity(entity: EntityHandle, cursor: DerivedRangeCursor): boolean;\n /** Publish rows whose values were written directly into a derived column. */\n publishChangedRows(bindingIndex: number, changed: Uint8Array): Result<void, EcsError>;\n writeRange(\n bindingIndex: number,\n base: number,\n start: number,\n count: number,\n kernel: DerivedRangeKernel<R, C>,\n context: unknown,\n ): Result<void, EcsError>;\n /**\n * Probe and commit rows in one pass. The probe must only inspect the derived\n * value prepared in reusable scratch storage; the commit copies that value.\n * The writer publishes only contiguous changed runs and does not allocate in\n * the hot loop.\n */\n probeAndCommitRange(\n bindingIndex: number,\n base: number,\n start: number,\n count: number,\n probe: DerivedRangeRowProbe<R, C>,\n commit: DerivedRangeRowCommit<R, C>,\n context: unknown,\n ): Result<void, EcsError>;\n}\n\nexport function createDerivedRangeWriter<R extends Component, C extends Component>(\n world: World,\n component: C,\n source: DerivedRangeBindingSource,\n): DerivedRangeWriter<R, C> {\n let boundEpoch = -1;\n let bindingTables: readonly Table[] = [];\n let bindings: readonly DerivedColumnBinding<R, C>[] = [];\n let bindingByTable = new Map<number, number>();\n let runStartBuffers: readonly Int32Array[] = [];\n let runCountBuffers: readonly Int32Array[] = [];\n\n const rebind = (): void => {\n countAllocation('bindingRebuilds');\n const tables = source.tables();\n const nextBindings: DerivedColumnBinding<R, C>[] = [];\n const nextRunStartBuffers: Int32Array[] = [];\n const nextRunCountBuffers: Int32Array[] = [];\n for (const table of tables) {\n nextBindings.push({\n tableId: table.id,\n entities: (table.storage.get(componentId(Entity))?.fields.get('self')?.view ??\n new Uint32Array(0)) as Uint32Array,\n read: buildWholeColumnShape(table, source.readComponents) as ReadonlyColumnShape<R>,\n write: buildWholeColumnShape(table, source.writeComponents) as MutableColumnShape<C>,\n rowCapacity: table.size,\n });\n // A table with N rows can contain at most N changed runs. These buffers\n // are owned by the structural rebind and reused by every hot call.\n const runCapacity = Math.max(1, table.size);\n nextRunStartBuffers.push(new Int32Array(runCapacity));\n nextRunCountBuffers.push(new Int32Array(runCapacity));\n }\n bindingTables = tables;\n bindings = nextBindings;\n bindingByTable = new Map<number, number>();\n for (let index = 0; index < nextBindings.length; index += 1) {\n const binding = nextBindings[index];\n if (binding !== undefined) bindingByTable.set(binding.tableId, index);\n }\n runStartBuffers = nextRunStartBuffers;\n runCountBuffers = nextRunCountBuffers;\n boundEpoch = source.structureEpoch();\n };\n\n rebind();\n\n const writer: DerivedRangeWriter<R, C> = {\n get bindings() {\n if (boundEpoch !== source.structureEpoch()) rebind();\n return bindings;\n },\n locateEntity(entity, cursor) {\n if (world.execution.health === 'poisoned') return false;\n if (boundEpoch !== source.structureEpoch()) rebind();\n const archetype = world[worldInternal].getEntityArchetype(entity);\n if (archetype === undefined) return false;\n const bindingIndex = bindingByTable.get(archetype.tableId);\n if (bindingIndex === undefined) return false;\n const record = world[worldInternal].getRecords()[(entity as unknown as number) & 0x00ffffff];\n if (record === undefined || record.archetypeId !== archetype.id) return false;\n const row = archetype.rows[record.archetypeRow];\n const binding = bindings[bindingIndex];\n if (binding === undefined || row === undefined || row < 0 || row >= binding.rowCapacity) {\n return false;\n }\n cursor.bindingIndex = bindingIndex;\n cursor.row = row;\n return true;\n },\n publishChangedRows(bindingIndex, changed) {\n if (world.execution.health === 'poisoned') {\n return err(new WorldPoisonedError(world.identity, world.execution.fault));\n }\n if (boundEpoch !== source.structureEpoch()) rebind();\n const binding = bindings[bindingIndex];\n const table = bindingTables[bindingIndex];\n const runStarts = runStartBuffers[bindingIndex];\n const runCounts = runCountBuffers[bindingIndex];\n if (\n binding === undefined ||\n table === undefined ||\n runStarts === undefined ||\n runCounts === undefined ||\n !Number.isSafeInteger(bindingIndex) ||\n bindingIndex < 0 ||\n changed.length < binding.rowCapacity ||\n table.storage.get(componentOwner.componentId(component)) === undefined\n ) {\n return err(new DerivedRangeOutOfBoundsError(0, changed.length, binding?.rowCapacity ?? 0));\n }\n let runCount = 0;\n let runStart = -1;\n for (let row = 0; row < binding.rowCapacity; row += 1) {\n if ((changed[row] ?? 0) !== 0) {\n if (runStart < 0) runStart = row;\n } else if (runStart >= 0) {\n runStarts[runCount] = runStart;\n runCounts[runCount] = row - runStart;\n runCount += 1;\n runStart = -1;\n }\n }\n if (runStart >= 0) {\n runStarts[runCount] = runStart;\n runCounts[runCount] = binding.rowCapacity - runStart;\n runCount += 1;\n }\n if (runCount === 0) return ok(undefined);\n const previousEpoch = world[worldInternal].getMutationEpoch();\n let epoch: number;\n try {\n epoch = world[worldInternal].nextMutationEpoch();\n const componentIdentifier = componentOwner.componentId(component);\n for (let index = 0; index < runCount; index += 1) {\n world[worldInternal].publishDerivedRange(\n table,\n componentIdentifier,\n runStarts[index] ?? 0,\n runCounts[index] ?? 0,\n epoch,\n );\n }\n changed.fill(0, 0, binding.rowCapacity);\n return ok(undefined);\n } catch (cause) {\n world[worldInternal].restoreMutationEpoch(previousEpoch);\n world[worldInternal].poisonExecution({\n code: 'shared-kernel-failed',\n kernelName: `derived-range:${component.name}:publish`,\n cause,\n partialWrite: true,\n retryable: false,\n });\n return err(new SharedKernelFailureError(component.name, world.identity, cause, true));\n }\n },\n writeRange(bindingIndex, base, start, count, kernel, context) {\n if (world.execution.health === 'poisoned') {\n return err(new WorldPoisonedError(world.identity, world.execution.fault));\n }\n if (boundEpoch !== source.structureEpoch()) rebind();\n const binding = bindings[bindingIndex];\n const table = bindingTables[bindingIndex];\n if (\n binding === undefined ||\n table === undefined ||\n !Number.isSafeInteger(bindingIndex) ||\n !Number.isSafeInteger(base) ||\n !Number.isSafeInteger(start) ||\n !Number.isSafeInteger(count) ||\n bindingIndex < 0 ||\n base < 0 ||\n start < 0 ||\n count < 0 ||\n base + start + count > binding.rowCapacity ||\n table.storage.get(componentOwner.componentId(component)) === undefined\n ) {\n return err(new DerivedRangeOutOfBoundsError(start, count, binding?.rowCapacity ?? 0));\n }\n if (count === 0) return ok(undefined);\n\n const previousEpoch = world[worldInternal].getMutationEpoch();\n let epoch: number;\n try {\n epoch = world[worldInternal].nextMutationEpoch();\n } catch (cause) {\n return err(cause as EcsError);\n }\n try {\n kernel(binding, base, start, count, context);\n world[worldInternal].publishDerivedRange(\n table,\n componentOwner.componentId(component),\n base + start,\n count,\n epoch,\n );\n return ok(undefined);\n } catch (cause) {\n world[worldInternal].restoreMutationEpoch(previousEpoch);\n world[worldInternal].poisonExecution({\n code: 'shared-kernel-failed',\n kernelName: `derived-range:${component.name}`,\n cause,\n partialWrite: true,\n retryable: false,\n });\n return err(new SharedKernelFailureError(component.name, world.identity, cause, true));\n }\n },\n probeAndCommitRange(bindingIndex, base, start, count, probe, commit, context) {\n if (world.execution.health === 'poisoned') {\n return err(new WorldPoisonedError(world.identity, world.execution.fault));\n }\n if (boundEpoch !== source.structureEpoch()) rebind();\n const binding = bindings[bindingIndex];\n const table = bindingTables[bindingIndex];\n const runStarts = runStartBuffers[bindingIndex];\n const runCounts = runCountBuffers[bindingIndex];\n if (\n binding === undefined ||\n table === undefined ||\n runStarts === undefined ||\n runCounts === undefined ||\n !Number.isSafeInteger(bindingIndex) ||\n !Number.isSafeInteger(base) ||\n !Number.isSafeInteger(start) ||\n !Number.isSafeInteger(count) ||\n bindingIndex < 0 ||\n base < 0 ||\n start < 0 ||\n count < 0 ||\n base + start + count > binding.rowCapacity ||\n table.storage.get(componentOwner.componentId(component)) === undefined\n ) {\n return err(new DerivedRangeOutOfBoundsError(start, count, binding?.rowCapacity ?? 0));\n }\n if (count === 0) return ok(undefined);\n\n const previousEpoch = world[worldInternal].getMutationEpoch();\n let runCount = 0;\n let epoch = 0;\n let epochReserved = false;\n let runStart = -1;\n try {\n for (let offset = 0; offset < count; offset += 1) {\n const row = base + start + offset;\n const changed = probe(binding, row, context);\n if (changed) {\n if (!epochReserved) {\n try {\n epoch = world[worldInternal].nextMutationEpoch();\n epochReserved = true;\n } catch (cause) {\n // Nothing has been committed yet. Keep the World healthy and\n // preserve the source error so the caller can retry unchanged.\n return err(cause as EcsError);\n }\n }\n if (runStart < 0) runStart = row;\n commit(binding, row, context);\n } else if (runStart >= 0) {\n runStarts[runCount] = runStart;\n runCounts[runCount] = row - runStart;\n runCount += 1;\n runStart = -1;\n }\n }\n if (runStart >= 0) {\n runStarts[runCount] = runStart;\n runCounts[runCount] = base + start + count - runStart;\n runCount += 1;\n }\n\n // Every changed run in this call shares the epoch reserved immediately\n // before the first commit. Publication remains deferred until the\n // complete probe/commit pass has succeeded.\n if (runCount > 0) {\n const componentIdentifier = componentOwner.componentId(component);\n for (let index = 0; index < runCount; index += 1) {\n const runStartValue = runStarts[index] ?? 0;\n const runLength = runCounts[index] ?? 0;\n world[worldInternal].publishDerivedRange(\n table,\n componentIdentifier,\n runStartValue,\n runLength,\n epoch,\n );\n }\n }\n return ok(undefined);\n } catch (cause) {\n if (epochReserved) world[worldInternal].restoreMutationEpoch(previousEpoch);\n world[worldInternal].poisonExecution({\n code: 'shared-kernel-failed',\n kernelName: `derived-range:${component.name}:probe`,\n cause,\n partialWrite: true,\n retryable: false,\n });\n return err(new SharedKernelFailureError(component.name, world.identity, cause, true));\n }\n },\n };\n return writer;\n}\n\nfunction buildWholeColumnShape(\n table: Table,\n components: readonly Component[],\n): Record<string, unknown> {\n countAllocation('shapeAllocations');\n const shape: Record<string, unknown> = {};\n for (const component of components) {\n const fields = table.storage.get(componentOwner.componentId(component))?.fields;\n if (fields === undefined) continue;\n for (const [fieldName, column] of fields) shape[fieldName] = column.view;\n }\n return shape;\n}\n","import { err, ok, type Result } from '@forgeax/engine-types';\nimport {\n type Component,\n type ComponentId,\n type ComponentSchema,\n componentId,\n componentSchema,\n isManagedField,\n type ShapeOf,\n type TypedArrayFor,\n} from '../component';\nimport { Disabled, Entity } from '../entity';\nimport type { EntityHandle } from '../entity-handle';\nimport {\n QueryDataRequiresFieldsError,\n QueryDescriptorConflictError,\n QueryIterationActiveError,\n QueryIterationInvalidatedError,\n QuerySpanUnavailableError,\n type QuerySpanUnavailableReason,\n RelationshipTargetReadonlyError,\n} from '../errors';\nimport { DERIVED_WRITER } from '../internal';\nimport { isRelationshipTarget, relationshipRole } from '../relationship-index';\nimport type { Archetype, ArchetypeId } from '../storage/archetype';\nimport type { ArchetypeGraph } from '../storage/archetype-graph';\nimport { sparseTagIndex } from '../storage/change-detection';\nimport type { FieldView, ManagedColumnReader } from '../storage/column';\nimport type { Table } from '../storage/table';\nimport { type WorldInternal, worldInternal } from '../world-internal';\nimport { createDerivedRangeWriter, type DerivedRangeWriter } from './derived-range-writer';\n\nexport interface QueryDescriptor<\n R extends readonly Component[] = readonly Component[],\n W extends readonly Component[] = readonly Component[],\n O extends readonly Component[] = readonly Component[],\n> {\n readonly read?: R;\n readonly write?: W;\n readonly optional?: O;\n readonly with?: readonly Component[];\n readonly without?: readonly Component[];\n readonly changed?: readonly Component[];\n readonly added?: readonly Component[];\n}\n\nexport type ReadonlyRowShape<C> =\n C extends Component<string, infer S> ? Readonly<ShapeOf<S>> : never;\nexport type MutableRowShape<C> =\n C extends Component<string, infer S>\n ? { -readonly [K in keyof ShapeOf<S>]: ShapeOf<S>[K] }\n : never;\n\ntype ColumnShapeForSchema<S extends ComponentSchema> = {\n [K in keyof S]: TypedArrayFor<S[K]>;\n};\n\nexport type ReadonlyColumnShape<C> =\n C extends Component<string, infer S> ? Readonly<ColumnShapeForSchema<S>> : never;\nexport type MutableColumnShape<C> =\n C extends Component<string, infer S>\n ? { -readonly [K in keyof ColumnShapeForSchema<S>]: ColumnShapeForSchema<S>[K] }\n : never;\n\nexport interface QueryRow<\n R extends readonly Component[] = readonly Component[],\n W extends readonly Component[] = readonly Component[],\n O extends readonly Component[] = readonly Component[],\n> {\n readonly entity: EntityHandle;\n /** Test component presence without materialising its row object. */\n has(component: R[number] | W[number] | O[number]): boolean;\n get<C extends R[number]>(component: C): ReadonlyRowShape<C>;\n get<C extends O[number]>(component: C): ReadonlyRowShape<C> | undefined;\n mut<C extends W[number]>(component: C): MutableRowShape<C>;\n}\n\nexport interface QuerySpan<\n R extends readonly Component[] = readonly Component[],\n W extends readonly Component[] = readonly Component[],\n> {\n /** Packed entity identities for this contiguous table range. */\n readonly entities: Readonly<Uint32Array>;\n readonly length: number;\n get<C extends R[number]>(component: C): ReadonlyColumnShape<C>;\n mut<C extends W[number]>(component: C): MutableColumnShape<C>;\n}\n\nexport interface Query<\n R extends readonly Component[] = readonly Component[],\n W extends readonly Component[] = readonly Component[],\n O extends readonly Component[] = readonly Component[],\n> extends Iterable<QueryRow<R, W, O>> {\n /**\n * Read one known entity without iterating the query's matching tables.\n * Structural descriptor constraints are applied; temporal `changed` and\n * `added` filters are intentionally not evaluated because this is an\n * identity-addressed read, not a version scan.\n */\n at(entity: EntityHandle): QueryRow<R, W, O> | undefined;\n spans(): Result<Iterable<QuerySpan<R, W>>, QuerySpanUnavailableError>;\n combinations(k?: number): Iterable<readonly QueryRow<R, W, O>[]>;\n}\n\nexport type QueryCreationError = QueryDescriptorConflictError | QueryDataRequiresFieldsError;\n\ninterface WorldQueryAccess {\n readonly [worldInternal]: WorldInternal;\n}\n\ninterface CompiledDescriptor<\n R extends readonly Component[],\n W extends readonly Component[],\n O extends readonly Component[],\n> {\n readonly descriptor: QueryDescriptor<R, W, O>;\n readonly requiredIds: readonly ComponentId[];\n readonly withoutIds: readonly ComponentId[];\n readonly changedIds: readonly ComponentId[];\n readonly addedIds: readonly ComponentId[];\n readonly sparseRoute: boolean;\n}\n\ntype Role = 'read' | 'write' | 'optional' | 'with' | 'without';\n\nfunction compileDescriptor<\n const R extends readonly Component[],\n const W extends readonly Component[],\n const O extends readonly Component[],\n>(descriptor: QueryDescriptor<R, W, O>): Result<CompiledDescriptor<R, W, O>, QueryCreationError> {\n const read = descriptor.read ?? ([] as unknown as R);\n const write = descriptor.write ?? ([] as unknown as W);\n const optional = descriptor.optional ?? ([] as unknown as O);\n const withComponents = descriptor.with ?? [];\n const withoutComponents = [...(descriptor.without ?? [])];\n const roles = new Map<Component, Role[]>();\n const addRole = (component: Component, role: Role): void => {\n const current = roles.get(component);\n if (current === undefined) roles.set(component, [role]);\n else current.push(role);\n };\n for (const component of read) addRole(component, 'read');\n for (const component of write) addRole(component, 'write');\n for (const component of optional) addRole(component, 'optional');\n for (const component of withComponents) addRole(component, 'with');\n for (const component of withoutComponents) addRole(component, 'without');\n\n for (const [component, componentRoles] of roles) {\n if (componentRoles.length > 1) {\n return err(new QueryDescriptorConflictError(component.name, componentRoles));\n }\n }\n for (const component of [...read, ...write, ...optional]) {\n if (Object.keys(componentSchema(component)).length === 0) {\n return err(new QueryDataRequiresFieldsError(component.name));\n }\n }\n\n const required = [\n ...read,\n ...write,\n ...withComponents,\n ...(descriptor.changed ?? []),\n ...(descriptor.added ?? []),\n ];\n const requiredIds = [...new Set(required.map((component) => componentId(component)))];\n const withoutIds = [...new Set(withoutComponents.map((component) => componentId(component)))];\n if (!requiredIds.includes(componentId(Disabled)) && !withoutIds.includes(componentId(Disabled))) {\n withoutIds.push(componentId(Disabled));\n }\n return ok({\n descriptor,\n requiredIds,\n withoutIds,\n changedIds: [...new Set((descriptor.changed ?? []).map((component) => componentId(component)))],\n addedIds: [...new Set((descriptor.added ?? []).map((component) => componentId(component)))],\n sparseRoute: [\n ...required,\n ...withoutComponents,\n ...(descriptor.changed ?? []),\n ...(descriptor.added ?? []),\n ].some((component) => component.storage === 'sparse'),\n });\n}\n\nclass QueryRowFacade<\n R extends readonly Component[],\n W extends readonly Component[],\n O extends readonly Component[],\n> implements QueryRow<R, W, O>\n{\n entity = 0 as EntityHandle;\n private archetype: Archetype | undefined;\n\n constructor(private readonly world: WorldQueryAccess) {}\n\n bind(entity: EntityHandle, archetype: Archetype): this {\n this.entity = entity;\n this.archetype = archetype;\n return this;\n }\n\n snapshot(): QueryRowFacade<R, W, O> {\n if (this.archetype === undefined) throw new Error('Query row is not bound.');\n return new QueryRowFacade<R, W, O>(this.world).bind(this.entity, this.archetype);\n }\n\n has(component: R[number] | W[number] | O[number]): boolean {\n return (\n this.archetype?.components.some(\n (candidate) => componentId(candidate) === componentId(component),\n ) === true\n );\n }\n\n get<C extends R[number]>(component: C): ReadonlyRowShape<C>;\n get<C extends O[number]>(component: C): ReadonlyRowShape<C> | undefined;\n get(component: Component): Record<string, unknown> | undefined {\n if (\n !this.archetype?.components.some(\n (candidate) => componentId(candidate) === componentId(component),\n )\n ) {\n return undefined;\n }\n const result = this.world[worldInternal].getQueryRow(this.entity, component);\n if (!result.ok) throw result.error;\n return result.value;\n }\n\n mut<C extends W[number]>(component: C): MutableRowShape<C> {\n const current = this.get(component);\n if (current === undefined) throw new Error(`Query row lacks ${component.name}.`);\n if (isRelationshipTarget(component)) {\n throw new RelationshipTargetReadonlyError(component.name, 'query row');\n }\n // Relationship sources must let the owner validate before recording\n // authored evidence. A stale/cyclic target therefore has zero mutation\n // side effects, while ordinary components retain the existing eager\n // `mut()` evidence semantics.\n const relationshipSource = relationshipRole(component)?.kind === 'source';\n if (!relationshipSource) {\n this.world[worldInternal].markComponentChanged(this.entity, componentId(component));\n }\n return new Proxy(current, {\n set: (target, property, value) => {\n if (typeof property !== 'string') return false;\n const result = this.world[worldInternal].setQueryRow(this.entity, component, {\n [property]: value,\n });\n if (!result.ok) throw result.error;\n (target as Record<string, unknown>)[property] = value;\n return true;\n },\n }) as MutableRowShape<C>;\n }\n}\n\nclass QuerySpanFacade<R extends readonly Component[], W extends readonly Component[]>\n implements QuerySpan<R, W>\n{\n readonly entities: Readonly<Uint32Array>;\n\n constructor(\n private readonly world: WorldQueryAccess,\n private readonly table: Table,\n private readonly rowStart: number,\n readonly length: number,\n ) {\n const entityColumn = table.storage.get(componentId(Entity))?.fields.get('self');\n this.entities = (\n entityColumn === undefined\n ? new Uint32Array(0)\n : rowStart === 0 && length === entityColumn.view.length\n ? entityColumn.view\n : entityColumn.view.subarray(rowStart, rowStart + length)\n ) as Readonly<Uint32Array>;\n }\n\n get<C extends R[number]>(component: C): ReadonlyColumnShape<C> {\n return buildColumnShape(\n this.table,\n component,\n this.rowStart,\n this.length,\n ) as ReadonlyColumnShape<C>;\n }\n\n mut<C extends W[number]>(component: C): MutableColumnShape<C> {\n // A span exposes live column storage. Relationship source and target\n // columns must never obtain that raw write capability: source writes need\n // target-side maintenance and target writes are engine-owned projections.\n if (relationshipRole(component) !== undefined) {\n throw new RelationshipTargetReadonlyError(component.name, 'query span');\n }\n this.world[worldInternal].markComponentRangeChanged(\n this.table,\n componentId(component),\n this.rowStart,\n this.length,\n );\n return buildColumnShape(\n this.table,\n component,\n this.rowStart,\n this.length,\n ) as MutableColumnShape<C>;\n }\n}\n\nfunction makeManagedColumnReader(\n view: FieldView,\n length: number,\n fieldType: string,\n): ManagedColumnReader<string> {\n const slots = view.length === length ? view : view.subarray(0, length);\n return Object.freeze({\n length,\n get(i: number): number {\n return slots[i] ?? 0;\n },\n __managed: fieldType,\n });\n}\n\nfunction buildColumnShape(\n table: Table,\n component: Component,\n rowStart: number,\n rowCount: number,\n): Record<string, FieldView | ManagedColumnReader<string>> {\n const shape: Record<string, FieldView | ManagedColumnReader<string>> = {};\n const fields = table.storage.get(componentId(component))?.fields;\n if (fields === undefined) return shape;\n for (const [fieldName, column] of fields) {\n const start = rowStart * column.arity;\n const end = start + rowCount * column.arity;\n const view =\n start === 0 && end === column.view.length ? column.view : column.view.subarray(start, end);\n const fieldType = componentSchema(component)[fieldName];\n shape[fieldName] =\n fieldType !== undefined && isManagedField(fieldType)\n ? makeManagedColumnReader(view, view.length, fieldType)\n : view;\n }\n return shape;\n}\n\nclass ExecutableQuery<\n R extends readonly Component[],\n W extends readonly Component[],\n O extends readonly Component[],\n> implements Query<R, W, O>\n{\n private matchedArchetypes: ArchetypeId[] = [];\n private matchedTables: number[] = [];\n private matchedTableObjects: Table[] = [];\n private lastGraphGeneration = -1;\n private lastObservedEpoch = 0;\n private active = false;\n\n constructor(\n private readonly world: WorldQueryAccess,\n private readonly compiled: CompiledDescriptor<R, W, O>,\n ) {}\n\n [Symbol.iterator](): Iterator<QueryRow<R, W, O>> {\n this.beginIteration();\n this.refreshMatches();\n const structureEpoch = this.world[worldInternal].getStructureEpoch();\n const upperBound = this.world[worldInternal].getMutationEpoch();\n const row = new QueryRowFacade<R, W, O>(this.world);\n let archetypeIndex = 0;\n let tableIndex = 0;\n let rowIndex = 0;\n let finished = false;\n\n const close = (commit: boolean): void => {\n if (finished) return;\n finished = true;\n this.active = false;\n if (commit) this.lastObservedEpoch = upperBound;\n };\n\n return {\n next: (): IteratorResult<QueryRow<R, W, O>> => {\n if (finished) return { done: true, value: undefined };\n if (this.world[worldInternal].getStructureEpoch() !== structureEpoch) {\n close(false);\n throw new QueryIterationInvalidatedError(\n structureEpoch,\n this.world[worldInternal].getStructureEpoch(),\n );\n }\n if (!this.compiled.sparseRoute) {\n while (tableIndex < this.matchedTables.length) {\n const table =\n this.world[worldInternal].getGraph().tables[this.matchedTables[tableIndex] ?? -1];\n if (table === undefined || rowIndex >= table.size) {\n tableIndex += 1;\n rowIndex = 0;\n continue;\n }\n const currentTableRow = rowIndex++;\n const entityColumn = table.storage.get(componentId(Entity))?.fields.get('self');\n if (entityColumn === undefined) continue;\n const entity = (entityColumn.view[currentTableRow] ?? 0) as EntityHandle;\n if (!this.changeMatches(entity, table, currentTableRow, upperBound)) continue;\n const recordArchetype = this.world[worldInternal].getEntityArchetype(entity);\n if (recordArchetype === undefined) continue;\n return { done: false, value: row.bind(entity, recordArchetype) };\n }\n close(true);\n return { done: true, value: undefined };\n }\n while (archetypeIndex < this.matchedArchetypes.length) {\n const archetype =\n this.world[worldInternal].getGraph().archetypes[\n this.matchedArchetypes[archetypeIndex] ?? -1\n ];\n if (archetype === undefined || rowIndex >= archetype.size) {\n archetypeIndex += 1;\n rowIndex = 0;\n continue;\n }\n const currentArchetypeRow = rowIndex++;\n const currentTableRow = archetype.rows[currentArchetypeRow] ?? 0;\n const table = this.world[worldInternal].getGraph().tables[archetype.tableId];\n if (table === undefined) continue;\n const entityColumn = table.storage.get(componentId(Entity))?.fields.get('self');\n if (entityColumn === undefined) continue;\n const entity = (entityColumn.view[currentTableRow] ?? 0) as EntityHandle;\n if (!this.changeMatches(entity, table, currentTableRow, upperBound)) continue;\n return { done: false, value: row.bind(entity, archetype) };\n }\n close(true);\n return { done: true, value: undefined };\n },\n return: (): IteratorResult<QueryRow<R, W, O>> => {\n close(false);\n return { done: true, value: undefined };\n },\n };\n }\n\n at(entity: EntityHandle): QueryRow<R, W, O> | undefined {\n const archetype = this.world[worldInternal].getEntityArchetype(entity);\n if (archetype === undefined || !this.archetypeMatches(archetype)) return undefined;\n return new QueryRowFacade<R, W, O>(this.world).bind(entity, archetype).snapshot();\n }\n\n spans(): Result<Iterable<QuerySpan<R, W>>, QuerySpanUnavailableError> {\n const reason = this.spanUnavailableReason();\n if (reason !== undefined) return err(new QuerySpanUnavailableError(reason));\n const query = this;\n return ok({\n [Symbol.iterator](): Iterator<QuerySpan<R, W>> {\n query.beginIteration();\n query.refreshMatches();\n const structureEpoch = query.world[worldInternal].getStructureEpoch();\n const upperBound = query.world[worldInternal].getMutationEpoch();\n let tableIndex = 0;\n let rowIndex = 0;\n let finished = false;\n const close = (commit: boolean): void => {\n if (finished) return;\n finished = true;\n query.active = false;\n if (commit) query.lastObservedEpoch = upperBound;\n };\n return {\n next(): IteratorResult<QuerySpan<R, W>> {\n if (finished) return { done: true, value: undefined };\n if (query.world[worldInternal].getStructureEpoch() !== structureEpoch) {\n close(false);\n throw new QueryIterationInvalidatedError(\n structureEpoch,\n query.world[worldInternal].getStructureEpoch(),\n );\n }\n while (tableIndex < query.matchedTables.length) {\n const table =\n query.world[worldInternal].getGraph().tables[query.matchedTables[tableIndex] ?? -1];\n if (table === undefined || table.size === 0) {\n tableIndex += 1;\n rowIndex = 0;\n continue;\n }\n if (query.compiled.changedIds.length === 0 && query.compiled.addedIds.length === 0) {\n tableIndex += 1;\n rowIndex = 0;\n return {\n done: false,\n value: new QuerySpanFacade<R, W>(query.world, table, 0, table.size),\n };\n }\n while (\n rowIndex < table.size &&\n !query.denseChangeMatches(table, rowIndex, upperBound)\n ) {\n rowIndex += 1;\n }\n if (rowIndex >= table.size) {\n tableIndex += 1;\n rowIndex = 0;\n continue;\n }\n const start = rowIndex;\n rowIndex += 1;\n while (\n rowIndex < table.size &&\n query.denseChangeMatches(table, rowIndex, upperBound)\n ) {\n rowIndex += 1;\n }\n return {\n done: false,\n value: new QuerySpanFacade<R, W>(query.world, table, start, rowIndex - start),\n };\n }\n close(true);\n return { done: true, value: undefined };\n },\n return(): IteratorResult<QuerySpan<R, W>> {\n close(false);\n return { done: true, value: undefined };\n },\n };\n },\n });\n }\n\n [DERIVED_WRITER]<C extends W[number]>(\n component: C,\n ): Result<DerivedRangeWriter<R[number], C>, QuerySpanUnavailableError> {\n const reason = this.spanUnavailableReason();\n if (reason !== undefined) return err(new QuerySpanUnavailableError(reason));\n return ok(\n createDerivedRangeWriter<R[number], C>(\n this.world as unknown as import('../world').World,\n component,\n {\n structureEpoch: () => this.world[worldInternal].getStructureEpoch(),\n tables: () => {\n this.refreshMatches();\n return this.matchedTableObjects;\n },\n readComponents: this.compiled.descriptor.read ?? [],\n writeComponents: this.compiled.descriptor.write ?? [],\n },\n ),\n );\n }\n\n combinations(k = 2): Iterable<readonly QueryRow<R, W, O>[]> {\n const query = this;\n return {\n *[Symbol.iterator](): Iterator<readonly QueryRow<R, W, O>[]> {\n if (!Number.isInteger(k) || k < 1) return;\n const previousObservedEpoch = query.lastObservedEpoch;\n const structureEpoch = query.world[worldInternal].getStructureEpoch();\n const rows: QueryRow<R, W, O>[] = [];\n for (const row of query) {\n rows.push((row as QueryRowFacade<R, W, O>).snapshot());\n }\n query.active = true;\n let completed = false;\n try {\n if (k <= rows.length) {\n const indices = Array.from({ length: k }, (_, index) => index);\n while (true) {\n if (query.world[worldInternal].getStructureEpoch() !== structureEpoch) {\n throw new QueryIterationInvalidatedError(\n structureEpoch,\n query.world[worldInternal].getStructureEpoch(),\n );\n }\n yield indices.map((index) => rows[index] as QueryRow<R, W, O>);\n let pivot = k - 1;\n while (pivot >= 0 && (indices[pivot] ?? 0) === rows.length - k + pivot) pivot -= 1;\n if (pivot < 0) break;\n indices[pivot] = (indices[pivot] ?? 0) + 1;\n for (let index = pivot + 1; index < k; index++) {\n indices[index] = (indices[index - 1] ?? 0) + 1;\n }\n }\n }\n completed = true;\n } finally {\n query.active = false;\n if (!completed) query.lastObservedEpoch = previousObservedEpoch;\n }\n },\n };\n }\n\n private beginIteration(): void {\n if (this.active) throw new QueryIterationActiveError();\n this.active = true;\n }\n\n private refreshMatches(): void {\n const graph = this.world[worldInternal].getGraph() as ArchetypeGraph;\n if (this.lastGraphGeneration === graph.generation) return;\n this.matchedArchetypes = graph.archetypes\n .filter((archetype) => this.archetypeMatches(archetype))\n .map((archetype) => archetype.id);\n this.matchedTables = graph.tables\n .filter((table) => this.tableMatches(table))\n .map((table) => table.id);\n this.matchedTableObjects = this.matchedTables.flatMap((id) => {\n const table = graph.tables[id];\n return table === undefined ? [] : [table];\n });\n this.lastGraphGeneration = graph.generation;\n }\n\n private archetypeMatches(archetype: Archetype): boolean {\n for (const requiredId of this.compiled.requiredIds) {\n if (!archetype.components.some((component) => componentId(component) === requiredId))\n return false;\n }\n for (const excludedId of this.compiled.withoutIds) {\n if (archetype.components.some((component) => componentId(component) === excludedId))\n return false;\n }\n return true;\n }\n\n private tableMatches(table: Table): boolean {\n for (const componentId of this.compiled.requiredIds) {\n if (!table.storage.has(componentId)) return false;\n }\n for (const componentId of this.compiled.withoutIds) {\n if (table.storage.has(componentId)) return false;\n }\n return true;\n }\n\n private changeMatches(\n entity: EntityHandle,\n table: Table,\n row: number,\n upperBound: number,\n ): boolean {\n const graph = this.world[worldInternal].getGraph();\n for (const componentId of this.compiled.changedIds) {\n const sparseSet = graph.sparseTags.get(componentId);\n const denseIndex = sparseSet === undefined ? -1 : sparseTagIndex(sparseSet, entity);\n const epoch =\n denseIndex >= 0\n ? (sparseSet?.changed[denseIndex] ?? 0)\n : (table.storage.get(componentId)?.epochs.changed[row] ?? 0);\n if (epoch <= this.lastObservedEpoch || epoch > upperBound) return false;\n }\n for (const componentId of this.compiled.addedIds) {\n const sparseSet = graph.sparseTags.get(componentId);\n const denseIndex = sparseSet === undefined ? -1 : sparseTagIndex(sparseSet, entity);\n const epoch =\n denseIndex >= 0\n ? (sparseSet?.added[denseIndex] ?? 0)\n : (table.storage.get(componentId)?.epochs.added[row] ?? 0);\n if (epoch <= this.lastObservedEpoch || epoch > upperBound) return false;\n }\n return true;\n }\n\n private denseChangeMatches(table: Table, row: number, upperBound: number): boolean {\n for (const componentId of this.compiled.changedIds) {\n const epoch = table.storage.get(componentId)?.epochs.changed[row] ?? 0;\n if (epoch <= this.lastObservedEpoch || epoch > upperBound) return false;\n }\n for (const componentId of this.compiled.addedIds) {\n const epoch = table.storage.get(componentId)?.epochs.added[row] ?? 0;\n if (epoch <= this.lastObservedEpoch || epoch > upperBound) return false;\n }\n return true;\n }\n\n private spanUnavailableReason(): QuerySpanUnavailableReason | undefined {\n if (this.compiled.sparseRoute) return 'sparse-component';\n if ((this.compiled.descriptor.optional?.length ?? 0) > 0) return 'optional-data';\n // A writable relationship source would bypass the source owner (and its\n // materialized target/backpointer), while a target is an ECS-owned\n // projection. Keep read-only relationship inputs usable by Scene's\n // derived writer; only the descriptor's writable role is ineligible.\n if ((this.compiled.descriptor.write ?? []).some((component) => relationshipRole(component))) {\n return 'relationship-component';\n }\n return undefined;\n }\n}\n\nexport function createQuery<\n const R extends readonly Component[] = readonly [],\n const W extends readonly Component[] = readonly [],\n const O extends readonly Component[] = readonly [],\n>(\n world: WorldQueryAccess,\n descriptor: QueryDescriptor<R, W, O>,\n): Result<Query<R, W, O>, QueryCreationError> {\n const compiled = compileDescriptor(descriptor);\n if (!compiled.ok) return compiled;\n return ok(new ExecutableQuery(world, compiled.value));\n}\n","// @forgeax/engine-ecs — Resource store: typed key-value global singletons.\n//\n// Map<string, unknown> backend. insertResource is idempotent (overwrites).\n// getResource throws ResourceNotFoundError if key absent.\n\nimport { ResourceNotFoundError } from './errors';\n\n// ────────────────────────────────────────────────────────────────────────────\n// ResourceStore\n// ────────────────────────────────────────────────────────────────────────────\n\n/** Internal resource storage. */\nexport interface ResourceEntry {\n value: unknown;\n added: number;\n changed: number;\n}\n\nexport interface ResourceStore {\n readonly entries: Map<string, ResourceEntry>;\n}\n\n/** Create a fresh resource store. */\nexport function createResourceStore(): ResourceStore {\n return { entries: new Map() };\n}\n\n/**\n * Insert or overwrite a resource (idempotent, E-13).\n *\n * @example\n * ```ts\n * import { createResourceStore, insertResource, type ResourceStore } from './resource';\n *\n * const store: ResourceStore = createResourceStore();\n * insertResource(store, 'health', 100);\n * // overwriting is idempotent (no error / no duplicate slot):\n * insertResource(store, 'health', 95);\n * ```\n */\nexport function insertResource<T>(store: ResourceStore, key: string, value: T, epoch = 0): void {\n const current = store.entries.get(key);\n if (current === undefined) {\n store.entries.set(key, { value, added: epoch, changed: epoch });\n } else {\n current.value = value;\n current.changed = epoch;\n }\n}\n\n/**\n * Get a resource by key.\n * @throws ResourceNotFoundError if key does not exist (E-14).\n *\n * @example\n * ```ts\n * import { getResource, insertResource, type ResourceStore } from './resource';\n *\n * declare const store: ResourceStore;\n * insertResource(store, 'health', 100);\n * const hp = getResource<number>(store, 'health');\n * // hp === 100; throws ResourceNotFoundError on missing key (charter proposition 4)\n * ```\n */\nexport function getResource<T>(store: ResourceStore, key: string): T {\n const entry = store.entries.get(key);\n if (entry === undefined) {\n throw new ResourceNotFoundError(key);\n }\n return entry.value as T;\n}\n\n/**\n * Check if a resource exists.\n *\n * @example\n * ```ts\n * import { hasResource, insertResource, type ResourceStore } from './resource';\n *\n * declare const store: ResourceStore;\n * insertResource(store, 'health', 100);\n * if (hasResource(store, 'health')) {\n * // guarded access avoids ResourceNotFoundError from getResource\n * }\n * ```\n */\nexport function hasResource(store: ResourceStore, key: string): boolean {\n return store.entries.has(key);\n}\n\n/**\n * Remove a resource by key.\n *\n * @example\n * ```ts\n * import { hasResource, insertResource, removeResource, type ResourceStore } from './resource';\n *\n * declare const store: ResourceStore;\n * insertResource(store, 'health', 100);\n * removeResource(store, 'health');\n * // hasResource(store, 'health') === false; idempotent on missing keys\n * ```\n */\nexport function removeResource(store: ResourceStore, key: string): boolean {\n return store.entries.delete(key);\n}\n","// @forgeax/engine-ecs - Layer-3 default-value SSOT helper (feat-20260517-\n// spawn-default-fallback / M1).\n//\n// AI users: this file is the SINGLE PHYSICAL LOCATION of the layer-3\n// `typeDefault(fieldType)` table. Three runtime paths consume it (D-2\n// / plan-strategy §2.1 / AC-05):\n//\n// - `world.spawn(...)` (M2 — t9)\n// - `world.addComponent(...)` (M2 — t9, ComponentData<S> shared)\n//\n// Two-layer split (D-3 / plan-strategy §2.2 — DELIBERATELY NOT MERGED):\n//\n// layer-3 (this file)\n// \"raw value fallback\" — fills missing schema fields with the\n// spawn-data raw shape: 0 / false / ENTITY_NULL_RAW / [] / 0 (slot\n// id placeholder). The output is the input shape `world.spawn`\n// receives (`Partial<ShapeOf<S>>` -> `Record<string, unknown>` with\n// all schema keys present).\n//\n// layer-4 (silent fallback inside writeRow / write{Buffer,Array,\n// UniqueRef}Field)\n// \"column-store value fallback\" — when raw === 0 hits a managed-\n// family arm (string / unique<T> / buffer / buffer<N> / array<T> for\n// T != entity), the column store routes 0 to \"empty slot\" semantics\n// (UniqueRefStore handle 0 / BufferPool slot 0 / array slot\n// length === 0). The two layers are NEVER merged — layer-3 stays\n// pure / unaware of column physics; layer-4 stays inside writeRow\n// where the column instance is in scope.\n//\n// The 14-vocab x default-value table (AC-06 closed table, grep-gate t2\n// keyword \"layer-3 typeDefault table\"):\n//\n// ScalarFieldType (11 arms):\n// f32 / f64 / i32 / u32 / i16 / u16 / i8 / u8 -> 0\n// bool -> false\n// enum / ref (legacy scalar) -> 0\n//\n// SchemaVocabKeyword (8 arms; one \"buffer\" + one \"buffer<N>\"; one\n// \"ref<T>\" + one \"handle<T>\"; one \"entity\" + one \"string\"; two array\n// variants — array<T,N> / array<T> — collapse to two table arms:\n// 'string' -> 0 (uniqueRefs handle slot;\n// resolved payload '' on read)\n// 'entity' -> ENTITY_NULL_RAW (NULL_ENTITY u32\n// = 0xffffffff)\n// 'array<entity>' -> [] (THE ONLY array<T> arm with []\n// — entity[] runtime shape is a\n// JS array of Entity, not a\n// BufferPool slot id)\n// 'array<T>' (T != entity) -> 0 (BufferPool slot id; layer-4\n// writeArrayField bottoms out to\n// empty slot — D-2 asymmetric;\n// SceneAsset byte-equivalence,\n// OOS-6 letter)\n// 'array<T, N>' (any T) -> 0 (inline stride-N column,\n// feat-20260602; fallback writes the\n// zeroed row, not a slot id)\n// 'buffer' -> 0 (BufferPool slot id; variable\n// byte capacity)\n// 'buffer<N>' -> 0 (inline stride-N u8 column,\n// feat-20260602; fallback writes the\n// zeroed row, not a slot id)\n// 'unique<T>' -> 0 (UniqueRefStore handle slot)\n// 'handle<T>' -> 0 (unmanaged handle phantom u32;\n// schema-level nullable -> NULL\n// sentinel 0)\n//\n// Brand-class semantics (AC-10 / requirements §A-3 reframe round 2):\n// `handle<T>` and `ref<T>` are SCHEMA-LEVEL nullable. Spawn `data: {}`\n// is legal; layer-3 fills 0 (NULL sentinel for unmanaged handles) /\n// 0 (uniqueRefs handle slot, '' payload). SceneAsset.instantiate\n// produces byte-equivalent column state.\n//\n// Anchors:\n// - requirements §AC-05 (helper SSOT) + §AC-06 (closed 14-vocab table)\n// + §AC-09 (SceneAsset byte-equiv) + §AC-10 (brand-class nullable)\n// - plan-strategy §2.1 (helper file location decision)\n// §2.2 (two-layer split JSDoc declaration)\n// §2.3 (array<T> T!=entity asymmetric raw 0)\n// §3.1 (helper node in component graph)\n// §8.2 (naming rules: fillComponentDefaults / typeDefault)\n// §8.4 (head JSDoc as discovery anchor)\n\nimport type { Component, ComponentSchema } from './component';\nimport { componentSchema } from './component';\nimport { componentDefinition } from './component-schema';\nimport { ENTITY_NULL_RAW } from './entity-handle';\nimport { SpawnDataUnknownFieldError } from './errors';\n\n/**\n * Layer-3 silent default for a single schema field type. Returned when\n * the spawn-data raw input (layer 1) and the owner definition defaults\n * map (layer 2) both omit a known schema field.\n *\n * Pure function — runs once per missing field per (component, spawn /\n * instantiate) call. No `BufferPool` / `UniqueRefStore` / `World`\n * dependency: the helper hands back raw column-shape values (u32 / bool\n * / number array literal); the layer-4 silent fallback inside\n * `writeRow` / `write{Buffer,Array,UniqueRef}Field` turns raw `0` into\n * the live column-store value (unique-ref handle 0 / BufferPool slot\n * id 0 / array slot length 0).\n *\n * Mapping is the same closed table the head-JSDoc table documents.\n *\n * @internal — helper-private; AI users call `fillComponentDefaults`.\n */\nfunction typeDefault(fieldType: string): unknown {\n // bool is the only scalar arm with a non-zero default.\n if (fieldType === 'bool') return false;\n // 'entity' uses the runtime NULL_ENTITY sentinel (0xffffffff).\n if (fieldType === 'entity') return ENTITY_NULL_RAW;\n // 'array<entity>' is the only array<T> arm whose layer-3 default is a\n // JS array literal — entity[] runtime shape is a JS Array<Entity>,\n // not a BufferPool slot id (D-2 asymmetric pivot).\n if (fieldType === 'array<entity>') return [];\n // every other vocab keyword (incl. 'string' / 'unique<T>' / 'handle<T>'\n // / 'buffer' / 'buffer<N>' / 'array<T>' (T!=entity) / 'array<T, N>')\n // and every remaining ScalarFieldType (f* / i* / u* / enum / ref)\n // defaults to numeric 0 at the spawn-data raw surface. Layer-4\n // silent fallback inside writeRow turns 0 into the empty-slot\n // shape on the column-store side when applicable.\n return 0;\n}\n\n/**\n * Fill missing schema fields on a partial spawn-data raw with their\n * layer-2 / layer-3 defaults. Public surface used by:\n *\n * - `World.spawn` (writeRow entry, M2)\n * - `World.addComponent` (writeRow entry, M2)\n *\n * Resolution order (matches scene-instance-container.ts JSDoc):\n *\n * layer 1 — explicit raw value (caller passed `data[field] = v`).\n * Carrier: the raw input itself; not handled by this\n * helper — copied through the `if (key in raw)` branch.\n * SceneAsset.instantiate additionally remaps `entity` /\n * `array<entity>` LocalEntityId values BEFORE handing the raw\n * to the helper (the entity-remap layer is NOT this\n * helper's responsibility).\n *\n * layer 2 — owner definition defaults (declared via\n * `defineComponent(name, schema, { defaults })`). Layer-2\n * defaults beat layer-3.\n *\n * layer 3 — `typeDefault(fieldType)` (this file's private dispatch).\n *\n * Returns a fresh `Record<string, unknown>` carrying every schema\n * field. The output is column-shape raw — the caller's writeRow path\n * walks it field-by-field and applies layer-4 silent fallback when a\n * raw `0` lands on a managed-family arm.\n *\n * Pure: no World / store side effect. Thread-safety irrelevant (single-\n * thread JS engine), but the helper allocates one `Object.create(null)`\n * per call so repeated invocations cannot share a mutable record.\n *\n * @param token Component token (name + schema + optional defaults).\n * @param raw Partial spawn-data raw — caller's `Partial<ShapeOf<S>>`.\n * Keys not present in the schema are passed through\n * unchanged (the spawn write path will emit a write-time\n * error if applicable; helper does not validate keys).\n * @returns Record with every schema field populated by layer-1 /\n * layer-2 / layer-3 defaults in that order.\n */\nexport function fillComponentDefaults<S extends ComponentSchema>(\n token: Component<string, S>,\n raw: Partial<Record<string, unknown>> | undefined,\n): Record<string, unknown> {\n const schema = componentSchema(token) as Record<string, string>;\n const layer2 = componentDefinition(token).defaults;\n const out: Record<string, unknown> = Object.create(null);\n const rawObj = (raw as Record<string, unknown> | undefined) ?? undefined;\n for (const fieldName of Object.keys(schema)) {\n const fieldType = schema[fieldName];\n if (fieldType === undefined) continue;\n // layer 1 — explicit raw value (caller may pass undefined to mean\n // \"use default\"; mirror the existing scene-instance-container\n // behaviour where the gate is `fieldName in raw`).\n if (rawObj !== undefined && fieldName in rawObj) {\n out[fieldName] = rawObj[fieldName];\n continue;\n }\n // layer 2 — component-level defaults map.\n if (layer2 !== undefined && fieldName in layer2) {\n out[fieldName] = layer2[fieldName];\n continue;\n }\n // layer 3 — TS type defaults (silent — no error code).\n out[fieldName] = typeDefault(fieldType);\n }\n return out;\n}\n\n// Re-export the private dispatch for unit-test introspection (t1\n// keyword pin — every vocab arm gets a one-liner it() block). The\n// helper-private arity is preserved at callers via the\n// `fillComponentDefaults` boundary.\nexport { typeDefault };\n\n/**\n * Validate that every key in `raw` is a declared schema field on `token`.\n *\n * Returned as a `SpawnDataUnknownFieldError` on the FIRST offending key\n * (deterministic for AI users; subsequent unknown keys surface on the next\n * spawn after the first is fixed). Pre-fix the unknown key was silently\n * dropped inside `fillComponentDefaults` (which iterates only schema keys),\n * routing typos like `MeshRenderer { material }` (singular legacy field name)\n * into the empty-default path and producing invisible / mid-grey entities\n * downstream.\n *\n * Pure: no World / store side effect; allocates no closure on the hot path\n * (early-returns null when raw is undefined / empty).\n *\n * Call order at every spawn / addComponent / SceneAsset.instantiate /\n * Commands.spawn site: validate FIRST, then `fillComponentDefaults`. The\n * split keeps `fillComponentDefaults` pure (charter P3 SSOT — a fill helper\n * never validates) while every layer-1 raw key reaches one validator gate.\n *\n * @param token Component token (name + schema).\n * @param raw Caller's `Partial<ShapeOf<S>>` — raw spawn payload.\n * @returns `null` on success; `SpawnDataUnknownFieldError` on the first\n * key not declared in `componentSchema(token)`.\n */\nexport function validateComponentDataKeys<S extends ComponentSchema>(\n token: Component<string, S>,\n raw: Partial<Record<string, unknown>> | undefined,\n): SpawnDataUnknownFieldError | null {\n if (raw === undefined) return null;\n const schema = componentSchema(token) as Record<string, unknown>;\n const rawObj = raw as Record<string, unknown>;\n for (const fieldName of Object.keys(rawObj)) {\n if (!(fieldName in schema)) {\n return new SpawnDataUnknownFieldError(token.name, fieldName, Object.keys(schema));\n }\n }\n return null;\n}\n","// @forgeax/engine-ecs — CommandBuffer: deferred structural changes.\n//\n// System execution queues spawn/despawn/addComponent/removeComponent commands.\n// world.update() flushes the queue at frame end with while(queue.length > 0)\n// cascade support (D-06). Deferred spawn returns pending Entity handle (D-07).\n\nimport type { Result } from '@forgeax/engine-types';\nimport type { Component, ComponentSchema } from './component';\nimport { componentId } from './component';\nimport { fillComponentDefaults, validateComponentDataKeys } from './component-default-fallback';\nimport { Entity } from './entity';\nimport { ENTITY_NULL_RAW, type EntityHandle, entityGeneration, entityIndex } from './entity-handle';\nimport {\n type CommandCommitEvidence,\n CommandFailedError,\n type CommandKind,\n ComponentAlreadyPresentError,\n ComponentNotPresentError,\n RelationshipSelfCycleError,\n RelationshipTargetReadonlyError,\n RemoveEssentialComponentError,\n StaleEntityError,\n SystemFailedError,\n} from './errors';\nimport { isRelationshipTarget, relationshipRole } from './relationship-index';\nimport type { ComponentData, EcsError } from './world';\nimport { type WorldInternal, worldInternal } from './world-internal';\n\n// ────────────────────────────────────────────────────────────────────────────\n// Command types\n// ────────────────────────────────────────────────────────────────────────────\n\nexport type Command =\n | { type: 'spawn'; componentDatas: ComponentData[]; entity: EntityHandle }\n | { type: 'despawn'; entity: EntityHandle }\n | { type: 'addComponent'; entity: EntityHandle; componentData: ComponentData }\n | { type: 'removeComponent'; entity: EntityHandle; component: Component };\n\n// ────────────────────────────────────────────────────────────────────────────\n// CommandBuffer interface\n// ────────────────────────────────────────────────────────────────────────────\n\n/**\n * CommandBuffer queues structural changes (spawn/despawn/addComponent/removeComponent)\n * during system execution. Flushed at end of world.update().\n */\nexport interface CommandBuffer {\n readonly status: 'open' | 'committed' | 'aborted';\n /** Deferred spawn: returns pending Entity handle. */\n spawn(...componentDatas: ComponentData[]): EntityHandle;\n /** Deferred despawn. */\n despawn(entity: EntityHandle): unknown;\n /** Deferred addComponent. */\n addComponent<S extends ComponentSchema>(\n entity: EntityHandle,\n componentData: ComponentData<S>,\n ): unknown;\n /** Deferred removeComponent. */\n removeComponent<S extends ComponentSchema>(\n entity: EntityHandle,\n component: Component<string, S>,\n ): unknown;\n /** Check if an entity is pending (deferred spawn, not yet flushed). */\n isDeferred(entity: EntityHandle): boolean;\n commit(): void;\n abort(error?: unknown): void;\n}\n\n// ────────────────────────────────────────────────────────────────────────────\n// World access interface (avoids circular import)\n// ────────────────────────────────────────────────────────────────────────────\n\n/** Minimal world interface needed by CommandBuffer for entity allocation. */\nexport interface WorldForCommands {\n readonly [worldInternal]: WorldInternal;\n /**\n * Allocate a pending entity index, returning [entity handle, index slot].\n * @internal\n */\n /**\n * Mark a pending entity as materialized (flush phase).\n * @internal\n */\n /** Execute despawn directly (flush phase). */\n despawn(entity: EntityHandle): Result<void, EcsError>;\n /** Execute addComponent directly (flush phase). */\n addComponent<S extends ComponentSchema>(\n entity: EntityHandle,\n componentData: ComponentData<S>,\n ): Result<void, EcsError>;\n /** Execute removeComponent directly (flush phase). */\n removeComponent<S extends ComponentSchema>(\n entity: EntityHandle,\n component: Component<string, S>,\n ): Result<void, EcsError>;\n /** Fast membership probe used by command preflight. */\n hasComponent(entity: EntityHandle, component: Component): boolean;\n}\n\n// ────────────────────────────────────────────────────────────────────────────\n// Implementation\n// ────────────────────────────────────────────────────────────────────────────\n\nexport interface CommandBufferImpl extends CommandBuffer {\n /** @internal */\n _queue: Command[];\n /** @internal */\n _pendingEntities: Set<number>;\n /** @internal First validation failure captured while the system was staging commands. */\n _queueError: {\n readonly index: number;\n readonly kind: CommandKind;\n readonly cause: unknown;\n } | null;\n /** @internal */\n readonly _systemName: string;\n /** @internal */\n readonly _scheduleName: string;\n /** @internal */\n _setStatus(status: 'committed' | 'aborted'): void;\n}\n\n/**\n * Create a CommandBuffer bound to a World.\n * @param world - the World (for pending entity allocation)\n */\nexport function createCommandBuffer(\n world: WorldForCommands,\n context: { readonly systemName?: string; readonly scheduleName?: string } = {},\n): CommandBufferImpl {\n const queue: Command[] = [];\n const pendingEntities = new Set<number>();\n let status: CommandBuffer['status'] = 'open';\n let queueError: CommandBufferImpl['_queueError'] = null;\n const ensureOpen = (): void => {\n if (status !== 'open') throw new Error(`CommandBuffer is ${status}`);\n };\n const recordQueueError = (index: number, kind: CommandKind, cause: unknown): void => {\n if (queueError === null) queueError = { index, kind, cause };\n };\n\n const buffer: CommandBufferImpl = {\n _queue: queue,\n _pendingEntities: pendingEntities,\n _systemName: context.systemName ?? '<unknown-system>',\n _scheduleName: context.scheduleName ?? '<unknown-schedule>',\n get status() {\n return status;\n },\n get _queueError() {\n return queueError;\n },\n _setStatus(next) {\n if (status === 'open') status = next;\n },\n commit() {\n ensureOpen();\n status = 'committed';\n queue.length = 0;\n pendingEntities.clear();\n queueError = null;\n },\n abort() {\n if (status !== 'open') return;\n for (const raw of pendingEntities) {\n world[worldInternal].cancelPendingEntity(raw as EntityHandle);\n }\n status = 'aborted';\n queue.length = 0;\n pendingEntities.clear();\n queueError = null;\n },\n\n spawn(...componentDatas: ComponentData[]): EntityHandle {\n ensureOpen();\n // bug-20260615: validate raw spawn keys at queue time (synchronous,\n // points at the calling system's stack) rather than only at flush\n // time. Commands.spawn returns EntityHandle (no Result channel), so\n // unknown-key is captured as a batch preflight failure. The handle is\n // still reserved so callers may compose later commands; abort releases\n // every reservation without leaking a free slot.\n for (const cd of componentDatas) {\n const keyErr = validateComponentDataKeys(cd.component, cd.data as Record<string, unknown>);\n if (keyErr !== null) recordQueueError(queue.length, 'spawn', keyErr);\n }\n const entity = world[worldInternal].allocatePendingEntity();\n pendingEntities.add(entity as unknown as number);\n queue.push({ type: 'spawn', componentDatas, entity });\n return entity;\n },\n\n despawn(entity: EntityHandle): void {\n ensureOpen();\n queue.push({ type: 'despawn', entity });\n },\n\n addComponent<S extends ComponentSchema>(\n entity: EntityHandle,\n componentData: ComponentData<S>,\n ): void {\n ensureOpen();\n const keyErr = validateComponentDataKeys(\n componentData.component,\n componentData.data as Record<string, unknown>,\n );\n if (keyErr !== null) recordQueueError(queue.length, 'addComponent', keyErr);\n queue.push({ type: 'addComponent', entity, componentData: componentData as ComponentData });\n },\n\n removeComponent<S extends ComponentSchema>(\n entity: EntityHandle,\n component: Component<string, S>,\n ): void {\n ensureOpen();\n queue.push({ type: 'removeComponent', entity, component: component as Component });\n },\n\n isDeferred(entity: EntityHandle): boolean {\n return pendingEntities.has(entity as unknown as number);\n },\n };\n\n return buffer;\n}\n\nfunction commandFailure(\n buffer: CommandBufferImpl,\n index: number,\n kind: CommandKind,\n cause: unknown,\n): CommandFailedError {\n return new CommandFailedError(buffer._systemName, buffer._scheduleName, index, kind, cause);\n}\n\ntype RelationshipOverlay = Map<number, Map<number, EntityHandle | null>>;\n\nfunction relationshipTarget(\n component: Component,\n data: Readonly<Record<string, unknown>>,\n): EntityHandle | null {\n const role = relationshipRole(component);\n if (role?.kind !== 'source') return null;\n const raw = data[role.sourceField];\n if (raw === null || raw === undefined || raw === ENTITY_NULL_RAW) return null;\n return raw as EntityHandle;\n}\n\nfunction overlayTarget(\n overlay: RelationshipOverlay,\n entity: EntityHandle,\n component: Component,\n): EntityHandle | null | undefined {\n return overlay.get(entity as number)?.get(componentId(component));\n}\n\nfunction setOverlayTarget(\n overlay: RelationshipOverlay,\n entity: EntityHandle,\n component: Component,\n target: EntityHandle | null,\n): void {\n let entries = overlay.get(entity as number);\n if (entries === undefined) {\n entries = new Map();\n overlay.set(entity as number, entries);\n }\n entries.set(componentId(component), target);\n}\n\n/**\n * Check a relationship edge against committed rows plus the batch overlay.\n * The overlay is the only extra state needed: it records at most one target\n * per affected source/component, so a batch remains O(C + A) rather than\n * rescanning every World entity.\n */\nfunction relationshipCycle(\n world: WorldForCommands,\n holder: EntityHandle,\n component: Component,\n target: EntityHandle | null,\n overlay: RelationshipOverlay,\n): RelationshipSelfCycleError | undefined {\n if (target === null) return undefined;\n const role = relationshipRole(component);\n const allowSelf = role?.kind === 'source' && role.allowSelf;\n if (holder === target && !allowSelf) {\n return new RelationshipSelfCycleError(component.name, holder as number, target as number);\n }\n const visited = new Set<number>();\n let current: EntityHandle | null = target;\n while (current !== null) {\n const raw = current as number;\n if (raw === (holder as number) && !(holder === target && allowSelf)) {\n return new RelationshipSelfCycleError(component.name, holder as number, raw);\n }\n if (visited.has(raw)) return undefined;\n visited.add(raw);\n const staged = overlayTarget(overlay, current, component);\n if (staged !== undefined || overlay.get(raw)?.has(componentId(component)) === true) {\n current = staged ?? null;\n continue;\n }\n const row = world[worldInternal].getQueryRow(current, component);\n if (!row.ok) return undefined;\n current = relationshipTarget(component, row.value);\n }\n return undefined;\n}\n\n/**\n * Validate the failures that can be proven from the current World and the\n * command batch without mutating storage. The commit loop remains the only\n * writer; any failure not provable here is treated as an unexpected post-write\n * failure and poisons the World.\n */\nfunction preflightCommands(buffer: CommandBufferImpl, world: WorldForCommands): void {\n if (buffer._queueError !== null) {\n const { index, kind, cause } = buffer._queueError;\n throw commandFailure(buffer, index, kind, cause);\n }\n\n type Shadow = {\n readonly components: Set<number>;\n readonly added: Set<number>;\n readonly removed: Set<number>;\n dead: boolean;\n pending: boolean;\n };\n const shadows = new Map<number, Shadow>();\n const relationshipOverlay: RelationshipOverlay = new Map();\n const unavailableEntities = new Set<number>();\n const availablePendingEntities = new Set<number>();\n const shadowFor = (entity: EntityHandle): Shadow => {\n const raw = entity as unknown as number;\n const current = shadows.get(raw);\n if (current !== undefined) return current;\n const shadow: Shadow = {\n components: new Set<number>(),\n added: new Set<number>(),\n removed: new Set<number>(),\n dead: false,\n pending: false,\n };\n shadows.set(raw, shadow);\n return shadow;\n };\n const validateData = (\n holder: EntityHandle | null,\n componentData: ComponentData,\n ): unknown | undefined => {\n const result = world[worldInternal].preflightComponentData(\n holder,\n componentData,\n availablePendingEntities,\n unavailableEntities,\n );\n return result.ok ? undefined : result.error;\n };\n const liveError = (entity: EntityHandle, operation: string, component?: Component): unknown => {\n const result = world[worldInternal].lookupAlive(entity, operation, component?.name);\n return result.ok ? undefined : result.error;\n };\n for (const [index, command] of buffer._queue.entries()) {\n switch (command.type) {\n case 'spawn': {\n const raw = command.entity as unknown as number;\n const shadow = shadowFor(command.entity);\n shadow.pending = true;\n availablePendingEntities.add(raw);\n for (const componentData of command.componentDatas) {\n const dataError = validateData(command.entity, componentData);\n if (dataError !== undefined) throw commandFailure(buffer, index, command.type, dataError);\n if (shadow.components.has(componentId(componentData.component))) {\n throw commandFailure(\n buffer,\n index,\n command.type,\n new ComponentAlreadyPresentError(raw, componentData.component.name),\n );\n }\n shadow.components.add(componentId(componentData.component));\n const role = relationshipRole(componentData.component);\n if (role?.kind === 'source') {\n const filled = fillComponentDefaults(\n componentData.component,\n componentData.data as Record<string, unknown>,\n );\n const target = relationshipTarget(componentData.component, filled);\n setOverlayTarget(relationshipOverlay, command.entity, componentData.component, target);\n const cycle = relationshipCycle(\n world,\n command.entity,\n componentData.component,\n target,\n relationshipOverlay,\n );\n if (cycle !== undefined) throw commandFailure(buffer, index, command.type, cycle);\n }\n }\n break;\n }\n case 'despawn': {\n const shadow = shadowFor(command.entity);\n if (!shadow.pending && !world.hasComponent(command.entity, Entity)) {\n // A stale handle is a no-op for the direct facade today; preserve\n // that contract instead of inventing a new command error.\n shadow.dead = true;\n unavailableEntities.add(command.entity as unknown as number);\n availablePendingEntities.delete(command.entity as unknown as number);\n break;\n }\n shadow.dead = true;\n unavailableEntities.add(command.entity as unknown as number);\n availablePendingEntities.delete(command.entity as unknown as number);\n break;\n }\n case 'addComponent': {\n const raw = command.entity as unknown as number;\n const shadow = shadowFor(command.entity);\n const dataError = validateData(command.entity, command.componentData);\n if (dataError !== undefined) throw commandFailure(buffer, index, command.type, dataError);\n if (!shadow.pending) {\n const stale = liveError(\n command.entity,\n 'command.addComponent',\n command.componentData.component,\n );\n if (stale !== undefined) throw commandFailure(buffer, index, command.type, stale);\n }\n const role = relationshipRole(command.componentData.component);\n const present = shadow.pending\n ? shadow.components.has(componentId(command.componentData.component))\n : shadow.removed.has(componentId(command.componentData.component))\n ? false\n : shadow.added.has(componentId(command.componentData.component)) ||\n world.hasComponent(command.entity, command.componentData.component);\n if (shadow.dead) {\n throw commandFailure(\n buffer,\n index,\n command.type,\n liveError(command.entity, 'command.addComponent', command.componentData.component) ??\n new StaleEntityError(\n raw,\n entityIndex(command.entity),\n entityGeneration(command.entity),\n {\n operation: 'command.addComponent',\n expectedGeneration: entityGeneration(command.entity),\n actualGeneration: -1,\n },\n ),\n );\n }\n const reparent =\n present && role?.kind === 'source' && role.exclusive === true && !shadow.pending;\n if (present && !reparent) {\n throw commandFailure(\n buffer,\n index,\n command.type,\n new ComponentAlreadyPresentError(raw, command.componentData.component.name),\n );\n }\n shadow.components.add(componentId(command.componentData.component));\n if (!reparent) shadow.added.add(componentId(command.componentData.component));\n shadow.removed.delete(componentId(command.componentData.component));\n if (role?.kind === 'source') {\n const filled = fillComponentDefaults(\n command.componentData.component,\n command.componentData.data as Record<string, unknown>,\n );\n const target = relationshipTarget(command.componentData.component, filled);\n setOverlayTarget(\n relationshipOverlay,\n command.entity,\n command.componentData.component,\n target,\n );\n const cycle = relationshipCycle(\n world,\n command.entity,\n command.componentData.component,\n target,\n relationshipOverlay,\n );\n if (cycle !== undefined) throw commandFailure(buffer, index, command.type, cycle);\n }\n break;\n }\n case 'removeComponent': {\n const raw = command.entity as unknown as number;\n if (isRelationshipTarget(command.component)) {\n throw commandFailure(\n buffer,\n index,\n command.type,\n new RelationshipTargetReadonlyError(command.component.name, 'removeComponent'),\n );\n }\n if (componentId(command.component) === 0) {\n throw commandFailure(\n buffer,\n index,\n command.type,\n new RemoveEssentialComponentError(command.component.name),\n );\n }\n const shadow = shadowFor(command.entity);\n if (shadow.dead) {\n throw commandFailure(\n buffer,\n index,\n command.type,\n liveError(command.entity, 'command.removeComponent', command.component) ??\n new StaleEntityError(\n raw,\n entityIndex(command.entity),\n entityGeneration(command.entity),\n {\n operation: 'command.removeComponent',\n expectedGeneration: entityGeneration(command.entity),\n actualGeneration: -1,\n },\n ),\n );\n }\n if (!shadow.pending) {\n const stale = liveError(command.entity, 'command.removeComponent', command.component);\n if (stale !== undefined) throw commandFailure(buffer, index, command.type, stale);\n }\n const present = shadow.pending\n ? shadow.components.has(componentId(command.component))\n : shadow.removed.has(componentId(command.component))\n ? false\n : shadow.added.has(componentId(command.component)) ||\n world.hasComponent(command.entity, command.component);\n if (!present) {\n throw commandFailure(\n buffer,\n index,\n command.type,\n new ComponentNotPresentError(raw, command.component.name),\n );\n }\n shadow.components.delete(componentId(command.component));\n shadow.removed.add(componentId(command.component));\n shadow.added.delete(componentId(command.component));\n if (relationshipRole(command.component)?.kind === 'source') {\n setOverlayTarget(relationshipOverlay, command.entity, command.component, null);\n }\n break;\n }\n }\n }\n}\n\n/**\n * Flush all queued commands against the World.\n * Uses while(queue.length > 0) to support cascade (commands spawned during flush).\n */\nexport function flushCommands(buffer: CommandBufferImpl, world: WorldForCommands): void {\n if (buffer.status !== 'open') return;\n const queue = buffer._queue;\n try {\n preflightCommands(buffer, world);\n } catch (error) {\n buffer.abort(error);\n throw error;\n }\n let applied = 0;\n let commandIndex = -1;\n let currentCommand: Command | undefined;\n let lastCommittedCommand: CommandCommitEvidence | null = null;\n try {\n const requireSuccess = (result: unknown): void => {\n if (\n result !== null &&\n typeof result === 'object' &&\n 'ok' in result &&\n (result as { readonly ok: boolean }).ok === false\n ) {\n throw (result as { readonly error?: unknown }).error ?? new Error('Command failed');\n }\n };\n while (queue.length > 0) {\n // biome-ignore lint/style/noNonNullAssertion: queue length is checked\n const cmd = queue.shift()!;\n commandIndex += 1;\n currentCommand = cmd;\n switch (cmd.type) {\n case 'spawn':\n requireSuccess(\n world[worldInternal].materializePendingEntity(cmd.entity, cmd.componentDatas),\n );\n buffer._pendingEntities.delete(cmd.entity as unknown as number);\n applied += 1;\n lastCommittedCommand = { index: commandIndex, kind: cmd.type };\n break;\n case 'despawn':\n requireSuccess(world.despawn(cmd.entity));\n applied += 1;\n lastCommittedCommand = { index: commandIndex, kind: cmd.type };\n break;\n case 'addComponent':\n requireSuccess(world.addComponent(cmd.entity, cmd.componentData));\n applied += 1;\n lastCommittedCommand = { index: commandIndex, kind: cmd.type };\n break;\n case 'removeComponent':\n requireSuccess(world.removeComponent(cmd.entity, cmd.component));\n applied += 1;\n lastCommittedCommand = { index: commandIndex, kind: cmd.type };\n break;\n }\n }\n buffer.commit();\n } catch (error) {\n buffer.abort(error);\n if (error instanceof CommandFailedError) throw error;\n if (applied === 0) {\n throw commandFailure(\n buffer,\n Math.max(commandIndex, 0),\n currentCommand?.type ?? 'spawn',\n error,\n );\n }\n const poison = world[worldInternal].poisonExecution;\n poison({\n code: 'shared-kernel-failed',\n kernelName: 'CommandBuffer.flush',\n cause: error,\n partialWrite: true,\n retryable: false,\n });\n throw new SystemFailedError(\n buffer._systemName,\n buffer._scheduleName,\n error,\n lastCommittedCommand,\n );\n }\n}\n","// @forgeax/engine-ecs — DAG Schedule: Kahn topological sort + cycle detection.\n//\n// addSystem registers a system + marks dirty. First update() triggers buildSchedule().\n// Same in-degree systems ordered by addSystem call order (stable tie-breaker, D-05).\n\nimport { err, ok, type Result } from '@forgeax/engine-types';\nimport { type CommandBuffer, createCommandBuffer, flushCommands } from './commands';\nimport type { Component } from './component';\nimport {\n CyclicDependencyError,\n ScheduleMutationError,\n SystemFailedError,\n type SystemSetNotRegisteredError,\n systemSetNotRegistered,\n} from './errors';\nimport type { Query, QueryDescriptor } from './query/query';\n// type-only import: erases at build time, carries no runtime edge (same\n// criterion as scripts/check-ecs-no-runtime-import.mjs). `world.ts` already\n// value-imports `schedule.ts`; this back-reference is type-space only so no\n// runtime cycle forms (plan-strategy D-1).\nimport type { ScheduleToken } from './schedule-token';\nimport type { World } from './world';\nimport { worldInternal } from './world-internal';\n\n// ────────────────────────────────────────────────────────────────────────────\n// Types\n// ────────────────────────────────────────────────────────────────────────────\n\ntype SystemQueryResults<\n Qs extends ReadonlyArray<QueryDescriptor> = ReadonlyArray<QueryDescriptor>,\n> = {\n [K in keyof Qs]: Qs[K] extends QueryDescriptor<\n infer R extends ReadonlyArray<Component>,\n infer W extends ReadonlyArray<Component>,\n infer O extends ReadonlyArray<Component>\n >\n ? Query<NoInfer<R>, NoInfer<W>, NoInfer<O>>\n : Query;\n};\n\n/**\n * System descriptor passed to `world.addSystem` — `fn` receives one persistent\n * executable Query per descriptor, mapped over `Qs` without casts.\n *\n * `Qs` is the tuple of query descriptors; defaults to\n * `readonly QueryDescriptor[]` so non-generic call sites stay zero-modification\n * (KD-5). The `fn` first parameter is mapped over `Qs` so each\n * `queryResults[i]` recovers its own row access roles (S-5, KD-2).\n *\n * @example\n * ```ts\n * // Single-query system — row access recovers each component schema.\n * import { defineComponent, World } from '@forgeax/engine-ecs';\n *\n * const Position = defineComponent('Position', { x: 'f32', y: 'f32' });\n * const Velocity = defineComponent('Velocity', { dx: 'f32', dy: 'f32' });\n *\n * const world = new World();\n * world.addSystem(Update, {\n * name: 'movement',\n * queries: [{ write: [Position], read: [Velocity] }],\n * fn: (_world, queryResults, _commands) => {\n * for (const row of queryResults[0]) {\n * row.mut(Position).x += row.get(Velocity).dx;\n * }\n * },\n * });\n * ```\n *\n * @example\n * ```ts\n * // Multi-query system — each queryResults[i] keeps its own row shape.\n * const Health = defineComponent('Health', { hp: 'f32' });\n * world.addSystem(Update, {\n * name: 'multi',\n * queries: [{ read: [Position] }, { read: [Health] }],\n * fn: (_world, queryResults) => {\n * for (const row of queryResults[0]) void row.get(Position).x;\n * for (const row of queryResults[1]) void row.get(Health).hp;\n * },\n * });\n * ```\n *\n * @example\n * ```ts\n * // Commands-only system — `queries: []` is a legal form; fn receives `[]`.\n * world.addSystem(Update, {\n * name: 'spawner',\n * queries: [],\n * fn: (_world, _queryResults, commands) => {\n * commands.spawn({ component: Position, data: { x: 0, y: 0 } });\n * },\n * });\n * ```\n */\nexport interface SystemDescriptor<\n Qs extends ReadonlyArray<QueryDescriptor> = ReadonlyArray<QueryDescriptor>,\n> {\n /** Unique system name (used for before/after references). */\n readonly name: string;\n /** Query descriptors this system reads. */\n readonly queries: Qs;\n /**\n * System function — receives the World, resolved query results, and commands.\n *\n * @param world The owning World — read resources (`world.getResource(KEY)`),\n * resolve components by name, etc. without closure capture.\n * @param queryResults Mapped over `Qs`: each entry is a persistent Query.\n * @param commands Deferred-mutation buffer (flushed after the system).\n */\n readonly fn: (\n world: World,\n queryResults: SystemQueryResults<Qs>,\n commands: CommandBuffer,\n ) => void | unknown;\n /** Run this system after named systems or the FixedUpdate anchor. */\n readonly after?: ReadonlyArray<string | ScheduleToken>;\n /** Run this system before named systems or the FixedUpdate anchor. */\n readonly before?: ReadonlyArray<string | ScheduleToken>;\n /**\n * Run condition. Evaluated each frame after ParamValidation passes (tag\n * 'ok') and before query iteration. Returning `false` skips the system silently —\n * no query runs, no fn call, no state added (plan-strategy D-8). Omitting it\n * (undefined) always runs the system.\n */\n readonly runIf?: (world: World) => boolean;\n}\n\n/**\n * A registered system token returned by {@link defineSystem}. Structurally the\n * frozen {@link SystemDescriptor} itself (plan-strategy D-6 — \"define ==\n * register\"). `world.addSystem(handle)` consumes it directly; the generic `Qs`\n * flows through so the `fn` per-query row access shapes survive (S-5).\n */\nexport type SystemHandle<\n Qs extends ReadonlyArray<QueryDescriptor> = ReadonlyArray<QueryDescriptor>,\n> = SystemDescriptor<Qs>;\n\n/** Internal system record with registration index. */\ninterface SystemRecord {\n descriptor: SystemDescriptor;\n /** Registration order index (for tie-breaking). */\n registrationIndex: number;\n /** Cached executable Queries, one per descriptor. */\n queries: Query[] | null;\n}\n\n// ────────────────────────────────────────────────────────────────────────────\n// Schedule\n// ────────────────────────────────────────────────────────────────────────────\n\n/**\n * Per-set record in the Schedule. Created lazily on first addSystems /\n * addSystems call for a given set name.\n */\nexport interface SetRecord {\n /** Member system names (insertion-ordered, Set preserves add order). */\n readonly members: Set<string>;\n /** Snapshot of runIf from the defining token. */\n readonly runIf: ((world: import('./world').World) => boolean) | undefined;\n /** Snapshot of chained from the defining token. */\n readonly chained: boolean;\n}\n\n/** The Schedule manages system registration, DAG sorting, and execution. */\nexport interface Schedule {\n /** Owning token for scope-aware diagnostics. */\n readonly token: ScheduleToken;\n /** All registered systems by name. */\n systems: Map<string, SystemRecord>;\n /** Set records keyed by set name. Created lazily. */\n sets: Map<string, SetRecord>;\n /** Next registration index. */\n nextIndex: number;\n /** Whether the sorted order is stale. */\n dirty: boolean;\n /** Sorted system names after buildSchedule(). */\n sortedOrder: string[];\n /** Direct predecessor names derived while the DAG is built. */\n predecessors: Map<string, Set<string>>;\n}\n\n/** Create a fresh Schedule. */\nexport function createSchedule(token: ScheduleToken): Schedule {\n return {\n token,\n systems: new Map(),\n sets: new Map(),\n nextIndex: 0,\n dirty: true,\n sortedOrder: [],\n predecessors: new Map(),\n };\n}\n\n/**\n * Register a system. Marks schedule as dirty.\n * Queries are lazily initialized on first runSchedule.\n *\n * `const Qs` locks the `queries` tuple at the call site so `fn`'s first\n * parameter recovers per-query row shapes without `as const` annotations\n * (S-5, KD-2). `SystemRecord` itself is intentionally non-generic — the\n * heterogeneous `Qs` cannot be expressed inside the systems Map (KD-3).\n */\nexport function addSystem<const Qs extends ReadonlyArray<QueryDescriptor>>(\n schedule: Schedule,\n descriptor: SystemDescriptor<Qs>,\n): void {\n const record: SystemRecord = {\n descriptor: descriptor as unknown as SystemDescriptor,\n registrationIndex: schedule.nextIndex++,\n queries: null,\n };\n schedule.systems.set(descriptor.name, record);\n schedule.dirty = true;\n}\n\n// ────────────────────────────────────────────────────────────────────────────\n// System token construction (token-first World ownership)\n// ────────────────────────────────────────────────────────────────────────────\n\n/**\n * Define a system at module level. Returns a frozen {@link SystemHandle} token\n * (the descriptor itself); executable registration is World-local.\n *\n * `world.addSystem(handle)` consumes the token directly — no by-name overload\n * (OOS-8). Duplicate names are resolved by the owning World schedule.\n *\n * `const Qs` locks the `queries` tuple so `fn`'s query-results parameter\n * recovers per-query row access shapes without `as const` (S-5).\n *\n * @example\n * ```ts\n * const Move = defineSystem({\n * name: 'movement',\n * queries: [{ with: [Position, Velocity] }],\n * fn: (_world, queryResults) => { ... },\n * });\n * world.addSystem(Move);\n * ```\n */\nexport function defineSystem<const Qs extends ReadonlyArray<QueryDescriptor>>(\n descriptor: SystemDescriptor<Qs>,\n): SystemHandle<Qs> {\n const handle = Object.freeze(descriptor) as unknown as SystemHandle<Qs>;\n return handle;\n}\n\n/**\n */\n// ────────────────────────────────────────────────────────────────────────────\n// SystemSet — nominal token (D-2c step 1, w2)\n// ────────────────────────────────────────────────────────────────────────────\n\n/** Brand symbol for {@link SystemSet}. Declared (not runtime-initialised) so\n * the token interface carries nominal identity without a runtime allocation.\n * Mirrors the `FORGEAX_STATE_BRAND` pattern in `@forgeax/engine-state`. */\ndeclare const FORGEAX_SYSTEM_SET_BRAND: unique symbol;\n\n/**\n * Opaque branded type for system-set tokens.\n *\n * Use {@link defineSystemSet} to create a token; never construct manually.\n * The {@link __forgeaxSystemSet} brand prevents plain-object assignment and\n * enables TypeScript narrowing at the two mutation entry points.\n */\nexport interface SystemSet {\n /** Brand — prevents structural compatibility with plain objects. */\n readonly __forgeaxSystemSet: typeof FORGEAX_SYSTEM_SET_BRAND;\n /** The user-supplied set name. */\n readonly name: string;\n /** Optional per-frame run condition. Consumed by M3 condition gate. */\n readonly runIf?: (world: import('./world').World) => boolean;\n /** Whether this set forms a sequential chain (M2). */\n readonly chained?: boolean;\n}\n\n/**\n * Define a system set at module level. Returns a frozen branded token and\n * keeps membership in the World-local Schedule.\n *\n * Duplicate names are independent tokens; the owning World decides membership.\n *\n * @example\n * ```ts\n * const GameplaySet = defineSystemSet({ name: 'gameplay', runIf: (w) => !w.getResource<boolean>('paused') });\n * const OrderedSet = defineSystemSet({ name: 'ordered', chained: true });\n * ```\n */\nexport function defineSystemSet(opts: {\n readonly name: string;\n readonly runIf?: (world: import('./world').World) => boolean;\n readonly chained?: boolean;\n}): SystemSet {\n const token: Record<string, unknown> = {\n __forgeaxSystemSet: undefined as unknown as typeof FORGEAX_SYSTEM_SET_BRAND,\n name: opts.name,\n };\n if (opts.runIf !== undefined) {\n token.runIf = opts.runIf;\n }\n if (opts.chained !== undefined) {\n token.chained = opts.chained;\n }\n const frozen = Object.freeze(token) as unknown as SystemSet;\n return frozen;\n}\n\n/**\n/**\n * Validate every token in `tokens` for local structural validity.\n * Returns `ok(undefined)` for a structurally valid token and reports an empty\n * token name as a structured registration error.\n *\n * Does not write any Schedule state — callers consume the `Result` and proceed\n * only on `ok`.\n */\nexport function validateSystemSetTokens(\n tokens: readonly SystemSet[],\n): Result<void, SystemSetNotRegisteredError> {\n for (const token of tokens) {\n if (token.name.length === 0) {\n return err(systemSetNotRegistered(token.name, []));\n }\n }\n return ok(undefined);\n}\n\n/**\n * Remove a registered system by name (M2 — plan-strategy D-3).\n *\n * Drops the entry from `schedule.systems` and marks the schedule dirty so the\n * next `runSchedule` rebuilds the sorted order via Kahn topo. Cycle detection\n * already happens inside `buildSchedule`, so a removal that breaks an unrelated\n * `before/after` reference simply skips the unknown name (existing behaviour).\n *\n * Failure: name not registered → `Result.err(ScheduleMutationError)` with\n * `.code = 'system-before-unknown'` and `.detail.candidates` carrying the\n * registered names for AI-friendly typo recovery.\n */\nexport function removeSystem(\n schedule: Schedule,\n name: string,\n): Result<void, ScheduleMutationError> {\n if (!schedule.systems.has(name)) {\n return err(\n new ScheduleMutationError(\n 'system-before-unknown',\n `Cannot removeSystem: no system registered as \"${name}\".`,\n 'Call world.inspect().systems to discover registered names.',\n { candidates: [...schedule.systems.keys()] },\n ),\n );\n }\n schedule.systems.delete(name);\n // Prune set membership: remove this system name from every set's members (D-1).\n for (const [, setRecord] of schedule.sets) {\n setRecord.members.delete(name);\n }\n schedule.dirty = true;\n return ok(undefined);\n}\n\n/**\n * Replace a registered system in-place (M2 — plan-strategy D-3 atomic semantics).\n *\n * Overwrites the `descriptor` field of the existing `SystemRecord` while\n * keeping `registrationIndex` and the `Map` slot identical, so all `before /\n * after` edges that reference this name remain bound to the same slot. Marks\n * the schedule dirty: the next `runSchedule` re-sorts.\n *\n * Failure: name not registered → `Result.err(ScheduleMutationError)` with\n * `.code = 'system-before-unknown'`.\n */\nexport function replaceSystem<const Qs extends ReadonlyArray<QueryDescriptor>>(\n schedule: Schedule,\n name: string,\n descriptor: SystemDescriptor<Qs>,\n): Result<void, ScheduleMutationError> {\n const record = schedule.systems.get(name);\n if (!record) {\n return err(\n new ScheduleMutationError(\n 'system-before-unknown',\n `Cannot replaceSystem: no system registered as \"${name}\".`,\n 'Call world.inspect().systems to discover registered names; or addSystem(descriptor) to register a new system.',\n { candidates: [...schedule.systems.keys()] },\n ),\n );\n }\n record.descriptor = descriptor as unknown as SystemDescriptor;\n // Reset cached query states — descriptor.queries may have changed shape.\n record.queries = null;\n schedule.dirty = true;\n return ok(undefined);\n}\n\n/**\n * Batch-register systems to a set. Validates the set token before writing.\n *\n * - First call for a system name: registers via the existing `addSystem` path.\n * - Subsequent calls: only adds the system name to the set's members (dedup).\n * - `runIf` / `chained` are snapshotted from the token into the SetRecord on\n * first encounter.\n *\n * Returns `Result.err` with `SystemSetNotRegisteredError` if the set token\n * fails identity validation.\n */\nexport function addSystems<const Qs extends ReadonlyArray<QueryDescriptor>>(\n schedule: Schedule,\n set: SystemSet,\n systems: ReadonlyArray<SystemDescriptor<Qs>>,\n): Result<void, SystemSetNotRegisteredError> {\n const validated = validateSystemSetTokens([set]);\n if (!validated.ok) {\n return err(validated.error);\n }\n\n const setName = set.name;\n let record = schedule.sets.get(setName);\n if (!record) {\n record = {\n members: new Set(),\n runIf: set.runIf,\n chained: set.chained ?? false,\n };\n schedule.sets.set(setName, record);\n }\n\n for (const system of systems) {\n const name = system.name;\n // Dedup: only register the system once in schedule.systems.\n if (!schedule.systems.has(name)) {\n addSystem(schedule, system);\n }\n // Always add membership — multi-belong is supported.\n record.members.add(name);\n }\n\n schedule.dirty = true;\n return ok(undefined);\n}\n\n/**\n * Build the sorted execution order via Kahn's topological sort.\n * Throws CyclicDependencyError if a cycle is detected.\n *\n * @returns sorted system names\n */\nexport function buildSchedule(schedule: Schedule): string[] {\n const systems = schedule.systems;\n const names = [...systems.keys()];\n if (schedule.token.name === 'Update') names.push('FixedUpdate');\n const nameSet = new Set(names);\n\n // Build adjacency list + in-degree map.\n const adj = new Map<string, string[]>(); // adj[a] = [b] means a → b (a must run before b)\n const inDegree = new Map<string, number>();\n const predecessors = new Map<string, Set<string>>();\n\n for (const name of names) {\n adj.set(name, []);\n inDegree.set(name, 0);\n predecessors.set(name, new Set());\n }\n\n const addEdge = (source: string, target: string): void => {\n adj.get(source)?.push(target);\n predecessors.get(target)?.add(source);\n inDegree.set(target, (inDegree.get(target) ?? 0) + 1);\n };\n const orderReferenceName = (reference: string | ScheduleToken): string =>\n typeof reference === 'string' ? reference : reference.name;\n\n for (const [name, record] of systems) {\n const desc = record.descriptor;\n\n // \"after\" constraints: for each dep in after, dep → name (dep runs before name)\n if (desc.after) {\n for (const reference of desc.after) {\n const dep = orderReferenceName(reference);\n if (!nameSet.has(dep)) continue; // scope validation handles cross-schedule references\n addEdge(dep, name);\n }\n }\n\n // \"before\" constraints: for each target in before, name → target (name runs before target)\n if (desc.before) {\n for (const reference of desc.before) {\n const target = orderReferenceName(reference);\n if (!nameSet.has(target)) continue; // scope validation handles cross-schedule references\n addEdge(name, target);\n }\n }\n }\n\n // Set membership contributes only run conditions and optional chaining.\n for (const [, setRecord] of schedule.sets) {\n if (setRecord.chained) {\n const members = [...setRecord.members];\n for (let i = 0; i < members.length - 1; i++) {\n const m1 = members[i];\n const m2 = members[i + 1];\n if (!m1 || !m2 || !nameSet.has(m1) || !nameSet.has(m2)) continue;\n // m1 → m2 (m1 runs before m2)\n addEdge(m1, m2);\n }\n }\n }\n\n // Kahn's algorithm with registration-order tie-breaker.\n // Use a queue sorted by registrationIndex for deterministic ordering.\n const queue: string[] = [];\n for (const name of names) {\n if (inDegree.get(name) === 0) {\n queue.push(name);\n }\n }\n // Sort initial queue by registration index. The fixed anchor is intrinsic and\n // receives a deterministic slot after user systems with the same indegree.\n queue.sort(\n (a, b) =>\n (systems.get(a)?.registrationIndex ?? Number.MAX_SAFE_INTEGER) -\n (systems.get(b)?.registrationIndex ?? Number.MAX_SAFE_INTEGER),\n );\n\n const sorted: string[] = [];\n while (queue.length > 0) {\n // biome-ignore lint/style/noNonNullAssertion: while(queue.length > 0) guarantees shift() returns a value\n const current = queue.shift()!;\n sorted.push(current);\n\n const neighbors = adj.get(current) ?? [];\n // Collect newly freed neighbors, then sort by registration index\n const freed: string[] = [];\n for (const neighbor of neighbors) {\n const newDeg = (inDegree.get(neighbor) ?? 0) - 1;\n inDegree.set(neighbor, newDeg);\n if (newDeg === 0) {\n freed.push(neighbor);\n }\n }\n freed.sort(\n (a, b) =>\n (systems.get(a)?.registrationIndex ?? Number.MAX_SAFE_INTEGER) -\n (systems.get(b)?.registrationIndex ?? Number.MAX_SAFE_INTEGER),\n );\n queue.push(...freed);\n }\n\n // Cycle detection: if we didn't process all nodes, there's a cycle.\n if (sorted.length < names.length) {\n // Find nodes still with in-degree > 0 (part of cycle).\n const remaining = names.filter((n) => !sorted.includes(n));\n const cyclePath = findCyclePath(remaining, adj);\n throw new CyclicDependencyError(cyclePath);\n }\n\n schedule.sortedOrder = sorted;\n schedule.predecessors = predecessors;\n schedule.dirty = false;\n return sorted;\n}\n\n/**\n * Find a cycle path among the remaining (unprocessed) nodes.\n * Returns the cycle as a readonly array of node names.\n */\nfunction findCyclePath(remaining: string[], adj: Map<string, string[]>): readonly string[] {\n const remainSet = new Set(remaining);\n const visited = new Set<string>();\n const path: string[] = [];\n\n function dfs(node: string): readonly string[] | null {\n if (visited.has(node)) {\n // Found cycle: extract cycle from path\n const cycleStart = path.indexOf(node);\n const cycle = path.slice(cycleStart);\n cycle.push(node);\n return cycle;\n }\n visited.add(node);\n path.push(node);\n\n for (const neighbor of adj.get(node) ?? []) {\n if (!remainSet.has(neighbor)) continue;\n const result = dfs(neighbor);\n if (result) return result;\n }\n\n path.pop();\n return null;\n }\n\n for (const start of remaining) {\n visited.clear();\n path.length = 0;\n const result = dfs(start);\n if (result) return result;\n }\n\n /* istanbul ignore next -- fallback: DFS always finds cycle in remaining nodes */\n return remaining;\n}\n\nfunction poisonSystemFailure(world: World, systemName: string, cause: unknown): void {\n const poison = world[worldInternal].poisonExecution;\n poison({\n code: 'shared-kernel-failed',\n kernelName: `system:${systemName}`,\n cause,\n partialWrite: true,\n retryable: false,\n });\n}\n\nfunction abortOutstandingCommands(\n commandsBySystem: Map<string, ReturnType<typeof createCommandBuffer>>,\n): void {\n for (const commands of commandsBySystem.values()) {\n if (commands.status === 'open') commands.abort();\n }\n}\n\n/**\n * Execute all systems in sorted order. Rebuilds schedule if dirty.\n * Each system receives its query results and a command buffer.\n * The world parameter provides the archetype graph, component ID resolution,\n * and resource checks.\n *\n * Layer 2 (ParamValidation): query empty → skip, resource missing → invalid.\n * A returned Result error poisons the active frame and stops execution.\n */\nfunction runScheduleBody(\n schedule: Schedule,\n world: World,\n selectedNames: readonly string[] | undefined,\n commandsBySystem: Map<string, ReturnType<typeof createCommandBuffer>>,\n finalDrain = true,\n): void {\n if (schedule.dirty) {\n buildSchedule(schedule);\n }\n if (\n selectedNames === undefined &&\n schedule.sets.size === 0 &&\n commandsBySystem.size === 0 &&\n schedule.sortedOrder.every((name) => {\n const record = schedule.systems.get(name);\n return (\n record !== undefined &&\n record.descriptor.queries.length === 0 &&\n record.descriptor.runIf === undefined &&\n (schedule.predecessors.get(name)?.size ?? 0) === 0\n );\n })\n ) {\n for (const name of schedule.sortedOrder) {\n const record = schedule.systems.get(name);\n /* istanbul ignore next -- sortedOrder comes from systems Map keys */\n if (!record) continue;\n\n const commands = createCommandBuffer(world, {\n systemName: name,\n scheduleName: schedule.token.name,\n });\n commandsBySystem.set(name, commands);\n let returnValue: unknown;\n try {\n returnValue = record.descriptor.fn(world, [], commands);\n } catch (error) {\n abortOutstandingCommands(commandsBySystem);\n poisonSystemFailure(world, name, error);\n throw new SystemFailedError(name, schedule.token.name, error);\n }\n if (returnValue && typeof returnValue === 'object' && 'ok' in returnValue) {\n const result = returnValue as { ok: boolean; error?: unknown };\n if (result.ok === false && result.error !== undefined) {\n abortOutstandingCommands(commandsBySystem);\n poisonSystemFailure(world, name, result.error);\n throw new SystemFailedError(name, schedule.token.name, result.error);\n }\n }\n }\n if (finalDrain) {\n try {\n for (const commands of commandsBySystem.values()) {\n flushCommands(commands, world);\n }\n } catch (error) {\n abortOutstandingCommands(commandsBySystem);\n throw error;\n }\n }\n return;\n }\n const selected = selectedNames ? new Set(selectedNames) : undefined;\n\n // Build reverse map: system name → set names it belongs to (D-5).\n // Rebuilt each frame so removeSystem / replaceSystem membership changes\n // take effect on the next frame.\n const systemToSets = new Map<string, string[]>();\n for (const [setName, setRecord] of schedule.sets) {\n for (const memberName of setRecord.members) {\n if (schedule.systems.has(memberName)) {\n let list = systemToSets.get(memberName);\n if (!list) {\n list = [];\n systemToSets.set(memberName, list);\n }\n list.push(setName);\n }\n }\n }\n\n // Per-frame set runIf cache (D-5). Discarded at frame end — no cross-frame state.\n const setRunIfCache = new Map<string, boolean>();\n\n for (const name of schedule.sortedOrder) {\n if (selected && !selected.has(name)) continue;\n const record = schedule.systems.get(name);\n /* istanbul ignore next -- defensive: sortedOrder comes from systems Map keys */\n if (!record) continue;\n\n // Apply only buffers that have an explicit graph edge into this system.\n for (const predecessor of schedule.predecessors.get(name) ?? []) {\n const producerCommands = commandsBySystem.get(predecessor);\n if (producerCommands) {\n try {\n flushCommands(producerCommands, world);\n } catch (error) {\n abortOutstandingCommands(commandsBySystem);\n throw error;\n }\n }\n }\n\n // Lazily initialize the persistent executable queries on first run.\n if (record.queries === null) {\n record.queries = record.descriptor.queries.map((descriptor) => {\n const result = world.query(descriptor);\n if (!result.ok) throw result.error;\n return result.value;\n });\n }\n // ── Set-level runIf AND gate (D-5) ──\n // before system-level runIf. Each set's runIf is lazily cached per frame. ──\n const setNames = systemToSets.get(name);\n let allSetConditionsPass = true;\n if (setNames) {\n for (const setName of setNames) {\n const setRecord = schedule.sets.get(setName);\n if (setRecord?.runIf) {\n let cached = setRunIfCache.get(setName);\n if (cached === undefined) {\n cached = setRecord.runIf(world);\n setRunIfCache.set(setName, cached);\n }\n if (!cached) {\n allSetConditionsPass = false;\n break;\n }\n }\n }\n }\n if (!allSetConditionsPass) {\n continue; // skip system: no system runIf, query iteration, or fn\n }\n\n // ── Run condition (runIf) — evaluated after ParamValidation 'ok', before\n // query iteration. false -> skip silently (no query, no fn, no cursor advance). ──\n if (record.descriptor.runIf && !record.descriptor.runIf(world)) {\n continue;\n }\n\n // ── Layer 3: system execution + Result collection ──\n // trusted-cast: the descriptor tuple constructed the matching Query tuple above.\n const commands = createCommandBuffer(world, {\n systemName: name,\n scheduleName: schedule.token.name,\n });\n commandsBySystem.set(name, commands);\n let returnValue: unknown;\n try {\n returnValue = record.descriptor.fn(\n world,\n record.queries as Parameters<typeof record.descriptor.fn>[1],\n commands,\n );\n } catch (error) {\n abortOutstandingCommands(commandsBySystem);\n poisonSystemFailure(world, name, error);\n throw new SystemFailedError(name, schedule.token.name, error);\n }\n\n // A returned Result error is a poisoned frame failure.\n if (returnValue && typeof returnValue === 'object' && 'ok' in (returnValue as object)) {\n const result = returnValue as { ok: boolean; error?: unknown };\n if (result.ok === false && result.error !== undefined) {\n abortOutstandingCommands(commandsBySystem);\n poisonSystemFailure(world, name, result.error);\n throw new SystemFailedError(name, schedule.token.name, result.error);\n }\n }\n // void return is treated as successful execution.\n }\n\n if (finalDrain) {\n // A schedule boundary drains every remaining buffer, including commands\n // enqueued by lifecycle hooks while another command is being applied.\n try {\n for (const commands of commandsBySystem.values()) {\n flushCommands(commands, world);\n }\n } catch (error) {\n abortOutstandingCommands(commandsBySystem);\n throw error;\n }\n }\n}\n\n/**\n * Execute one schedule with a terminalization guard. Query construction,\n * run-if evaluation, DAG compilation, and command draining may all throw an\n * unexpected error; every still-open buffer is nevertheless aborted before the\n * error reaches World.update.\n */\nexport function runSchedule(\n schedule: Schedule,\n world: World,\n selectedNames?: readonly string[],\n commandsBySystem = new Map<string, ReturnType<typeof createCommandBuffer>>(),\n finalDrain = true,\n): void {\n let completed = false;\n try {\n runScheduleBody(schedule, world, selectedNames, commandsBySystem, finalDrain);\n completed = true;\n } finally {\n // When Update is split around the FixedUpdate anchor, the first segment\n // deliberately leaves its command buffers open so FixedUpdate observes a\n // stable pre-frame World and the second segment can drain them. Only the\n // final segment (or an exceptional exit) may abort outstanding buffers.\n if (!completed || finalDrain) abortOutstandingCommands(commandsBySystem);\n }\n}\n","// feat-20260713-mount-override-component-add-and-shared-ref-round M2 / w9 —\n// P3 shared-field value gate.\n//\n// `validateComponentDataKeys` (component-default-fallback.ts) checks that every\n// key in a spawn / addComponent / set payload is a declared schema field. It\n// does NOT check value TYPES. A `shared<T>` scalar / `array<shared<T>>` element\n// must be a resolved numeric Handle; a raw GUID string / `{ guid }` / `{ kind }`\n// object (the pre-resolution shape a sidecar hands an AI user) was silently\n// coerced to the all-zero sentinel by the column packer\n// (`typed[i] = typeof val === 'number' ? val : 0`) / scalar write path, so a\n// mis-bound reference read back as `0` / `[0,0,0,0]` and rendered blank with no\n// error.\n//\n// This module closes that value-type gap. It is a pure validator (no World /\n// store side effect) invoked at all three write entries (spawn / addComponent /\n// set) BEFORE any archetype mutation, mirroring the validate-first ordering of\n// `validateComponentDataKeys`. §2.5: it depends only on the schema field-type\n// SHAPE (`shared<...>` / `array<shared<...>>`), never on any GUID / asset\n// concretion — the GUID domain stays sealed in assets-runtime; ecs only sees a\n// numeric handle vs a non-handle.\n\nimport type { Component, ComponentSchema } from './component';\nimport { componentSchema } from './component';\nimport { componentDefinition } from './component-schema';\nimport { ManagedArrayInvalidValueError, SharedFieldInvalidValueError } from './errors';\n\n/** A resolved shared handle is a plain number (the branded Handle bit pattern). */\nfunction isNumericHandle(v: unknown): boolean {\n return typeof v === 'number';\n}\n\n/** `shared<T>` scalar field type. */\nfunction isSharedScalarType(fieldType: string): boolean {\n return fieldType.startsWith('shared<') && fieldType.endsWith('>');\n}\n\n/**\n * `array<shared<T>>` / `array<shared<T>, N>` field type. The inner element type\n * is a `shared<...>` template; we test the array wrapper and the `shared<`\n * infix rather than fully re-parsing (parseManagedArraySchema owns the strict\n * grammar — here we only need the coarse \"is this an array of shared refs\"\n * discriminant).\n */\nfunction isSharedArrayType(fieldType: string): boolean {\n if (!fieldType.startsWith('array<') || !fieldType.endsWith('>')) return false;\n const inner = fieldType.slice(6, -1);\n const head = inner.indexOf(',') === -1 ? inner : inner.slice(0, inner.indexOf(',')).trim();\n return head.startsWith('shared<') && head.endsWith('>');\n}\n\nfunction isArrayPayload(value: unknown): boolean {\n if (Array.isArray(value)) return true;\n // DataView and ArrayBuffer are views/buffers without an element `length`;\n // the storage writer cannot interpret them as a managed array payload.\n return ArrayBuffer.isView(value) && typeof (value as { length?: unknown }).length === 'number';\n}\n\n/**\n * Validate the outer value shape for every managed `array<T>` field present in\n * a write payload. This is deliberately a preflight-only check: element\n * coercion remains owned by the column writer, while arbitrary objects are\n * rejected before any row, buffer slot, retain, or epoch mutation can occur.\n */\nexport function validateManagedArrayValues<S extends ComponentSchema>(\n token: Component<string, S>,\n raw: Partial<Record<string, unknown>> | undefined,\n): ManagedArrayInvalidValueError | null {\n if (raw === undefined) return null;\n const fields = componentDefinition(token).fields as Readonly<\n Record<string, { readonly type: string; readonly arrayMeta?: unknown }>\n >;\n const rawObj = raw as Record<string, unknown>;\n for (const fieldName of Object.keys(rawObj)) {\n const reflection = fields[fieldName];\n if (reflection?.arrayMeta === undefined) continue;\n const value = rawObj[fieldName];\n // `fillComponentDefaults` deliberately uses numeric zero as the layer-3\n // raw sentinel for every non-entity array vocabulary. The column writer\n // owns translating that sentinel into an empty variable slot or a\n // zero-filled fixed row, so it must pass this preflight just like an\n // omitted/null value. Other scalar/object values remain invalid.\n if (value === 0) continue;\n if (value === undefined || value === null || isArrayPayload(value)) continue;\n return new ManagedArrayInvalidValueError(token.name, fieldName, reflection.type, value);\n }\n return null;\n}\n\n/**\n * Validate that every `shared<T>` scalar / `array<shared<T>>` element present in\n * `raw` is a resolved numeric Handle. Returns the FIRST offending field's\n * `SharedFieldInvalidValueError` (deterministic for AI users), or `null` on\n * success.\n *\n * Pure: no World / store side effect. Only fields PRESENT in `raw` are checked\n * (an omitted shared field takes its schema default — a numeric sentinel — via\n * `fillComponentDefaults`, so it is never a non-handle). `undefined` / `null`\n * values are treated as \"omitted\" (the write path routes them to the sentinel\n * intentionally); only a concrete non-numeric value (string / object) is a\n * mis-bound GUID and fails fast.\n *\n * @param token Component token (name + schema).\n * @param raw Caller's raw payload (spawn / addComponent / set value).\n * @returns `null` on success; `SharedFieldInvalidValueError` on the first\n * shared field bound to a non-handle value.\n */\nexport function validateSharedFieldValues<S extends ComponentSchema>(\n token: Component<string, S>,\n raw: Partial<Record<string, unknown>> | undefined,\n): SharedFieldInvalidValueError | null {\n if (raw === undefined) return null;\n const schema = componentSchema(token) as Record<string, string>;\n const rawObj = raw as Record<string, unknown>;\n for (const fieldName of Object.keys(rawObj)) {\n const fieldType = schema[fieldName];\n if (fieldType === undefined) continue; // key validation owns unknown keys.\n const value = rawObj[fieldName];\n if (value === undefined || value === null) continue; // omitted -> sentinel default.\n if (isSharedScalarType(fieldType)) {\n if (!isNumericHandle(value)) {\n return new SharedFieldInvalidValueError(token.name, fieldName, fieldType, value);\n }\n } else if (isSharedArrayType(fieldType)) {\n if (!Array.isArray(value)) continue; // non-array raw for an array field: write path no-ops.\n for (let i = 0; i < value.length; i++) {\n const el = value[i];\n if (el === undefined || el === null) continue;\n if (!isNumericHandle(el)) {\n return new SharedFieldInvalidValueError(token.name, fieldName, fieldType, el, i);\n }\n }\n }\n }\n return null;\n}\n","// @forgeax/engine-ecs — world-component-storage: row and resource storage.\n//\n// Owns the low-level archetype row representation, managed reference lifetime,\n// array/buffer byte storage, and archetype migration. WorldComponentAccess owns\n// the typed public component operations and composes this state capability.\n\nimport { BUILTIN_BASE, type Handle, toShared, toUnique, unwrapHandle } from '@forgeax/engine-types';\nimport type { BufferPool } from './buffer-pool';\nimport {\n type ArrayMeta,\n type Component,\n type ComponentSchema,\n componentId,\n componentSchema,\n fieldTypeToMetaKey,\n isEntityField,\n isManagedArrayField,\n isManagedBufferField,\n isManagedField,\n type ManagedArrayElementType,\n type ShapeOf,\n TYPE_METADATA,\n} from './component';\nimport { componentDefinition } from './component-schema';\nimport { Entity as EntityComponent } from './entity';\nimport { ENTITY_NULL_RAW, type EntityHandle, entityGeneration, entityIndex } from './entity-handle';\nimport type { ManagedArrayErrorEnvelope } from './errors';\n\ntype ErrorContext = { readonly systemName: string };\n\nimport type { SharedRefStore } from './shared-ref-store';\nimport { type Archetype, appendArchetypeRow, removeArchetypeRow } from './storage/archetype';\nimport { type ArchetypeGraph, getTable } from './storage/archetype-graph';\nimport { copyComponentEpoch } from './storage/change-detection';\nimport { arrayCountColumnName, type FieldView, normalizeBufferWrite } from './storage/column';\nimport { appendTableRow, removeTableRow, type Table } from './storage/table';\nimport type { UniqueRefStore } from './unique-ref-store';\nimport type { EntityRecord } from './world';\n\nexport interface ComponentStorageState {\n readonly graph: ArchetypeGraph;\n readonly records: EntityRecord[];\n readonly bufferPool: BufferPool;\n readonly uniqueRefs: UniqueRefStore;\n readonly sharedRefs: SharedRefStore;\n routeError(err: unknown, ctx: ErrorContext): void;\n}\n\nexport class ComponentStorage {\n constructor(private readonly state: ComponentStorageState) {}\n\n private get records(): EntityRecord[] {\n return this.state.records;\n }\n\n private table(archetype: Archetype): Table {\n return getTable(this.state.graph, archetype.tableId);\n }\n\n private get bufferPool(): BufferPool {\n return this.state.bufferPool;\n }\n\n private get uniqueRefs(): UniqueRefStore {\n return this.state.uniqueRefs;\n }\n\n private get sharedRefs(): SharedRefStore {\n return this.state.sharedRefs;\n }\n\n private routeError(err: unknown, ctx: ErrorContext): void {\n this.state.routeError(err, ctx);\n }\n\n readArrayView(\n arch: Archetype,\n component: Component,\n row: number,\n fieldName: string,\n ): FieldView | undefined {\n const fieldCols = this.table(arch).storage.get(componentId(component))?.fields;\n if (!fieldCols) return undefined;\n\n const fieldType = componentSchema(component)[fieldName];\n if (fieldType === undefined) return undefined;\n // Component reflection already parses and freezes array metadata at\n // registration time. Reusing it here keeps the per-entity zero-copy path\n // parse-free; this accessor is called once for every renderable every\n // frame. The field lookup also preserves the existing undefined result\n // for non-array fields without reparsing arbitrary schema strings.\n const arrayMeta = componentDefinition(component).fields[fieldName]?.arrayMeta;\n if (arrayMeta === undefined) return undefined;\n\n const col = fieldCols.get(fieldName);\n if (!col) return undefined;\n\n if (arrayMeta.length !== undefined) {\n const elementBytes = elementByteSize(arrayMeta.elementType);\n const arity = col.arity;\n const rowByteOffset = col.view.byteOffset + row * arity * elementBytes;\n return reinterpretBufferRegion(\n col.view.buffer,\n rowByteOffset,\n arrayMeta.elementType,\n arrayMeta.length,\n );\n }\n\n const slotId = col.view[row] as number;\n const liveBytes = this.bufferPool.view(slotId);\n const countCol = fieldCols.get(arrayCountColumnName(fieldName));\n const elementCount = (countCol?.view[row] as number | undefined) ?? 0;\n return reinterpretSlotBytes(liveBytes, arrayMeta.elementType, elementCount);\n }\n\n /**\n * Read the live length of an array field without materialising a typed view.\n * Relationship consumers use this narrow storage seam for hot reverse-list\n * walks; the target array remains owned by the ECS column and no snapshot is\n * created per entity.\n */\n readArrayLength(\n arch: Archetype,\n component: Component,\n row: number,\n fieldName: string,\n ): number | undefined {\n const fieldCols = this.table(arch).storage.get(componentId(component))?.fields;\n if (fieldCols === undefined) return undefined;\n const arrayMeta = componentDefinition(component).fields[fieldName]?.arrayMeta;\n if (arrayMeta === undefined) return undefined;\n if (arrayMeta.length !== undefined) return arrayMeta.length;\n const count = fieldCols.get(arrayCountColumnName(fieldName))?.view[row];\n return typeof count === 'number' ? count : 0;\n }\n\n /**\n * Read one array element directly from its backing column/BufferPool slot.\n * The relationship target vocabulary is `array<entity>`, so its hot path\n * decodes the packed u32 in-place and does not allocate a TypedArray view.\n */\n readArrayElement(\n arch: Archetype,\n component: Component,\n row: number,\n fieldName: string,\n index: number,\n ): number | undefined {\n if (!Number.isSafeInteger(index) || index < 0) return undefined;\n const fieldCols = this.table(arch).storage.get(componentId(component))?.fields;\n if (fieldCols === undefined) return undefined;\n const arrayMeta = componentDefinition(component).fields[fieldName]?.arrayMeta;\n if (arrayMeta === undefined) return undefined;\n const length = this.readArrayLength(arch, component, row, fieldName);\n if (length === undefined || index >= length) return undefined;\n const col = fieldCols.get(fieldName);\n if (col === undefined) return undefined;\n if (arrayMeta.length !== undefined) {\n return col.view[row * col.arity + index] as number;\n }\n const slotId = col.view[row] as number;\n const bytes = this.bufferPool.view(slotId);\n if (arrayMeta.elementType === 'entity') {\n const byteOffset = index * 4;\n if (byteOffset + 4 > bytes.byteLength) return undefined;\n return (\n ((bytes[byteOffset] ?? 0) |\n ((bytes[byteOffset + 1] ?? 0) << 8) |\n ((bytes[byteOffset + 2] ?? 0) << 16) |\n ((bytes[byteOffset + 3] ?? 0) << 24)) >>>\n 0\n );\n }\n return this.readArrayElementAt(bytes, index, arrayMeta.elementType);\n }\n\n /** Read one scalar field without constructing a component shape. */\n readFieldValue(\n arch: Archetype,\n component: Component,\n row: number,\n fieldName: string,\n ): number | undefined {\n return this.table(arch).storage.get(componentId(component))?.fields.get(fieldName)?.view[row] as\n | number\n | undefined;\n }\n\n // ──────────────────────────────────────────────────────────────────────────\n // Internal — archetype data read/write\n // ──────────────────────────────────────────────────────────────────────────\n\n readRow<S extends ComponentSchema>(\n arch: Archetype,\n component: Component<string, S>,\n row: number,\n ): ShapeOf<S> {\n const localId = componentId(component);\n const fieldCols = this.table(arch).storage.get(localId)?.fields;\n const out = {} as ShapeOf<S>;\n /* istanbul ignore next -- defensive: component is registered and arch has it */\n if (!fieldCols) {\n return out;\n }\n for (const [fieldName, fieldType] of Object.entries(componentSchema(component))) {\n const col = fieldCols.get(fieldName);\n if (!col) {\n continue;\n }\n const raw = col.view[row];\n if (fieldType === 'bool') {\n (out as Record<string, unknown>)[fieldName] = raw === 1;\n } else if (isEntityField(fieldType)) {\n // Entity field: decode the stored raw u32 verbatim back to Entity\n // (or null when the slot carries the ENTITY_NULL_RAW sentinel). No\n // liveness validation happens here -- a slot referencing a despawned\n // target returns its original raw encoding unchanged; the consumer is\n // responsible for checking liveness (e.g. `world.get(ref, Entity)`).\n (out as Record<string, unknown>)[fieldName] = raw === ENTITY_NULL_RAW ? null : raw;\n } else if (isManagedBufferField(fieldType)) {\n if (fieldType !== 'buffer') {\n // feat-20260602: fixed `buffer<N>` lives inline (stride-N u8 column,\n // arity = N). Return the row's byte window directly -- no pool slot.\n const arity = col.arity;\n (out as Record<string, unknown>)[fieldName] = (col.view as Uint8Array).subarray(\n row * arity,\n row * arity + arity,\n );\n } else {\n // Variable `'buffer'`: column stores slot id; the live view is\n // resolved on demand so post-grow callers always see the refreshed\n // Uint8Array.\n (out as Record<string, unknown>)[fieldName] = this.bufferPool.view(raw as number);\n }\n } else if (fieldType === 'string') {\n // M1 string-field read path (AC-03 / AC-09): resolve the column\n // u32 handle through UniqueRefStore -- same dispatch arm as the\n // 'unique<T>' read (D-R3). Returns the native JS string payload by\n // strong reference; identity is stable across reads until the\n // next set or release (AC-03 read-side identity contract).\n // Released / sentinel handles surface as unique-ref-released via\n // resolve; we fall back to '' rather than propagate the error so\n // the read shape (`out.value: string`) stays total -- AI users\n // never see undefined or wrapper objects.\n const resolveR = this.uniqueRefs.resolve<'String'>(toUnique<'String'>(raw as number));\n (out as Record<string, unknown>)[fieldName] = resolveR.ok ? resolveR.value : '';\n } else {\n const arrayMeta = componentDefinition(component).fields[fieldName]?.arrayMeta;\n if (arrayMeta !== undefined) {\n // Internal row path: materialise a fresh TypedArray view each call\n // without copying its backing bytes. Public World.get detaches a\n // relationship target array after this read; ECS relationship and\n // Scene owners use this readRow seam as zero-copy storage access.\n (out as Record<string, unknown>)[fieldName] = this.materializeArrayView(\n arch,\n component,\n row,\n fieldName,\n arrayMeta.elementType,\n arrayMeta.length,\n raw as number,\n );\n } else {\n (out as Record<string, unknown>)[fieldName] = raw;\n }\n }\n }\n return out;\n }\n\n /**\n * Write the full packed entity handle into the row's essential id=0 `Entity`\n * column (`self` field). Called by `spawn` / `_materializePendingEntity`\n * after the row is appended (feat-20260602 / plan-strategy D-3). The column\n * always exists -- `createArchetype` folds the Entity column into every\n * archetype -- so this is a direct u32 store, no readRow/writeRow walk.\n */\n writeEntitySelf(arch: Archetype, row: number, handle: EntityHandle): void {\n const col = this.table(arch).storage.get(componentId(EntityComponent))?.fields.get('self');\n /* istanbul ignore next -- defensive: Entity column is folded into every archetype */\n if (!col) return;\n col.view[row] = handle as unknown as number;\n }\n\n writeRow<S extends ComponentSchema>(\n arch: Archetype,\n component: Component<string, S>,\n row: number,\n value: ShapeOf<S>,\n options?: { readonly skipVariableArrayInitialization?: boolean },\n ): void {\n const localId = componentId(component);\n const fieldCols = this.table(arch).storage.get(localId)?.fields;\n /* istanbul ignore next -- defensive: component is registered and arch has it */\n if (!fieldCols) {\n return;\n }\n for (const [fieldName, fieldType] of Object.entries(componentSchema(component))) {\n const col = fieldCols.get(fieldName);\n /* istanbul ignore next -- defensive: schema fields always have columns */\n if (!col) {\n continue;\n }\n const raw = (value as Record<string, unknown>)[fieldName];\n if (fieldType === 'bool') {\n col.view[row] = raw ? 1 : 0;\n } else if (isEntityField(fieldType)) {\n // M3 entity field: encode (slot, gen) into u32 column. `null`\n // / undefined map to ENTITY_NULL_RAW sentinel.\n col.view[row] = raw === null || raw === undefined ? ENTITY_NULL_RAW : (raw as number);\n } else if (isManagedBufferField(fieldType)) {\n // M2 spawn path: collapsed-vocab keyword family `'buffer'` (variable)\n // + `'buffer<N>'` (fixed):\n // - `buffer<N>` (feat-20260602) — lives inline as a stride-N u8\n // column (arity = N). Copy any provided payload straight into the\n // row window (truncate to N); no BufferPool slot.\n // - `'buffer'` — variable capacity; alloc one BufferPool slot sized\n // to the provided payload's byteLength. Missing / non-buffer raw\n // -> alloc(0) zero-length live view (verify round 1 B2 fix path;\n // pre-fix the bare keyword routed `bufferFieldByteLength('buffer')`\n // -> NaN -> alloc(NaN) -> managed-buffer-out-of-bounds, dropping\n // the payload bytes silently). Failures route to Layer 3\n // ErrorHandler; column slot stays at 0 (sentinel) so subsequent\n // release short-circuits.\n // raw is normalized from any AllowSharedBufferSource view to a\n // Uint8Array over its bytes (feat-20260621 V2 / AC-A4).\n const bytes = normalizeBufferWrite(raw);\n if (fieldType !== 'buffer') {\n const arity = col.arity;\n if (bytes !== null) {\n const copyLen = Math.min(bytes.byteLength, arity);\n (col.view as Uint8Array).set(bytes.subarray(0, copyLen), row * arity);\n }\n } else {\n const allocBytes = bytes !== null ? bytes.byteLength : 0;\n const allocR = this.bufferPool.alloc(allocBytes);\n if (!allocR.ok) {\n const ctx: ErrorContext = {\n systemName: `World.spawn (${component.name}.${fieldName})`,\n };\n this.routeError(allocR.error, ctx);\n col.view[row] = 0;\n continue;\n }\n const slot = allocR.value;\n if (bytes !== null) {\n // allocBytes is the payload's exact byteLength so no truncation.\n const copyLen = Math.min(bytes.byteLength, slot.view.byteLength);\n slot.view.set(bytes.subarray(0, copyLen));\n }\n col.view[row] = slot.id;\n }\n } else if (fieldType === 'string') {\n // M1 string-field spawn path (AC-04 / AC-06): route the JS string\n // payload through `uniqueRefs.alloc('String', text)` -- the same\n // UniqueRefStore the `ref<T>` arm uses (D-R3 single-arm dispatch).\n // The store holds the immutable string by strong reference so\n // identity is stable across reads (AC-03). Missing / non-string raw\n // falls back to '' so AI users always see a readable string on\n // get (no nullable handling).\n const text = typeof raw === 'string' ? raw : '';\n const handle = this.uniqueRefs.alloc<'String'>('String', text);\n col.view[row] = unwrapHandle(handle);\n } else {\n const arrayMeta = componentDefinition(component).fields[fieldName]?.arrayMeta;\n if (arrayMeta !== undefined) {\n if (options?.skipVariableArrayInitialization === true && arrayMeta.length === undefined) {\n // Relationship preparation can reserve the first target slot\n // before the mirror archetype is created. Leave the fresh row at\n // the sentinel until the owner installs that reservation; this\n // keeps an injected alloc failure out of the structural path.\n col.view[row] = 0;\n const countCol = fieldCols.get(arrayCountColumnName(fieldName));\n if (countCol !== undefined) countCol.view[row] = 0;\n continue;\n }\n // M1 spawn path for array<T> / array<T,N> fields (D-3 double-\n // column for variable; single column for fixed).\n // Spawn path: no prior-slot release (fresh rows carry stale debris\n // owned by the migrated entity in the new archetype) — feat-20260614\n // D-3 calling convention.\n this.writeArrayField(arch, component, row, fieldName, fieldType, arrayMeta, raw);\n } else {\n col.view[row] = raw as number;\n // feat-20260614 M5 / D-5: scalar 'shared<T>' spawn retain. The\n // alloc-grant rc=1 stays held by the producer (e.g. AssetRegistry);\n // each ECS holder bumps rc via this retain so despawn / overwrite\n // releases bring rc back symmetrically. Sentinel slot 0 is a no-op.\n if (fieldType.startsWith('shared<') && (raw as number) !== 0) {\n this.retainSharedScalarHandle(raw as number, component.name, fieldName);\n }\n }\n }\n }\n }\n\n // ──────────────────────────────────────────────────────────────────────────\n // Internal — managed-ref + managed-buffer release loop (M1 / M2)\n // ──────────────────────────────────────────────────────────────────────────\n\n /**\n * Release every managed-resource field on `component` for the row at\n * `row` in `arch`. Walks the schema once and delegates each field to\n * `releaseManagedFieldOnRow` (feat-20260614 M2 SSOT). Family coverage\n * (per-field) lives in that helper's JSDoc.\n *\n * Naming note (D-6 whitelist): the prefix `managed` here means\n * `managed = ECS-tracked` — i.e. fields whose lifecycle the ECS\n * actively releases on despawn / overwrite / removeComponent. It does\n * NOT refer to the retired `'managed' | 'unmanaged'` Handle brand\n * (renamed to `'unique' | 'shared'` in feat-20260614 M1). The helper\n * walks BOTH `'unique<T>'` and `'shared<T>'` fields because both are\n * ECS-tracked from the column's perspective; the per-field dispatch\n * inside `releaseManagedFieldOnRow` distinguishes drop-on-despawn\n * (unique) vs ref-counted release (shared).\n *\n * Skips sentinel slots (handle / id 0) and missing stores. Failures\n * (double release / lookup mismatch) route to the Layer 3 ErrorHandler so\n * the despawn / removeComponent chain never aborts (charter: explicit-\n * failure boundary; the chain is total).\n *\n * Four release paths route through this helper (AC-11, plan §6 M2):\n * 1. `world.despawn(e)` - every component on `e`.\n * 2. `world.removeComponent(e, C)` - the removed component only.\n * 3. `world.set` ref/string/buffer overwrite - per-field, before the new\n * value lands in the column.\n * 4. `writeArrayField` set arm prior-slot release (variable array<T>).\n *\n * After feat-20260614 M2 SSOT collapse the schema-field 3-arm dispatch\n * lives in `releaseManagedFieldOnRow` (one site); this method walks the\n * component schema and delegates per field.\n *\n * BufferPool slot id is reusable post-release: same-bucket free-list LIFO\n * (D-7) returns the freed id on the next `alloc(byteLength)`. Tests:\n * `__tests__/managed-array-release.test.ts` (w10) +\n * `__tests__/world-managed-roundtrip.unit.test.ts` (w3 net-zero matrix).\n */\n releaseManagedRefsOnRow(arch: Archetype, component: Component, row: number): void {\n const fieldCols = this.table(arch).storage.get(componentId(component))?.fields;\n if (!fieldCols) return;\n for (const fieldName of Object.keys(componentSchema(component))) {\n this.releaseManagedFieldOnRow(arch, component, row, fieldName);\n }\n }\n\n /**\n * SSOT release dispatch for a single managed field on a row (feat-20260614\n * M2 / D-2). Inspects the component schema's field type and routes to the\n * matching release path:\n *\n * - `'unique<T>'` / `'string'` (`isManagedField`) — release the\n * UniqueRefStore handle u32 stored in the column.\n * - `'buffer'` variable (`isManagedBufferField`) — release the\n * BufferPool slot id stored in the column. Fixed `'buffer<N>'` is\n * inline stride-N (feat-20260602) and has no slot to release.\n * - `array<T>` variable (`isManagedArrayField`) — release the\n * BufferPool slot id in the primary column + zero the column and the\n * `<fieldName>:count` sidecar so post-recycle reads observe count=0\n * (defense-in-depth; the swap-pop row migration overwrites both\n * columns anyway). Fixed `array<T,N>` is inline stride-N — nothing to\n * release.\n *\n * Sentinel handle / slot id 0 short-circuits silently. Double-release /\n * lookup mismatch routes via Layer 3 ErrorHandler so the despawn /\n * removeComponent / set chain never aborts (charter explicit-failure\n * boundary; the chain is total).\n *\n * SceneInstance state alloc/release rollback at world.ts:3494/3522 stays\n * a direct `uniqueRefs.release(stateRef)` (research Finding 1.8 / D-5):\n * those two sites are alloc-pair rollback, not schema-field dispatch.\n *\n * Naming note (D-6 whitelist): `releaseManagedFieldOnRow` uses\n * `managed = ECS-tracked` — every field family this dispatcher knows\n * (`'unique<T>'`, `'shared<T>'`, `'string'`, variable `'buffer'`,\n * variable `'array<T>'`) is one whose lifecycle the ECS owns. The\n * `'managed' | 'unmanaged'` Handle brand is gone (M1 renamed to\n * `'unique' | 'shared'`); the helper name was deliberately kept\n * because `managed` here is a column-side semantic, not a brand label.\n */\n releaseManagedFieldOnRow(\n arch: Archetype,\n component: Component,\n row: number,\n fieldName: string,\n ): void {\n const fieldCols = this.table(arch).storage.get(componentId(component))?.fields;\n if (!fieldCols) return;\n const col = fieldCols.get(fieldName);\n if (!col) return;\n const fieldType = (componentSchema(component) as Record<string, string>)[fieldName] ?? '';\n if (isManagedField(fieldType)) {\n // Sub-dispatch by the schema-vocab keyword (feat-20260614 M4 / AC-08):\n // - 'shared<T>' scalar -> SharedRefStore.release (rc--; drop on rc=0)\n // - 'unique<T>' / 'string' -> UniqueRefStore.release (direct slot drop)\n // Both column shapes are u32 handles; the lookup store differs.\n // Keeping both arms inside the unified `isManagedField` block is\n // intentional: meta key (TYPE_METADATA `'shared'` vs `'ref'`) decides\n // the store, not a separate top-level branch (architecture-principles\n // §1 SSOT — meta key = release semantics).\n const handleU32 = col.view[row] as number;\n if (fieldType.startsWith('shared<')) {\n this.releaseSharedRefHandle(handleU32, component.name, fieldName);\n return;\n }\n this.releaseManagedRefHandle(handleU32, component.name, fieldName);\n return;\n }\n if (isManagedBufferField(fieldType)) {\n if (fieldType === 'buffer') {\n const slotId = col.view[row] as number;\n this.releaseManagedBufferSlot(slotId, component.name, fieldName);\n col.view[row] = 0;\n }\n return;\n }\n if (isManagedArrayField(fieldType)) {\n // Use the pre-parsed arrayMeta cached on the component descriptor at\n // registration (AC-03c parse-free hot path); reaching for\n // `parseManagedArraySchema` here would violate the parse-free\n // invariant exercised by hierarchy.unit.test.ts §w5 AC-03(a).\n const arrayMeta = componentDefinition(component).fields[fieldName]?.arrayMeta;\n if (arrayMeta === undefined) return;\n const isSharedElement = arrayMeta.elementType.startsWith('shared<');\n if (arrayMeta.length === undefined) {\n // Variable `array<T>`: BufferPool slot id in primary column + live\n // count in `<fieldName>:count` sidecar. For `array<shared<T>>`,\n // walk live elements and release each shared handle BEFORE\n // releasing the slot bytes (feat-20260614 M4 / D-3 — slot bytes\n // are only valid until the slot is recycled).\n const slotId = col.view[row] as number;\n const countCol = fieldCols.get(arrayCountColumnName(fieldName));\n if (isSharedElement && slotId !== 0) {\n const liveCount = countCol !== undefined ? (countCol.view[row] as number) : 0;\n const slotView = liveCount > 0 ? this.bufferPool.view(slotId) : null;\n if (slotView !== null && slotView.byteLength > 0) {\n this.releaseSharedArrayElements(slotView, liveCount);\n }\n }\n this.releaseManagedBufferSlot(slotId, component.name, fieldName);\n col.view[row] = 0;\n if (countCol !== undefined) countCol.view[row] = 0;\n return;\n }\n // Fixed `array<T,N>` (feat-20260602): inline stride-N column, no\n // BufferPool slot to release. For `array<shared<T>,N>`, walk the N\n // inline elements and release each shared handle. Zero the row\n // window so subsequent writes do not double-release.\n if (isSharedElement) {\n const arity = col.arity;\n const elementBytes = (TYPE_METADATA.shared?.byteSize ?? 4) as number;\n const rowByteOffset = col.view.byteOffset + row * arity * elementBytes;\n const rowBytes = new Uint8Array(col.view.buffer, rowByteOffset, arity * elementBytes);\n this.releaseSharedArrayElements(rowBytes, arity);\n rowBytes.fill(0);\n }\n }\n }\n\n /**\n * Release a single managed handle u32. Routes failures through Layer 3.\n * Slot-0 sentinel short-circuits silently (no error); already-released\n * slots surface `unique-ref-double-release` through the ErrorHandler so\n * AI users see the structured payload (`.code` / `.hint` / `.expected` /\n * `.detail`) - charter explicit-failure boundary.\n *\n * Helper-internal only after feat-20260614 M2 (AC-03 grep gate). External\n * callers route via `releaseManagedFieldOnRow`.\n */\n releaseManagedRefHandle(handleU32: number, componentName: string, fieldName: string): void {\n if (handleU32 === 0) return; // sentinel: skip silently.\n const r = this.uniqueRefs.release(handleU32 as Handle<string, 'unique'>);\n if (r.ok) return;\n // Layer 3 routing: surface double-release as a structured error so AI\n // users see {code, hint, expected, detail} on their handler. Severity\n // defaults to Error so the chain continues; matchSeverity prints to\n // console.error rather than throw.\n const ctx: ErrorContext = {\n systemName: `World.release (${componentName}.${fieldName})`,\n };\n this.routeError(r.error, ctx);\n }\n\n /**\n * Release a single shared-ref handle u32 (feat-20260614 M4 / AC-08).\n * Decrements the SharedRefStore refcount; the slot drops on rc 1 -> 0.\n * Slot-0 sentinel short-circuits silently. Already-released slots route\n * `shared-ref-double-release` through Layer 3 ErrorHandler so AI users\n * see structured payloads (charter explicit-failure boundary).\n *\n * Mirrors `releaseManagedRefHandle` in shape; the store + error code are\n * the only differences. Helper-internal — external callers route via\n * `releaseManagedFieldOnRow` (D-2 SSOT).\n */\n releaseSharedRefHandle(handleU32: number, componentName: string, fieldName: string): void {\n // feat-20260614 M6 D-15 / R-14: builtin slots (< BUILTIN_BASE, including the\n // sentinel 0) are process-static and never reference-counted -> short-circuit\n // before touching SharedRefStore. This single guard is the SSOT for both the\n // scalar arm (here) and the array-element arm (releaseSharedArrayElements).\n if (handleU32 < BUILTIN_BASE) return;\n const r = this.sharedRefs.release(toShared<string>(handleU32));\n if (r.ok) return;\n const ctx: ErrorContext = {\n systemName: `World.release (${componentName}.${fieldName})`,\n };\n this.routeError(r.error, ctx);\n }\n\n /**\n * Retain a single `shared<T>` scalar slot id (feat-20260614 M5 / D-5).\n * Mirrors `releaseSharedRefHandle`; called from spawn / set scalar write\n * paths so each ECS holder participates in the SharedRefStore rc.\n * Sentinel slot 0 is a no-op. Failures (handle already released) route\n * via Layer 3 ErrorHandler so the spawn / set chain stays total.\n */\n retainSharedScalarHandle(handleU32: number, componentName: string, fieldName: string): void {\n // feat-20260614 M6 D-15 / R-14: builtin slots (< BUILTIN_BASE, including the\n // sentinel 0) short-circuit — process-static, never reference-counted. SSOT\n // guard shared with the array-element arm (retainSharedArrayElements).\n if (handleU32 < BUILTIN_BASE) return;\n const r = this.sharedRefs.retain(toShared<string>(handleU32));\n if (r.ok) return;\n const ctx: ErrorContext = {\n systemName: `World.write (${componentName}.${fieldName} shared scalar retain)`,\n };\n this.routeError(r.error, ctx);\n }\n\n /**\n * Release a single managed buffer slot id. Routes failures through Layer 3.\n * Slot id 0 (sentinel for unallocated buffer fields) short-circuits\n * silently. M2 v1 release surface is total - `BufferPool.release` returns\n * `Result<void, never>` for unknown ids, so the chain stays noise-free.\n *\n * Helper-internal only after feat-20260614 M2 (AC-03 grep gate). External\n * callers route via `releaseManagedFieldOnRow`.\n */\n releaseManagedBufferSlot(slotId: number, componentName: string, fieldName: string): void {\n if (slotId === 0) return; // sentinel: skip silently.\n const r = this.bufferPool.release(slotId);\n /* istanbul ignore if -- BufferPool.release is total in v1 (Result<void, never>); branch reserved for future fail-fast extension. */\n if (!r.ok) {\n const ctx: ErrorContext = {\n systemName: `World.release (${componentName}.${fieldName})`,\n };\n this.routeError(r.error, ctx);\n }\n }\n\n // ──────────────────────────────────────────────────────────────────────────\n // Internal — array<T> / array<T,N> spawn / set helpers (M1 / w7)\n // ──────────────────────────────────────────────────────────────────────────\n\n /**\n * Bridge a Layer-3 ErrorHandler call from a `ManagedArrayErrorEnvelope`.\n * The envelope shape (`code / hint / expected / detail`) already mirrors\n * the EcsError contract; this helper only attaches the systemName context\n * so AI users can correlate the error with the holder component / field.\n */\n routeArrayError(err: ManagedArrayErrorEnvelope, componentName: string, fieldName: string): void {\n const ctx: ErrorContext = {\n systemName: `World.write (${componentName}.${fieldName})`,\n };\n this.routeError(err, ctx);\n }\n\n /**\n * Write the value of an `array<T>` / `array<T,N>` field at `row` (D-3 +\n /**\n * Write an `array<T>` / `array<T,N>` field's payload at `row` (M1 / w7,\n * D-1; feat-20260614 M2 / D-3). Spawn and set both delegate here without\n * an `operation` parameter — the caller's calling convention encodes the\n * difference:\n * - Set path: caller invokes `releaseManagedFieldOnRow(arch, comp, row,\n * fieldName)` BEFORE this method to release the prior slot (variable\n * `array<T>`). Fixed `array<T,N>` is inline stride-N (feat-20260602)\n * and has no slot to release on either path.\n * - Spawn path: caller does NOT call the helper — fresh rows treat any\n * non-zero u32 in the column as stale swap-pop debris owned by the\n * migrated entity in the new archetype.\n *\n * Body:\n * - Alloc a fresh BufferPool slot of `payload.length * elementBytes`.\n * - Copy bytes from the payload's typed-array buffer into the slot view.\n * - Persist slot id in the primary u32 column. For `array<T>` (variable),\n * persist the live count in the sidecar `<fieldName>:count` column.\n *\n * Errors flow through `routeArrayError` with a uniform `World.write` label.\n */\n writeArrayField(\n arch: Archetype,\n component: Component,\n row: number,\n fieldName: string,\n _fieldType: string,\n arrayMeta: ArrayMeta,\n raw: unknown,\n ): void {\n const fieldCols = this.table(arch).storage.get(componentId(component))?.fields;\n /* istanbul ignore next -- writeArrayField caller validated the column map */\n if (!fieldCols) return;\n const col = fieldCols.get(fieldName);\n /* istanbul ignore next -- writeArrayField caller validated the column */\n if (!col) return;\n\n const elementType = arrayMeta.elementType;\n // Normalize parametrised element-type template literals to the family\n // key for TYPE_METADATA lookup; the column stores plain u32 handles\n // either way:\n // - `shared<X>` -> 'shared' (feat-20260614 M4 / D-3 -- element-level\n // retain/release semantics route via the dedicated `'shared'` arm\n // below)\n const metaKey = elementType.startsWith('shared<') ? 'shared' : (elementType as string);\n const meta = TYPE_METADATA[metaKey];\n /* istanbul ignore next -- arrayMeta.elementType is guaranteed in TYPE_METADATA */\n if (!meta) return;\n // biome-ignore lint/style/noNonNullAssertion: ManagedArrayElementType always scalar -> byteSize present\n const elementBytes = meta.byteSize!;\n\n const isVariable = arrayMeta.length === undefined;\n const fixedLength = arrayMeta.length ?? 0;\n\n // Determine the payload's logical element count. Accept any TypedArray\n // (Float32Array / Uint32Array / etc.) plus plain numeric arrays; an\n // undefined / missing payload is treated as a length-0 init. Bytes are\n // copied from the source's underlying ArrayBuffer when present.\n let payloadCount = 0;\n let payloadBytes: Uint8Array | null = null;\n if (raw !== null && raw !== undefined) {\n if (\n raw instanceof Float32Array ||\n raw instanceof Float64Array ||\n raw instanceof Int32Array ||\n raw instanceof Uint32Array ||\n raw instanceof Int16Array ||\n raw instanceof Uint16Array ||\n raw instanceof Int8Array ||\n raw instanceof Uint8Array\n ) {\n payloadCount = raw.length;\n payloadBytes = new Uint8Array(raw.buffer, raw.byteOffset, raw.byteLength);\n } else if (Array.isArray(raw)) {\n payloadCount = raw.length;\n // Plain JS array: pack each element through the declared element\n // type's TypedArray constructor (`meta.viewCtor`) so the numeric\n // VALUE is encoded, not its integer bit pattern. Dispatching on\n // `viewCtor` (the type SSOT) rather than byte size is what keeps\n // `array<f32,N>` distinct from `array<u32,N>` -- both are 4 bytes,\n // so a size-keyed setter would store an f32 `1.0` as the u32 bits\n // `0x00000001` (reads back ~1.4e-45). The TypedArray then exposes\n // its little-endian bytes for the shared copy path below.\n if (payloadCount > 0 && meta.viewCtor !== undefined) {\n const typed = new meta.viewCtor(payloadCount);\n for (let i = 0; i < payloadCount; i++) {\n const val = raw[i];\n typed[i] = typeof val === 'number' ? val : 0;\n }\n payloadBytes = new Uint8Array(typed.buffer, typed.byteOffset, typed.byteLength);\n }\n }\n }\n\n // Effective count for variable arrays = payload count; for fixed\n // arrays = schema-declared N (the payload's length is advisory — we\n // copy up to N elements and pad the rest with zero).\n const effectiveCount = isVariable ? payloadCount : fixedLength;\n\n // Fixed `array<T,N>` (feat-20260602): the column is an inline stride-N\n // view (`col.arity === N`), so write the payload bytes directly into the\n // row's stride window — no BufferPool slot, no slot-id store, no\n // prior-slot release. The byte window starts at `row * arity * elementBytes`\n // and spans N elements; payloads shorter than N copy a prefix and leave\n // the tail at its current value (spawn rows are zero-initialised by the\n // fresh column buffer; the swap-pop migration copies the whole block).\n if (!isVariable) {\n const arity = col.arity;\n const rowByteOffset = col.view.byteOffset + row * arity * elementBytes;\n const rowBytes = new Uint8Array(col.view.buffer, rowByteOffset, arity * elementBytes);\n const copyLen =\n payloadBytes === null ? 0 : Math.min(payloadBytes.byteLength, rowBytes.byteLength);\n if (copyLen > 0 && payloadBytes !== null) {\n rowBytes.set(payloadBytes.subarray(0, copyLen));\n }\n // Zero the tail past the copied prefix so a short / missing payload\n // matches the prior fresh-slot semantics (the old pool path always\n // alloc'd a zeroed slot, so unwritten elements read back as 0).\n if (copyLen < rowBytes.byteLength) {\n rowBytes.fill(0, copyLen);\n }\n // feat-20260614 M4 / D-3: `array<shared<T>,N>` element-level retain.\n // Walk the copied prefix as u32 handles and retain each non-sentinel\n // element. Caller releases priors via `releaseManagedFieldOnRow` on\n // the set path (D-3 calling convention); the spawn path's fresh row\n // is zero-initialised so no priors exist.\n if (metaKey === 'shared' && copyLen > 0) {\n this.retainSharedArrayElements(rowBytes, copyLen >>> 2);\n }\n return;\n }\n\n // Variable `array<T>`: prior-slot release lives at the caller (set path)\n // — D-3 calling convention. Spawn path's fresh rows carry stale swap-pop\n // debris which MUST NOT be released here.\n const byteLength = effectiveCount * elementBytes;\n const allocR = this.bufferPool.alloc(byteLength);\n if (!allocR.ok) {\n this.routeArrayError(\n {\n code: allocR.error.code,\n hint: allocR.error.hint,\n expected: allocR.error.expected,\n detail: allocR.error.detail,\n } as ManagedArrayErrorEnvelope,\n component.name,\n fieldName,\n );\n col.view[row] = 0;\n if (isVariable) {\n const countCol = fieldCols.get(arrayCountColumnName(fieldName));\n if (countCol !== undefined) countCol.view[row] = 0;\n }\n return;\n }\n const slot = allocR.value;\n if (payloadBytes !== null) {\n const copyLen = Math.min(payloadBytes.byteLength, slot.view.byteLength);\n slot.view.set(payloadBytes.subarray(0, copyLen));\n }\n col.view[row] = slot.id;\n if (isVariable) {\n const countCol = fieldCols.get(arrayCountColumnName(fieldName));\n /* istanbul ignore else -- count column allocated by createArchetype */\n if (countCol !== undefined) countCol.view[row] = effectiveCount;\n }\n // feat-20260614 M4 / D-3: variable `array<shared<T>>` element-level\n // retain. Walk the live element prefix (effectiveCount u32 handles) and\n // retain each non-sentinel handle. Prior elements were released by the\n // caller via `releaseManagedFieldOnRow` on the set path (D-3 calling\n // convention); the spawn path has no priors.\n if (metaKey === 'shared' && effectiveCount > 0) {\n this.retainSharedArrayElements(slot.view, effectiveCount);\n }\n }\n\n /**\n * Walk the first `count` u32 handles in `bytes` and call\n * `SharedRefStore.retain` on each non-sentinel slot id (feat-20260614 M4 /\n * D-3). Failures route via Layer 3 ErrorHandler so the write chain stays\n * total; charter explicit-failure boundary lets AI users see structured\n * `shared-ref-released` payloads when retaining a stale handle.\n *\n * Helper-internal -- only called from `writeArrayField`'s `'shared'` arm.\n */\n retainSharedArrayElements(bytes: Uint8Array, count: number): void {\n const view = new Uint32Array(bytes.buffer, bytes.byteOffset, count);\n for (let i = 0; i < count; i++) {\n const raw = view[i];\n if (raw === undefined) continue;\n // R-14: route through the scalar SSOT helper so the `< BUILTIN_BASE`\n // short-circuit (builtin slots + sentinel 0) lives in exactly one place.\n this.retainSharedScalarHandle(raw, 'array<shared<T>>', 'element');\n }\n }\n\n /**\n * Walk the first `count` u32 handles in `bytes` and call\n * `SharedRefStore.release` on each non-sentinel slot id (feat-20260614 M4 /\n * D-3). Mirrors `retainSharedArrayElements`; called from\n * `releaseManagedFieldOnRow`'s array arm BEFORE the BufferPool slot is\n * released so the underlying bytes are still valid.\n */\n releaseSharedArrayElements(bytes: Uint8Array, count: number): void {\n const view = new Uint32Array(bytes.buffer, bytes.byteOffset, count);\n for (let i = 0; i < count; i++) {\n const raw = view[i];\n if (raw === undefined) continue;\n // R-14: route through the scalar SSOT helper so the `< BUILTIN_BASE`\n // short-circuit (builtin slots + sentinel 0) lives in exactly one place.\n this.releaseSharedRefHandle(raw, 'array<shared<T>>', 'element');\n }\n }\n\n writeArrayElementAt(\n bytes: Uint8Array,\n idx: number,\n elementType: ManagedArrayElementType,\n value: number,\n ): void {\n writeArrayElementAt(bytes, idx, elementType, value);\n }\n\n readArrayElementAt(bytes: Uint8Array, idx: number, elementType: ManagedArrayElementType): number {\n return readArrayElementAt(bytes, idx, elementType);\n }\n\n /**\n * Materialise a fresh `TypedArray` view for an `array<T,N>` / `array<T>`\n * field at `row`. This is the internal row-storage path: the returned view\n * aliases the live column or BufferPool slot. `WorldComponentAccess.get`\n * detaches relationship target arrays at the public boundary; internal ECS\n * relationship maintenance and Scene traversal keep this zero-copy path.\n *\n * **Transient view contract (feat-20260602):** for fixed `array<T,N>`\n * columns the returned `TypedArray` aliases the inline column buffer\n * directly (`col.view.subarray(row * arity, ...)`); for variable\n * `array<T>` columns it aliases the live `BufferPool` slot bytes\n * (zero-copy; `pool.view(slotId)` is the SSOT byte region). In both cases\n * the view is valid only until the next structural change. Internal callers\n * must not write through it except via the owner mutation helpers.\n *\n * For variable arrays the typed-array length matches the live count from\n * the sidecar `<fieldName>:count` column; for fixed arrays it matches the\n * schema-declared `N`. `entity` element fields surface as a `Uint32Array`\n * view (Entity packs slot+gen into u32).\n */\n materializeArrayView(\n arch: Archetype,\n component: Component,\n row: number,\n fieldName: string,\n elementType: ManagedArrayElementType,\n fixedLength: number | undefined,\n slotId: number,\n ):\n | Float32Array\n | Float64Array\n | Int32Array\n | Uint32Array\n | Int16Array\n | Uint16Array\n | Int8Array\n | Uint8Array {\n const fieldCols = this.table(arch).storage.get(componentId(component))?.fields;\n if (fixedLength !== undefined) {\n // Fixed `array<T,N>` (feat-20260602): the elements live INLINE in the\n // stride-N column. Reinterpret the row's byte window directly — no\n // BufferPool indirection (`slotId` is unused for fixed arrays).\n const col = fieldCols?.get(fieldName);\n /* istanbul ignore next -- caller validated the column exists */\n if (col === undefined) return reinterpretSlotBytes(new Uint8Array(0), elementType, 0);\n const elementBytes = elementByteSize(elementType);\n const arity = col.arity;\n const rowByteOffset = col.view.byteOffset + row * arity * elementBytes;\n return reinterpretBufferRegion(col.view.buffer, rowByteOffset, elementType, fixedLength);\n }\n const liveBytes = this.bufferPool.view(slotId);\n const countCol = fieldCols?.get(arrayCountColumnName(fieldName));\n const elementCount = (countCol?.view[row] as number | undefined) ?? 0;\n return reinterpretSlotBytes(liveBytes, elementType, elementCount);\n }\n\n // ──────────────────────────────────────────────────────────────────────────\n // Internal — archetype migration\n // ──────────────────────────────────────────────────────────────────────────\n\n /**\n * Migrate an entity from srcArch to targetArch.\n * Copies all shared component data, then removes from src via swap-pop.\n *\n * AC-04 carry-over contract (M4): for every component that survives the\n * migration (i.e. the target archetype carries the same `compId`), every\n * field column's u32 value is copied verbatim from src to target. This\n * preserves every managed resource handle in place:\n *\n * - `ref<T>` field - the u32 (managed handle = (slot << 8) | gen) is\n * bit-equal across migrate, so `Object.is` on the\n * handle holds and `UniqueRefStore.resolve` returns\n * the same payload object reference (per-(slot, gen)\n * wrapper singleton, D-3).\n * - `buffer<N>` field - fixed-capacity inline stride-N `u8` column\n * (feat-20260602): the N bytes are copied verbatim\n * by the generic per-column row copy, so the live\n * bytes survive byte-for-byte. No BufferPool slot\n * (only variable `buffer` carries a pool slot id).\n * - `entity` field - the u32 (encoded slot+gen) is bit-equal across\n * migrate.\n * - `array<T,N>` field - fixed-capacity inline stride-N column\n * (feat-20260602): the N elements live contiguously\n * in the column row and are copied verbatim by the\n * generic per-column row copy, so they survive\n * byte-for-byte (no BufferPool slot). The TypedArray\n * snapshot is rematerialised on every `world.get`\n * (D-4 no cache); we do NOT guarantee `Object.is` on\n * the wrapper — only the underlying bytes (D-R7 weak\n * carry-over).\n * - `array<T>` field - dual u32 columns: primary slot id + sidecar\n * `<fieldName>:count`. Both columns are copied via\n * the generic per-column loop below, so count and\n * slot id stay in lock-step. Capacity is derived\n * from `BufferPool.view(slotId).byteLength /\n * elementBytes` and is therefore preserved by the\n * slot-id carry-over alone (no separate column).\n *\n * Negative invariant: this routine MUST NOT call UniqueRefStore.release /\n * BufferPool.release for surviving components. The pre-migrate release\n * loop lives at `removeComponent` (only for the component being removed)\n * and `despawn` (every component); migrate is only a column copy. The\n * array-field release-loop split (D-3 / D-5) further guarantees that\n * spawn into a vacated row treats stale slot-id debris as no-op (the slot\n * is owned by the migrated entity in the new archetype) — see\n * `writeArrayField`'s `operation: 'spawn' | 'set'` discriminant.\n * Tests: `__tests__/managed-carry-over.test.ts` (w16),\n * `__tests__/managed-array-carry-over.test.ts` (w8).\n */\n migrateEntity(record: EntityRecord, srcArch: Archetype, targetArch: Archetype): void {\n const oldArchetypeRow = record.archetypeRow;\n const oldTableRow = srcArch.rows[oldArchetypeRow] ?? 0;\n const srcTable = this.table(srcArch);\n const targetTable = this.table(targetArch);\n const entity = (srcTable.storage.get(componentId(EntityComponent))?.fields.get('self')?.view[\n oldTableRow\n ] ?? 0) as EntityHandle;\n const newTableRow = appendTableRow(targetTable, entity);\n const newArchetypeRow = appendArchetypeRow(targetArch, newTableRow);\n\n // Copy shared component data.\n for (const [compId, srcComponentStorage] of srcTable.storage) {\n const srcFieldCols = srcComponentStorage.fields;\n const targetComponentStorage = targetTable.storage.get(compId);\n const targetFieldCols = targetComponentStorage?.fields;\n if (!targetFieldCols) {\n continue; // Component was removed — skip.\n }\n for (const [fieldName, srcCol] of srcFieldCols) {\n const targetCol = targetFieldCols.get(fieldName);\n if (!targetCol) {\n continue;\n }\n // Copy the whole stride-N block per row. Scalar / variable / `:count`\n // columns have arity 1 (single-element copy, byte-identical to the\n // prior `view[newRow] = view[oldRow]` form); fixed inline\n // `array<T,N>` / `buffer<N>` columns carry their N elements inline and\n // must migrate the entire block (feat-20260602).\n const arity = srcCol.arity;\n targetCol.view.set(\n srcCol.view.subarray(oldTableRow * arity, oldTableRow * arity + arity),\n newTableRow * arity,\n );\n }\n if (targetComponentStorage !== undefined) {\n copyComponentEpoch(\n srcComponentStorage.epochs,\n oldTableRow,\n targetComponentStorage.epochs,\n newTableRow,\n );\n }\n }\n\n const archetypeSwap = removeArchetypeRow(srcArch, oldArchetypeRow);\n if (archetypeSwap !== null) {\n const movedEntity = (srcTable.storage.get(componentId(EntityComponent))?.fields.get('self')\n ?.view[archetypeSwap.movedTableRow] ?? 0) as EntityHandle;\n const movedRecord = this.records[entityIndex(movedEntity)];\n if (movedRecord?.generation === entityGeneration(movedEntity)) {\n movedRecord.archetypeRow = archetypeSwap.newRow;\n }\n }\n const tableSwap = removeTableRow(srcTable, oldTableRow);\n if (tableSwap !== null) {\n const movedRecord = this.records[entityIndex(tableSwap.movedEntity)];\n if (movedRecord?.generation === entityGeneration(tableSwap.movedEntity)) {\n const movedArchetype = this.state.graph.archetypes[movedRecord.archetypeId];\n if (movedArchetype !== undefined) {\n movedArchetype.rows[movedRecord.archetypeRow] = tableSwap.newRow;\n }\n }\n }\n\n record.archetypeId = targetArch.id;\n record.archetypeRow = newArchetypeRow;\n }\n\n moveEntityArchetype(record: EntityRecord, srcArch: Archetype, targetArch: Archetype): void {\n const table = this.table(srcArch);\n if (srcArch.tableId !== targetArch.tableId) {\n throw new Error('Logical archetype move requires a shared Table.');\n }\n const oldArchetypeRow = record.archetypeRow;\n const tableRow = srcArch.rows[oldArchetypeRow] ?? 0;\n const archetypeSwap = removeArchetypeRow(srcArch, oldArchetypeRow);\n if (archetypeSwap !== null) {\n const movedEntity = (table.storage.get(componentId(EntityComponent))?.fields.get('self')\n ?.view[archetypeSwap.movedTableRow] ?? 0) as EntityHandle;\n const movedRecord = this.records[entityIndex(movedEntity)];\n if (movedRecord?.generation === entityGeneration(movedEntity)) {\n movedRecord.archetypeRow = archetypeSwap.newRow;\n }\n }\n record.archetypeId = targetArch.id;\n record.archetypeRow = appendArchetypeRow(targetArch, tableRow);\n }\n}\n\n/**\n * Reinterpret a `BufferPool` slot's `Uint8Array` byte region as the typed\n * view for `elementType`, sliced to `elementCount` elements. This is the\n * internal materialization used by `readRow`/`materializeArrayView`: the\n * returned view aliases live slot bytes. `WorldComponentAccess.get` detaches\n * relationship-target `array<entity>` values at the public boundary; other\n * public array fields retain the existing transient live-view contract.\n * `_getArrayView` and other internal owners always retain zero-copy access.\n * `entity` element fields surface as `Uint32Array` (Entity packs slot+gen\n * into u32).\n */\n/**\n * Element-byte-width for a managed-array element type, read off the global\n * TYPE_METADATA table (single SSOT). `entity` stores as `u32` (4 bytes); every\n * scalar maps to its own key. `fieldTypeToMetaKey` always resolves a key for a\n * ManagedArrayElementType, and every such row carries a concrete `byteSize`.\n */\nfunction elementByteSize(elementType: ManagedArrayElementType): number {\n const key = fieldTypeToMetaKey(elementType);\n // biome-ignore lint/style/noNonNullAssertion: every ManagedArrayElementType resolves to a row with a concrete byteSize\n return TYPE_METADATA[key!]!.byteSize!;\n}\n\nfunction reinterpretSlotBytes(\n bytes: Uint8Array,\n elementType: ManagedArrayElementType,\n elementCount: number,\n): ReturnType<typeof reinterpretBufferRegion> {\n return reinterpretBufferRegion(bytes.buffer, bytes.byteOffset, elementType, elementCount);\n}\n\nfunction reinterpretBufferRegion(\n buffer: ArrayBufferLike,\n byteOffset: number,\n elementType: ManagedArrayElementType,\n elementCount: number,\n):\n | Float32Array\n | Float64Array\n | Int32Array\n | Uint32Array\n | Int16Array\n | Uint16Array\n | Int8Array\n | Uint8Array {\n // shared<X> template literals: column-stored as u32 handles, reinterpret\n // as Uint32Array. The brand is applied at the FieldValueType level;\n // runtime storage is plain u32 (feat-20260614 M5; replaces the retired\n // 'handle<X>' arm).\n if (elementType.startsWith('shared<')) {\n return new Uint32Array(buffer, byteOffset, elementCount);\n }\n switch (elementType) {\n case 'f32':\n return new Float32Array(buffer, byteOffset, elementCount);\n case 'f64':\n return new Float64Array(buffer, byteOffset, elementCount);\n case 'i32':\n return new Int32Array(buffer, byteOffset, elementCount);\n case 'u32':\n case 'enum':\n case 'ref':\n case 'entity':\n return new Uint32Array(buffer, byteOffset, elementCount);\n case 'i16':\n return new Int16Array(buffer, byteOffset, elementCount);\n case 'u16':\n return new Uint16Array(buffer, byteOffset, elementCount);\n case 'i8':\n return new Int8Array(buffer, byteOffset, elementCount);\n case 'u8':\n case 'bool':\n return new Uint8Array(buffer, byteOffset, elementCount);\n }\n // Exhaustiveness fallthrough: TypeScript template-literal type\n // (`shared<${string}>`) is structurally not narrowed away by the\n // `startsWith` guard above, so this branch is unreachable yet TS still\n // requires a return path.\n return new Uint32Array(buffer, byteOffset, elementCount);\n}\n\n/**\n * Reinterpret `bytes` as the typed view for `elementType` and write `value`\n * at element index `idx`. Mirrors the `array<T>` storage law (4/8/2/1-byte\n * element widths per TYPE_METADATA.byteSize) and is used by `world.push`\n * to land a new tail element into BufferPool slot bytes after a `grow`.\n */\nfunction writeArrayElementAt(\n bytes: Uint8Array,\n idx: number,\n elementType: ManagedArrayElementType,\n value: number,\n): void {\n const buf = bytes.buffer;\n const offset = bytes.byteOffset;\n const byteLen = bytes.byteLength;\n switch (elementType) {\n case 'f32':\n new Float32Array(buf, offset, byteLen >>> 2)[idx] = value;\n return;\n case 'f64':\n new Float64Array(buf, offset, byteLen >>> 3)[idx] = value;\n return;\n case 'i32':\n new Int32Array(buf, offset, byteLen >>> 2)[idx] = value;\n return;\n case 'u32':\n case 'enum':\n case 'ref':\n case 'entity':\n new Uint32Array(buf, offset, byteLen >>> 2)[idx] = value;\n return;\n case 'i16':\n new Int16Array(buf, offset, byteLen >>> 1)[idx] = value;\n return;\n case 'u16':\n new Uint16Array(buf, offset, byteLen >>> 1)[idx] = value;\n return;\n case 'i8':\n new Int8Array(buf, offset, byteLen)[idx] = value;\n return;\n case 'u8':\n case 'bool':\n new Uint8Array(buf, offset, byteLen)[idx] = value;\n return;\n }\n}\n\n/**\n * Reinterpret `bytes` as the typed view for `elementType` and read element\n * `idx`. Mirrors `writeArrayElementAt` -- consumed by `world.pop` to materialise\n * the tail value before the count is decremented.\n */\nfunction readArrayElementAt(\n bytes: Uint8Array,\n idx: number,\n elementType: ManagedArrayElementType,\n): number {\n const buf = bytes.buffer;\n const offset = bytes.byteOffset;\n const byteLen = bytes.byteLength;\n // shared<X> template literals: column-stored as u32 handles, read as\n // Uint32Array. (feat-20260614 M5; replaces retired 'handle<X>' arm.)\n if (elementType.startsWith('shared<')) {\n return new Uint32Array(buf, offset, byteLen >>> 2)[idx] ?? 0;\n }\n switch (elementType) {\n case 'f32':\n return new Float32Array(buf, offset, byteLen >>> 2)[idx] ?? 0;\n case 'f64':\n return new Float64Array(buf, offset, byteLen >>> 3)[idx] ?? 0;\n case 'i32':\n return new Int32Array(buf, offset, byteLen >>> 2)[idx] ?? 0;\n case 'u32':\n case 'enum':\n case 'ref':\n case 'entity':\n return new Uint32Array(buf, offset, byteLen >>> 2)[idx] ?? 0;\n case 'i16':\n return new Int16Array(buf, offset, byteLen >>> 1)[idx] ?? 0;\n case 'u16':\n return new Uint16Array(buf, offset, byteLen >>> 1)[idx] ?? 0;\n case 'i8':\n return new Int8Array(buf, offset, byteLen)[idx] ?? 0;\n case 'u8':\n case 'bool':\n return new Uint8Array(buf, offset, byteLen)[idx] ?? 0;\n }\n return 0;\n}\n","// @forgeax/engine-ecs — world-component-access: component storage and access.\n//\n// This module owns component rows, managed storage, array operations, archetype\n// migration, and the relationship callbacks that mutate component storage. World\n// remains the typed facade and supplies one narrow per-World state capability.\n\nimport { err, isRetiredSlot, ok, type Result, unwrapHandle } from '@forgeax/engine-types';\nimport type { BufferPool } from './buffer-pool';\nimport {\n bufferFieldByteLength,\n type Component,\n type ComponentSchema,\n componentId,\n componentSchema,\n type InputShapeOf,\n isEntityField,\n isManagedBufferField,\n isManagedField,\n type ManagedArrayElementType,\n type ManagedArrayElementValue,\n type ShapeOf,\n TYPE_METADATA,\n} from './component';\nimport { fillComponentDefaults, validateComponentDataKeys } from './component-default-fallback';\nimport { componentDefinition, expandComponentRequirements } from './component-schema';\nimport { validateManagedArrayValues, validateSharedFieldValues } from './component-value-validate';\nimport { Entity as EntityComponent } from './entity';\nimport {\n ENTITY_MAX_INDEX,\n ENTITY_NULL_RAW,\n type EntityHandle,\n encodeEntity,\n entityGeneration,\n entityIndex,\n} from './entity-handle';\nimport {\n ComponentAlreadyPresentError,\n ComponentNotPresentError,\n EntityIndexOverflowError,\n FixedSizeMismatchError,\n ManagedBufferOutOfBoundsError,\n RelationshipSelfCycleError,\n RelationshipTargetReadonlyError,\n RemoveEssentialComponentError,\n StaleEntityError,\n validateEnumFieldValues,\n validateNumericFieldValues,\n} from './errors';\nimport {\n isRelationshipTarget,\n RelationshipIndex,\n relationshipMirror,\n relationshipRole,\n} from './relationship-index';\nimport type { SharedRefStore } from './shared-ref-store';\nimport { type Archetype, appendArchetypeRow } from './storage/archetype';\nimport {\n type ArchetypeGraph,\n getAddEdge,\n getOrCreateArchetype,\n getRemoveEdge,\n getTable,\n} from './storage/archetype-graph';\nimport { removeSparseTag } from './storage/change-detection';\nimport { arrayCountColumnName, type FieldView, normalizeBufferWrite } from './storage/column';\nimport type { StructuralEvidenceInput } from './storage/structural-evidence';\nimport { appendTableRow, type Table } from './storage/table';\nimport type { UniqueRefStore } from './unique-ref-store';\nimport type { ComponentData, EcsError, EntityRecord } from './world';\nimport { ComponentStorage } from './world-component-storage';\n\ntype ErrorContext = { readonly systemName: string };\n\n/**\n * Prepared target-side work for one relationship source write.\n *\n * A reservation is deliberately kept outside the World columns until the\n * source operation is ready to commit. That lets direct, spawn, and deferred\n * source writes observe BufferPool failures before adding a mirror component\n * or advancing any ECS epoch.\n */\ninterface RelationshipPreparation {\n readonly target: EntityHandle;\n readonly mirror: Component;\n readonly fieldName: string;\n readonly mirrorPresent: boolean;\n reservedSlotId: number | undefined;\n}\n\ntype ArrayFieldsOf<S extends ComponentSchema> = {\n [K in keyof S]: S[K] extends\n | `array<${ManagedArrayElementType}>`\n | `array<${ManagedArrayElementType}, ${number}>`\n ? K\n : never;\n}[keyof S];\n\ntype ArrayFieldElementValue<\n S extends ComponentSchema,\n K extends keyof S,\n> = S[K] extends `array<${infer Elem extends ManagedArrayElementType}>`\n ? ManagedArrayElementValue<Elem>\n : S[K] extends `array<${infer Elem extends ManagedArrayElementType}, ${number}>`\n ? ManagedArrayElementValue<Elem>\n : never;\n\nfunction relationshipPayloadWrites(data: Readonly<Record<string, unknown>>): boolean {\n return Object.values(data).some((value) => {\n if (Array.isArray(value)) return value.length > 0;\n if (ArrayBuffer.isView(value)) return value.byteLength > 0;\n return true;\n });\n}\n\n/**\n * Relationship target arrays are public read-only projections. Keep the\n * detached-copy rule at the World.get boundary while internal relationship\n * owners continue to borrow the live storage through `_getArrayView`.\n */\nfunction detachRelationshipTargetArray(value: unknown): unknown {\n return value instanceof Uint32Array ? value.slice() : value;\n}\n\nexport interface ComponentAccessState {\n readonly graph: ArchetypeGraph;\n readonly records: EntityRecord[];\n readonly freeIndices: number[];\n readonly bufferPool: BufferPool;\n readonly uniqueRefs: UniqueRefStore;\n readonly sharedRefs: SharedRefStore;\n readonly relationshipIndexes: Map<number, RelationshipIndex>;\n readonly markComponentAdded: (entity: EntityHandle, componentId: number) => void;\n readonly markComponentsAdded: (entity: EntityHandle, componentIds: readonly number[]) => void;\n readonly markComponentChanged: (entity: EntityHandle, componentId: number) => void;\n readonly markStructureChanged: () => void;\n readonly recordStructuralEvidence: (evidence: StructuralEvidenceInput) => void;\n routeError(err: unknown, ctx: ErrorContext): void;\n}\n\nexport class WorldComponentAccess {\n private readonly storage: ComponentStorage;\n\n constructor(private readonly state: ComponentAccessState) {\n this.storage = new ComponentStorage(state);\n }\n\n private get graph(): ArchetypeGraph {\n return this.state.graph;\n }\n\n private get records(): EntityRecord[] {\n return this.state.records;\n }\n\n private table(archetype: Archetype): Table {\n return getTable(this.graph, archetype.tableId);\n }\n\n private tableRow(record: EntityRecord): number {\n return this.graph.archetypes[record.archetypeId]?.rows[record.archetypeRow] ?? -1;\n }\n\n private get freeIndices(): number[] {\n return this.state.freeIndices;\n }\n\n private get bufferPool(): BufferPool {\n return this.state.bufferPool;\n }\n\n private get uniqueRefs(): UniqueRefStore {\n return this.state.uniqueRefs;\n }\n\n private routeError(err: unknown, ctx: ErrorContext): void {\n this.state.routeError(err, ctx);\n }\n\n private relationshipIndex(component: Component): RelationshipIndex | undefined {\n if (relationshipRole(component)?.kind !== 'source') return undefined;\n let index = this.state.relationshipIndexes.get(componentId(component));\n if (index === undefined) {\n index = new RelationshipIndex();\n this.state.relationshipIndexes.set(componentId(component), index);\n }\n return index;\n }\n\n /**\n * Read the World-owned materialized target array without a public snapshot.\n * This is an internal relationship-owner path: it borrows the live\n * `Uint32Array` so attach/detach stays zero-copy. Public `World.get` detaches\n * target arrays before returning them to callers.\n */\n relationshipTargetEntries(source: Component, target: EntityHandle): readonly EntityHandle[] {\n const role = relationshipRole(source);\n if (role?.kind !== 'source') return [];\n const mirror = relationshipMirror(source);\n if (mirror === undefined) return [];\n const entries = this._getArrayView(target, mirror, role.targetField);\n return entries === undefined ? [] : (entries as unknown as readonly EntityHandle[]);\n }\n\n private markComponentAdded(entity: EntityHandle, component: Component): void {\n this.state.markComponentAdded(entity, componentId(component));\n }\n\n private markComponentChanged(entity: EntityHandle, component: Component): void {\n this.state.markComponentChanged(entity, componentId(component));\n }\n\n private markStructureChanged(): void {\n this.state.markStructureChanged();\n }\n\n relationshipTargetEntity(\n component: Component,\n value: Record<string, unknown>,\n ): EntityHandle | null {\n for (const [fieldName, fieldType] of Object.entries(componentSchema(component))) {\n if (isEntityField(fieldType)) {\n const raw = value[fieldName];\n if (raw === null || raw === undefined) return null;\n const asNum = raw as number;\n if (asNum === ENTITY_NULL_RAW) return null;\n return asNum as EntityHandle;\n }\n }\n return null;\n }\n\n private preflightComponentFieldValues(\n holder: EntityHandle | null,\n componentData: ComponentData,\n ): Result<void, EcsError> {\n const data = componentData.data as Record<string, unknown>;\n const arrayError = validateManagedArrayValues(componentData.component, data);\n if (arrayError !== null) return err(arrayError as unknown as EcsError);\n const sharedError = validateSharedFieldValues(componentData.component, data);\n if (sharedError !== null) return err(sharedError as unknown as EcsError);\n const numericError = validateNumericFieldValues(\n componentData.component,\n data,\n holder === null ? undefined : (holder as number),\n );\n if (numericError !== null) return err(numericError as unknown as EcsError);\n return ok(undefined);\n }\n\n /**\n * Validate one structural component payload without touching archetypes,\n * columns, relationship mirrors, epochs, or managed-reference stores.\n * CommandBuffer uses this same owner-level gate as the direct World facade;\n * the optional pending set lets a batch refer to an entity reserved earlier\n * in that batch without mistaking it for a stale live handle.\n */\n preflightComponentData(\n holder: EntityHandle | null,\n componentData: ComponentData,\n pendingEntities?: ReadonlySet<number>,\n unavailableEntities?: ReadonlySet<number>,\n ): Result<void, EcsError> {\n const data = componentData.data as Record<string, unknown>;\n const keyError = validateComponentDataKeys(componentData.component, data);\n if (keyError !== null) return err(keyError as unknown as EcsError);\n const valuePreflight = this.preflightComponentFieldValues(holder, componentData);\n if (!valuePreflight.ok) return valuePreflight;\n if (isRelationshipTarget(componentData.component) && relationshipPayloadWrites(data)) {\n return err(new RelationshipTargetReadonlyError(componentData.component.name, 'command'));\n }\n\n const filled = fillComponentDefaults(componentData.component, data);\n const enumError = validateEnumFieldValues(\n componentData.component,\n filled,\n holder === null ? undefined : (holder as number),\n );\n if (enumError !== null) return err(enumError as unknown as EcsError);\n\n const role = relationshipRole(componentData.component as Component);\n if (role?.kind !== 'source') return ok(undefined);\n const target = this.relationshipTargetEntity(componentData.component as Component, filled);\n if (target === null) return ok(undefined);\n\n const targetRaw = target as unknown as number;\n if (unavailableEntities?.has(targetRaw) === true) {\n const targetRecord = this.records[entityIndex(target)];\n return err(\n new StaleEntityError(target as number, entityIndex(target), entityGeneration(target), {\n operation: 'relationship-insert',\n component: componentData.component.name,\n expectedGeneration: entityGeneration(target),\n actualGeneration: targetRecord?.generation ?? -1,\n }),\n );\n }\n const targetIsPending = pendingEntities?.has(targetRaw) === true;\n const targetRecord = this.records[entityIndex(target)];\n const actualGeneration = targetRecord?.generation ?? -1;\n const targetLive = this.recordIsLive(targetRecord, entityGeneration(target));\n // A source edge is never allowed to publish a dangling target. Pending\n // targets are the only exception, and are admitted only for the deferred\n // command batch that reserved that exact handle.\n if (!targetIsPending && !targetLive) {\n return err(\n new StaleEntityError(target as number, entityIndex(target), entityGeneration(target), {\n operation: 'relationship-insert',\n component: componentData.component.name,\n expectedGeneration: entityGeneration(target),\n actualGeneration,\n }),\n );\n }\n\n // A pending holder has no row to walk yet. Once materialized, its target\n // is still checked by the same source-side relationship callback.\n if (holder === null || pendingEntities?.has(holder as unknown as number) === true) {\n return ok(undefined);\n }\n const roleAllowsSelf = role?.kind === 'source' && role.allowSelf;\n if (holder === target && !roleAllowsSelf) {\n return err(\n new RelationshipSelfCycleError(\n componentData.component.name,\n holder as number,\n target as number,\n ),\n );\n }\n\n const cycleHit =\n holder === target && roleAllowsSelf\n ? null\n : this.relationshipCycleHit(componentData.component as Component, target, holder);\n if (cycleHit !== null) {\n return err(\n new RelationshipSelfCycleError(\n componentData.component.name,\n holder as number,\n cycleHit as number,\n ),\n );\n }\n return ok(undefined);\n }\n\n private relationshipCycleHit(\n holderComponent: Component,\n start: EntityHandle,\n holder: EntityHandle,\n ): EntityHandle | null {\n const visited = new Set<number>();\n let current = start;\n while (true) {\n if (current === holder) return current;\n const raw = current as unknown as number;\n if (visited.has(raw)) return null;\n visited.add(raw);\n const record = this.records[entityIndex(current)];\n if (!this.recordIsLive(record, entityGeneration(current))) return null;\n const archetype = this.graph.archetypes[record.archetypeId];\n if (\n !archetype?.components.some(\n (candidate) => componentId(candidate) === componentId(holderComponent),\n )\n ) {\n return null;\n }\n const value = this.readRow(archetype, holderComponent, this.tableRow(record)) as Record<\n string,\n unknown\n >;\n const next = this.relationshipTargetEntity(holderComponent, value);\n if (next === null) return null;\n current = next;\n }\n }\n\n /**\n * Reserve target-side relationship capacity without touching World columns.\n *\n * A missing mirror reserves its first slot before the mirror archetype is\n * created. An existing mirror either reserves an empty slot or grows its\n * existing BufferPool slot; both failure paths return before any component,\n * relationship index, or ECS epoch changes.\n */\n prepareRelationshipInsert(\n component: Component,\n value: Record<string, unknown>,\n ): Result<RelationshipPreparation | undefined, EcsError> {\n const role = relationshipRole(component);\n if (role?.kind !== 'source') return ok(undefined);\n const target = this.relationshipTargetEntity(component, value);\n if (target === null) return ok(undefined);\n const mirror = relationshipMirror(component);\n if (mirror === undefined) return ok(undefined);\n const targetRec = this.records[entityIndex(target)];\n const actualGeneration = targetRec?.generation ?? -1;\n if (!this.recordIsLive(targetRec, entityGeneration(target))) {\n return err(\n new StaleEntityError(target as number, entityIndex(target), entityGeneration(target), {\n operation: 'relationship-insert',\n component: component.name,\n expectedGeneration: entityGeneration(target),\n actualGeneration,\n }),\n );\n }\n const targetArch = this.graph.archetypes[targetRec.archetypeId];\n const mirrorLocalId = componentId(mirror);\n const mirrorPresent =\n targetArch?.components.some((candidate) => componentId(candidate) === mirrorLocalId) ?? false;\n const fieldName = role.targetField;\n const arrayMeta = componentDefinition(mirror).fields[fieldName]?.arrayMeta;\n if (arrayMeta === undefined) {\n return err(new ComponentNotPresentError(target as number, mirror.name));\n }\n const meta = TYPE_METADATA[arrayMeta.elementType];\n if (meta?.byteSize === undefined) {\n return err(new ComponentNotPresentError(target as number, mirror.name));\n }\n let currentLength = 0;\n let slotId = 0;\n if (mirrorPresent) {\n currentLength = this._getArrayLength(target, mirror, fieldName) ?? 0;\n const fieldCols = this.table(targetArch as Archetype).storage.get(mirrorLocalId)?.fields;\n const column = fieldCols?.get(fieldName);\n if (column === undefined) {\n return err(new ComponentNotPresentError(target as number, mirror.name));\n }\n const row = this.tableRow(targetRec);\n slotId = column.view[row] as number;\n }\n const requiredBytes = (currentLength + 1) * meta.byteSize;\n if (!Number.isSafeInteger(requiredBytes)) {\n return err(new ManagedBufferOutOfBoundsError(requiredBytes, Number.MAX_SAFE_INTEGER));\n }\n\n const preparation: RelationshipPreparation = {\n target,\n mirror,\n fieldName,\n mirrorPresent,\n reservedSlotId: undefined,\n };\n if (!mirrorPresent || slotId === 0) {\n const allocated = this.bufferPool.alloc(requiredBytes);\n if (!allocated.ok) return allocated;\n preparation.reservedSlotId = allocated.value.id;\n } else if (this.bufferPool.view(slotId).byteLength < requiredBytes) {\n const grown = this.bufferPool.grow(slotId, requiredBytes);\n if (!grown.ok) return grown;\n }\n return ok(preparation);\n }\n\n /** Release a target-capacity reservation that did not reach commit. */\n releaseRelationshipPreparation(preparation: RelationshipPreparation | undefined): void {\n if (preparation === undefined || preparation.reservedSlotId === undefined) return;\n const slotId = preparation.reservedSlotId;\n this.bufferPool.release(slotId);\n preparation.reservedSlotId = undefined;\n }\n\n /** Install a reserved slot after the target mirror archetype exists. */\n private installRelationshipPreparation(\n preparation: RelationshipPreparation,\n ): Result<void, EcsError> {\n const record = this.lookupAlive(\n preparation.target,\n 'relationship-capacity',\n preparation.mirror.name,\n );\n if (!record.ok) return record;\n const arch = this.graph.archetypes[record.value.archetypeId];\n if (arch === undefined) {\n return err(\n new ComponentNotPresentError(preparation.target as number, preparation.mirror.name),\n );\n }\n const fieldCols = this.table(arch).storage.get(componentId(preparation.mirror))?.fields;\n const column = fieldCols?.get(preparation.fieldName);\n if (column === undefined) {\n return err(\n new ComponentNotPresentError(preparation.target as number, preparation.mirror.name),\n );\n }\n const slotId = preparation.reservedSlotId;\n if (slotId !== undefined) {\n column.view[this.tableRow(record.value)] = slotId;\n preparation.reservedSlotId = undefined;\n }\n return ok(undefined);\n }\n\n /** Append `holder` to the materialized target list. */\n relationshipOnInsert(\n holder: EntityHandle,\n component: Component,\n value: Record<string, unknown>,\n preparation?: RelationshipPreparation,\n ): Result<void, EcsError> {\n const role = relationshipRole(component);\n if (role?.kind !== 'source') return ok(undefined);\n const target = this.relationshipTargetEntity(component, value);\n if (target === null) return ok(undefined);\n const mirror = relationshipMirror(component);\n /* istanbul ignore next -- defineComponent relationship validation guarantees mirror exists */\n if (mirror === undefined) return ok(undefined);\n\n let prepared = preparation;\n if (prepared === undefined) {\n const preparedResult = this.prepareRelationshipInsert(component, value);\n if (!preparedResult.ok) return preparedResult;\n prepared = preparedResult.value;\n }\n if (prepared === undefined) return ok(undefined);\n\n // Lazy-create the mirror component on the target when absent (D-3c).\n const targetSlot = entityIndex(target);\n const targetRec = this.records[targetSlot];\n const actualGeneration = targetRec?.generation ?? -1;\n if (!this.recordIsLive(targetRec, entityGeneration(target))) {\n return err(\n new StaleEntityError(target as number, targetSlot, entityGeneration(target), {\n operation: 'relationship-insert',\n component: component.name,\n expectedGeneration: entityGeneration(target),\n actualGeneration: actualGeneration,\n }),\n );\n }\n const targetArch = this.graph.archetypes[targetRec.archetypeId];\n const mirrorLocalId = componentId(mirror);\n const hasMirror =\n targetArch?.components.some((component) => componentId(component) === mirrorLocalId) ?? false;\n if (!hasMirror) {\n const added = this._addComponentCore(\n target,\n {\n component: mirror,\n data: {} as Partial<ShapeOf<ComponentSchema>>,\n },\n true,\n false,\n true,\n );\n if (!added.ok) {\n this.releaseRelationshipPreparation(prepared);\n return added;\n }\n }\n const installed = this.installRelationshipPreparation(prepared);\n if (!installed.ok) {\n this.releaseRelationshipPreparation(prepared);\n return installed;\n }\n const targetEntries = this.relationshipTargetEntries(component, target);\n const slot = targetEntries.length;\n const mirrored = this.appendArrayElement(\n target,\n mirror as Component<string, ComponentSchema>,\n role.targetField as never,\n holder as never,\n );\n if (!mirrored.ok) {\n this.releaseRelationshipPreparation(prepared);\n return mirrored;\n }\n this.relationshipIndex(component)?.attach(holder, target, slot);\n return ok(undefined);\n }\n\n /** Remove `holder` from the materialized target list. */\n relationshipOnRemove(\n holder: EntityHandle,\n component: Component,\n oldValue: Record<string, unknown>,\n ): Result<void, EcsError> {\n const role = relationshipRole(component);\n if (role?.kind !== 'source') return ok(undefined);\n const target = this.relationshipTargetEntity(component, oldValue);\n if (target === null) return ok(undefined);\n const mirror = relationshipMirror(component);\n /* istanbul ignore next -- defineComponent relationship validation guarantees mirror exists */\n if (mirror === undefined) return ok(undefined);\n const targetSlot = entityIndex(target);\n const targetRec = this.records[targetSlot];\n if (!this.recordIsLive(targetRec, entityGeneration(target))) return ok(undefined);\n\n const index = this.relationshipIndex(component);\n if (index === undefined) return ok(undefined);\n const slot = index.slotOf(holder);\n if (slot === undefined || index.targetOf(holder) !== target) return ok(undefined);\n const mirrored = this.removeArrayElementAt(\n target,\n mirror as Component<string, ComponentSchema>,\n role.targetField as never,\n slot,\n );\n if (!mirrored.ok) return mirrored;\n index.detach(holder);\n if (mirrored.value !== undefined) index.updateSlot(mirrored.value, target, slot);\n return ok(undefined);\n }\n\n /**\n * Read component data from an entity.\n *\n * **Public array contract:** relationship target `array<entity>` fields are\n * detached `Uint32Array` copies. Mutating that returned array cannot alter\n * the materialized target, relationship index, or source. Other array\n * fields retain the existing transient view contract: fixed-capacity\n * `array<T,N>` and `buffer<N>` fields alias the archetype column buffer\n * directly, while variable managed arrays alias their BufferPool slot. Those\n * views are valid only until the next structural change (`spawn` /\n * `despawn` / `addComponent` / `removeComponent`); callers must re-fetch\n * `world.get(e, C)` on every access. Internal owners use `readRow` and\n * `_getArrayView` directly and retain zero-copy access.\n *\n * @returns `Result<ShapeOf<S>, EcsError>` —\n * `ok(ShapeOf<S>)` on success;\n * `err(StaleEntityError)` (`.code = 'stale-entity'`) if entity is dead;\n * `err(ComponentNotPresentError)` (`.code = 'component-not-present'`) if\n * the entity does not have the component (a never-present component on\n * this entity degrades to the same `component-not-present` path — there is\n * no separate \"not registered\" failure; components are global at\n * `defineComponent` time).\n *\n * @example\n * ```ts\n * const Position = defineComponent('Position', { x: 'f32', y: 'f32' });\n * const world = new World();\n * const e = world.spawn({ component: Position, data: { x: 1, y: 2 } }).unwrap();\n * const r = world.get(e, Position);\n * if (!r.ok) { return; } // r.error.code === 'stale-entity' on dead handle\n * const pos = r.value;\n * ```\n */\n get<S extends ComponentSchema>(\n entity: EntityHandle,\n component: Component<string, S>,\n ): Result<ShapeOf<S>, EcsError> {\n const record = this.lookupAlive(entity, 'get', component.name);\n if (!record.ok) return record;\n\n const rec = record.value;\n const arch = this.graph.archetypes[rec.archetypeId];\n /* istanbul ignore next -- defensive: alive record always has valid archetypeId */\n if (!arch) {\n return err(\n new StaleEntityError(entity as number, entityIndex(entity), entityGeneration(entity), {\n operation: 'get',\n component: component.name,\n expectedGeneration: entityGeneration(entity),\n actualGeneration: rec.generation,\n }),\n );\n }\n\n // Check if this archetype has the component (using World-local ID).\n const localId = componentId(component);\n if (!arch.components.some((candidate) => componentId(candidate) === localId)) {\n return err(new ComponentNotPresentError(entity as number, component.name));\n }\n\n const value = this.storage.readRow(arch, component, this.tableRow(rec));\n const role = relationshipRole(component);\n if (role?.kind === 'target') {\n const targetValue = value as Record<string, unknown>;\n targetValue[role.targetField] = detachRelationshipTargetArray(targetValue[role.targetField]);\n }\n return ok(value);\n }\n\n /**\n * Column-level zero-copy view of an `array<T, N>` / `array<T>` field.\n *\n * Resolves the live byte region for `(entity, component, fieldName)`\n * directly at the column level and returns the element-typed TypedArray\n * aliasing it (`view.buffer` is the SSOT byte region; mutations route\n * through `world.set`). Unlike `get`, this does NOT build the\n * `{}` whole-component object nor walk every schema field. Per-frame\n * consumers that need one column (the resolved world mat4) take this path to\n * avoid the `get` overhead (1 `{}` alloc + N-field readRow walk).\n *\n * Fixed `array<T,N>` columns (feat-20260602) store their elements inline, so\n * the view aliases the archetype column buffer directly (no BufferPool\n * indirection); variable `array<T>` columns still alias the BufferPool slot.\n * The returned view's element type follows the schema element type\n * (`array<entity,N>` -> `Uint32Array`, `array<f32,N>` -> `Float32Array`,\n * etc.) -- the prior f32-only early-return gate is removed.\n *\n * **Transient view contract:** the returned `TypedArray` aliases the column\n * buffer and is valid only until the next structural change (`spawn` /\n * `despawn` / `addComponent` / `removeComponent`). Column growth\n * (`growColumn`) detaches the old `ArrayBuffer` via `transfer()`; a\n * swap-remove at the same row index leaves the view pointing to the wrong\n * entity. **Callers must re-fetch `_getArrayView` on every access** and must\n * not hold the view across any operation that may cause archetype migration.\n * All existing per-frame consumers (`propagateTransforms` / `render-extract`\n * / `pick`) already conform -- they fetch the view inside a single pass with\n * no intervening structural changes.\n *\n * Returns `undefined` when the entity is dead, the component is absent, the\n * field does not exist, or the field is not an `array<...>` column.\n *\n * @internal Engine-internal fast path; AI users read public component values\n * through `world.get`. This accessor is the zero-materialization route the\n * propagate kernel, relationship owner, and render walk use; it bypasses\n * the detached public relationship-target snapshot.\n */\n _getArrayView(\n entity: EntityHandle,\n component: Component,\n fieldName: string,\n ): FieldView | undefined {\n const record = this.lookupAlive(entity, '_getArrayView', component.name);\n if (!record.ok) return undefined;\n\n const rec = record.value;\n const arch = this.graph.archetypes[rec.archetypeId];\n if (!arch) return undefined;\n return this.storage.readArrayView(arch, component, this.tableRow(rec), fieldName);\n }\n\n /** Internal zero-materialisation read for ECS-owned relationship lists. */\n _getArrayLength(\n entity: EntityHandle,\n component: Component,\n fieldName: string,\n ): number | undefined {\n const record = this.lookupAlive(entity, 'relationship-read', component.name);\n if (!record.ok) return undefined;\n const arch = this.graph.archetypes[record.value.archetypeId];\n if (arch === undefined) return undefined;\n return this.storage.readArrayLength(arch, component, this.tableRow(record.value), fieldName);\n }\n\n /** Internal zero-materialisation read for one ECS-owned array element. */\n _getArrayElement(\n entity: EntityHandle,\n component: Component,\n fieldName: string,\n index: number,\n ): number | undefined {\n const record = this.lookupAlive(entity, 'relationship-read', component.name);\n if (!record.ok) return undefined;\n const arch = this.graph.archetypes[record.value.archetypeId];\n if (arch === undefined) return undefined;\n return this.storage.readArrayElement(\n arch,\n component,\n this.tableRow(record.value),\n fieldName,\n index,\n );\n }\n\n /** Internal scalar-column read used by parent-first hierarchy traversal. */\n _getFieldValue(\n entity: EntityHandle,\n component: Component,\n fieldName: string,\n ): number | undefined {\n const record = this.lookupAlive(entity, 'relationship-read', component.name);\n if (!record.ok) return undefined;\n const arch = this.graph.archetypes[record.value.archetypeId];\n if (arch === undefined) return undefined;\n return this.storage.readFieldValue(arch, component, this.tableRow(record.value), fieldName);\n }\n\n /**\n * Converge one writable relationship source mutation through the source\n * owner. The source scalar and its materialized target list are committed as\n * one operation; no caller receives a raw source column view that could\n * bypass the mirror/index maintenance.\n */\n private setRelationshipSource(\n entity: EntityHandle,\n component: Component,\n value: Record<string, unknown>,\n record: EntityRecord,\n arch: Archetype,\n markChanged: boolean,\n ): Result<void, EcsError> {\n const role = relationshipRole(component);\n if (role?.kind !== 'source') return ok(undefined);\n const row = this.tableRow(record);\n const current = this.storage.readRow(arch, component, row) as Record<string, unknown>;\n const valuePreflight = this.preflightComponentFieldValues(entity, {\n component,\n data: value as never,\n });\n if (!valuePreflight.ok) return valuePreflight;\n const merged = { ...current, ...value };\n const enumError = validateEnumFieldValues(component, merged, entity as number);\n if (enumError !== null) return err(enumError as unknown as EcsError);\n\n const oldTarget = this.relationshipTargetEntity(component, current);\n const target = this.relationshipTargetEntity(component, merged);\n if (target !== null) {\n const targetRecord = this.records[entityIndex(target)];\n const actualGeneration = targetRecord?.generation ?? -1;\n if (!this.recordIsLive(targetRecord, entityGeneration(target))) {\n return err(\n new StaleEntityError(target as number, entityIndex(target), entityGeneration(target), {\n operation: 'relationship-insert',\n component: component.name,\n expectedGeneration: entityGeneration(target),\n actualGeneration,\n }),\n );\n }\n const roleAllowsSelf = role.allowSelf;\n if (entity === target && !roleAllowsSelf) {\n return err(\n new RelationshipSelfCycleError(component.name, entity as number, target as number),\n );\n }\n const cycleHit =\n entity === target && roleAllowsSelf\n ? null\n : this.relationshipCycleHit(component, target, entity);\n if (cycleHit !== null) {\n return err(\n new RelationshipSelfCycleError(component.name, entity as number, cycleHit as number),\n );\n }\n }\n\n // A same-target source write still counts as authored evidence but does\n // not churn the target mirror or relationship index.\n if (oldTarget !== target) {\n const prepared = this.prepareRelationshipInsert(component, merged);\n if (!prepared.ok) return prepared;\n const preparation = prepared.value;\n if (oldTarget !== null) {\n const detached = this.relationshipOnRemove(entity, component, current);\n if (!detached.ok) {\n this.releaseRelationshipPreparation(preparation);\n return detached;\n }\n }\n const attached = this.relationshipOnInsert(entity, component, merged, preparation);\n if (!attached.ok) {\n this.releaseRelationshipPreparation(preparation);\n return attached;\n }\n }\n\n const fieldCols = this.table(arch).storage.get(componentId(component))?.fields;\n const sourceColumn = fieldCols?.get(role.sourceField);\n if (sourceColumn === undefined) {\n return err(new ComponentNotPresentError(entity as number, component.name));\n }\n sourceColumn.view[row] = target === null ? ENTITY_NULL_RAW : (target as number);\n if (markChanged) this.markComponentChanged(entity, component);\n return ok(undefined);\n }\n\n /**\n * Write (partial) component data to an entity.\n *\n * @returns `Result<void, EcsError>` —\n * `ok(void)` on success;\n * `err(StaleEntityError)` (`.code = 'stale-entity'`) if entity is dead;\n * `err(ComponentNotPresentError)` (`.code = 'component-not-present'`) if\n * entity does not have the component (F-02: no longer silently ignores).\n *\n * @example\n * ```ts\n * const Position = defineComponent('Position', { x: 'f32', y: 'f32' });\n * const world = new World();\n * const e = world.spawn({ component: Position, data: { x: 0, y: 0 } }).unwrap();\n * const r = world.set(e, Position, { x: 10 });\n * if (!r.ok) { return; } // r.error.code === 'stale-entity' on dead handle\n * r.unwrap();\n * ```\n */\n set<S extends ComponentSchema>(\n entity: EntityHandle,\n component: Component<string, S>,\n value: Partial<InputShapeOf<S>>,\n markChanged = true,\n ): Result<void, EcsError> {\n const record = this.lookupAlive(entity, 'set', component.name);\n if (!record.ok) return record;\n\n const rec = record.value;\n const arch = this.graph.archetypes[rec.archetypeId];\n /* istanbul ignore next -- defensive: alive record always has valid archetypeId */\n if (!arch) {\n return err(\n new StaleEntityError(entity as number, entityIndex(entity), entityGeneration(entity), {\n operation: 'set',\n component: component.name,\n expectedGeneration: entityGeneration(entity),\n actualGeneration: rec.generation,\n }),\n );\n }\n const localId = componentId(component);\n if (!arch.components.some((candidate) => componentId(candidate) === localId)) {\n // F-02: set on missing component returns err instead of silent ignore\n return err(new ComponentNotPresentError(entity as number, component.name));\n }\n const role = relationshipRole(component as Component);\n if (role?.kind === 'target') {\n return err(new RelationshipTargetReadonlyError(component.name, 'set'));\n }\n if (role?.kind === 'source') {\n return this.setRelationshipSource(\n entity,\n component,\n value as Record<string, unknown>,\n rec,\n arch,\n markChanged,\n );\n }\n const valuePreflight = this.preflightComponentFieldValues(entity, {\n component,\n data: value,\n });\n if (!valuePreflight.ok) return valuePreflight;\n const currentValue = this.storage.readRow(arch, component, this.tableRow(rec)) as Record<\n string,\n unknown\n >;\n const enumError = validateEnumFieldValues(\n component,\n { ...currentValue, ...(value as Record<string, unknown>) },\n entity as number,\n );\n if (enumError !== null) return err(enumError as unknown as EcsError);\n if (component.storage === 'sparse') {\n if (markChanged) this.markComponentChanged(entity, component);\n return ok(undefined);\n }\n const fieldCols = this.table(arch).storage.get(localId)?.fields;\n if (fieldCols === undefined) {\n throw new Error(`Table storage for ${component.name} does not exist.`);\n }\n for (const fieldName of Object.keys(value)) {\n const col = fieldCols.get(fieldName);\n if (!col) {\n continue;\n }\n const fieldType = (componentSchema(component) as Record<string, string>)[fieldName] ?? '';\n // M1/M2 release loop (set path): release the prior managed value\n // BEFORE writing the new one. Single SSOT helper `releaseManagedFieldOnRow`\n // (feat-20260614 D-2) covers every managed-field family (`ref<T>` /\n // `string` / `buffer` / variable `array<T>`); it self-skips fields that\n // do not match `isManagedField` here, but for set-ref/string we already\n // gated on it so the call is hot. Zeroes the column when applicable.\n if (isManagedField(fieldType)) {\n this.storage.releaseManagedFieldOnRow(arch, component, this.tableRow(rec), fieldName);\n }\n const raw = (value as Record<string, unknown>)[fieldName];\n if (fieldType === 'bool') {\n col.view[this.tableRow(rec)] = raw ? 1 : 0;\n } else if (isEntityField(fieldType)) {\n // M3 entity field overwrite: encode null as ENTITY_NULL_RAW;\n // otherwise store the Entity bit pattern (slot+gen).\n col.view[this.tableRow(rec)] =\n raw === null || raw === undefined ? ENTITY_NULL_RAW : (raw as number);\n } else if (isManagedBufferField(fieldType)) {\n // M2 set path: collapsed-vocab keyword family `'buffer'` (variable) +\n // `'buffer<N>'` (fixed). The two shapes diverge here:\n // - `buffer<N>` — schema-declared byteLength is fixed; raw must be a\n // `Uint8Array` whose `byteLength === N`. Mismatched payloads route\n // `FixedSizeMismatchError` via Result.err so AI users observe an\n // explicit failure instead of silent truncation (verify round 1\n // B1 fix; charter P3 — explicit failure > silent acceptance).\n // - `'buffer'` — variable capacity; release the prior slot then\n // alloc a fresh one sized to the new payload's byteLength (mirrors\n // the `array<T>` set path's release-then-alloc D-5 ordering).\n // raw is normalized from any AllowSharedBufferSource view to a\n // Uint8Array over its bytes (feat-20260621 V2 / AC-A4). Non-buffer\n // raw (a forced cast feeding e.g. a number) normalizes to null and\n // is treated as a no-op (column slot stays unchanged).\n const isFixedBuffer = fieldType !== 'buffer';\n const bytes = normalizeBufferWrite(raw);\n if (bytes !== null) {\n if (isFixedBuffer) {\n // feat-20260602: fixed `buffer<N>` lives inline as a stride-N u8\n // column (arity = N bytes). Write the payload straight into the\n // row window -- no BufferPool slot.\n const expected = bufferFieldByteLength(fieldType);\n if (bytes.byteLength !== expected) {\n return err(new FixedSizeMismatchError(fieldName, expected, bytes.byteLength));\n }\n const arity = col.arity;\n (col.view as Uint8Array).set(bytes.subarray(0, arity), this.tableRow(rec) * arity);\n } else {\n // Variable `'buffer'` set: release prior slot via SSOT helper\n // (feat-20260614 D-2) then alloc fresh sized to the new payload\n // (verify round 1 B2 fix path). The helper zeroes the column on\n // release; sentinel slot id 0 is a no-op.\n this.storage.releaseManagedFieldOnRow(arch, component, this.tableRow(rec), fieldName);\n const allocR = this.bufferPool.alloc(bytes.byteLength);\n if (!allocR.ok) {\n const ctx: ErrorContext = {\n systemName: `World.set (${component.name}.${fieldName})`,\n };\n this.routeError(allocR.error, ctx);\n col.view[this.tableRow(rec)] = 0;\n continue;\n }\n const slot = allocR.value;\n slot.view.set(bytes);\n col.view[this.tableRow(rec)] = slot.id;\n }\n }\n } else if (fieldType === 'string') {\n // M1 string-field set path (AC-05 path 3): the prior handle was\n // already released by the unified `isManagedField` pre-write block\n // above (D-R3) -- here we just alloc the new handle and store the\n // u32. Mirrors the array<T> release-then-alloc pattern (D-5) so AI\n // users observe the UniqueRefStore _liveCount net-zero invariant\n // on field overwrite. Missing / non-string raw -> '' fallback\n // (AC-06).\n const text = typeof raw === 'string' ? raw : '';\n const handle = this.uniqueRefs.alloc<'String'>('String', text);\n col.view[this.tableRow(rec)] = unwrapHandle(handle);\n } else {\n const arrayMeta = componentDefinition(component).fields[fieldName]?.arrayMeta;\n if (arrayMeta !== undefined) {\n // M1 set path for array<T> / array<T,N> fields (feat-20260614 D-3\n // calling convention). The set semantics mirror spawn: release the\n // prior slot via the SSOT helper, then alloc a fresh one sized to\n // the new value, copy bytes verbatim, store slot id (+ count for\n // variable). Fixed `array<T,N>` is inline — the helper short-\n // circuits and writeArrayField writes directly into the row's\n // stride window with no pool traffic.\n this.storage.releaseManagedFieldOnRow(arch, component, this.tableRow(rec), fieldName);\n this.storage.writeArrayField(\n arch,\n component,\n this.tableRow(rec),\n fieldName,\n fieldType,\n arrayMeta,\n raw,\n );\n } else {\n // The pre-write `releaseManagedFieldOnRow` block above already\n // released the prior `'shared<T>'` rc via SharedRefStore.release;\n // here we retain the new value so net rc delta is +1 / 0 / -1 per\n // M4 invariant (set: -1+1=0; spawn: 0+1=+1; despawn: -1).\n col.view[this.tableRow(rec)] = raw as number;\n if (fieldType.startsWith('shared<') && (raw as number) !== 0) {\n this.storage.retainSharedScalarHandle(raw as number, component.name, fieldName);\n }\n }\n }\n }\n if (markChanged) this.markComponentChanged(entity, component);\n return ok(undefined);\n }\n\n // ──────────────────────────────────────────────────────────────────────────\n // Internal relationship array maintenance. Public array mutation is always\n // expressed as one `world.set` payload; these helpers only implement the\n // engine-owned target projection and backpointer swap-remove path.\n //\n // Append/remove are engine-owned relationship maintenance only.\n //\n // The `fieldName` parameter is typed `ArrayFieldsOf<S>` so cross-shape\n // access (entity / buffer / string / scalar field names) is rejected at\n // compile time -- AI users see a TS error well before any runtime path.\n // ──────────────────────────────────────────────────────────────────────────\n\n /**\n * Append `value` to the variable `array<T>` field `fieldName` on `entity`.\n *\n * BufferPool grow is amortized O(1) via the size-class freelist (research\n * Finding 5). Relationship target arrays grow byte-wise.\n *\n * @returns `Result<void, EcsError>` with the normal stale/component errors.\n *\n * The helper is called only by relationship synchronization.\n */\n private appendArrayElement<S extends ComponentSchema, K extends ArrayFieldsOf<S>>(\n entity: EntityHandle,\n component: Component<string, S>,\n fieldName: K,\n value: ArrayFieldElementValue<S, K>,\n ): Result<void, EcsError> {\n const record = this.lookupAlive(entity, 'relationship-append', component.name);\n if (!record.ok) return record;\n const rec = record.value;\n const arch = this.graph.archetypes[rec.archetypeId];\n /* istanbul ignore next -- alive record always has a valid archetype */\n if (!arch) {\n return err(\n new StaleEntityError(entity as number, entityIndex(entity), entityGeneration(entity), {\n operation: 'relationship-append',\n component: component.name,\n expectedGeneration: entityGeneration(entity),\n actualGeneration: rec.generation,\n }),\n );\n }\n const localId = componentId(component);\n const fieldCols = this.table(arch).storage.get(localId)?.fields;\n if (!fieldCols) {\n return err(new ComponentNotPresentError(entity as number, component.name));\n }\n const fieldNameStr = fieldName as string;\n const col = fieldCols.get(fieldNameStr);\n /* istanbul ignore next -- ArrayFieldsOf filter ensures the column exists */\n if (!col) return err(new ComponentNotPresentError(entity as number, component.name));\n const arrayMeta = componentDefinition(component).fields[fieldNameStr]?.arrayMeta;\n /* istanbul ignore next -- ArrayFieldsOf filter guarantees array<*> */\n if (arrayMeta === undefined) {\n return err(new ComponentNotPresentError(entity as number, component.name));\n }\n const meta = TYPE_METADATA[arrayMeta.elementType];\n /* istanbul ignore next -- arrayMeta.elementType is guaranteed in TYPE_METADATA */\n if (!meta) return err(new ComponentNotPresentError(entity as number, component.name));\n // biome-ignore lint/style/noNonNullAssertion: ManagedArrayElementType always scalar -> byteSize present\n const elementBytes = meta.byteSize!;\n const slotId = col.view[this.tableRow(rec)] as number;\n\n const countCol = fieldCols.get(arrayCountColumnName(fieldNameStr));\n /* istanbul ignore next -- variable arrays always allocate the count column */\n if (countCol === undefined) {\n return err(new ComponentNotPresentError(entity as number, component.name));\n }\n const count = countCol.view[this.tableRow(rec)] as number;\n const newCount = count + 1;\n const newByteLength = newCount * elementBytes;\n\n let liveSlotId = slotId;\n if (liveSlotId === 0) {\n // Empty/unallocated slot — alloc fresh.\n const allocR = this.bufferPool.alloc(newByteLength);\n if (!allocR.ok) return err(allocR.error);\n liveSlotId = allocR.value.id;\n col.view[this.tableRow(rec)] = liveSlotId;\n } else {\n // A previously-allocated slot may have drained below its high-water\n // mark: swap-remove (`_removeArrayElementByValue`) and `pop` only lower\n // the count column, never shrink the managed buffer. When the refilled\n // length still fits inside the slot's current logical length, reuse the\n // buffer in place -- routing through `grow` would hit the (correct, but\n // here irrelevant) shrink-not-supported guard and strand the field\n // (e.g. `Children.entities` never repopulating after a full drain).\n if (newByteLength > this.bufferPool.view(liveSlotId).byteLength) {\n const growR = this.bufferPool.grow(liveSlotId, newByteLength);\n if (!growR.ok) return err(growR.error);\n }\n }\n const liveBytes = this.bufferPool.view(liveSlotId);\n // Reinterpret the slot bytes as the element-typed view and write at the\n // tail index. Entity values are stored as their u32 bit pattern.\n this.storage.writeArrayElementAt(liveBytes, count, arrayMeta.elementType, value as number);\n countCol.view[this.tableRow(rec)] = newCount;\n this.markComponentChanged(entity, component);\n return ok(undefined);\n }\n\n /**\n * Remove one variable-array element at a known slot. Relationship holders\n * supply the slot from their backpointer, so this is O(1) and never scans\n * the materialized target array.\n */\n private removeArrayElementAt(\n entity: EntityHandle,\n component: Component<string, ComponentSchema>,\n fieldName: string,\n slot: number,\n ): Result<EntityHandle | undefined, EcsError> {\n const record = this.lookupAlive(entity, 'removeArrayElementAt', component.name);\n if (!record.ok) return record;\n const rec = record.value;\n const arch = this.graph.archetypes[rec.archetypeId];\n if (!arch) return err(new ComponentNotPresentError(entity as number, component.name));\n const fieldCols = this.table(arch).storage.get(componentId(component))?.fields;\n if (!fieldCols) return err(new ComponentNotPresentError(entity as number, component.name));\n const col = fieldCols.get(fieldName);\n const arrayMeta = componentDefinition(component).fields[fieldName]?.arrayMeta;\n const countCol = fieldCols.get(arrayCountColumnName(fieldName));\n if (!col || !arrayMeta || arrayMeta.length !== undefined || !countCol) {\n return err(new ComponentNotPresentError(entity as number, component.name));\n }\n const row = this.tableRow(rec);\n const count = countCol.view[row] as number;\n if (slot < 0 || slot >= count) return ok(undefined);\n const slotId = col.view[row] as number;\n if (slotId === 0) return ok(undefined);\n const liveBytes = this.bufferPool.view(slotId);\n const last = count - 1;\n const moved =\n slot === last\n ? undefined\n : (this.storage.readArrayElementAt(liveBytes, last, arrayMeta.elementType) as EntityHandle);\n if (slot !== last) {\n this.storage.writeArrayElementAt(liveBytes, slot, arrayMeta.elementType, moved as number);\n }\n countCol.view[row] = last;\n this.markComponentChanged(entity, component);\n return ok(moved);\n }\n\n // ──────────────────────────────────────────────────────────────────────────\n // addComponent / removeComponent (archetype migration via edges, AC-07)\n // ──────────────────────────────────────────────────────────────────────────\n\n /**\n * Add a component to an existing entity, triggering archetype migration.\n *\n * @returns `Result<void, EcsError>` —\n * `ok(void)` on success;\n * `err(StaleEntityError)` (`.code = 'stale-entity'`) if entity is dead;\n * `err(ComponentAlreadyPresentError)` (`.code = 'component-already-present'`)\n * if entity already has the component (E-03).\n *\n * @example\n * ```ts\n * const Position = defineComponent('Position', { x: 'f32', y: 'f32' });\n * const Velocity = defineComponent('Velocity', { dx: 'f32', dy: 'f32' });\n * const world = new World();\n * const e = world.spawn({ component: Position, data: { x: 0, y: 0 } }).unwrap();\n * const r = world.addComponent(e, { component: Velocity, data: { dx: 1, dy: 0 } });\n * if (!r.ok) { return; } // r.error.code === 'stale-entity' on dead handle\n * r.unwrap();\n * ```\n */\n addComponent<S extends ComponentSchema>(\n entity: EntityHandle,\n componentData: ComponentData<S>,\n ): Result<void, EcsError> {\n return this._addComponentCore(entity, componentData, false);\n }\n\n /**\n * Core implementation of `addComponent` with reentry guard.\n *\n * @param internal — `true` when called from relationship maintenance\n * (lazy mirror create or exclusive reparent).\n * @internal\n */\n _addComponentCore<S extends ComponentSchema>(\n entity: EntityHandle,\n componentData: ComponentData<S>,\n internal: boolean,\n resolveRequirements = true,\n skipVariableArrayInitialization = false,\n ): Result<void, EcsError> {\n const record = this.lookupAlive(entity, 'addComponent', componentData.component.name);\n if (!record.ok) return record;\n\n const rec = record.value;\n let srcArch = this.graph.archetypes[rec.archetypeId];\n /* istanbul ignore next -- defensive: alive record always has valid archetypeId */\n if (!srcArch) {\n return err(\n new StaleEntityError(entity as number, entityIndex(entity), entityGeneration(entity), {\n operation: 'addComponent',\n component: componentData.component.name,\n expectedGeneration: entityGeneration(entity),\n actualGeneration: rec.generation,\n }),\n );\n }\n\n const preflight = this.preflightComponentData(entity, componentData);\n if (!preflight.ok) return preflight;\n\n // bug-20260615: unknown-key fail-fast BEFORE archetype mutation so a\n // typo aborts cleanly without partial state (mirrors _spawnCore).\n const keyErr = validateComponentDataKeys(\n componentData.component,\n componentData.data as Record<string, unknown>,\n );\n if (keyErr !== null) {\n return err(keyErr as unknown as EcsError);\n }\n const arrayErr = validateManagedArrayValues(\n componentData.component,\n componentData.data as Record<string, unknown>,\n );\n if (arrayErr !== null) {\n return err(arrayErr as unknown as EcsError);\n }\n // feat-20260713 M2 / w9: P3 shared-field value gate (see _spawnCore). Runs\n // before archetype mutation so a mis-bound GUID aborts cleanly.\n const sharedErr = validateSharedFieldValues(\n componentData.component,\n componentData.data as Record<string, unknown>,\n );\n if (sharedErr !== null) {\n return err(sharedErr as unknown as EcsError);\n }\n const filled = fillComponentDefaults(\n componentData.component,\n componentData.data as Record<string, unknown>,\n );\n const enumErr = validateEnumFieldValues(componentData.component, filled, entity as number);\n if (enumErr !== null) {\n return err(enumErr as unknown as EcsError);\n }\n\n const localId = componentId(componentData.component);\n let relationshipPreparation: RelationshipPreparation | undefined;\n const componentAlreadyPresent = srcArch.components.some(\n (candidate) => componentId(candidate) === localId,\n );\n // Reserve relationship target storage before resolving required source\n // components. A failed mirror allocation must not leave a requirement\n // component (or its epochs) behind on the source entity.\n if (\n !internal &&\n !componentAlreadyPresent &&\n relationshipRole(componentData.component as Component)?.kind === 'source'\n ) {\n const prepared = this.prepareRelationshipInsert(\n componentData.component as Component,\n filled as Record<string, unknown>,\n );\n if (!prepared.ok) return prepared;\n relationshipPreparation = prepared.value;\n }\n\n // Generic component requirements are resolved once at the structural\n // boundary. Explicit data remains authoritative; only missing required\n // identities are added before the requested component is migrated.\n if (resolveRequirements) {\n const required = expandComponentRequirements([componentData]).slice(1);\n for (const requirement of required) {\n if (\n srcArch.components.some(\n (candidate) => componentId(candidate) === componentId(requirement.component),\n )\n ) {\n continue;\n }\n // The closure is expanded once above. Bypass requirement expansion for\n // each member so malformed dependency cycles remain finite and the\n // structural work still happens in one deterministic sequence.\n const added = this._addComponentCore(entity, requirement as ComponentData, internal, false);\n if (!added.ok) {\n this.releaseRelationshipPreparation(relationshipPreparation);\n return added;\n }\n srcArch = this.graph.archetypes[rec.archetypeId];\n if (!srcArch) {\n this.releaseRelationshipPreparation(relationshipPreparation);\n return err(\n new StaleEntityError(entity as number, entityIndex(entity), entityGeneration(entity), {\n operation: 'addComponent',\n component: componentData.component.name,\n expectedGeneration: rec.generation,\n actualGeneration: rec.generation,\n }),\n );\n }\n }\n }\n\n // Check if entity already has this component (using World-local ID).\n if (srcArch.components.some((candidate) => componentId(candidate) === localId)) {\n this.releaseRelationshipPreparation(relationshipPreparation);\n // M2 exclusive relationship: re-adding the holder with a (possibly new)\n // target auto-reparents instead of failing (AC-12). Route the complete\n // source mutation through one owner operation so the old mirror, new\n // mirror, source scalar, and backpointer converge atomically. Engine\n // internal mirror maintenance never re-adds a source component.\n const role = relationshipRole(componentData.component as Component);\n if (role?.kind === 'source' && role.exclusive && !internal) {\n return this.setRelationshipSource(\n entity,\n componentData.component as Component,\n filled as Record<string, unknown>,\n rec,\n srcArch,\n true,\n );\n }\n return err(new ComponentAlreadyPresentError(entity as number, componentData.component.name));\n }\n\n // Get target archetype via edge cache.\n const targetArch = getAddEdge(\n this.graph,\n srcArch,\n localId,\n componentData.component as Component,\n );\n\n if (componentData.component.storage === 'sparse') {\n this.storage.moveEntityArchetype(rec, srcArch, targetArch);\n } else {\n this.storage.migrateEntity(rec, srcArch, targetArch);\n }\n\n // Write the new component's data. Apply layer-2 + layer-3 silent\n // fallback so addComponent shares the SAME default-resolution path\n // as spawn / SceneAsset.instantiate (feat-20260517 / M2 / AC-04\n // research §F4 auto-symmetry; ComponentData<S>['data'] is the\n // physical bridge).\n if (componentData.component.storage === 'table') {\n this.storage.writeRow(\n targetArch,\n componentData.component,\n this.tableRow(rec),\n filled as ShapeOf<S>,\n skipVariableArrayInitialization ? { skipVariableArrayInitialization: true } : undefined,\n );\n }\n this.markComponentAdded(entity, componentData.component as Component);\n // Relationship sync: append to the materialized target list.\n if (!internal && relationshipRole(componentData.component as Component)?.kind === 'source') {\n const relationshipResult = this.relationshipOnInsert(\n entity,\n componentData.component as Component,\n filled as Record<string, unknown>,\n relationshipPreparation,\n );\n if (!relationshipResult.ok) {\n this.releaseRelationshipPreparation(relationshipPreparation);\n return relationshipResult;\n }\n }\n\n this.markStructureChanged();\n this.state.recordStructuralEvidence({\n kind: 'component-added',\n entity,\n componentId: localId,\n });\n return ok(undefined);\n }\n\n /**\n * Remove a component from an existing entity, triggering archetype migration.\n *\n * @returns `Result<void, EcsError>` —\n * `ok(void)` on success;\n * `err(StaleEntityError)` (`.code = 'stale-entity'`) if entity is dead;\n * `err(ComponentNotPresentError)` (`.code = 'component-not-present'`)\n * if entity doesn't have the component (E-04).\n *\n * @example\n * ```ts\n * const Position = defineComponent('Position', { x: 'f32', y: 'f32' });\n * const world = new World();\n * const e = world.spawn({ component: Position, data: { x: 0, y: 0 } }).unwrap();\n * const r = world.removeComponent(e, Position);\n * if (!r.ok) { return; } // r.error.code === 'stale-entity' on dead handle\n * r.unwrap();\n * ```\n */\n removeComponent<S extends ComponentSchema>(\n entity: EntityHandle,\n component: Component<string, S>,\n ): Result<void, EcsError> {\n return this._removeComponentCore(entity, component, false);\n }\n\n /**\n * Core implementation of `removeComponent` with reentry guard.\n *\n * @param internal — `true` when called from relationship maintenance\n * (exclusive reparent).\n * @internal\n */\n _removeComponentCore<S extends ComponentSchema>(\n entity: EntityHandle,\n component: Component<string, S>,\n internal: boolean,\n ): Result<void, EcsError> {\n // Essential-component hard reject (feat-20260602 / plan-strategy D-3): the\n // id=0 `Entity` component is carried by every archetype unconditionally (it\n // is the row's own packed handle) and cannot be removed. Reject before any\n // liveness lookup so the rejection is structural, not entity-state-dependent.\n if (componentId(component) === componentId(EntityComponent)) {\n return err(new RemoveEssentialComponentError(component.name));\n }\n\n const record = this.lookupAlive(entity, 'removeComponent', component.name);\n if (!record.ok) return record;\n\n const rec = record.value;\n const srcArch = this.graph.archetypes[rec.archetypeId];\n /* istanbul ignore next -- defensive: alive record always has valid archetypeId */\n if (!srcArch) {\n return err(\n new StaleEntityError(entity as number, entityIndex(entity), entityGeneration(entity), {\n operation: 'removeComponent',\n component: component.name,\n expectedGeneration: entityGeneration(entity),\n actualGeneration: rec.generation,\n }),\n );\n }\n\n // Check if entity has this component (using World-local ID).\n const localId = componentId(component);\n if (!srcArch.components.some((candidate) => componentId(candidate) === localId)) {\n return err(new ComponentNotPresentError(entity as number, component.name));\n }\n\n // Capture the old relationship value before column removal so the\n // materialized target list can be pruned.\n const role = relationshipRole(component as Component);\n const needsOldValue = role?.kind === 'source' && !internal;\n if (needsOldValue) {\n const oldValue = this.storage.readRow(\n srcArch,\n component as Component,\n this.tableRow(rec),\n ) as Record<string, unknown>;\n // Relationship sync: prune the holder from the target's materialized list.\n if (role?.kind === 'source' && !internal) {\n const relation = this.relationshipOnRemove(entity, component as Component, oldValue);\n if (!relation.ok) return relation;\n }\n }\n\n // M1 release loop (removeComponent path): release every `ref<T>` field\n // on the component being removed before migration drops the row.\n if (component.storage === 'table') {\n this.storage.releaseManagedRefsOnRow(srcArch, component as Component, this.tableRow(rec));\n }\n\n // Get target archetype via edge cache.\n const targetArch = getRemoveEdge(this.graph, srcArch, localId);\n\n if (component.storage === 'sparse') {\n this.storage.moveEntityArchetype(rec, srcArch, targetArch);\n const set = this.graph.sparseTags.get(componentId(component));\n if (set !== undefined) removeSparseTag(set, entity);\n } else {\n this.storage.migrateEntity(rec, srcArch, targetArch);\n }\n this.markStructureChanged();\n this.state.recordStructuralEvidence({\n kind: 'component-removed',\n entity,\n componentId: localId,\n });\n return ok(undefined);\n }\n\n // ──────────────────────────────────────────────────────────────────────────\n // Internal — deferred command support (CommandBuffer interface)\n // ──────────────────────────────────────────────────────────────────────────\n\n /**\n * @internal Allocate a pending entity for deferred spawn.\n * Returns an Entity handle. The entity is \"pending\" because\n * archetypeId === -1 (set by allocateIndex); no separate flag needed.\n */\n _allocatePendingEntity(): EntityHandle {\n const indexSlot = this.allocateIndex();\n // biome-ignore lint/style/noNonNullAssertion: allocateIndex guarantees a valid slot with an initialized record\n return encodeEntity(indexSlot, this.records[indexSlot]!.generation);\n }\n\n /**\n * Return a deferred-spawn reservation to the free-list without publishing a\n * row or advancing an epoch. CommandBuffer.abort is the sole caller; a\n * materialized entity is intentionally left untouched so an unexpected\n * post-write failure poisons the World instead of attempting an unsafe undo.\n */\n _cancelPendingEntity(entity: EntityHandle): void {\n const slot = entityIndex(entity);\n const record = this.records[slot];\n if (record === undefined || record.generation !== entityGeneration(entity)) return;\n if (record.archetypeId !== -1 || record.archetypeRow !== -1) return;\n record.generation += 1;\n if (!isRetiredSlot(record.generation)) this.freeIndices.push(slot);\n }\n\n /**\n * @internal Materialize a pending entity: actually place it into an archetype.\n * Idempotent: a record with archetypeId !== -1 is already materialized.\n */\n _materializePendingEntity(\n entity: EntityHandle,\n componentDatas: ComponentData[],\n ): Result<void, EcsError> {\n componentDatas = expandComponentRequirements(componentDatas);\n const slot = entityIndex(entity);\n const record = this.records[slot];\n if (!record || record.archetypeId !== -1) return ok(undefined);\n\n // Reserve target-side relationship storage before materializing this\n // pending row. The command preflight has already checked the batch graph;\n // this owner-level reservation closes the remaining managed-capacity\n // failure window without adding a mirror component or advancing an epoch.\n const relationshipPreparations: (RelationshipPreparation | undefined)[] = [];\n for (let index = 0; index < componentDatas.length; index += 1) {\n const componentData = componentDatas[index];\n if (\n componentData === undefined ||\n relationshipRole(componentData.component as Component)?.kind !== 'source'\n ) {\n continue;\n }\n const filled = fillComponentDefaults(\n componentData.component,\n componentData.data as Record<string, unknown>,\n );\n const target = this.relationshipTargetEntity(\n componentData.component as Component,\n filled as Record<string, unknown>,\n );\n const targetRecord = target === null ? undefined : this.records[entityIndex(target)];\n // A pending target is materialized by an earlier command in the normal\n // supported order. Leave it to the existing relationship callback when\n // that target row becomes live; current-world targets are fully\n // prepared before this source row is appended.\n if (\n target !== null &&\n targetRecord !== undefined &&\n this.recordIsLive(targetRecord, entityGeneration(target))\n ) {\n const prepared = this.prepareRelationshipInsert(\n componentData.component as Component,\n filled as Record<string, unknown>,\n );\n if (!prepared.ok) {\n for (const reservation of relationshipPreparations) {\n this.releaseRelationshipPreparation(reservation);\n }\n return prepared;\n }\n relationshipPreparations[index] = prepared.value;\n }\n }\n\n // Find or create target archetype (using World-local IDs).\n const componentIds = componentDatas.map((cd) => componentId(cd.component));\n const components = componentDatas.map((cd) => cd.component);\n const arch = getOrCreateArchetype(this.graph, componentIds, components);\n\n // Append entity row.\n const table = this.table(arch);\n const tableRow = appendTableRow(table, entity);\n const archetypeRow = appendArchetypeRow(arch, tableRow);\n record.archetypeId = arch.id;\n record.archetypeRow = archetypeRow;\n\n // Write initial data. Apply layer-2 + layer-3 silent fallback so\n // deferred-spawn (Commands.spawn) shares the SAME default-resolution\n // path as the synchronous `world.spawn` / `addComponent` /\n // SceneAsset.instantiate (feat-20260517 / M2 / AC-04 + AC-09).\n this.state.markComponentsAdded(entity, [\n componentId(EntityComponent),\n ...componentDatas.map((cd) => componentId(cd.component)),\n ]);\n for (const cd of componentDatas) {\n const filled = fillComponentDefaults(cd.component, cd.data as Record<string, unknown>);\n this.storage.writeRow(arch, cd.component, tableRow, filled as ShapeOf<ComponentSchema>);\n }\n\n // Essential id=0 `Entity` column write (feat-20260602 / plan-strategy D-3),\n // mirroring the synchronous `spawn` path: the deferred handle was minted at\n // `_allocatePendingEntity` time and is passed in here.\n this.storage.writeEntitySelf(arch, tableRow, entity);\n\n // Publish relationship targets after all rows are written.\n for (let index = 0; index < componentDatas.length; index += 1) {\n const cd = componentDatas[index];\n if (cd === undefined) continue;\n if (relationshipRole(cd.component as Component)?.kind === 'source') {\n const filled = fillComponentDefaults(cd.component, cd.data as Record<string, unknown>);\n const relationshipResult = this.relationshipOnInsert(\n entity,\n cd.component as Component,\n filled as Record<string, unknown>,\n relationshipPreparations[index],\n );\n if (!relationshipResult.ok) {\n for (const reservation of relationshipPreparations) {\n this.releaseRelationshipPreparation(reservation);\n }\n return relationshipResult;\n }\n }\n }\n this.markStructureChanged();\n this.state.recordStructuralEvidence({\n kind: 'spawn',\n entity,\n });\n return ok(undefined);\n }\n\n // ──────────────────────────────────────────────────────────────────────────\n // Internal — entity index allocation\n // ──────────────────────────────────────────────────────────────────────────\n\n allocateIndex(): number {\n const recycled = this.freeIndices.pop();\n if (recycled !== undefined) {\n return recycled;\n }\n const slot = this.records.length;\n if (slot > ENTITY_MAX_INDEX) {\n throw new EntityIndexOverflowError(slot);\n }\n this.records.push({ generation: 0, archetypeId: -1, archetypeRow: -1 });\n return slot;\n }\n\n /**\n * Single liveness predicate (feat-20260602 / plan-strategy D-4): a slot is\n * live for a given handle generation iff the record exists, its generation\n * still matches the handle (despawn bumps generation, so a stale or recycled\n * handle fails here), and the slot is materialized into an archetype\n * (archetypeId !== -1). Replaces the former `record.alive && record.generation\n * === gen` conjunction and the intermediate `!record.pending` clause.\n */\n recordIsLive(record: EntityRecord | undefined, gen: number): record is EntityRecord {\n return record !== undefined && record.generation === gen && record.archetypeId !== -1;\n }\n\n lookupAlive(\n entity: EntityHandle,\n operation: string,\n component?: string,\n ): Result<EntityRecord, EcsError> {\n const slot = entityIndex(entity);\n const gen = entityGeneration(entity);\n const record = this.records[slot];\n if (!this.recordIsLive(record, gen)) {\n return err(\n new StaleEntityError(entity as number, slot, gen, {\n operation,\n ...(component !== undefined ? { component } : {}),\n expectedGeneration: gen,\n actualGeneration: this.records[slot]?.generation ?? -1,\n }),\n );\n }\n return ok(record);\n }\n\n readRow<S extends ComponentSchema>(\n arch: Archetype,\n component: Component<string, S>,\n row: number,\n ): ShapeOf<S> {\n return this.storage.readRow(arch, component, row);\n }\n\n writeEntitySelf(arch: Archetype, row: number, handle: EntityHandle): void {\n this.storage.writeEntitySelf(arch, row, handle);\n }\n\n writeRow<S extends ComponentSchema>(\n arch: Archetype,\n component: Component<string, S>,\n row: number,\n value: ShapeOf<S>,\n ): void {\n this.storage.writeRow(arch, component, row, value);\n }\n\n releaseManagedRefsOnRow(arch: Archetype, component: Component, row: number): void {\n this.storage.releaseManagedRefsOnRow(arch, component, row);\n }\n}\n","// World-owned managed array storage. Small fields use eight radix-4 free\n// lists; larger fields allocate dedicated buffers and drop them on release.\n// Pooling policy never limits a field to the largest pooled class. Slot IDs\n// remain private to ECS and survive archetype migration and growth.\n\nimport { err, ok, type Result } from '@forgeax/engine-types';\nimport { ManagedBufferOutOfBoundsError, ManagedBufferShrinkNotSupportedError } from './errors';\n\n/**\n * Size-class bucket boundaries in bytes (D-5, radix 4). Frozen tuple - the\n * order is load-bearing: bucket index = ascending position in the array.\n *\n * `alloc(byteLength)` rounds up to `SIZE_CLASSES[i]` for the smallest `i`\n * with `byteLength <= SIZE_CLASSES[i]`. byteLength === 0 is the special path\n * (no bucket); larger requests use dedicated, unpooled allocations.\n */\nexport const SIZE_CLASSES: readonly number[] = Object.freeze([\n 16, 64, 256, 1024, 4096, 16384, 65536, 262144,\n]);\n\n/** Result envelope for a fresh alloc - id + initial view. */\nexport interface BufferAllocResult {\n /** Stable slot id; archetype columns store this u32 in their `buffer:<N>` field. */\n readonly id: number;\n /** Live Uint8Array view of length `byteLength` (D-5 rounding visible only via `view.buffer.byteLength`). */\n readonly view: Uint8Array;\n}\n\n/**\n * Module-level cache for `ArrayBuffer.prototype.transfer` support.\n *\n * Mirrors `column.ts` HAS_TRANSFER probe: ES2024 transfer is the zero-copy\n * fast path on Node 22+ / dawn-node / modern browsers; the fallback re-allocs\n * + byte-copies. Both paths preserve the byte-equal carry-over invariant\n * (AC-07).\n */\nconst HAS_TRANSFER: boolean =\n typeof (ArrayBuffer.prototype as { transfer?: unknown }).transfer === 'function';\n\ninterface SlotState {\n /** Bucket index, SIZE_CLASSES.length for dedicated storage, or -1 for zero length. */\n sizeClassIdx: number;\n /** Underlying ArrayBuffer for the slot's current bucket (zero-length for sizeClassIdx === -1). */\n buffer: ArrayBuffer;\n /** Live view; sliced to `byteLength <= buffer.byteLength`. */\n view: Uint8Array;\n /** Logical byteLength (== view.byteLength). */\n byteLength: number;\n /** false when the slot has been released and its id is parked on the free-list. */\n live: boolean;\n}\n\n/**\n * Round `byteLength` up to a bucket index. Returns -1 for the legal zero\n * path; returns `SIZE_CLASSES.length` (out-of-range) for byteLength larger\n * than the top bucket so the caller can use a dedicated allocation.\n */\nfunction bucketIndex(byteLength: number): number {\n if (byteLength === 0) return -1;\n for (let i = 0; i < SIZE_CLASSES.length; i++) {\n const b = SIZE_CLASSES[i];\n if (b !== undefined && byteLength <= b) return i;\n }\n return SIZE_CLASSES.length;\n}\n\n/**\n * Per-(slot id) managed Uint8Array store backing the `buffer:<bytes>` schema\n * vocab keyword. Eight size-class free-lists (radix 4); cross-bucket growth\n * uses `ArrayBuffer.transfer` when available with a copy fallback for older\n * runtimes.\n *\n * AI users do not interact with `BufferPool` directly - it sits behind\n * `world.get(e, C).<bufferField>` and the M4 carry-over migrate path. The\n * pool is exposed as a class so World can hold one instance per\n * `new World()` (D-2 per-World lifecycle).\n */\nexport class BufferPool {\n private readonly slots = new Map<number, SlotState>();\n /**\n * Per-bucket free-lists: `freeBuckets[i]` is a LIFO stack of slot ids\n * whose backing buffer is parked on bucket `i`. Released slots stay on\n * their original bucket's free-list - v1 never moves a slot between\n * buckets on release (D-7 no trim).\n */\n private readonly freeBuckets: number[][] = SIZE_CLASSES.map(() => [] as number[]);\n private nextId = 1;\n\n /**\n * Allocate a managed buffer slot of at least `byteLength` bytes.\n *\n * Routes:\n * - invalid byteLength -> structured out-of-bounds error.\n * - byteLength == 0 -> ok({ id, view: zero-length Uint8Array }) (no bucket).\n * - byteLength <= 262144 -> ok({ id, view }), bucket = smallest >= byteLength.\n * - byteLength > 262144 -> a dedicated allocation; allocation failure is structured.\n *\n * D-5: size classes are radix-4 (16 / 64 / 256 / 1K / 4K / 16K / 64K / 256K).\n * Free-list pop reuses the most recently released slot id at the same bucket;\n * miss falls through to a fresh allocation.\n */\n alloc(byteLength: number): Result<BufferAllocResult, ManagedBufferOutOfBoundsError> {\n if (byteLength === 0) {\n const id = this.nextId++;\n const buffer = new ArrayBuffer(0);\n const view = new Uint8Array(buffer);\n this.slots.set(id, { sizeClassIdx: -1, buffer, view, byteLength: 0, live: true });\n return ok({ id, view });\n }\n if (!Number.isSafeInteger(byteLength) || byteLength < 0) {\n return err(new ManagedBufferOutOfBoundsError(byteLength, 0));\n }\n const idx = bucketIndex(byteLength);\n if (idx === SIZE_CLASSES.length) {\n // Large fields are dedicated allocations, not permanently retained\n // pool buckets. Small fields keep exactly the existing allocation cost.\n try {\n const buffer = new ArrayBuffer(byteLength);\n const view = new Uint8Array(buffer);\n const id = this.nextId++;\n this.slots.set(id, { sizeClassIdx: idx, buffer, view, byteLength, live: true });\n return ok({ id, view });\n } catch {\n return err(new ManagedBufferOutOfBoundsError(byteLength, 0));\n }\n }\n const bucketBytes = SIZE_CLASSES[idx];\n /* istanbul ignore next -- bucketIndex returns < SIZE_CLASSES.length here */\n if (bucketBytes === undefined) {\n return err(new ManagedBufferOutOfBoundsError(byteLength, 0));\n }\n // Free-list reuse path: pop the most recently released slot of this bucket.\n const free = this.freeBuckets[idx];\n if (free !== undefined && free.length > 0) {\n const id = free.pop() as number;\n const slot = this.slots.get(id);\n /* istanbul ignore next -- freeBuckets only carries ids that exist in slots */\n if (slot === undefined) {\n return err(new ManagedBufferOutOfBoundsError(byteLength, 0));\n }\n // Re-slice the parked buffer to the new logical length; bucket buffer\n // is reused as-is (D-7 no realloc on release).\n slot.byteLength = byteLength;\n slot.view = new Uint8Array(slot.buffer, 0, byteLength);\n slot.live = true;\n // Defensively clear bytes so AI users never see stale data from the\n // prior tenant of the slot.\n new Uint8Array(slot.buffer).fill(0);\n return ok({ id, view: slot.view });\n }\n // Fresh allocation: bucket bytes (rounded up) -> sliced view of byteLength.\n const id = this.nextId++;\n const buffer = new ArrayBuffer(bucketBytes);\n const view = new Uint8Array(buffer, 0, byteLength);\n this.slots.set(id, {\n sizeClassIdx: idx,\n buffer,\n view,\n byteLength,\n live: true,\n });\n return ok({ id, view });\n }\n\n /**\n * Grow slot `id` to `newBytes`. Returns the post-grow Uint8Array view.\n *\n * Routes (D-6 / D-7):\n * - newBytes < current -> err(managed-buffer-shrink-not-supported).\n * - newBytes == current -> ok(current view) (no-op, identity preserved).\n * - newBytes > current && same bucket -> ok(re-sliced view) (no transfer).\n * - newBytes > current && cross bucket -> ok(new view) backed by a fresh\n * bucket buffer; the prior ArrayBuffer is detached via transfer (ES2024)\n * or replaced via allocate-and-copy fallback. Old `view`s captured by\n * the caller become detached / orphaned - callers must use `pool.view(id)`\n * after grow to read the refreshed view (the `release` loop refreshes\n * automatically).\n * - newBytes beyond the last pooled class -> dedicated allocation.\n */\n grow(\n id: number,\n newBytes: number,\n ): Result<Uint8Array, ManagedBufferShrinkNotSupportedError | ManagedBufferOutOfBoundsError> {\n const slot = this.slots.get(id);\n if (slot === undefined) {\n // Treat unknown id as out-of-bounds against a 0-byte slot (closes the\n // surface; AI users hit this only on use-after-release of a slot id).\n return err(new ManagedBufferOutOfBoundsError(newBytes, 0));\n }\n if (newBytes < slot.byteLength) {\n return err(new ManagedBufferShrinkNotSupportedError(newBytes, slot.byteLength));\n }\n if (newBytes === slot.byteLength) {\n return ok(slot.view);\n }\n if (!Number.isSafeInteger(newBytes) || newBytes < 0) {\n return err(new ManagedBufferOutOfBoundsError(newBytes, slot.buffer.byteLength));\n }\n const newIdx = bucketIndex(newBytes);\n if (newBytes <= slot.buffer.byteLength) {\n // Same bucket: re-slice the existing backing ArrayBuffer to the new\n // logical length. No transfer; old view stays valid until next grow.\n slot.byteLength = newBytes;\n slot.view = new Uint8Array(slot.buffer, 0, newBytes);\n return ok(slot.view);\n }\n // Cross-bucket: detach old buffer + carry old bytes into the new bucket.\n const newBucketBytes = SIZE_CLASSES[newIdx] ?? Math.max(newBytes, slot.buffer.byteLength * 2);\n const oldByteLength = slot.byteLength;\n let nextBuffer: ArrayBuffer;\n try {\n if (HAS_TRANSFER) {\n // ES2024 transfer: copy contents into a fresh ArrayBuffer of the new\n // bucket size and detach the source. The transferred buffer keeps the\n // old prefix bytes intact.\n nextBuffer = (\n slot.buffer as unknown as { transfer(newByteLength: number): ArrayBuffer }\n ).transfer(newBucketBytes);\n } /* istanbul ignore next -- fallback only on runtimes without ES2024 transfer() */ else {\n nextBuffer = new ArrayBuffer(newBucketBytes);\n new Uint8Array(nextBuffer).set(new Uint8Array(slot.buffer, 0, oldByteLength));\n }\n } catch {\n return err(new ManagedBufferOutOfBoundsError(newBytes, slot.buffer.byteLength));\n }\n slot.sizeClassIdx = newIdx;\n slot.buffer = nextBuffer;\n slot.byteLength = newBytes;\n slot.view = new Uint8Array(nextBuffer, 0, newBytes);\n return ok(slot.view);\n }\n\n /**\n * Release slot `id` back to its bucket's free-list. Releasing an unknown id\n * is a no-op - World's release loop drives this and idempotency keeps the\n * despawn chain free of bookkeeping noise. Bucket free-lists are NEVER\n * trimmed in v1 (D-7 no trim).\n */\n release(id: number): Result<void, never> {\n const slot = this.slots.get(id);\n if (slot === undefined) return ok(undefined);\n if (!slot.live) return ok(undefined);\n slot.live = false;\n if (slot.sizeClassIdx >= 0 && slot.sizeClassIdx < SIZE_CLASSES.length) {\n const bucket = this.freeBuckets[slot.sizeClassIdx];\n if (bucket !== undefined) bucket.push(id);\n } else {\n // Zero-length or dedicated slot: drop the slot record entirely so\n // the id is not retained.\n this.slots.delete(id);\n }\n return ok(undefined);\n }\n\n /**\n * Return the live view for slot `id`. Used by World after `grow` to\n * refresh the column's stored view reference. Returns a zero-length view\n * for unknown / released ids so callers never crash on use-after-release.\n */\n view(id: number): Uint8Array {\n const slot = this.slots.get(id);\n if (slot === undefined || !slot.live) return new Uint8Array(0);\n return slot.view;\n }\n\n /**\n * Return the bucket-rounded byte capacity for slot `id` --- i.e.\n * `SIZE_CLASSES[slot.sizeClassIdx]`. Used by managed-buffer view callers\n * (D-4 no-cache: re-queried per accessor). Returns `0` for the zero-length\n * (`alloc(0)`) slot; returns `0` for unknown / released ids (mirrors\n * `view(id)` use-after-release semantics).\n */\n byteCapacity(id: number): number {\n const slot = this.slots.get(id);\n if (slot === undefined || !slot.live) return 0;\n if (slot.sizeClassIdx < 0) return 0;\n return slot.buffer.byteLength;\n }\n\n /**\n * Reset the logical byteLength of slot `id` to `newByteLength` while\n * keeping the same bucket allocation (no transfer, no release). Only\n * legal when `newByteLength <= bucketBytes`; the slot's bucket index\n * does not move (D-7 v1 forbids cross-bucket shrink). Used by managed-\n * buffer clear paths so the slot retains its `byteCapacity` while the\n * live view becomes zero-length. Bytes past the new logical length are\n * zero-filled defensively.\n *\n * Returns `err(ManagedBufferShrinkNotSupportedError)` when called on a\n * `sizeClassIdx === -1` slot (alloc(0)) with `newByteLength > 0`, or\n * when `newByteLength` exceeds the bucket capacity.\n */\n setLogicalLength(\n id: number,\n newByteLength: number,\n ): Result<Uint8Array, ManagedBufferShrinkNotSupportedError | ManagedBufferOutOfBoundsError> {\n const slot = this.slots.get(id);\n if (slot === undefined) {\n return err(new ManagedBufferOutOfBoundsError(newByteLength, 0));\n }\n if (slot.sizeClassIdx < 0) {\n // alloc(0) slot has no bucket; only newByteLength === 0 is legal.\n if (newByteLength === 0) {\n slot.byteLength = 0;\n slot.view = new Uint8Array(slot.buffer);\n return ok(slot.view);\n }\n return err(new ManagedBufferOutOfBoundsError(newByteLength, 0));\n }\n const bucketBytes = slot.buffer.byteLength;\n if (newByteLength > bucketBytes) {\n return err(new ManagedBufferOutOfBoundsError(newByteLength, bucketBytes));\n }\n // Zero-fill the prefix bytes that fall past the new logical length so\n // AI users never see stale tail bytes through a future grow.\n if (newByteLength < slot.byteLength) {\n new Uint8Array(slot.buffer, newByteLength, slot.byteLength - newByteLength).fill(0);\n }\n slot.byteLength = newByteLength;\n slot.view = new Uint8Array(slot.buffer, 0, newByteLength);\n return ok(slot.view);\n }\n\n /** @internal Diagnostic count of live slots. Exposed for tests + inspector. */\n _liveCount(): number {\n let n = 0;\n for (const s of this.slots.values()) if (s.live) n += 1;\n return n;\n }\n}\n","// @forgeax/engine-ecs - SharedRefStore.\n//\n// Reference-counted store for AssetRegistry-style shared handles. Schema vocab\n// `shared<T>` fields derive `Handle<T, 'shared'>` whose lifecycle is tracked\n// by retain/release on the holder side - allocators (typically the asset\n// registry) call `alloc` once and let consumers retain/release as the asset\n// flows through ECS components and external systems. When rc transitions\n// 1 -> 0 the store publishes release evidence. External owners dispose their\n// payloads from their own lifecycle effects; ECS does not invoke callbacks.\n//\n// Companion to UniqueRefStore (1-holder-direct-release semantics). The two\n// stores share storage shape and code patterns; only the lifecycle differs:\n//\n// UniqueRefStore: alloc -> store; release -> drop. No retain.\n// SharedRefStore: alloc -> rc=1; retain -> rc++; release -> rc--; rc=0 -> drop.\n//\n// §contract - shared handles are refcounted AND carry a generation\n// The handle u32 packs `(generation << 24) | slot` via the shared codec in\n// `@forgeax/engine-types` (same SSOT codec as UniqueRefStore and ECS\n// EntityHandle). `alloc` welds the slot's current generation; resolve /\n// retain / release compare the handle generation against\n// `_generations[slot]` BEFORE any refcount/payload work, so a handle whose\n// slot was released and re-allocated returns `SharedRefStaleError`\n// ('shared-ref-stale') instead of silently resolving the next payload.\n// Generation advances on the rc=0 drop and retires the slot when gen would\n// exceed MAX_GEN (gen 255 is still usable; retire at would-be 256, no wrap).\n// AI users keep the rule \"don't cache a handle\n// past release\" - the AssetRegistry mediates most shared handle lifecycles,\n// but a stale handle now fails structurally rather than silently.\n//\n// §tier boundary (feat-20260614 M6 D-15)\n// This store manages ONLY user-tier slots (`slot >= BUILTIN_BASE`). Builtin\n// asset payloads in the builtin range are process-static and live in their\n// authoring package; they\n// are never reference-counted. `nextSlot` starts at `BUILTIN_BASE` so minted\n// handles never collide with builtin slots, and alloc/retain/release/resolve\n// fail-fast with `BuiltinSlotNotOwnedError` when handed a builtin slot.\n//\n// Storage shape:\n// - `payloads: Map<number, unknown>` - key = handle u32 = slot index.\n// - `refcounts: Map<number, number>` - key = handle u32; rc >= 1 while live;\n// removed (not set to 0) on final release\n// so resolve / retain can detect the\n// released state via `payloads.has(raw)`.\n// - `freeSlots: number[]` - LIFO stack of recyclable slot indices.\n// - `nextSlot` - bump counter for the never-recycled tail\n// (starts at BUILTIN_BASE; user tier only).\n//\n// 24 bits = 16_777_215 simultaneous live shared handles - same ceiling as\n// UniqueRefStore + Entity, so the three managed-handle resources fail-fast\n// at the same bound.\n//\n// Release path (D-1 codes):\n// - resolve(h): err(SharedRefReleasedError) if payload absent.\n// - markChanged(h): publish an in-place payload mutation to subscribers.\n// - retain(h): err(SharedRefReleasedError) if payload absent.\n// - release(h): err(SharedRefDoubleReleaseError, rc=0) on rc=0 input.\n// - any(builtin slot): err(BuiltinSlotNotOwnedError) (D-15).\n//\n// Identity invariant (mirrors UniqueRefStore): resolve(h) returns the SAME\n// payload object on every call until the final release. Archetype migration\n// preserves this trivially - the column carries the u32 handle, never the\n// payload reference.\n\nimport type { Handle } from '@forgeax/engine-types';\nimport {\n BUILTIN_BASE,\n err,\n handleGeneration,\n handleSlot,\n isRetiredSlot,\n MAX_SLOT,\n ok,\n pack,\n type Result,\n toShared,\n unwrapHandle,\n} from '@forgeax/engine-types';\nimport {\n BuiltinSlotNotOwnedError,\n SharedRefDoubleReleaseError,\n SharedRefPayloadInvalidError,\n SharedRefReleasedError,\n SharedRefStaleError,\n} from './errors';\n\nconst SHARED_REF_RELEASE_EVIDENCE_CAPACITY = 4096;\n\nexport interface SharedRefMutation {\n readonly epoch: number;\n readonly handle: number;\n}\n\nexport interface SharedRefReleaseEvidence {\n readonly payload: unknown;\n readonly refcount: 0;\n readonly generation: number;\n readonly evidence: 'released';\n}\n\nexport interface SharedRefMutationRead {\n readonly cursor: number;\n readonly records: readonly SharedRefMutation[];\n}\n\n// MAX_SLOT is now imported from @forgeax/engine-types (codec SSOT, D-1).\n// The local constant is removed to avoid drift (AC-15).\n\n/**\n * Reference-counted store for ECS-aware `Handle<T, 'shared'>` lifecycles.\n *\n * The producer (typically AssetRegistry) calls `alloc` once and owns the\n * \"alloc-grant\" rc=1; consumers (ECS schema fields, external systems) call\n * `retain` on each new holder and `release` when the holder drops. When rc\n * transitions 1 -> 0 the store publishes one structured release-evidence\n * record; it does not invoke a user callback or own payload disposal.\n *\n * D-15: manages ONLY user-tier slots (`slot >= BUILTIN_BASE`). Builtin slots\n * (`< BUILTIN_BASE`) fail-fast with `BuiltinSlotNotOwnedError`.\n *\n * Public API:\n * - alloc(target, payload) -> Handle<T, 'shared'> (rc=1)\n * - intern(target, payload) -> stable producer handle per target + object identity\n * - resolve(handle) -> Result<T, SharedRefReleasedError | SharedRefStaleError | BuiltinSlotNotOwnedError>\n * - markChanged(handle) -> Result<void, SharedRefReleasedError | SharedRefStaleError | BuiltinSlotNotOwnedError>\n * - getMutationEpoch() -> monotonic payload-mutation cursor\n * - retain(handle) -> Result<void, SharedRefReleasedError | SharedRefStaleError | BuiltinSlotNotOwnedError>\n * - release(handle) -> Result<release evidence | undefined, ...>\n * - refcount(handle) -> number (0 == released; debug + tests)\n * - _liveCount() -> live slot count (debug + inspector)\n */\nexport class SharedRefStore {\n private readonly payloads = new Map<number, unknown>();\n private readonly refcounts = new Map<number, number>();\n private readonly freeSlots: number[] = [];\n private readonly internedByTarget = new Map<string, WeakMap<object, number>>();\n private readonly internedKeys = new Map<\n number,\n { readonly target: string; readonly payload: object }\n >();\n private nextSlot = BUILTIN_BASE;\n private mutationEpoch = 0;\n /** Latest published mutation epoch per live handle; not an event journal. */\n private readonly mutationEpochs = new Map<number, number>();\n private readonly releaseJournal: SharedRefReleaseEvidence[] = [];\n\n /**\n * Generation table indexed by slot (D-6). Each entry tracks the current\n * generation for the slot — written to during alloc (welded into the\n * returned handle via pack) and incremented on release (M4).\n *\n * @internal\n */\n // biome-ignore lint/style/useNamingConvention: internal field — @internal JSDoc suppresses lint:internal gate\n private readonly _generations: number[] = [];\n\n /**\n * Allocate a fresh shared handle for `payload`, branded against `target`.\n * Refcount starts at 1 (the alloc-grant). Nullish payloads are rejected\n * before a slot or free-list is touched.\n *\n * The returned handle carries a generation tag welded via codec.pack\n * (D-8, OOS-2): first allocation gen=0 (AC-06), reused slot gen = the\n * current generation from _generations[slot]. The toShared brand cast\n * happens internally — external callers no longer construct Handle<...>\n * directly.\n *\n * Minted slots are user-tier (`>= BUILTIN_BASE`); builtin slots are never\n * produced here (D-15).\n */\n alloc<Target extends string, T = unknown>(target: Target, payload: T): Handle<Target, 'shared'> {\n void target; // target is a phantom - tag flows only at the type level via Handle<Target,_>.\n if (payload === null || payload === undefined) {\n throw new SharedRefPayloadInvalidError(target, payload === null ? 'null' : 'undefined');\n }\n const slot = this.freeSlots.pop() ?? this.nextSlot++;\n if (slot > MAX_SLOT) {\n throw new RangeError(\n `SharedRefStore: slot index ${slot} exceeds 24-bit max (${MAX_SLOT}). ` +\n 'Reduce simultaneous shared handles or investigate handle leaks.',\n );\n }\n const gen = this._generations[slot] ?? 0;\n const raw = pack(slot, gen);\n this.payloads.set(raw, payload);\n this.refcounts.set(raw, 1);\n return toShared(raw);\n }\n\n /**\n * Return the idempotent producer handle for one object payload in this\n * store. Identity includes `target`, so the same object branded for two\n * asset kinds does not alias.\n *\n * A cache hit deliberately does not retain: this is one producer grant,\n * discovered repeatedly by an asset catalogue. Actual holders retain and\n * release through the ECS write barrier. Callers needing independent\n * grants or a per-handle deleter must use {@link alloc}.\n */\n intern<Target extends string, T extends object>(\n target: Target,\n payload: T,\n ): Handle<Target, 'shared'> {\n let byPayload = this.internedByTarget.get(target);\n if (byPayload === undefined) {\n byPayload = new WeakMap<object, number>();\n this.internedByTarget.set(target, byPayload);\n }\n\n const existingRaw = byPayload.get(payload);\n if (existingRaw !== undefined && this.payloads.has(existingRaw)) {\n return toShared(existingRaw);\n }\n\n const handle = this.alloc(target, payload);\n const raw = unwrapHandle(handle);\n byPayload.set(payload, raw);\n this.internedKeys.set(raw, { target, payload });\n return handle;\n }\n\n /**\n * Look up `payload` by handle. Returns `err(shared-ref-released)` when\n * the handle's slot has no live payload (rc reached 0, no re-alloc has\n * filled the slot); `err(builtin-slot-not-owned)` for a builtin slot.\n *\n * §contract - mirrors UniqueRefStore: a stale handle whose slot has been\n * released and re-allocated returns `err(shared-ref-stale)` - the handle's\n * welded generation no longer matches `_generations[slot]`. The gen check\n * runs before payload lookup, so stale-by-reuse is caught deterministically.\n */\n resolve<Target extends string, T = unknown>(\n handle: Handle<Target, 'shared'>,\n ): Result<T, SharedRefReleasedError | SharedRefStaleError | BuiltinSlotNotOwnedError> {\n const raw = unwrapHandle(handle);\n if (raw < BUILTIN_BASE) return err(new BuiltinSlotNotOwnedError(raw));\n // Gen comparison (M4): extract slot + handle gen, compare against\n // store's current gen. Mismatch means slot was released and re-allocated —\n // the caller's handle is stale. This check runs BEFORE payload lookup so\n // stale-by-reuse is always caught (AC-01).\n const slot = handleSlot(handle);\n const handleGen = handleGeneration(handle);\n const storeGen = this._generations[slot] ?? 0;\n if (handleGen !== storeGen) {\n return err(new SharedRefStaleError(slot, handleGen, storeGen));\n }\n const payload = this.payloads.get(raw);\n if (payload === undefined) {\n return err(new SharedRefReleasedError(raw, '<unknown>'));\n }\n return ok(payload as T);\n }\n\n /**\n * Publish that a live payload was mutated in place. Consumers that retain\n * projections of shared payload data compare the monotonic epoch and\n * explicitly refresh instead of rescanning every payload each frame.\n */\n markChanged<Target extends string>(\n handle: Handle<Target, 'shared'>,\n ): Result<void, SharedRefReleasedError | SharedRefStaleError | BuiltinSlotNotOwnedError> {\n const resolved = this.resolve(handle);\n if (!resolved.ok) return resolved;\n if (this.mutationEpoch >= Number.MAX_SAFE_INTEGER) {\n throw new RangeError('SharedRefStore mutation epoch exhausted');\n }\n this.mutationEpoch += 1;\n this.mutationEpochs.set(unwrapHandle(handle), this.mutationEpoch);\n return ok(undefined);\n }\n\n /** Current upper bound for explicitly published payload mutations. */\n getMutationEpoch(): number {\n return this.mutationEpoch;\n }\n\n /** Read each live handle whose latest published mutation is after `cursor`. */\n readChangesSince(cursor: number): SharedRefMutationRead {\n const records: SharedRefMutation[] = [];\n for (const [handle, epoch] of this.mutationEpochs) {\n if (epoch > cursor) records.push({ epoch, handle });\n }\n records.sort((left, right) => left.epoch - right.epoch || left.handle - right.handle);\n return {\n cursor: this.mutationEpoch,\n records,\n };\n }\n\n /**\n * Increment the refcount of a live shared handle. Returns\n * `err(shared-ref-released)` when the handle is not live - retain MUST\n * NOT resurrect a released slot (charter P3 explicit failure; would\n * defeat the rc=0 -> drop invariant); `err(builtin-slot-not-owned)` for a\n * builtin slot.\n */\n retain<Target extends string>(\n handle: Handle<Target, 'shared'>,\n ): Result<void, SharedRefReleasedError | SharedRefStaleError | BuiltinSlotNotOwnedError> {\n const raw = unwrapHandle(handle);\n if (raw < BUILTIN_BASE) return err(new BuiltinSlotNotOwnedError(raw));\n // Gen comparison runs before rc read (q12: all three operations compare gen first).\n const slot = handleSlot(handle);\n const handleGen = handleGeneration(handle);\n const storeGen = this._generations[slot] ?? 0;\n if (handleGen !== storeGen) {\n return err(new SharedRefStaleError(slot, handleGen, storeGen));\n }\n const rc = this.refcounts.get(raw);\n if (rc === undefined) {\n return err(new SharedRefReleasedError(raw, '<unknown>'));\n }\n this.refcounts.set(raw, rc + 1);\n return ok(undefined);\n }\n\n /**\n * Decrement the refcount. When rc transitions 1 -> 0, the slot is dropped\n * and one structured release-evidence record is published. The evidence\n * captures the payload, zero refcount, next generation and `released` marker\n * after the store has removed the live slot.\n *\n * Returns `err(shared-ref-double-release, rc=0)` when the handle has\n * already reached rc=0 (or was never live); `err(builtin-slot-not-owned)`\n * for a builtin slot. AI users branch on `.code` and route the\n * second-release log to Layer 3 ErrorHandler without aborting the despawn\n * chain.\n */\n release<Target extends string>(\n handle: Handle<Target, 'shared'>,\n ): Result<\n SharedRefReleaseEvidence | undefined,\n SharedRefDoubleReleaseError | SharedRefStaleError | BuiltinSlotNotOwnedError\n > {\n const raw = unwrapHandle(handle);\n if (raw < BUILTIN_BASE) return err(new BuiltinSlotNotOwnedError(raw));\n // Gen comparison runs FIRST — before rc read, before any mutation (q12).\n const slot = handleSlot(handle);\n const handleGen = handleGeneration(handle);\n const storeGen = this._generations[slot] ?? 0;\n if (handleGen !== storeGen) {\n // AC-03: stale release MUST NOT touch rc / payload / freeSlots.\n return err(new SharedRefStaleError(slot, handleGen, storeGen));\n }\n const rc = this.refcounts.get(raw);\n if (rc === undefined) {\n return err(new SharedRefDoubleReleaseError(raw, '<unknown>', 0));\n }\n if (rc > 1) {\n this.refcounts.set(raw, rc - 1);\n return ok(undefined);\n }\n // rc === 1 -> drop. Capture the payload for release evidence before\n // clearing the live slot; nullish payloads never enter the store.\n const payload = this.payloads.get(raw);\n const internedKey = this.internedKeys.get(raw);\n if (internedKey !== undefined) {\n const byPayload = this.internedByTarget.get(internedKey.target);\n if (byPayload?.get(internedKey.payload) === raw) {\n byPayload.delete(internedKey.payload);\n }\n this.internedKeys.delete(raw);\n }\n this.refcounts.delete(raw);\n this.payloads.delete(raw);\n this.mutationEpochs.delete(raw);\n // Gen increment + retire (AC-07): bump gen; once it would exceed MAX_GEN\n // (gen 255 is still usable; the bump to 256 triggers retire) the slot is\n // permanently retired — NOT pushed to freeSlots. This prevents handle\n // aliasing. Shares the isRetiredSlot SSOT predicate with EntityHandle.\n const generation = storeGen + 1;\n this._generations[slot] = generation;\n if (!isRetiredSlot(generation)) {\n this.freeSlots.push(slot);\n }\n // else: slot retired (gen exceeded MAX_GEN) - never returns to freeSlots.\n const evidence = Object.freeze({\n payload,\n refcount: 0 as const,\n generation,\n evidence: 'released' as const,\n });\n this.releaseJournal.push(evidence);\n if (this.releaseJournal.length > SHARED_REF_RELEASE_EVIDENCE_CAPACITY) {\n this.releaseJournal.shift();\n }\n return ok(evidence);\n }\n\n /** Read the bounded release evidence owned by this store. */\n readReleaseEvidence(): readonly SharedRefReleaseEvidence[] {\n return this.releaseJournal;\n }\n\n /**\n * Return the current refcount for `handle`. Returns 0 for a released\n * (or never-allocated) slot. Primarily a debug + tests entry point;\n * production code rarely reads rc directly (the rc=0 -> drop invariant\n * is the surface AI users consume via release / the per-handle deleter).\n */\n refcount<Target extends string>(handle: Handle<Target, 'shared'>): number {\n const raw = unwrapHandle(handle);\n return this.refcounts.get(raw) ?? 0;\n }\n\n /** @internal Diagnostic count of live slots. Exposed for tests + inspector. */\n _liveCount(): number {\n return this.payloads.size;\n }\n}\n","import type { EntityHandle } from '../entity-handle';\n\nexport type StructuralEvidenceKind = 'spawn' | 'despawn' | 'component-added' | 'component-removed';\n\nexport interface StructuralEvidenceInput {\n readonly kind: StructuralEvidenceKind;\n readonly entity: EntityHandle;\n readonly componentId?: number;\n}\n\nexport interface StructuralEvidence extends StructuralEvidenceInput {\n readonly sequence: number;\n}\n\nexport type StructuralEvidenceRead =\n | {\n readonly status: 'ok';\n readonly cursor: number;\n readonly events: readonly StructuralEvidence[];\n }\n | { readonly status: 'overflow'; readonly cursor: number; readonly oldestAvailable: number };\n\n/** Bounded producer-owned structural evidence; consumers never infer facts by scanning. */\nexport class StructuralEvidenceRing {\n private readonly events: Array<StructuralEvidence | undefined>;\n private nextSequence = 1;\n\n constructor(readonly capacity = 1024) {\n if (!Number.isSafeInteger(capacity) || capacity <= 0) {\n throw new RangeError('StructuralEvidenceRing capacity must be a positive safe integer');\n }\n this.events = new Array<StructuralEvidence | undefined>(capacity);\n }\n\n get cursor(): number {\n return this.nextSequence - 1;\n }\n\n append(input: StructuralEvidenceInput): number {\n const sequence = this.nextSequence;\n this.nextSequence += 1;\n this.events[(sequence - 1) % this.capacity] = { ...input, sequence };\n return sequence;\n }\n\n readAfter(cursor: number): StructuralEvidenceRead {\n const latest = this.cursor;\n if (!Number.isSafeInteger(cursor) || cursor < 0 || cursor > latest) {\n throw new RangeError(`StructuralEvidenceRing cursor ${cursor} is outside 0..${latest}`);\n }\n const oldestAvailable = Math.max(1, latest - this.capacity + 1);\n if (cursor < oldestAvailable - 1)\n return { status: 'overflow', cursor: latest, oldestAvailable };\n const events: StructuralEvidence[] = [];\n for (let sequence = cursor + 1; sequence <= latest; sequence += 1) {\n const event = this.events[(sequence - 1) % this.capacity];\n if (event === undefined || event.sequence !== sequence) {\n return { status: 'overflow', cursor: latest, oldestAvailable };\n }\n events.push(event);\n }\n return { status: 'ok', cursor: latest, events };\n }\n}\n","// @forgeax/engine-ecs - UniqueRefStore.\n//\n// Per-slot singleton store for ECS-managed asset handles. Schema vocab\n// `ref<T>` fields derive `Handle<T, 'unique'>` whose lifecycle is owned by\n// the ECS - World hooks `despawn` / `removeComponent` / `set` into\n// `UniqueRefStore.release` so dropping a holder entity reliably releases the\n// referenced asset slot. AssetRegistry handles (`handle<T>` schema vocab) take\n// the orthogonal `'shared'` mode and never enter this store.\n//\n// §contract — handles carry a generation; stale-by-reuse is detected\n// The handle u32 packs `(generation << 24) | slot` via the shared codec in\n// `@forgeax/engine-types` (the same SSOT codec ECS `EntityHandle` uses). The\n// slot occupies the low 24 bits (capped at MAX_SLOT == ENTITY_MAX_INDEX);\n// the generation occupies the high 8 bits. `alloc` welds the slot's current\n// generation into the returned handle; `resolve` / `release` compare the\n// handle's generation against the store's `_generations[slot]` BEFORE any\n// payload work, so a handle whose slot was released and re-allocated is\n// caught deterministically and returns `UniqueRefStaleError` ('unique-ref-\n// stale') — it no longer silently resolves to the next payload.\n//\n// Generation advances on release and retires the slot when gen would exceed\n// MAX_GEN (255) — gen 255 is still usable; the bump to 256 triggers retire —\n// rather than wrapping, so a re-used slot can never collide with an old\n// handle's generation (mirrors EntityHandle via the isRetiredSlot SSOT).\n//\n// AC-06 (unique-ref-double-release) remains payload-presence detected\n// (`payloads.has(raw)`) for a handle whose generation still matches; the\n// generation check catches the orthogonal stale-by-reuse case first.\n//\n// Storage shape:\n// - `payloads: Map<number, unknown>` - key = handle u32 = slot index.\n// Strong reference; deleted on release.\n// Type-erased (the store never inspects\n// payload fields); `Handle<T, 'unique'>`\n// carries `T` at the type level and the\n// single read site (World.get's ref path)\n// narrows `unknown -> T` at the boundary.\n// - `freeSlots: number[]` - LIFO stack of recyclable slot indices.\n// - `releaseCallbacks: Map<...>` - per-slot onRelease cb cleared before fire.\n// - `nextSlot` - bump counter for the never-recycled tail.\n//\n// 24 bits = 16_777_215 simultaneous live managed handles - the same ceiling\n// as Entity, so an ECS that hit the entity ceiling cannot grow past the\n// managed-ref ceiling either. Ceiling-exhaust handling is a future concern;\n// the store deliberately panics on overflow to fail fast rather than\n// silently wrap.\n//\n// Release path (D-1 codes):\n// - resolve(h): err(UniqueRefReleasedError) if payload absent.\n// - release(h): err(UniqueRefDoubleReleaseError) on second release.\n//\n// Object.is identity invariant (AC-04 prelude):\n// resolve(h) returns the SAME payload object on every call until release\n// - the store does not clone, wrap, or proxy the payload. M4 carry-over\n// reuses this invariant: archetype migrate moves the row index, not the\n// payload reference, so wrapper identity survives migration.\n\nimport type { Handle } from '@forgeax/engine-types';\nimport {\n err,\n handleGeneration,\n handleSlot,\n isRetiredSlot,\n MAX_SLOT,\n ok,\n pack,\n type Result,\n toUnique,\n unwrapHandle,\n} from '@forgeax/engine-types';\nimport { UniqueRefDoubleReleaseError, UniqueRefReleasedError, UniqueRefStaleError } from './errors';\n\n// MAX_SLOT is now imported from @forgeax/engine-types (codec SSOT, D-1).\n// The local constant is removed to avoid drift (AC-15).\n\n/**\n * Per-slot singleton store for ECS-managed `Handle<T, 'unique'>` lifecycles.\n * World hooks the three release paths (despawn, removeComponent, set) into\n * `release(handle)`; `resolve(handle)` is the read path AI users reach\n * indirectly through `world.get(e, C)` for `ref<T>` schema fields.\n *\n * §contract — handles carry a generation; stale-by-reuse is detected: the\n * handle u32 packs `(gen << 24) | slot` via the shared codec; `resolve` /\n * `release` compare the handle generation against `_generations[slot]` and\n * return `UniqueRefStaleError` ('unique-ref-stale') when a released slot has\n * been re-allocated, instead of silently resolving to the next payload.\n * README §\"Managed handles carry a generation\" is the canonical AI-user-\n * facing statement.\n *\n * Identity invariant (AC-04 prelude): the payload returned by `resolve` is\n * the same object reference on every call until `release`. Carry-over (M4)\n * relies on this - archetype migrate moves the row index, not the payload.\n *\n * Storage is type-erased (`unknown`): the store routes lifecycle without ever\n * inspecting payload fields. Per-call payload typing flows through method\n * generics: `alloc<T>` accepts a `T` payload + matching `onRelease(T)`, and\n * `resolve<T>` returns `Result<T, ...>`. Both narrow at the call boundary\n * (the single read site is World.get's ref path); making the class generic\n * on `T` was decoration with no internal use, so the parameter was dropped\n * (architecture-principles.md §1 SSOT).\n */\nexport class UniqueRefStore {\n private readonly payloads = new Map<number, unknown>();\n private readonly freeSlots: number[] = [];\n private readonly releaseCallbacks = new Map<number, ((payload: unknown) => void) | undefined>();\n private nextSlot = 1;\n\n /**\n * Generation table indexed by slot (D-6). Each entry tracks the current\n * generation for the slot — written to during alloc (welded into the\n * returned handle via pack) and incremented on release (M4).\n *\n * Slot 0 is the sentinel and always has gen=0 — it is never allocated\n * and never incremented (R6).\n *\n * @internal\n */\n // biome-ignore lint/style/useNamingConvention: internal field — @internal JSDoc suppresses lint:internal gate\n private readonly _generations: number[] = [];\n\n /**\n * Allocate a fresh managed handle for `payload`, branded against `target`.\n *\n * Slot 0 is reserved as the \"null/unset\" sentinel - schema-vocab `ref<T>`\n * fields default to this sentinel before the first write, and World's\n * release loop uses it to short-circuit (`shouldRelease(0) === false`).\n *\n * The returned handle carries a generation tag welded via codec.pack\n * (D-8, OOS-2): first allocation gen=0 (AC-06), reused slot gen = the\n * current generation from _generations[slot]. The toUnique brand cast\n * happens internally — external callers no longer construct Handle<...>\n * directly.\n *\n * @returns a `Handle<T, 'unique'>` u32. The branded number is safe to\n * widen to `number` for GPU upload (charter consistent abstraction).\n */\n alloc<Target extends string, T = unknown>(\n target: Target,\n payload: T,\n onRelease?: (payload: T) => void,\n ): Handle<Target, 'unique'> {\n void target; // target is a phantom - tag flows only at the type level via Handle<Target,_>.\n const slot = this.freeSlots.pop() ?? this.nextSlot++;\n if (slot > MAX_SLOT) {\n throw new RangeError(\n `UniqueRefStore: slot index ${slot} exceeds 24-bit max (${MAX_SLOT}). ` +\n 'Reduce simultaneous managed handles or investigate handle leaks.',\n );\n }\n const gen = this._generations[slot] ?? 0;\n const raw = pack(slot, gen);\n this.payloads.set(raw, payload);\n if (onRelease !== undefined) {\n this.releaseCallbacks.set(raw, onRelease as (payload: unknown) => void);\n }\n return toUnique(raw);\n }\n\n /**\n * Look up `payload` by handle. Returns `err(unique-ref-released)` when\n * the handle's slot has no live payload (release happened in between, and\n * no re-alloc has filled the slot). Resolves the same payload object on\n * every call - identity-stable until release.\n *\n * §contract: a stale handle whose slot has been released and re-allocated\n * returns `err(unique-ref-stale)` — the generation welded into the handle\n * no longer matches `_generations[slot]`. The gen check runs before the\n * payload lookup, so stale-by-reuse is caught deterministically — see\n * README §\"Managed handles carry a generation\".\n *\n * `T` flows from the caller's `Handle<T, 'unique'>` type; the store erases\n * payload types at the storage layer and the call boundary re-narrows.\n */\n resolve<Target extends string, T = unknown>(\n handle: Handle<Target, 'unique'>,\n ): Result<T, UniqueRefReleasedError | UniqueRefStaleError> {\n const raw = unwrapHandle(handle);\n // Gen comparison (M4): extract slot + handle gen, compare against\n // store's current gen. Runs BEFORE payload lookup.\n const slot = handleSlot(handle);\n const handleGen = handleGeneration(handle);\n const storeGen = this._generations[slot] ?? 0;\n if (handleGen !== storeGen) {\n return err(new UniqueRefStaleError(slot, handleGen, storeGen));\n }\n const payload = this.payloads.get(raw);\n if (payload === undefined) {\n // Slot 0 (sentinel) and any handle whose payload was already removed\n // both surface as released. The phantom Target is unavailable at\n // runtime - the error carries '<unknown>' to keep the structured\n // shape consistent.\n return err(new UniqueRefReleasedError(raw, '<unknown>'));\n }\n return ok(payload as T);\n }\n\n /**\n * Release `handle` - drop the payload and push the slot onto the free list.\n * Releasing the same handle twice surfaces `unique-ref-double-release`\n * (D-1) so World's release loop can route the second release to Layer 3\n * ErrorHandler without aborting the despawn chain. Detection is by\n * payload-presence, not generation (§contract — managed handles are\n * operational, not persistent).\n *\n * Releasing the slot-0 sentinel is a no-op - World's release loop calls\n * `shouldRelease` first to filter sentinels.\n */\n release<Target extends string>(\n handle: Handle<Target, 'unique'>,\n ): Result<void, UniqueRefDoubleReleaseError | UniqueRefStaleError> {\n const raw = unwrapHandle(handle);\n // Gen comparison runs FIRST (q12: all operations compare gen first).\n const slot = handleSlot(handle);\n const handleGen = handleGeneration(handle);\n const storeGen = this._generations[slot] ?? 0;\n if (handleGen !== storeGen) {\n // AC-03: stale release MUST NOT drop payload / fire callback / touch freeSlots.\n return err(new UniqueRefStaleError(slot, handleGen, storeGen));\n }\n const payload = this.payloads.get(raw);\n if (payload === undefined) {\n return err(new UniqueRefDoubleReleaseError(raw, '<unknown>'));\n }\n // Order (feat-20260614 M1 D-1): clean up ALL store state BEFORE invoking\n // onRelease. The payload is captured on the stack above so cb still\n // observes the value (D-5 RAII-equivalent semantics preserved); both\n // releaseCallbacks and payloads entries are dropped first, then the\n // freelist push happens, and only then is cb invoked. A throwing cb\n // leaves the store fully consistent: a second release sees\n // `payloads.has(raw) === false` and returns UniqueRefDoubleReleaseError\n // without re-firing the callback (AC-01, AC-02, AC-06). try/finally is\n // explicitly NOT used (D-1 alternative (a) rejected — would swallow the\n // first-release throw and violate spec section 3.1).\n const cb = this.releaseCallbacks.get(raw);\n this.releaseCallbacks.delete(raw);\n this.payloads.delete(raw);\n // Gen increment + retire (AC-07): bump gen; once it would exceed MAX_GEN\n // (gen 255 is still usable; the bump to 256 triggers retire) the slot is\n // permanently retired — NOT pushed to freeSlots.\n this._generations[slot] = storeGen + 1;\n if (!isRetiredSlot(this._generations[slot])) {\n this.freeSlots.push(slot);\n }\n // else: slot retired (gen exceeded MAX_GEN) — never returns to freeSlots.\n if (cb !== undefined) {\n cb(payload);\n }\n return ok(undefined);\n }\n\n /** @internal Replace the payload of a live slot without changing its handle. */\n _setPayload<Target extends string, T>(handle: Handle<Target, 'unique'>, payload: T): void {\n const raw = unwrapHandle(handle);\n if (!this.payloads.has(raw)) {\n throw new Error(`UniqueRefStore: cannot replace released payload ${raw}.`);\n }\n this.payloads.set(raw, payload);\n }\n\n /**\n * `true` if `handle` references a live slot - used by World's release loop\n * to decide whether to call `release` (skips sentinel + already-released).\n *\n * The release loop differentiates \"expected sentinel\" (no error) from\n * \"leaked already-released handle\" (`unique-ref-double-release`) at the\n * caller layer; this helper handles only the no-op short-circuit.\n */\n isLive<Target extends string>(handle: Handle<Target, 'unique'>): boolean {\n const raw = unwrapHandle(handle);\n if (raw === 0) return false;\n return this.payloads.has(raw);\n }\n\n /** @internal Diagnostic count of live slots. Exposed for tests + inspector. */\n _liveCount(): number {\n return this.payloads.size;\n }\n}\n","import { BufferPool } from './buffer-pool';\nimport { createWorldIdentity } from './execution/shared-kernel';\nimport type { RelationshipIndex } from './relationship-index';\nimport type { SharedRefStore } from './shared-ref-store';\nimport { SharedRefStore as SharedRefStoreImpl } from './shared-ref-store';\nimport { type ArchetypeGraph, createArchetypeGraph } from './storage/archetype-graph';\nimport { StructuralEvidenceRing } from './storage/structural-evidence';\nimport type { UniqueRefStore } from './unique-ref-store';\nimport { UniqueRefStore as UniqueRefStoreImpl } from './unique-ref-store';\nimport type { EntityRecord } from './world';\n\ninterface WorldStorageCore {\n readonly graph: ArchetypeGraph;\n readonly records: EntityRecord[];\n readonly freeIndices: number[];\n readonly bufferPool: BufferPool;\n readonly uniqueRefs: UniqueRefStore;\n readonly sharedRefs: SharedRefStore;\n}\n\nfunction createWorldStorageCore(\n shared: boolean,\n refs: { readonly uniqueRefs: UniqueRefStore; readonly sharedRefs: SharedRefStore },\n): WorldStorageCore {\n return {\n graph: createArchetypeGraph(shared),\n records: [],\n freeIndices: [],\n bufferPool: new BufferPool(),\n uniqueRefs: refs.uniqueRefs,\n sharedRefs: refs.sharedRefs,\n };\n}\n\n/**\n * Package-private state authority for World. A World is the public facade;\n * this object is the only owner of archetype storage, entity records, managed\n * stores, epochs, and bounded change evidence.\n */\nexport class WorldCore {\n readonly identity: string = createWorldIdentity();\n readonly uniqueRefs: UniqueRefStore = new UniqueRefStoreImpl();\n readonly sharedRefs: SharedRefStore = new SharedRefStoreImpl();\n readonly storage: WorldStorageCore;\n readonly componentMutationEpochs: number[] = [];\n readonly structuralEvidence = new StructuralEvidenceRing();\n /** One packed reverse index per relationship source component. */\n readonly relationshipIndexes = new Map<number, RelationshipIndex>();\n mutationEpoch = 0;\n structureEpoch = 0;\n\n constructor(sharedStorage: boolean) {\n this.storage = createWorldStorageCore(sharedStorage, {\n uniqueRefs: this.uniqueRefs,\n sharedRefs: this.sharedRefs,\n });\n }\n\n get graph() {\n return this.storage.graph;\n }\n\n get records() {\n return this.storage.records;\n }\n\n get freeIndices() {\n return this.storage.freeIndices;\n }\n\n get bufferPool() {\n return this.storage.bufferPool;\n }\n}\n","// @forgeax/engine-ecs — world-entity-lifecycle: entity lifecycle and hierarchy.\n//\n// Owns entity materialization/retirement plus hierarchy orchestration. Component\n// storage remains in WorldComponentAccess; this module composes its typed\n// relationship mutations into public lifecycle behavior.\n\nimport { err, isRetiredSlot, ok, pack, type Result } from '@forgeax/engine-types';\nimport type { Component, ComponentSchema, InputShapeOf, ShapeOf } from './component';\nimport { componentId, componentSchema } from './component';\nimport { fillComponentDefaults, validateComponentDataKeys } from './component-default-fallback';\nimport { expandComponentRequirements } from './component-schema';\nimport { validateManagedArrayValues, validateSharedFieldValues } from './component-value-validate';\nimport { Entity } from './entity';\nimport {\n ENTITY_NULL_RAW,\n type EntityHandle,\n encodeEntity,\n entityGeneration,\n entityIndex,\n} from './entity-handle';\nimport {\n ComponentNotPresentError,\n RelationshipDetachMismatchError,\n RelationshipSelfCycleError,\n StaleEntityError,\n validateEnumFieldValues,\n} from './errors';\nimport { relationshipRole, relationshipSource } from './relationship-index';\nimport { type Archetype, appendArchetypeRow, removeArchetypeRow } from './storage/archetype';\nimport type { ArchetypeGraph } from './storage/archetype-graph';\nimport { getOrCreateArchetype, getTable } from './storage/archetype-graph';\nimport { removeSparseTag } from './storage/change-detection';\nimport { appendTableRow, removeTableRow } from './storage/table';\nimport type { EcsError, World } from './world';\nimport { worldInternal } from './world-internal';\n\nfunction tableRow(world: World, record: { archetypeId: number; archetypeRow: number }): number {\n const archetype = world[worldInternal].getGraph().archetypes[record.archetypeId];\n return archetype?.rows[record.archetypeRow] ?? -1;\n}\n\n/**\n * Core implementation of `spawn` with a relationship reentry guard.\n *\n * @param internal - `true` when relationship maintenance creates a mirror.\n */\nexport function spawnCore(\n world: World,\n componentDatas: { component: Component; data: Partial<Record<string, unknown>> }[],\n internal: boolean,\n): Result<EntityHandle, EcsError> {\n componentDatas = expandComponentRequirements(componentDatas);\n const filledData: Record<string, unknown>[] = [];\n for (const cd of componentDatas) {\n const preflight = world[worldInternal].preflightComponentData(null, cd);\n if (!preflight.ok) return preflight;\n const keyErr = validateComponentDataKeys(cd.component, cd.data as Record<string, unknown>);\n if (keyErr !== null) return err(keyErr as unknown as EcsError);\n const arrayErr = validateManagedArrayValues(cd.component, cd.data as Record<string, unknown>);\n if (arrayErr !== null) return err(arrayErr as unknown as EcsError);\n const sharedErr = validateSharedFieldValues(cd.component, cd.data as Record<string, unknown>);\n if (sharedErr !== null) return err(sharedErr as unknown as EcsError);\n const filled = fillComponentDefaults(cd.component, cd.data as Record<string, unknown>);\n const enumErr = validateEnumFieldValues(cd.component, filled);\n if (enumErr !== null) return err(enumErr as unknown as EcsError);\n filledData.push(filled as Record<string, unknown>);\n }\n // Reserve every relationship target before allocating the new source row.\n // In particular, an injected BufferPool failure must not leave a source\n // entity, mirror component, or mutation epoch behind.\n const relationshipPreparations: unknown[] = [];\n if (!internal) {\n for (let index = 0; index < componentDatas.length; index += 1) {\n const componentData = componentDatas[index];\n const value = filledData[index];\n if (\n componentData === undefined ||\n value === undefined ||\n relationshipRole(componentData.component as Component)?.kind !== 'source'\n ) {\n continue;\n }\n const prepared = world[worldInternal].prepareRelationshipInsert(\n componentData.component as Component,\n value,\n );\n if (!prepared.ok) {\n for (const reservation of relationshipPreparations) {\n world[worldInternal].releaseRelationshipPreparation(reservation);\n }\n return prepared;\n }\n relationshipPreparations[index] = prepared.value;\n }\n }\n const indexSlot = world[worldInternal].allocateIndex();\n const record = world[worldInternal].getRecords()[indexSlot];\n if (record === undefined)\n return err(\n new Error('Internal: allocateIndex did not initialize record') as unknown as EcsError,\n );\n const componentIds = componentDatas.map((cd) => componentId(cd.component));\n const components = componentDatas.map((cd) => cd.component);\n const graph = world[worldInternal].getGraph();\n const arch = getOrCreateArchetype(graph, componentIds, components);\n const table = getTable(graph, arch.tableId);\n const spawnedEntity = encodeEntity(indexSlot, record.generation);\n const tableRow = appendTableRow(table, spawnedEntity);\n const archetypeRow = appendArchetypeRow(arch, tableRow);\n record.archetypeId = arch.id;\n record.archetypeRow = archetypeRow;\n for (let i = 0; i < componentDatas.length; i++) {\n const cdi = componentDatas[i];\n const fdi = filledData[i];\n if (cdi === undefined || fdi === undefined) continue;\n world[worldInternal].writeRow(arch, cdi.component, tableRow, fdi as ShapeOf<ComponentSchema>);\n }\n world[worldInternal].writeEntitySelf(arch, tableRow, spawnedEntity);\n world[worldInternal].markComponentsAdded(spawnedEntity, [\n componentId(Entity),\n ...componentDatas.map((cd) => componentId(cd.component)),\n ]);\n for (let i = 0; i < componentDatas.length; i++) {\n const cd = componentDatas[i];\n const filled = filledData[i];\n if (!cd || filled === undefined) continue;\n if (!internal && relationshipRole(cd.component as Component)?.kind === 'source') {\n const relation = world[worldInternal].relationshipOnInsert(\n spawnedEntity,\n cd.component as Component,\n filled,\n relationshipPreparations[i],\n );\n if (!relation.ok) {\n for (const reservation of relationshipPreparations) {\n world[worldInternal].releaseRelationshipPreparation(reservation);\n }\n return relation;\n }\n }\n }\n world[worldInternal].markStructureChanged();\n world[worldInternal].recordStructuralEvidence({\n kind: 'spawn',\n entity: spawnedEntity,\n });\n return ok(spawnedEntity);\n}\n\n/**\n * Core implementation of `despawn` with a linked-spawn cascade guard.\n *\n * @param internal - `true` while recursively retiring linked children.\n */\nexport function despawnCore(\n world: World,\n entity: EntityHandle,\n internal: boolean,\n): Result<void, EcsError> {\n const slot = entityIndex(entity);\n const gen = entityGeneration(entity);\n const record = world[worldInternal].getRecords()[slot];\n if (!world[worldInternal].recordIsLive(record, gen)) return ok(undefined);\n const arch = world[worldInternal].getGraph().archetypes[record?.archetypeId];\n const linkedChildren = arch ? relationshipLinkedSpawnChildren(world, entity, arch) : [];\n if (arch) {\n const graph = world[worldInternal].getGraph();\n const table = getTable(graph, arch.tableId);\n const archetypeRow = record.archetypeRow;\n const tableRow = arch.rows[archetypeRow] ?? 0;\n for (const comp of arch.components) {\n const role = relationshipRole(comp);\n const needsOldValue = role?.kind === 'source' && !internal;\n if (needsOldValue) {\n const oldValue = world[worldInternal].readRow(arch, comp, tableRow) as Record<\n string,\n unknown\n >;\n if (role?.kind === 'source' && !internal) {\n const relation = world[worldInternal].relationshipOnRemove(entity, comp, oldValue);\n if (!relation.ok) return relation;\n }\n }\n world[worldInternal].releaseManagedRefsOnRow(arch, comp, tableRow);\n }\n for (const component of arch.components) {\n if (component.storage !== 'sparse') continue;\n const set = graph.sparseTags.get(componentId(component));\n if (set !== undefined) removeSparseTag(set, entity);\n }\n const archetypeSwap = removeArchetypeRow(arch, archetypeRow);\n if (archetypeSwap !== null) {\n const movedEntity = (table.storage.get(componentId(Entity))?.fields.get('self')?.view[\n archetypeSwap.movedTableRow\n ] ?? 0) as EntityHandle;\n const movedRecord = world[worldInternal].getRecords()[entityIndex(movedEntity)];\n if (movedRecord?.generation === entityGeneration(movedEntity)) {\n movedRecord.archetypeRow = archetypeSwap.newRow;\n }\n }\n const tableSwap = removeTableRow(table, tableRow);\n if (tableSwap !== null) {\n const movedRecord = world[worldInternal].getRecords()[entityIndex(tableSwap.movedEntity)];\n if (movedRecord?.generation === entityGeneration(tableSwap.movedEntity)) {\n const movedArchetype = graph.archetypes[movedRecord.archetypeId];\n if (movedArchetype !== undefined) {\n movedArchetype.rows[movedRecord.archetypeRow] = tableSwap.newRow;\n }\n }\n }\n }\n world[worldInternal].recordStructuralEvidence({\n kind: 'despawn',\n entity,\n });\n if (record) {\n record.archetypeId = -1;\n record.archetypeRow = -1;\n record.generation += 1;\n if (!isRetiredSlot(record.generation)) world[worldInternal].getFreeIndices().push(slot);\n }\n for (const child of linkedChildren) despawnCore(world, child, true);\n world[worldInternal].markStructureChanged();\n return ok(undefined);\n}\n\n/** Attach a child and maintain the relationship mirror through component storage. */\nexport function worldAddChild<S extends ComponentSchema>(\n world: World,\n parent: EntityHandle,\n child: EntityHandle,\n component: Component<string, S>,\n data: Partial<InputShapeOf<S>>,\n): Result<void, EcsError> {\n const holderComp = component as Component;\n const role = relationshipRole(holderComp);\n if (role?.kind !== 'source') {\n return err(new ComponentNotPresentError(child as number, component.name));\n }\n\n const parentSlot = entityIndex(parent);\n const parentGeneration = entityGeneration(parent);\n const parentRecord = world[worldInternal].getRecords()[parentSlot];\n if (!world[worldInternal].recordIsLive(parentRecord, parentGeneration)) {\n return err(\n new StaleEntityError(parent as number, parentSlot, parentGeneration, {\n operation: 'addChild',\n component: component.name,\n expectedGeneration: parentGeneration,\n actualGeneration: world[worldInternal].getRecords()[parentSlot]?.generation ?? -1,\n }),\n );\n }\n\n const childSlot = entityIndex(child);\n const childGeneration = entityGeneration(child);\n const childRecord = world[worldInternal].getRecords()[childSlot];\n if (!world[worldInternal].recordIsLive(childRecord, childGeneration)) {\n return err(\n new StaleEntityError(child as number, childSlot, childGeneration, {\n operation: 'addChild',\n component: component.name,\n expectedGeneration: childGeneration,\n actualGeneration: world[worldInternal].getRecords()[childSlot]?.generation ?? -1,\n }),\n );\n }\n\n if (child === parent && !(role?.kind === 'source' && role.allowSelf)) {\n return err(new RelationshipSelfCycleError(component.name, child as number, child as number));\n }\n const cycleHit =\n child === parent && role?.kind === 'source' && role.allowSelf\n ? null\n : relationshipChainCycleHit(world, holderComp, parentSlot, parentGeneration, childSlot);\n if (cycleHit !== null) {\n return err(new RelationshipSelfCycleError(component.name, child as number, cycleHit as number));\n }\n\n return world.addComponent(child, { component, data });\n}\n\n/** Detach a child only when its current relationship target matches `parent`. */\nexport function worldRemoveChild<S extends ComponentSchema>(\n world: World,\n parent: EntityHandle,\n child: EntityHandle,\n component: Component<string, S>,\n): Result<void, EcsError> {\n const holderComp = component as Component;\n const childResult = world[worldInternal].lookupAlive(child, 'removeChild', component.name);\n if (!childResult.ok) return childResult;\n\n const childRecord = childResult.value;\n const childArch = (world[worldInternal].getGraph() as ArchetypeGraph).archetypes[\n childRecord.archetypeId\n ];\n if (!childArch) {\n return err(\n new StaleEntityError(child as number, entityIndex(child), entityGeneration(child), {\n operation: 'removeChild',\n component: component.name,\n expectedGeneration: entityGeneration(child),\n actualGeneration: childRecord.generation,\n }),\n );\n }\n if (\n !childArch.components.some((component) => componentId(component) === componentId(holderComp))\n ) {\n return err(\n new RelationshipDetachMismatchError(component.name, child as number, parent as number, 0),\n );\n }\n\n const oldValue = world[worldInternal].readRow(\n childArch,\n holderComp,\n tableRow(world, childRecord),\n ) as Record<string, unknown>;\n const currentTarget = relationshipTargetEntity(holderComp, oldValue);\n if (currentTarget !== parent) {\n return err(\n new RelationshipDetachMismatchError(\n component.name,\n child as number,\n parent as number,\n currentTarget ?? 0,\n ),\n );\n }\n\n return world.removeComponent(child, component);\n}\n\n/** Move a child to a new parent after cycle validation and old-mirror detachment. */\nexport function worldReparent<S extends ComponentSchema>(\n world: World,\n child: EntityHandle,\n newParent: EntityHandle,\n component: Component<string, S>,\n data: Partial<InputShapeOf<S>>,\n): Result<void, EcsError> {\n const holderComp = component as Component;\n const role = relationshipRole(holderComp);\n if (role?.kind !== 'source') {\n return err(new ComponentNotPresentError(child as number, component.name));\n }\n if (child === newParent && !(role?.kind === 'source' && role.allowSelf)) {\n return err(\n new RelationshipSelfCycleError(component.name, child as number, newParent as number),\n );\n }\n const cycleHit =\n child === newParent && role?.kind === 'source' && role.allowSelf\n ? null\n : relationshipChainCycleHit(\n world,\n holderComp,\n entityIndex(newParent),\n entityGeneration(newParent),\n entityIndex(child),\n );\n if (cycleHit !== null) {\n return err(new RelationshipSelfCycleError(component.name, child as number, cycleHit as number));\n }\n\n const childResult = world[worldInternal].lookupAlive(child, 'reparent', component.name);\n if (!childResult.ok) return childResult;\n\n const childRecord = childResult.value;\n const childArch = (world[worldInternal].getGraph() as ArchetypeGraph).archetypes[\n childRecord.archetypeId\n ];\n if (!childArch) {\n return err(\n new StaleEntityError(child as number, entityIndex(child), entityGeneration(child), {\n operation: 'reparent',\n component: component.name,\n expectedGeneration: entityGeneration(child),\n actualGeneration: childRecord.generation,\n }),\n );\n }\n const payload = {\n ...(data as Record<string, unknown>),\n [role.sourceField]: newParent,\n } as Partial<InputShapeOf<S>>;\n if (\n childArch.components.some((candidate) => componentId(candidate) === componentId(holderComp))\n ) {\n // Existing exclusive sources are updated through the same owner-level\n // write barrier as `world.set`; remove+add would expose a partial mirror\n // state and would invalidate unrelated query spans.\n return world.set(child, component as never, payload as never);\n }\n return world.addComponent(child, { component, data: payload });\n}\n\n/** Iterate ancestors in child-to-root order while safely terminating corrupt cycles. */\nexport function worldIterAncestors(world: World, entity: EntityHandle): Iterable<EntityHandle> {\n return {\n *[Symbol.iterator]() {\n const records = world[worldInternal].getRecords();\n const slot = entityIndex(entity);\n const generation = entityGeneration(entity);\n if (!world[worldInternal].recordIsLive(records[slot], generation)) return;\n\n const visited = new Set<number>();\n let currentSlot = slot;\n let currentGeneration = generation;\n while (true) {\n const key = pack(currentSlot, currentGeneration);\n if (visited.has(key)) return;\n visited.add(key);\n\n const currentRecord = records[currentSlot];\n if (!world[worldInternal].recordIsLive(currentRecord, currentGeneration)) return;\n const currentArch = (world[worldInternal].getGraph() as ArchetypeGraph).archetypes[\n currentRecord.archetypeId\n ];\n if (!currentArch) return;\n\n let foundParent = false;\n for (const component of currentArch.components) {\n if (\n relationshipRole(component)?.kind !== 'source' ||\n !currentArch.components.some(\n (candidate) => componentId(candidate) === componentId(component),\n )\n )\n continue;\n const value = world[worldInternal].readRow(\n currentArch,\n component,\n tableRow(world, currentRecord),\n ) as Record<string, unknown>;\n const target = relationshipTargetEntity(component, value);\n if (target === null) continue;\n yield target;\n currentSlot = entityIndex(target);\n currentGeneration = entityGeneration(target);\n if (!world[worldInternal].recordIsLive(records[currentSlot], currentGeneration)) return;\n foundParent = true;\n break;\n }\n if (!foundParent) return;\n }\n },\n };\n}\n\n/** Iterate descendants depth-first through relationship mirror lists. */\nexport function worldIterDescendants(world: World, entity: EntityHandle): Iterable<EntityHandle> {\n return {\n *[Symbol.iterator]() {\n const records = world[worldInternal].getRecords();\n const slot = entityIndex(entity);\n const generation = entityGeneration(entity);\n if (!world[worldInternal].recordIsLive(records[slot], generation)) return;\n\n const visited = new Set<number>();\n const stack: number[] = [slot];\n while (stack.length > 0) {\n const currentSlot = stack.pop();\n if (currentSlot === undefined) break;\n const currentRecord = records[currentSlot];\n if (!currentRecord || currentRecord.archetypeId === -1) continue;\n const currentArch = world[worldInternal].getGraph().archetypes[currentRecord.archetypeId];\n if (!currentArch) continue;\n\n for (const child of descendantChildren(\n world,\n currentArch,\n tableRow(world, currentRecord),\n )) {\n const childSlot = entityIndex(child);\n const childGeneration = entityGeneration(child);\n const key = pack(childSlot, childGeneration);\n if (\n visited.has(key) ||\n !world[worldInternal].recordIsLive(records[childSlot], childGeneration)\n ) {\n continue;\n }\n visited.add(key);\n yield child;\n stack.push(childSlot);\n }\n }\n },\n };\n}\n\nfunction descendantChildren(world: World, arch: Archetype, row: number): EntityHandle[] {\n const children: EntityHandle[] = [];\n for (const component of arch.components) {\n if (!arch.components.some((candidate) => componentId(candidate) === componentId(component)))\n continue;\n const value = world[worldInternal].readRow(arch, component, row) as Record<string, unknown>;\n for (const [fieldName, fieldType] of Object.entries(componentSchema(component))) {\n if (fieldType !== 'array<entity>') continue;\n const list = value[fieldName];\n if (!(list instanceof Uint32Array)) continue;\n for (const raw of list) children.push(raw as EntityHandle);\n }\n }\n return children;\n}\n\nfunction relationshipTargetEntity(\n component: Component,\n value: Record<string, unknown>,\n): EntityHandle | null {\n for (const [fieldName, fieldType] of Object.entries(componentSchema(component))) {\n if (fieldType !== 'entity') continue;\n const raw = value[fieldName];\n if (raw === null || raw === undefined || raw === ENTITY_NULL_RAW) return null;\n return raw as EntityHandle;\n }\n return null;\n}\n\nfunction relationshipChainCycleHit(\n world: World,\n holderComponent: Component,\n startSlot: number,\n startGeneration: number,\n targetSlot: number,\n): EntityHandle | null {\n const visited = new Set<number>();\n let currentSlot = startSlot;\n let currentGeneration = startGeneration;\n while (true) {\n const key = pack(currentSlot, currentGeneration);\n if (visited.has(key)) return null;\n visited.add(key);\n const currentRecord = world[worldInternal].getRecords()[currentSlot];\n if (!world[worldInternal].recordIsLive(currentRecord, currentGeneration)) return null;\n const currentArchetype = (world[worldInternal].getGraph() as ArchetypeGraph).archetypes[\n currentRecord.archetypeId\n ];\n if (\n !currentArchetype?.components.some(\n (candidate) => componentId(candidate) === componentId(holderComponent),\n )\n )\n return null;\n const value = world[worldInternal].readRow(\n currentArchetype,\n holderComponent,\n tableRow(world, currentRecord),\n ) as Record<string, unknown>;\n const target = relationshipTargetEntity(holderComponent, value);\n if (target === null) return null;\n const targetEntitySlot = entityIndex(target);\n if (targetEntitySlot === targetSlot) return target;\n currentSlot = targetEntitySlot;\n currentGeneration = entityGeneration(target);\n }\n}\n\nfunction linkedSpawnMirrorField(mirror: Component): string | undefined {\n const source = relationshipSource(mirror);\n const role = source === undefined ? undefined : relationshipRole(source);\n return role?.kind === 'source' && role.linkedSpawn ? role.targetField : undefined;\n}\n\nfunction relationshipLinkedSpawnChildren(\n world: World,\n entity: EntityHandle,\n arch: Archetype,\n): EntityHandle[] {\n const record = world[worldInternal].getRecords()[entityIndex(entity)];\n const row = record === undefined ? -1 : tableRow(world, record);\n const collected: EntityHandle[] = [];\n for (const component of arch.components) {\n const mirrorField = linkedSpawnMirrorField(component);\n if (mirrorField === undefined) continue;\n const snapshot = world[worldInternal].readRow(arch, component, row) as Record<string, unknown>;\n const list = snapshot[mirrorField];\n if (!(list instanceof Uint32Array)) continue;\n for (const raw of list) {\n if (raw !== ENTITY_NULL_RAW) collected.push(raw as EntityHandle);\n }\n }\n return collected;\n}\n","// @forgeax/engine-ecs -- World schedule and resource orchestration.\n\nimport type { Handle } from '@forgeax/engine-types';\nimport { err, ok, type Result } from '@forgeax/engine-types';\nimport type { CommandBufferImpl } from './commands';\nimport {\n CommandFailedError,\n CyclicDependencyError,\n ProtectedResourceError,\n ScheduleScopeMismatchError,\n SystemFailedError,\n type SystemSetNotRegisteredError,\n TimeConfigInvalidError,\n TimeDeltaInvalidError,\n} from './errors';\nimport {\n SHARED_KERNEL_EXECUTOR_RESOURCE_KEY,\n type SharedKernelDispatch,\n type SharedKernelExecutor,\n SharedKernelFailureError,\n WorldPoisonedError,\n} from './execution/shared-kernel';\nimport type { QueryDescriptor } from './query/query';\nimport {\n getResource as resGet,\n hasResource as resHas,\n insertResource as resInsert,\n removeResource as resRemove,\n} from './resource';\nimport {\n buildSchedule,\n runSchedule,\n type Schedule,\n type SystemDescriptor,\n type SystemSet,\n addSystem as scheduleAddSystem,\n addSystems as scheduleAddSystems,\n removeSystem as scheduleRemoveSystem,\n replaceSystem as scheduleReplaceSystem,\n} from './schedule';\nimport { FixedUpdate, isScheduleToken, type ScheduleToken, Update } from './schedule-token';\nimport type { ArchetypeGraph } from './storage/archetype-graph';\nimport { FIXED_TIME_RESOURCE_KEY, type MutableFixedTimeResource, TIME_RESOURCE_KEY } from './time';\nimport type {\n World,\n WorldInspection,\n WorldScheduleData,\n WorldScheduleQueryData,\n WorldScheduleSystemData,\n} from './world';\nimport { worldInternal } from './world-internal';\n\nconst FIXED_ANCHOR_NAME = FixedUpdate.name;\ntype ResourceKey = string | { readonly name: string };\n\nfunction resourceName(key: ResourceKey): string {\n return typeof key === 'string' ? key : key.name;\n}\n\nfunction warmSharedKernel(world: World, descriptor: unknown): void {\n if (\n (descriptor as { readonly kind?: string }).kind !== 'shared-kernel' ||\n !world.hasResource(SHARED_KERNEL_EXECUTOR_RESOURCE_KEY)\n )\n return;\n world\n .getResource<SharedKernelExecutor>(SHARED_KERNEL_EXECUTOR_RESOURCE_KEY)\n .warmup?.(descriptor as SharedKernelDispatch);\n}\n\nfunction scheduleFor(\n world: World,\n token: ScheduleToken,\n): Result<Schedule, ScheduleScopeMismatchError> {\n const schedule = isScheduleToken(token) ? world[worldInternal].getSchedule(token) : undefined;\n if (schedule) return ok(schedule);\n return err(new ScheduleScopeMismatchError(token?.name ?? 'Unknown', Update.name));\n}\n\nfunction setOwner(world: World, set: SystemSet): ScheduleToken | undefined {\n for (const [token, schedule] of world[worldInternal].getSchedules()) {\n if (schedule.sets.has(set.name)) return token;\n }\n return undefined;\n}\n\nfunction scopeError(\n source: ScheduleToken,\n target: ScheduleToken,\n reference?: string,\n): Result<never, ScheduleScopeMismatchError> {\n return err(new ScheduleScopeMismatchError(source.name, target.name, reference));\n}\n\nexport function worldAddSystem<const Qs extends ReadonlyArray<QueryDescriptor>>(\n world: World,\n token: ScheduleToken,\n descriptor: SystemDescriptor<Qs>,\n): Result<void, ScheduleScopeMismatchError> {\n const target = scheduleFor(world, token);\n if (!target.ok) return target;\n scheduleAddSystem(target.value, descriptor);\n warmSharedKernel(world, descriptor);\n return ok(undefined);\n}\n\nexport function worldRemoveSystem(\n world: World,\n token: ScheduleToken,\n name: string,\n): ReturnType<typeof scheduleRemoveSystem> | Result<never, ScheduleScopeMismatchError> {\n const target = scheduleFor(world, token);\n if (!target.ok) return target;\n return scheduleRemoveSystem(target.value, name);\n}\n\nexport function worldReplaceSystem<const Qs extends ReadonlyArray<QueryDescriptor>>(\n world: World,\n token: ScheduleToken,\n name: string,\n descriptor: SystemDescriptor<Qs>,\n): ReturnType<typeof scheduleReplaceSystem> | Result<never, ScheduleScopeMismatchError> {\n const target = scheduleFor(world, token);\n if (!target.ok) return target;\n const replaced = scheduleReplaceSystem(target.value, name, descriptor);\n if (replaced.ok) warmSharedKernel(world, descriptor);\n return replaced;\n}\n\nexport function worldAddSystems<const Qs extends ReadonlyArray<QueryDescriptor>>(\n world: World,\n token: ScheduleToken,\n set: SystemSet,\n systems: ReadonlyArray<SystemDescriptor<Qs>>,\n): Result<void, SystemSetNotRegisteredError | ScheduleScopeMismatchError> {\n const target = scheduleFor(world, token);\n if (!target.ok) return target;\n const owner = setOwner(world, set);\n if (owner && owner !== token) return scopeError(token, owner, set.name);\n const added = scheduleAddSystems(target.value, set, systems);\n if (added.ok) {\n for (const system of systems) warmSharedKernel(world, system);\n }\n return added;\n}\n\nfunction validateScheduleReferences(\n world: World,\n token: ScheduleToken,\n schedule: Schedule,\n): ScheduleScopeMismatchError | undefined {\n for (const record of schedule.systems.values()) {\n for (const reference of [\n ...(record.descriptor.before ?? []),\n ...(record.descriptor.after ?? []),\n ]) {\n if (isScheduleToken(reference)) {\n const isFixedAnchor = token === Update && reference === FixedUpdate;\n if (reference !== token && !isFixedAnchor) {\n return new ScheduleScopeMismatchError(token.name, reference.name, reference.name);\n }\n continue;\n }\n if (typeof reference === 'string') {\n for (const [otherToken, other] of world[worldInternal].getSchedules()) {\n if (otherToken !== token && other.systems.has(reference)) {\n return new ScheduleScopeMismatchError(token.name, otherToken.name, reference);\n }\n }\n }\n }\n }\n return undefined;\n}\n\nfunction runFixed(\n world: World,\n fixed: MutableFixedTimeResource,\n accumulator: { value: number },\n): void {\n const fixedSchedule = world[worldInternal].getSchedule(FixedUpdate) as Schedule | undefined;\n if (!fixedSchedule) return;\n if (fixedSchedule.systems.size === 0) {\n discardFixedOverflow(fixed, accumulator);\n return;\n }\n let steps = 0;\n while (accumulator.value >= fixed.delta && steps < fixed.maxStepsPerUpdate) {\n accumulator.value = Math.round((accumulator.value - fixed.delta) * 1e12) / 1e12;\n fixed.overstep = accumulator.value;\n fixed.tick += 1;\n runSchedule(fixedSchedule, world);\n steps += 1;\n }\n if (steps === fixed.maxStepsPerUpdate && accumulator.value >= fixed.delta) {\n const remainder = accumulator.value % fixed.delta;\n const dropped = accumulator.value - remainder;\n accumulator.value = remainder;\n fixed.droppedSeconds += dropped;\n fixed.droppedUpdates += 1;\n }\n}\n\nfunction discardFixedOverflow(\n fixed: MutableFixedTimeResource,\n accumulator: { value: number },\n): void {\n if (accumulator.value < fixed.delta) return;\n const remainder = accumulator.value % fixed.delta;\n const dropped = accumulator.value - remainder;\n accumulator.value = remainder;\n fixed.droppedSeconds += dropped;\n fixed.droppedUpdates += 1;\n}\n\nexport function worldUpdate(\n world: World,\n deltaSeconds = 0,\n): Result<\n void,\n | TimeDeltaInvalidError\n | TimeConfigInvalidError\n | ScheduleScopeMismatchError\n | WorldPoisonedError\n | CommandFailedError\n | SystemFailedError\n | CyclicDependencyError\n | SharedKernelFailureError\n> {\n if (world.execution.health === 'poisoned') {\n return err(new WorldPoisonedError(world.identity, world.execution.fault));\n }\n if (!Number.isFinite(deltaSeconds) || deltaSeconds < 0)\n return err(new TimeDeltaInvalidError(deltaSeconds));\n\n const writer = world[worldInternal].getClockWriter();\n const time = writer.time;\n const fixed = writer.fixed;\n if (time.maxDeltaSeconds < (fixed.maxStepsPerUpdate + 1) * fixed.delta) {\n return err(\n new TimeConfigInvalidError({\n fixedDeltaSeconds: fixed.delta,\n maxStepsPerUpdate: fixed.maxStepsPerUpdate,\n maxDeltaSeconds: time.maxDeltaSeconds,\n }),\n );\n }\n\n for (const [token, schedule] of world[worldInternal].getSchedules()) {\n const mismatch = validateScheduleReferences(world, token, schedule);\n if (mismatch) return err(mismatch);\n }\n\n const measured = Math.min(deltaSeconds, time.maxDeltaSeconds);\n time.delta = measured;\n time.elapsed += measured;\n // Accumulate the measured frame delta. maxDeltaSeconds bounds Time's public\n // delta, while the fixed cap makes oversized host gaps observable via metrics.\n const accumulator = { value: world[worldInternal].getFixedAccumulator() + measured };\n const update = world[worldInternal].getSchedule(Update) as Schedule | undefined;\n if (!update) return err(new ScheduleScopeMismatchError('World', Update.name));\n\n try {\n if (update.dirty) buildSchedule(update);\n const order = update.sortedOrder;\n const anchor = order.indexOf(FIXED_ANCHOR_NAME);\n const fixedSchedule = world[worldInternal].getSchedule(FixedUpdate) as Schedule | undefined;\n const hasFixedSystems = (fixedSchedule?.systems.size ?? 0) > 0;\n if (anchor < 0 || !hasFixedSystems) {\n runSchedule(\n update,\n world,\n order.filter((name) => name !== FIXED_ANCHOR_NAME),\n );\n if (measured > 0) discardFixedOverflow(fixed, accumulator);\n } else {\n const updateCommands = new Map<string, CommandBufferImpl>();\n runSchedule(update, world, order.slice(0, anchor), updateCommands, false);\n if (measured > 0) runFixed(world, fixed, accumulator);\n runSchedule(update, world, order.slice(anchor + 1), updateCommands);\n }\n } catch (error) {\n if (error instanceof CommandFailedError || error instanceof SystemFailedError) {\n return err(error);\n }\n if (error instanceof CyclicDependencyError || error instanceof SharedKernelFailureError) {\n return err(error);\n }\n if (world.execution.health === 'healthy') {\n world[worldInternal].poisonExecution({\n code: 'shared-kernel-failed',\n kernelName: `schedule:${Update.name}`,\n cause: error,\n partialWrite: true,\n retryable: false,\n });\n }\n return err(new SystemFailedError('<schedule>', Update.name, error));\n }\n world[worldInternal].setFixedAccumulator(accumulator.value);\n fixed.overstep = accumulator.value;\n return ok(undefined);\n}\n\nexport function worldInsertResource<T>(world: World, key: ResourceKey, value: T): void {\n const name = resourceName(key);\n if (name === TIME_RESOURCE_KEY || name === FIXED_TIME_RESOURCE_KEY) {\n throw new ProtectedResourceError(name, 'insert');\n }\n resInsert(\n world[worldInternal].getResources(),\n name,\n value,\n world[worldInternal].nextMutationEpoch(),\n );\n}\n\nexport function worldGetResource<T>(world: World, key: ResourceKey): T {\n return resGet<T>(world[worldInternal].getResources(), resourceName(key));\n}\n\nexport function worldHasResource(world: World, key: ResourceKey): boolean {\n return resHas(world[worldInternal].getResources(), resourceName(key));\n}\n\nexport function worldRemoveResource(world: World, key: ResourceKey): void {\n const name = resourceName(key);\n if (name === TIME_RESOURCE_KEY || name === FIXED_TIME_RESOURCE_KEY) {\n throw new ProtectedResourceError(name, 'remove');\n }\n if (resHas(world[worldInternal].getResources(), name)) {\n resRemove(world[worldInternal].getResources(), name);\n world[worldInternal].nextMutationEpoch();\n }\n}\n\nexport function worldInspect(world: World): WorldInspection {\n const graph = world[worldInternal].getGraph() as ArchetypeGraph;\n const resources = world[worldInternal].getResources();\n let entityCount = 0;\n const archetypes: WorldInspection['archetypes'] = [];\n const activeComponentSet = new Set<string>();\n for (const arch of graph.archetypes) {\n if (!arch) continue;\n entityCount += arch.size;\n const componentNames = arch.components.map((component) => component.name);\n archetypes.push({\n key: arch.key,\n componentNames,\n entityCount: arch.size,\n tableId: arch.tableId,\n });\n if (arch.size > 0) for (const name of componentNames) activeComponentSet.add(name);\n }\n\n const schedules = [\n ...(world[worldInternal].getSchedules() as ReadonlyMap<ScheduleToken, Schedule>),\n ].map(([token, schedule]) => {\n const systems = [...schedule.systems.entries()]\n .filter(([name]) => name !== FIXED_ANCHOR_NAME)\n .map(([name]) => ({\n name,\n sets: [...schedule.sets].flatMap(([setName, record]) =>\n record.members.has(name) ? [setName] : [],\n ),\n }));\n return { schedule: token, systems };\n });\n const systems = schedules.flatMap((entry) => entry.systems);\n const tables = graph.tables.map((table) => ({\n id: table.id,\n key: table.key,\n componentNames: table.components.map((component) => component.name),\n entityCount: table.size,\n capacity: table.capacity,\n }));\n return {\n entityCount,\n archetypeCount: archetypes.length,\n archetypes,\n tableCount: tables.length,\n tables,\n activeComponents: [...activeComponentSet],\n systemCount: systems.length,\n systems,\n resourceKeys: [...resources.entries.keys()],\n schedules,\n scheduleSystemCount(token: ScheduleToken): number {\n return schedules.find((entry) => entry.schedule === token)?.systems.length ?? 0;\n },\n };\n}\n\nfunction referenceName(reference: string | ScheduleToken): string {\n return typeof reference === 'string' ? reference : reference.name;\n}\n\nfunction componentNames(components: readonly { readonly name: string }[] | undefined): string[] {\n return (components ?? []).map((component) => component.name);\n}\n\nfunction queryData(query: QueryDescriptor): WorldScheduleQueryData {\n return {\n with: componentNames(query.with),\n without: componentNames(query.without),\n optional: componentNames(query.optional),\n changed: componentNames(query.changed),\n added: componentNames(query.added),\n };\n}\n\n/** Project schedule registration into a JSON-safe graph for tooling and AI inspection. */\nexport function worldScheduleData(world: World): ReadonlyArray<WorldScheduleData> {\n return [...(world[worldInternal].getSchedules() as ReadonlyMap<ScheduleToken, Schedule>)].map(\n ([token, schedule]) => {\n if (schedule.dirty) buildSchedule(schedule);\n\n const systems: WorldScheduleSystemData[] = [...schedule.systems.entries()]\n .filter(([name]) => name !== FIXED_ANCHOR_NAME)\n .map(([name, record]) => {\n const descriptor = record.descriptor;\n const queries = descriptor.queries.map(queryData);\n return {\n name,\n sets: [...schedule.sets].flatMap(([setName, set]) =>\n set.members.has(name) ? [setName] : [],\n ),\n before: (descriptor.before ?? []).map((reference) => referenceName(reference)),\n after: (descriptor.after ?? []).map((reference) => referenceName(reference)),\n queries,\n resources: [],\n };\n });\n\n const systemSets = [...schedule.sets].map(([name, set]) => ({\n name,\n members: [...set.members].filter((member) => schedule.systems.has(member)),\n before: [],\n after: [],\n chained: set.chained,\n }));\n const dependencies = [...schedule.predecessors].flatMap(([target, predecessors]) =>\n [...predecessors].map((source) => [source, target] as const),\n );\n\n return { name: token.name, systems, systemSets, dependencies };\n },\n );\n}\n\nfunction queryUsesComponent(query: QueryDescriptor, component: object): boolean {\n return [\n query.read,\n query.write,\n query.optional,\n query.with,\n query.without,\n query.changed,\n query.added,\n ].some((items) => items?.includes(component as never) === true);\n}\n\n/** Control-plane guard used before releasing a World-local component registration. */\nexport function worldScheduleUsesComponent(world: World, component: object): boolean {\n for (const schedule of (\n world[worldInternal].getSchedules() as ReadonlyMap<ScheduleToken, Schedule>\n ).values()) {\n for (const record of schedule.systems.values()) {\n if (record.descriptor.queries.some((query) => queryUsesComponent(query, component)))\n return true;\n }\n }\n return false;\n}\n\nexport function worldAllocUniqueRef<Target extends string, T>(\n world: World,\n target: Target,\n payload: T,\n onRelease?: (payload: T) => void,\n): Handle<Target, 'unique'> {\n return world[worldInternal].getUniqueRefs().alloc(target, payload, onRelease);\n}\n\nexport function worldAllocSharedRef<Target extends string, T>(\n world: World,\n target: Target,\n payload: T,\n): Handle<Target, 'shared'> {\n return world[worldInternal].getSharedRefs().alloc(target, payload);\n}\n\nexport function worldInternSharedRef<Target extends string, T extends object>(\n world: World,\n target: Target,\n payload: T,\n): Handle<Target, 'shared'> {\n return world[worldInternal].getSharedRefs().intern(target, payload);\n}\n","// @forgeax/engine-ecs — World: top-level ECS container.\n//\n// World owns entities, archetypes (via ArchetypeGraph), and component registry.\n// Supports multi-component spawn, despawn (with generation retirement D-08),\n// get/set, addComponent/removeComponent (archetype migration via edges).\n// M3: addSystem / update (DAG schedule) + deferred commands + Resource CRUD.\n//\n// [w6] All 6 public methods return Result<T, EcsError> (AP-8 Layer 1).\n// Construction errors (EntityIndexOverflowError) still throw — they are\n// build-time / infrastructure failures.\n\nimport type { Handle, Result } from '@forgeax/engine-types';\nimport { err, ok } from '@forgeax/engine-types';\nimport type { BufferPool } from './buffer-pool';\nimport {\n type Component,\n ComponentCatalog,\n type ComponentSchema,\n componentId,\n type InputShapeOf,\n type ShapeOf,\n} from './component';\nimport { type EntityHandle, encodeEntity, entityGeneration, entityIndex } from './entity-handle';\nimport type {\n CommandFailedError,\n ComponentAlreadyPresentError,\n ComponentFieldInvalidValueError,\n ComponentNotDefinedError,\n ComponentNotPresentError,\n ComponentNumericValueInvalidError,\n DerivedRangeOutOfBoundsError,\n FixedSizeMismatchError,\n ManagedArrayInvalidValueError,\n ManagedBufferOutOfBoundsError,\n ManagedBufferShrinkNotSupportedError,\n RelationshipDetachMismatchError,\n RelationshipMirrorComponentNotRegisteredError,\n RelationshipMirrorFieldTypeMismatchError,\n RelationshipSelfCycleError,\n RemoveEssentialComponentError,\n ScheduleMutationError,\n ScheduleScopeMismatchError,\n SharedKernelEligibilityError,\n SharedKernelFailureError,\n StaleEntityError,\n SystemFailedError,\n SystemSetNotRegisteredError,\n TimeConfigInvalidError,\n TimeDeltaInvalidError,\n UniqueRefDoubleReleaseError,\n UniqueRefReleasedError,\n WorldPoisonedError,\n} from './errors';\nimport { ChangeEpochExhaustedError, RelationshipTargetReadonlyError } from './errors';\nimport {\n healthyWorldExecutionState,\n poisonedWorldExecutionState,\n type WorldExecutionFault,\n type WorldExecutionState,\n} from './execution/shared-kernel';\nimport type { QueryDescriptor } from './query/query';\nimport { createQuery, type Query, type QueryCreationError } from './query/query';\nimport {\n isRelationshipTarget,\n type RelationshipTargetComponent,\n relationshipRole,\n} from './relationship-index';\nimport { createResourceStore, type ResourceStore } from './resource';\nimport { createSchedule, type Schedule, type SystemDescriptor, type SystemSet } from './schedule';\nimport { FixedUpdate, Update } from './schedule-token';\nimport type { SharedRefStore } from './shared-ref-store';\nimport type { Archetype } from './storage/archetype';\nimport type { ArchetypeGraph } from './storage/archetype-graph';\nimport {\n type ChangeTicks,\n markComponentChanged,\n markComponentsAdded,\n readComponentChange,\n} from './storage/change-detection';\nimport type {\n StructuralEvidenceInput,\n StructuralEvidenceRing,\n} from './storage/structural-evidence';\nimport {\n type ClockWriter,\n createWorldClock,\n DEFAULT_TIME_POLICY,\n FIXED_TIME_RESOURCE_KEY,\n TIME_RESOURCE_KEY,\n type WorldOptions,\n} from './time';\nimport type { UniqueRefStore } from './unique-ref-store';\nimport { WorldComponentAccess } from './world-component-access';\nimport { WorldCore } from './world-core';\nimport {\n despawnCore,\n spawnCore,\n worldAddChild,\n worldIterAncestors,\n worldIterDescendants,\n worldRemoveChild,\n worldReparent,\n} from './world-entity-lifecycle';\nimport { type WorldInternal, worldInternal } from './world-internal';\nimport {\n worldAddSystem,\n worldAddSystems,\n worldAllocSharedRef,\n worldAllocUniqueRef,\n worldGetResource,\n worldHasResource,\n worldInsertResource,\n worldInspect,\n worldInternSharedRef,\n worldRemoveResource,\n worldRemoveSystem,\n worldReplaceSystem,\n worldScheduleData,\n worldScheduleUsesComponent,\n worldUpdate,\n} from './world-scheduling';\n\n/**\n * Union of all EcsError types that World methods can return via Result.\n * AI users: switch on `.code` for programmatic branching.\n */\nexport type EcsError =\n | CommandFailedError\n | StaleEntityError\n | ComponentNotPresentError\n | ComponentAlreadyPresentError\n | ComponentFieldInvalidValueError\n | ComponentNumericValueInvalidError\n | ManagedArrayInvalidValueError\n | UniqueRefReleasedError\n | UniqueRefDoubleReleaseError\n | ManagedBufferOutOfBoundsError\n | ManagedBufferShrinkNotSupportedError\n | FixedSizeMismatchError\n | RelationshipSelfCycleError\n | RelationshipMirrorComponentNotRegisteredError\n | RelationshipMirrorFieldTypeMismatchError\n | RelationshipDetachMismatchError\n | RelationshipTargetReadonlyError\n | ComponentNotDefinedError\n | RemoveEssentialComponentError\n | SystemSetNotRegisteredError\n | SystemFailedError\n | TimeDeltaInvalidError\n | TimeConfigInvalidError\n | ScheduleScopeMismatchError\n | SharedKernelEligibilityError\n | SharedKernelFailureError\n | DerivedRangeOutOfBoundsError\n | ChangeEpochExhaustedError\n | WorldPoisonedError;\n\n/** Component data for spawn/addComponent: component token + initial values.\n *\n * `data` is `Partial<InputShapeOf<S>>` (feat-20260517 / M2; tweak-20260616\n * input/output split): spawn / addComponent / SceneAsset.instantiate share the\n * SAME shape contract via the layer-2 + layer-3 silent fallback applied inside\n * `writeRow` (`fillComponentDefaults`). The input shape widens\n * `array<scalar, N>` / `array<scalar>` to also accept `readonly number[]`\n * because writeArrayField copies bytes from either shape — AI users can write\n * `times: [0.5]` instead of `new Float32Array([0.5])` boilerplate. Wrong-VALUE\n * fields (e.g. `{ fov: 'bad' }`) still fire field-level TS2322 — mapped-tuple\n * primary inference does not degrade to the \"No overload matches\" wall\n * (AC-03 / C-4). */\nexport interface ComponentData<S extends ComponentSchema = ComponentSchema> {\n component: Component<string, S>;\n data: Partial<InputShapeOf<S>>;\n}\n\ntype WritableComponent<C extends Component> = C extends RelationshipTargetComponent ? never : C;\n\n/**\n * Per-archetype summary returned by `world.inspect()`. Sorted ComponentId key\n * (always prefixed by the essential id=0 Entity column, e.g. \"0+2+5+7\"),\n * human-readable component names, live entity count, allocated row capacity.\n */\nexport interface ArchetypeInfo {\n /** Sorted ComponentId key, always prefixed by the id=0 Entity column (e.g. \"0+2+5+7\"). */\n readonly key: string;\n /** Human-readable component names in this archetype. */\n readonly componentNames: string[];\n /** Number of live entities in this archetype. */\n readonly entityCount: number;\n readonly tableId: number;\n}\n\nexport interface TableInfo {\n readonly id: number;\n readonly key: string;\n readonly componentNames: string[];\n readonly entityCount: number;\n readonly capacity: number;\n}\n\n/**\n * Typed diagnostic snapshot of the World state.\n * Returned by `world.inspect()` for programmatic introspection by AI users.\n */\nexport interface WorldInspection {\n /** Total number of live entities. */\n readonly entityCount: number;\n /** Number of archetypes currently allocated. */\n readonly archetypeCount: number;\n /** Per-archetype details. */\n readonly archetypes: ArchetypeInfo[];\n readonly tableCount: number;\n readonly tables: TableInfo[];\n /**\n * Names of components that are currently active in this World — i.e.\n * every distinct component name appearing on at least one non-empty\n * archetype. Collected by walking the archetype graph, so a component\n * that was defined but never spawned into this World does not appear.\n */\n readonly activeComponents: string[];\n /** Number of registered systems. Always equals `systems.length` (M2 derived invariant). */\n readonly systemCount: number;\n /**\n * Per-system summary (M3 — plan-strategy D-8). One entry per\n * registered system, in registration order. The `systemCount` field is\n * preserved as a derived alias of `systems.length` so existing inspector\n * P0 e2e cases that read `systemCount` keep working.\n *\n * `sets` is the list of set names this system belongs to (empty array for\n * systems registered via plain `addSystem` without `addSystems`).\n */\n readonly systems: ReadonlyArray<{ readonly name: string; readonly sets: readonly string[] }>;\n /** Keys of all inserted resources. */\n readonly resourceKeys: string[];\n /** Systems grouped by their schedule token. */\n readonly schedules: ReadonlyArray<{\n readonly schedule: import('./schedule-token').ScheduleToken;\n readonly systems: ReadonlyArray<{ readonly name: string; readonly sets: readonly string[] }>;\n }>;\n /** Count systems in one explicit schedule. */\n scheduleSystemCount(schedule: import('./schedule-token').ScheduleToken): number;\n}\n\n/** JSON-safe schedule graph and access metadata returned by `world.scheduleData()`. */\nexport interface WorldScheduleQueryData {\n readonly with: readonly string[];\n readonly without: readonly string[];\n readonly optional: readonly string[];\n readonly changed: readonly string[];\n readonly added: readonly string[];\n}\n\n/** JSON-safe system registration and access metadata. */\nexport interface WorldScheduleSystemData {\n readonly name: string;\n readonly sets: readonly string[];\n readonly before: readonly string[];\n readonly after: readonly string[];\n readonly queries: readonly WorldScheduleQueryData[];\n readonly resources: readonly string[];\n}\n\n/** JSON-safe system-set membership and ordering metadata. */\nexport interface WorldScheduleSetData {\n readonly name: string;\n readonly members: readonly string[];\n readonly before: readonly string[];\n readonly after: readonly string[];\n readonly chained: boolean;\n}\n\n/** JSON-safe projection of one explicit World schedule. */\nexport interface WorldScheduleData {\n readonly name: string;\n readonly systems: readonly WorldScheduleSystemData[];\n readonly systemSets: readonly WorldScheduleSetData[];\n readonly dependencies: readonly (readonly [string, string])[];\n}\n\n/**\n * Internal record describing where an entity lives.\n *\n * Liveness (feat-20260602 / plan-strategy D-4): the former `alive` boolean was\n * absorbed into `generation`. A despawn unconditionally bumps `generation` (so a\n * stale handle's `gen` no longer matches), and `gen > 255` retires the slot\n * permanently (it is never pushed back to `freeIndices`). The single liveness\n * predicate is therefore \"handle gen matches AND archetypeId !== -1\" -- see\n * `World.recordIsLive`. A deferred-spawn allocation is \"pending\" when\n * archetypeId === -1 (not yet materialized into an archetype row); no separate\n * boolean is needed.\n */\nexport interface EntityRecord {\n generation: number;\n archetypeId: number; // -1 if no archetype (pending / despawned)\n archetypeRow: number;\n}\n\n/**\n * The World owns:\n * - the registry of known component schemas;\n * - all archetypes (via ArchetypeGraph);\n * - the entity index table (records by index slot);\n * - the free-list of recyclable entity slots.\n */\nexport class World {\n /** Package-internal implementation seam; not exported from any entry point. */\n readonly [worldInternal]: WorldInternal;\n // ── Internal state ──\n\n /** The single package-private owner of storage, epochs, and change evidence. */\n private readonly core: WorldCore;\n get identity() {\n return this.core.identity;\n }\n /** Plugin-owned component discovery scoped to this World and removed through leases. */\n readonly components = new ComponentCatalog((component) => this.componentIsInUse(component));\n private executionState: WorldExecutionState;\n /** Monotonic clock advanced exactly once per successful mutation. */\n /** Monotonic revision for successful entity/component structure writes. */\n /** Last mutation epoch for each component id, used by component-owned projections. */\n /** Ordered, bounded evidence consumed by persistent engine-owned projections. */\n private get mutationEpoch() {\n return this.core.mutationEpoch;\n }\n private set mutationEpoch(value: number) {\n this.core.mutationEpoch = value;\n }\n private get structureEpoch() {\n return this.core.structureEpoch;\n }\n private set structureEpoch(value: number) {\n this.core.structureEpoch = value;\n }\n private get componentMutationEpochs() {\n return this.core.componentMutationEpochs;\n }\n /** Free index slots (LIFO stack). */\n private get records() {\n return this.core.records;\n }\n private get freeIndices() {\n return this.core.freeIndices;\n }\n /**\n * Relationship-sync reentry guard (feat-20260531 M2 / plan-strategy D-7).\n /** The archetype graph: manages all archetypes + edge caching. */\n private get graph(): ArchetypeGraph {\n return this.core.graph;\n }\n /** DAG schedules for the two built-in execution scopes. */\n private readonly schedules = new Map([\n [Update, createSchedule(Update)],\n [FixedUpdate, createSchedule(FixedUpdate)],\n ]);\n /** Resource store: typed key-value global singletons. */\n private readonly resources: ResourceStore = createResourceStore();\n private readonly clock: ReturnType<typeof createWorldClock>;\n /** Remainder carried between fixed-step runs. */\n private fixedAccumulator = 0;\n /**\n * ECS-managed handle store (M1). Owned by the World - constructed eagerly\n * so every spawn / despawn / set path can dispatch managed-ref releases\n * without caller-side wiring. AI users obtain `Handle<T,'unique'>` values\n * by accessing the store through internal channels (the surface is\n * private; managed-ref-bearing fields read through `world.get`).\n */\n // UniqueRefStore is type-erased at the storage layer (alloc/resolve are\n // method-generic over `T`); World holds the single per-instance store and\n // routes payload-agnostic release calls. Typed access flows through\n // `UniqueRefStore.resolve<T>` at the consumer layer.\n private get uniqueRefs(): UniqueRefStore {\n return this.core.uniqueRefs;\n }\n /**\n * Per-World `SharedRefStore` (feat-20260614 M3). Backs every `shared<T>`\n * schema field + the `world.allocSharedRef` facade. Public read-only so AI\n * users can `retain` / `release` / `resolve` user-tier handles directly off\n * the world (the surface is small enough that hiding it behind another\n * facade would be a phantom indirection - charter F1 single-entry\n * indexability).\n *\n * Final release publishes structured evidence; there is no callback surface.\n * M6 D-15: the store manages only user-tier slots\n * (`>= BUILTIN_BASE`); builtin handles are process-static in their\n * authoring package and never reference-counted.\n */\n get sharedRefs(): SharedRefStore {\n return this.core.sharedRefs;\n }\n /**\n * BufferPool backing every `buffer:<N>` schema-vocab field (M2). Eagerly\n * constructed (per-World, D-2). `spawn` allocs slots for buffer fields and\n * stores the slot id in the u32 column; `despawn` / `removeComponent`\n * release the slots; `set(e, C, { field: Uint8Array })` copies bytes into\n * the live view without re-allocating (schema-declared byteLength is\n * fixed in v1; runtime grow is reserved for the M4 carry-over path).\n */\n private get bufferPool() {\n return this.core.bufferPool;\n }\n private readonly componentAccess: WorldComponentAccess;\n\n constructor(options: WorldOptions = {}) {\n this.core = new WorldCore(options.storage === 'shared');\n this.executionState = healthyWorldExecutionState(this.identity);\n this.componentAccess = new WorldComponentAccess({\n graph: this.graph,\n records: this.records,\n freeIndices: this.freeIndices,\n bufferPool: this.bufferPool,\n uniqueRefs: this.uniqueRefs,\n sharedRefs: this.sharedRefs,\n relationshipIndexes: this.core.relationshipIndexes,\n markComponentAdded: (entity, component) => this.internalmarkComponentAdded(entity, component),\n markComponentsAdded: (entity, components) =>\n this.internalmarkComponentsAdded(entity, components),\n markComponentChanged: (entity, component) =>\n this.internalmarkComponentChanged(entity, component),\n markStructureChanged: () => this.internalmarkStructureChanged(),\n recordStructuralEvidence: (evidence) => this.internalrecordStructuralEvidence(evidence),\n routeError: (error, context) => this.internalrouteError(error as EcsError, context),\n });\n this.clock = createWorldClock({ ...DEFAULT_TIME_POLICY, ...options.time });\n this.resources.entries.set(TIME_RESOURCE_KEY, {\n value: this.clock.time,\n added: 0,\n changed: 0,\n });\n this.resources.entries.set(FIXED_TIME_RESOURCE_KEY, {\n value: this.clock.fixed,\n added: 0,\n changed: 0,\n });\n this[worldInternal] = {\n addComponentCore: this.internaladdComponentCore.bind(this),\n allocateIndex: this.internalallocateIndex.bind(this),\n allocatePendingEntity: this.internalallocatePendingEntity.bind(this),\n cancelPendingEntity: this.internalcancelPendingEntity.bind(this),\n despawnCore: this.internaldespawnCore.bind(this),\n getArrayView: this.internalgetArrayView.bind(this),\n getArrayLength: this.internalgetArrayLength.bind(this),\n getArrayElement: this.internalgetArrayElement.bind(this),\n getFieldValue: this.internalgetFieldValue.bind(this),\n getBufferPool: this.internalgetBufferPool.bind(this),\n getClockWriter: this.internalgetClockWriter.bind(this),\n getComponentChange: this.internalgetComponentChange.bind(this),\n getComponentMutationEpoch: this.internalgetComponentMutationEpoch.bind(this),\n getComponentMutationEpochs: this.internalgetComponentMutationEpochs.bind(this),\n getEntityArchetype: this.internalgetEntityArchetype.bind(this),\n getFixedAccumulator: this.internalgetFixedAccumulator.bind(this),\n getFreeIndices: this.internalgetFreeIndices.bind(this),\n getGraph: this.internalgetGraph.bind(this),\n getMutationEpoch: this.internalgetMutationEpoch.bind(this),\n getQueryRow: this.internalgetQueryRow.bind(this),\n getRecords: this.internalgetRecords.bind(this),\n getRelationshipEpoch: this.internalgetRelationshipEpoch.bind(this),\n getRelationshipTargetEntities: this.internalgetRelationshipTargetEntities.bind(this),\n getResources: this.internalgetResources.bind(this),\n getSchedule: this.internalgetSchedule.bind(this),\n getSchedules: this.internalgetSchedules.bind(this),\n getSharedRefs: this.internalgetSharedRefs.bind(this),\n getStructureEpoch: this.internalgetStructureEpoch.bind(this),\n getStructuralEvidence: this.internalgetStructuralEvidence.bind(this),\n getUniqueRefs: this.internalgetUniqueRefs.bind(this),\n lookupAlive: this.internallookupAlive.bind(this),\n markComponentAdded: this.internalmarkComponentAdded.bind(this),\n markComponentChanged: this.internalmarkComponentChanged.bind(this),\n markComponentRangeChanged: this.internalmarkComponentRangeChanged.bind(this),\n markComponentsAdded: this.internalmarkComponentsAdded.bind(this),\n markStructureChanged: this.internalmarkStructureChanged.bind(this),\n materializePendingEntity: this.internalmaterializePendingEntity.bind(this),\n nextMutationEpoch: this.internalnextMutationEpoch.bind(this),\n poisonExecution: this.internalpoisonExecution.bind(this),\n prepareRelationshipInsert: this.internalprepareRelationshipInsert.bind(this),\n publishDerivedRange: this.internalpublishDerivedRange.bind(this),\n preflightComponentData: this.internalpreflightComponentData.bind(this),\n readRow: this.internalreadRow.bind(this),\n recordStructuralEvidence: this.internalrecordStructuralEvidence.bind(this),\n recordIsLive: this.internalrecordIsLive.bind(this),\n relationshipOnInsert: this.internalrelationshipOnInsert.bind(this),\n relationshipOnRemove: this.internalrelationshipOnRemove.bind(this),\n releaseManagedRefsOnRow: this.internalreleaseManagedRefsOnRow.bind(this),\n releaseRelationshipPreparation: this.internalreleaseRelationshipPreparation.bind(this),\n removeComponentCore: this.internalremoveComponentCore.bind(this),\n routeError: this.internalrouteError.bind(this),\n restoreMutationEpoch: this.internalrestoreMutationEpoch.bind(this),\n setFixedAccumulator: this.internalsetFixedAccumulator.bind(this),\n setQueryRow: this.internalsetQueryRow.bind(this),\n spawnCore: this.internalspawnCore.bind(this),\n writeEntitySelf: this.internalwriteEntitySelf.bind(this),\n writeRow: this.internalwriteRow.bind(this),\n };\n }\n\n /** Immutable integrity state for execution coordinators and headless callers. */\n get execution(): WorldExecutionState {\n return this.executionState;\n }\n\n /** Resolve a schedule token owned by this World realm without package singleton identity. */\n scheduleToken(\n name: import('./schedule-token').ScheduleName,\n ): import('./schedule-token').ScheduleToken {\n if (name === 'Update') return Update;\n if (name === 'FixedUpdate') return FixedUpdate;\n return FixedUpdate;\n }\n\n /** SharedKernel is the only writer; application code recovers by constructing a new World. */\n private internalpoisonExecution(fault: WorldExecutionFault): void {\n if (this.executionState.health === 'healthy') {\n this.executionState = poisonedWorldExecutionState(this.identity, fault);\n }\n }\n\n query<\n const R extends readonly Component[] = readonly [],\n const W extends readonly Component[] = readonly [],\n const O extends readonly Component[] = readonly [],\n >(descriptor: QueryDescriptor<R, W, O>): Result<Query<R, W, O>, QueryCreationError> {\n return createQuery(this, descriptor);\n }\n\n // ──────────────────────────────────────────────────────────────────────────\n // Internal access — query engine\n // ──────────────────────────────────────────────────────────────────────────\n\n /** Expose archetype graph for query engine. Not part of public API. */\n private internalgetGraph(): ArchetypeGraph {\n return this.graph;\n }\n\n private componentIsInUse(component: Component): boolean {\n if (\n this.graph.archetypes.some(\n (archetype) =>\n archetype.size > 0 && archetype.components.some((candidate) => candidate === component),\n )\n ) {\n return true;\n }\n return worldScheduleUsesComponent(this, component);\n }\n\n /** Current upper bound for mutation observation. */\n private internalgetMutationEpoch(): number {\n return this.mutationEpoch;\n }\n\n /** Structure snapshot used to invalidate borrowed query facades. */\n private internalgetStructureEpoch(): number {\n return this.structureEpoch;\n }\n\n /** Typed structural facts are produced by this World and consumed by projections. */\n private internalgetStructuralEvidence(): StructuralEvidenceRing {\n return this.core.structuralEvidence;\n }\n\n private internalrecordStructuralEvidence(evidence: StructuralEvidenceInput): void {\n this.core.structuralEvidence.append(evidence);\n }\n\n /** Resolve current logical identity for a packed entity handle. */\n private internalgetEntityArchetype(entity: EntityHandle): Archetype | undefined {\n const record = this.records[entityIndex(entity)];\n if (!this.internalrecordIsLive(record, entityGeneration(entity))) return undefined;\n return this.graph.archetypes[record.archetypeId];\n }\n\n /** Component change state for query filters. */\n private internalgetComponentChange(\n entity: EntityHandle,\n componentId: number,\n ): ChangeTicks | undefined {\n const record = this.records[entityIndex(entity)];\n if (!this.internalrecordIsLive(record, entityGeneration(entity))) return undefined;\n return readComponentChange(this.graph, record, entity, componentId);\n }\n\n /** Allocate one epoch after a mutation has succeeded. */\n private internalnextMutationEpoch(): number {\n if (this.mutationEpoch >= Number.MAX_SAFE_INTEGER) {\n throw new ChangeEpochExhaustedError(this.mutationEpoch);\n }\n this.mutationEpoch += 1;\n return this.mutationEpoch;\n }\n\n private internalrestoreMutationEpoch(epoch: number): void {\n this.mutationEpoch = epoch;\n }\n\n private internalpublishDerivedRange(\n table: ArchetypeGraph['tables'][number],\n componentId: number,\n rowStart: number,\n rowCount: number,\n epoch: number,\n ): void {\n const epochs = table.storage.get(componentId)?.epochs;\n if (epochs === undefined) {\n throw new Error(`Derived component ${componentId} is not in the table.`);\n }\n epochs.changed.fill(epoch, rowStart, rowStart + rowCount);\n this.componentMutationEpochs[componentId] = epoch;\n }\n\n /** Record one successful structural mutation. */\n private internalmarkStructureChanged(): void {\n this.structureEpoch += 1;\n }\n\n /** Current structural revision for mounted World projections. */\n getStructureEpoch(): number {\n return this.structureEpoch;\n }\n\n /** Mark a component as both added and changed at the current tick. */\n private internalmarkComponentAdded(entity: EntityHandle, componentId: number): void {\n this.internalmarkComponentsAdded(entity, [componentId]);\n }\n\n /** Mark one mutation's component instances with a shared epoch. */\n private internalmarkComponentsAdded(entity: EntityHandle, componentIds: readonly number[]): void {\n const record = this.records[entityIndex(entity)];\n if (!this.internalrecordIsLive(record, entityGeneration(entity))) return;\n const epoch = this.internalnextMutationEpoch();\n markComponentsAdded(this.graph, record, entity, componentIds, epoch);\n for (const componentId of componentIds) {\n this.componentMutationEpochs[componentId] = epoch;\n }\n }\n\n /** Mark an existing component as changed at the current tick. */\n private internalmarkComponentChanged(entity: EntityHandle, componentId: number): void {\n const record = this.records[entityIndex(entity)];\n if (!this.internalrecordIsLive(record, entityGeneration(entity))) return;\n let epoch: number | undefined;\n markComponentChanged(this.graph, record, entity, componentId, () => {\n epoch = this.internalnextMutationEpoch();\n return epoch;\n });\n if (epoch !== undefined) {\n this.componentMutationEpochs[componentId] = epoch;\n }\n }\n\n /** Mark one contiguous component range with a single epoch. */\n private internalmarkComponentRangeChanged(\n table: ArchetypeGraph['tables'][number],\n componentId: number,\n rowStart: number,\n rowCount: number,\n ): void {\n const epochs = table.storage.get(componentId)?.epochs;\n if (epochs === undefined || rowCount === 0) return;\n const epoch = this.internalnextMutationEpoch();\n epochs.changed.fill(epoch, rowStart, rowStart + rowCount);\n this.componentMutationEpochs[componentId] = epoch;\n }\n\n /** Latest mutation token for one component-owned projection. */\n private internalgetComponentMutationEpoch(componentId: number): number {\n return this.componentMutationEpochs[componentId] ?? 0;\n }\n\n /** Borrow the component-version summary used to skip unrelated value columns. */\n private internalgetComponentMutationEpochs(): readonly number[] {\n return this.componentMutationEpochs;\n }\n\n /** Read a materialized relationship target in O(1 + k). */\n private internalgetRelationshipTargetEntities(\n source: Component,\n target: EntityHandle,\n ): readonly EntityHandle[] {\n return this.componentAccess.relationshipTargetEntries(source, target);\n }\n\n /** Monotonic epoch for the materialized relationship index. */\n private internalgetRelationshipEpoch(source: Component): number {\n return this.core.relationshipIndexes.get(componentId(source))?.epoch ?? 0;\n }\n\n /** Query facade write after the facade has already marked evidence. */\n private internalsetQueryRow(\n entity: EntityHandle,\n component: Component,\n value: Record<string, unknown>,\n ): Result<void, EcsError> {\n return this.componentAccess.set(\n entity,\n component,\n value as never,\n relationshipRole(component)?.kind === 'source',\n );\n }\n\n /** Query facade read that does not re-enter the public World API. */\n private internalgetQueryRow(\n entity: EntityHandle,\n component: Component,\n ): Result<Record<string, unknown>, EcsError> {\n return this.componentAccess.get(entity, component) as Result<Record<string, unknown>, EcsError>;\n }\n\n /** Return resource change ticks for diagnostics and resource-driven systems. */\n getResourceChange(name: string): ChangeTicks | undefined {\n const entry = this.resources.entries.get(name);\n return entry === undefined ? undefined : { added: entry.added, changed: entry.changed };\n }\n\n /**\n * Route a structured error from\n * an engine-internal subsystem (e.g. RenderSystem extract stage, w15).\n *\n * Mirrors the private `errorHandler(err, ctx)` call sites inside `World`\n * itself; the dedicated accessor avoids exposing `errorHandler` directly\n * and keeps the routing contract under the `_xxx` `@internal` umbrella so\n * AI users do not discover it through IDE autocomplete on `World`.\n *\n * Not part of the public API.\n */\n private internalrouteError(err: EcsError, ctx?: { readonly systemName: string }): void {\n // Internal expected failures are reported without becoming a second\n // schedule or terminal hook. The host owns fatal frame policy.\n console.error(`[${ctx?.systemName ?? 'World'}]`, err);\n }\n\n // ──────────────────────────────────────────────────────────────────────────\n // accessors — M1 extraction seam\n // ──────────────────────────────────────────────────────────────────────────\n\n /** */ private internalgetRecords(): EntityRecord[] {\n return this.records;\n }\n /** */ private internalgetFreeIndices(): number[] {\n return this.freeIndices;\n }\n /** */ private internalgetResources(): ResourceStore {\n return this.resources;\n }\n /** */ private internalgetFixedAccumulator(): number {\n return this.fixedAccumulator;\n }\n /** */ private internalsetFixedAccumulator(value: number): void {\n this.fixedAccumulator = value;\n }\n /** */ private internalgetUniqueRefs(): UniqueRefStore {\n return this.uniqueRefs;\n }\n /** */ private internalgetBufferPool(): BufferPool {\n return this.bufferPool;\n }\n /** Scheduler-owned mutable clock capability. */\n private internalgetClockWriter(): ClockWriter {\n return this.clock.writer;\n }\n /** */ private internalgetSchedule(\n token: import('./schedule-token').ScheduleToken,\n ): Schedule | undefined {\n return this.schedules.get(token);\n }\n /** */ private internalgetSchedules(): ReadonlyMap<\n import('./schedule-token').ScheduleToken,\n Schedule\n > {\n return this.schedules;\n }\n /** */ private internalgetSharedRefs(): SharedRefStore {\n return this.sharedRefs;\n }\n\n // ──────────────────────────────────────────────────────────────────────────\n // System registration + update (M3)\n // ──────────────────────────────────────────────────────────────────────────\n\n /**\n * Register a system with query descriptor and optional ordering constraints.\n *\n * `const Qs` mirrors the free `addSystem` signature so the call-site\n * `queries` tuple is locked literal-form, letting `descriptor.fn`'s first\n * parameter recover per-query row access shapes (S-5, KD-3 — class method\n * generic, not free function double track).\n *\n * @example\n * ```ts\n * const Position = defineComponent('Position', { x: 'f32', y: 'f32' });\n * const world = new World();\n * world.addSystem(Update, {\n * name: 'read-pos',\n * queries: [{ with: [Position] }],\n * fn: (world, queries) => { void world; for (const row of queries[0]) { void row.entity; } },\n * });\n * ```\n */\n addSystem<const Qs extends ReadonlyArray<QueryDescriptor>>(\n schedule: import('./schedule-token').ScheduleToken,\n descriptor: SystemDescriptor<Qs>,\n ): Result<void, ScheduleScopeMismatchError> {\n return worldAddSystem(this, schedule, descriptor);\n }\n\n /**\n * Remove a registered system by name (M2 — plan-strategy D-3).\n *\n * Returns `Result<void, ScheduleMutationError>`:\n * - ok branch: the slot is dropped and the schedule will rebuild on the\n * next `update()`.\n * - err branch with `.code === 'system-before-unknown'`: no system carries\n * this name; `.detail.candidates` lists the registered names.\n *\n * Designed to support `@forgeax/engine-remote`'s typed `injectSystem` /\n * `removeSystem` channel and the WS-disconnect reverse-remove path.\n *\n * @example\n * ```ts\n * const r = world.removeSystem(Update, 'movement');\n * if (!r.ok) console.error(r.error.code, r.error.detail.candidates);\n * ```\n */\n removeSystem(\n schedule: import('./schedule-token').ScheduleToken,\n name: string,\n ): Result<void, ScheduleMutationError | ScheduleScopeMismatchError> {\n return worldRemoveSystem(this, schedule, name);\n }\n\n /**\n * Replace a registered system in-place (M2 — plan-strategy D-3 atomic semantics).\n *\n * Overwrites the descriptor stored under `name` while preserving the\n * registration slot — `before / after` references that target this name\n * remain bound.\n *\n * Returns `Result<void, ScheduleMutationError>`:\n * - ok branch: descriptor swapped, schedule marked dirty.\n * - err branch with `.code === 'system-before-unknown'`: no system carries\n * this name; use `addSystem(descriptor)` to register a new one instead.\n *\n * @example\n * ```ts\n * const r = world.replaceSystem(Update, 'movement', {\n * name: 'movement',\n * queries: [{ with: [Position] }],\n * fn: (world, queryResults) => { ... },\n * });\n * ```\n */\n replaceSystem<const Qs extends ReadonlyArray<QueryDescriptor>>(\n schedule: import('./schedule-token').ScheduleToken,\n name: string,\n descriptor: SystemDescriptor<Qs>,\n ): Result<void, ScheduleMutationError | ScheduleScopeMismatchError> {\n return worldReplaceSystem(this, schedule, name, descriptor);\n }\n\n /**\n * Batch-register systems to a set. Validates the set token before writing.\n *\n * - First call for a system name: registers it via the existing `addSystem` path.\n * - Subsequent calls: only adds the system name to the set's members (dedup).\n *\n * Returns `Result.err` with `SystemSetNotRegisteredError` if the set token\n * fails identity validation.\n *\n * @example\n * ```ts\n * const GameplaySet = defineSystemSet({ name: 'gameplay' });\n * const world = new World();\n * const r = world.addSystems(Update, GameplaySet, [movement, collision]);\n * if (!r.ok) console.error(r.error.code, r.error.hint);\n * ```\n */\n addSystems<const Qs extends ReadonlyArray<QueryDescriptor>>(\n schedule: import('./schedule-token').ScheduleToken,\n set: SystemSet,\n systems: ReadonlyArray<SystemDescriptor<Qs>>,\n ): Result<void, SystemSetNotRegisteredError | ScheduleScopeMismatchError> {\n return worldAddSystems(this, schedule, set, systems);\n }\n\n /**\n * Execute one frame: run all systems in DAG order, then flush deferred commands.\n * Empty world (no systems) completes silently (E-09).\n *\n * @example\n * ```ts\n * const Position = defineComponent('Position', { x: 'f32', y: 'f32' });\n * const world = new World();\n * world.spawn({ component: Position, data: { x: 0, y: 0 } }).unwrap();\n * world.update(); // run all systems + flush commands\n * ```\n */\n update(\n deltaSeconds = 0,\n ): Result<\n void,\n | TimeDeltaInvalidError\n | TimeConfigInvalidError\n | ScheduleScopeMismatchError\n | WorldPoisonedError\n | CommandFailedError\n | SystemFailedError\n | import('./errors').CyclicDependencyError\n | SharedKernelFailureError\n > {\n return worldUpdate(this, deltaSeconds);\n }\n\n // ──────────────────────────────────────────────────────────────────────────\n // Resource CRUD (M3)\n // ──────────────────────────────────────────────────────────────────────────\n\n /** Insert or overwrite a resource (idempotent, E-13). */\n insertResource<T>(key: string | { readonly name: string }, value: T): void {\n worldInsertResource(this, key, value);\n }\n\n /**\n * Get a resource by key.\n * @throws ResourceNotFoundError if key not found (E-14).\n */\n getResource(key: typeof import('./time').Time): import('./time').TimeResource;\n getResource(key: typeof import('./time').FixedTime): import('./time').FixedTimeResource;\n getResource<T>(key: string | { readonly name: string }): T;\n getResource<T>(key: string | { readonly name: string }): T {\n return worldGetResource<T>(this, key);\n }\n\n /** Check if a resource exists. */\n hasResource(key: string | { readonly name: string }): boolean {\n return worldHasResource(this, key);\n }\n\n /** Remove a resource by key. */\n removeResource(key: string | { readonly name: string }): void {\n worldRemoveResource(this, key);\n }\n\n // ──────────────────────────────────────────────────────────────────────────\n // Inspection / diagnostics (M4)\n // ──────────────────────────────────────────────────────────────────────────\n\n /**\n * Return a typed diagnostic snapshot of the World state.\n * All fields are non-undefined. Useful for AI users to programmatically\n * introspect entity count, archetypes, registered components, systems,\n * and resources without console.log or a debugger.\n *\n * @example\n * ```ts\n * const Position = defineComponent('Position', { x: 'f32', y: 'f32' });\n * const world = new World();\n * world.spawn({ component: Position, data: { x: 0, y: 0 } }).unwrap();\n * const snap = world.inspect();\n * console.log(snap.entityCount, snap.activeComponents);\n * ```\n */\n inspect(): WorldInspection {\n return detachWorldInspection(worldInspect(this));\n }\n\n /** Return the registered schedule graphs and their declared access metadata. */\n scheduleData(): ReadonlyArray<WorldScheduleData> {\n return worldScheduleData(this);\n }\n\n // ──────────────────────────────────────────────────────────────────────────\n // Managed-ref public API (feat-20260528-rapier-physics M1 / t4)\n // ──────────────────────────────────────────────────────────────────────────\n\n /**\n * Allocate a standalone managed reference handle with an optional release\n * callback. Returns a branded {@link Handle}<Target, 'unique'> that can be\n * stored in schema-vocab `ref<T>` fields or resolved through\n * {@link UniqueRefStore.resolve} (via `world.get` on a component with\n * `ref<T>` fields).\n *\n * When the handle is released (despawn / removeComponent / set-overwrite),\n * the `onRelease` callback fires with the payload (captured on the stack);\n * by then the slot's bookkeeping (callback table, payload map, freelist) is\n * already cleared, so a *throwing* `onRelease` re-propagates from the first\n * `release` call without leaving the store inconsistent — a second `release`\n * of the same handle returns `UniqueRefDoubleReleaseError` as expected. RAII\n * cleanup semantics preserved (plan-strategy D-5; throw-safety AC-01/02).\n *\n * Handles are *operational, not persistent*: caching them across release\n * boundaries (despawn / removeComponent / set-overwrite) is undefined\n * behavior — the same `u32` may silently resolve to a freshly allocated\n * payload after slot reuse. See `packages/ecs/README.md` § \"Managed handles\n * are operational, not persistent\" and `docs/specs/2026-06-14-ecs-managed-\n * lifecycle-ssot-design.md` § 3.3.\n *\n * @typeParam Target - phantom string branding the handle (type-level only).\n * @typeParam T - the payload type stored alongside the handle.\n * @param target - phantom target string (type-level discriminant).\n * @param payload - the value to store. Identity-stable until release.\n * @param onRelease - optional cleanup hook called with the payload on release.\n * @returns a branded `Handle<Target, 'unique'>` u32.\n *\n * @example\n * ```ts\n * const world = new World();\n * const handle = world.allocUniqueRef<'PhysicsBody', RigidBodyHandle>(\n * 'PhysicsBody',\n * rapierHandle,\n * (h) => rapierWorld.removeRigidBody(h),\n * );\n * const Holder = defineComponent('Holder', { body: 'unique<PhysicsBody>' });\n * world.spawn(Holder, { body: handle });\n * // Despawn triggers onRelease -> Rapier body is cleaned up.\n * ```\n */\n allocUniqueRef<Target extends string, T>(\n target: Target,\n payload: T,\n onRelease?: (payload: T) => void,\n ): Handle<Target, 'unique'> {\n return worldAllocUniqueRef(this, target, payload, onRelease);\n }\n\n /**\n * Allocate a shared (refcount-tracked) handle through the per-World\n * {@link SharedRefStore}. Returns a `Handle<Target, 'shared'>` u32 with\n * rc=1 (the alloc-grant). Consumers retain/release via `world.sharedRefs`.\n *\n * Final release publishes structured evidence through the owning\n * {@link SharedRefStore}; payload disposal remains with the\n * renderer/assets/plugin owner and is not a user callback.\n *\n * Intended for asset-registry-style producers — anything whose lifecycle\n * is shared across multiple holders (ECS components + external systems).\n * The single-holder one-shot release pattern stays on\n * {@link World.allocUniqueRef} (`Handle<T, 'unique'>`).\n *\n * @typeParam Target - phantom string branding the handle (type-level only).\n * @typeParam T - the payload type stored alongside the handle.\n * @param target - phantom target string (type-level discriminant).\n * @param payload - the value to store. Identity-stable until final release.\n * @returns a branded `Handle<Target, 'shared'>` u32 with rc=1.\n *\n * @example\n * ```ts\n * const world = new World();\n * const handle = world.allocSharedRef<'MaterialAsset', MaterialPayload>(\n * 'MaterialAsset',\n * payload,\n * );\n * const M = defineComponent('M', { asset: 'shared<MaterialAsset>' });\n * world.spawn({ component: M, data: { asset: handle } });\n * // The write-barrier dispatch retains/releases automatically on spawn / despawn.\n * ```\n */\n allocSharedRef<Target extends string, T>(target: Target, payload: T): Handle<Target, 'shared'> {\n return worldAllocSharedRef(this, target, payload);\n }\n\n /**\n * Return one producer-owned shared handle per `(target, payload object)` in\n * this World. Repeated discovery does not retain; ECS holders still retain\n * and release through the normal write barrier. Asset catalogues use this\n * when repeated scene instantiation resolves the same catalogued payload.\n * Use {@link World.allocSharedRef} for independent resources or deleters.\n */\n internSharedRef<Target extends string, T extends object>(\n target: Target,\n payload: T,\n ): Handle<Target, 'shared'> {\n return worldInternSharedRef(this, target, payload);\n }\n\n // ──────────────────────────────────────────────────────────────────────────\n // Component access facade — storage ownership is world-component-access.\n // ──────────────────────────────────────────────────────────────────────────\n\n private relationshipTargetWriteError(\n component: Component,\n operation: string,\n ): Result<never, EcsError> {\n return err(new RelationshipTargetReadonlyError(component.name, operation));\n }\n\n private relationshipTargetPayloadWrites(data: Readonly<Record<string, unknown>>): boolean {\n return Object.values(data).some((value) => {\n if (Array.isArray(value)) return value.length > 0;\n if (ArrayBuffer.isView(value)) return value.byteLength > 0;\n return true;\n });\n }\n\n get<S extends ComponentSchema>(\n entity: EntityHandle,\n component: Component<string, S>,\n ): Result<ShapeOf<S>, EcsError> {\n return this.componentAccess.get(entity, component);\n }\n\n /**\n * Test live component presence without constructing a Result error.\n *\n * Read projections commonly need to branch on optional components for many\n * entities. Calling `get` for that branch allocates a structured\n * ComponentNotPresentError on every ordinary miss (and StaleEntityError for\n * a dangling handle). This predicate is deliberately non-throwing and\n * returns false for both cases; callers that need the detailed error should\n * continue to use `get`.\n */\n hasComponent(entity: EntityHandle, component: Component): boolean {\n const archetype = this.internalgetEntityArchetype(entity);\n return (\n archetype?.components.some(\n (candidate) => componentId(candidate) === componentId(component),\n ) === true\n );\n }\n\n private internalgetArrayView(\n entity: EntityHandle,\n component: Component,\n fieldName: string,\n ): ArrayLike<number> | undefined {\n return this.componentAccess._getArrayView(entity, component, fieldName);\n }\n\n private internalgetArrayLength(\n entity: EntityHandle,\n component: Component,\n fieldName: string,\n ): number | undefined {\n return this.componentAccess._getArrayLength(entity, component, fieldName);\n }\n\n private internalgetArrayElement(\n entity: EntityHandle,\n component: Component,\n fieldName: string,\n index: number,\n ): number | undefined {\n return this.componentAccess._getArrayElement(entity, component, fieldName, index);\n }\n\n private internalgetFieldValue(\n entity: EntityHandle,\n component: Component,\n fieldName: string,\n ): number | undefined {\n return this.componentAccess._getFieldValue(entity, component, fieldName);\n }\n\n set<S extends ComponentSchema, C extends Component<string, S>>(\n entity: EntityHandle,\n component: C & WritableComponent<C>,\n value: Partial<InputShapeOf<S>>,\n ): Result<void, EcsError> {\n if (isRelationshipTarget(component)) return this.relationshipTargetWriteError(component, 'set');\n return this.componentAccess.set(entity, component, value);\n }\n\n addComponent<S extends ComponentSchema, C extends Component<string, S>>(\n entity: EntityHandle,\n componentData: ComponentData<S> & { component: C & WritableComponent<C> },\n ): Result<void, EcsError> {\n if (\n isRelationshipTarget(componentData.component) &&\n this.relationshipTargetPayloadWrites(componentData.data as Record<string, unknown>)\n )\n return this.relationshipTargetWriteError(componentData.component, 'addComponent');\n return this.componentAccess.addComponent(entity, componentData);\n }\n\n private internaladdComponentCore<S extends ComponentSchema>(\n entity: EntityHandle,\n componentData: ComponentData<S>,\n internal: boolean,\n ): Result<void, EcsError> {\n return this.componentAccess._addComponentCore(entity, componentData, internal);\n }\n\n removeComponent<S extends ComponentSchema, C extends Component<string, S>>(\n entity: EntityHandle,\n component: C & WritableComponent<C>,\n ): Result<void, EcsError> {\n if (isRelationshipTarget(component))\n return this.relationshipTargetWriteError(component, 'removeComponent');\n return this.componentAccess.removeComponent(entity, component);\n }\n\n private internalremoveComponentCore<S extends ComponentSchema>(\n entity: EntityHandle,\n component: Component<string, S>,\n internal: boolean,\n ): Result<void, EcsError> {\n return this.componentAccess._removeComponentCore(entity, component, internal);\n }\n\n private internalallocatePendingEntity(): EntityHandle {\n return this.componentAccess._allocatePendingEntity();\n }\n /** */ private internalcancelPendingEntity(entity: EntityHandle): void {\n this.componentAccess._cancelPendingEntity(entity);\n }\n\n private internalmaterializePendingEntity(\n entity: EntityHandle,\n componentDatas: ComponentData[],\n ): Result<void, EcsError> {\n return this.componentAccess._materializePendingEntity(entity, componentDatas);\n }\n\n /** Shared structural preflight for direct and deferred writes. */\n private internalpreflightComponentData(\n holder: EntityHandle | null,\n componentData: ComponentData,\n pendingEntities?: ReadonlySet<number>,\n unavailableEntities?: ReadonlySet<number>,\n ): Result<void, EcsError> {\n return this.componentAccess.preflightComponentData(\n holder,\n componentData,\n pendingEntities,\n unavailableEntities,\n );\n }\n\n /** */ private internalallocateIndex(): number {\n return this.componentAccess.allocateIndex();\n }\n /** */ private internalrecordIsLive(r: EntityRecord | undefined, g: number): r is EntityRecord {\n return this.componentAccess.recordIsLive(r, g);\n }\n /** */ private internallookupAlive(\n e: EntityHandle,\n op: string,\n c?: string,\n ): Result<EntityRecord, EcsError> {\n return this.componentAccess.lookupAlive(e, op, c);\n }\n /** */ private internalreadRow<S extends ComponentSchema>(\n a: Archetype,\n c: Component<string, S>,\n r: number,\n ): ShapeOf<S> {\n return this.componentAccess.readRow(a, c, r);\n }\n /** */ private internalwriteEntitySelf(a: Archetype, r: number, h: EntityHandle): void {\n this.componentAccess.writeEntitySelf(a, r, h);\n }\n /** */ private internalwriteRow<S extends ComponentSchema>(\n a: Archetype,\n c: Component<string, S>,\n r: number,\n v: ShapeOf<S>,\n ): void {\n this.componentAccess.writeRow(a, c, r, v);\n }\n /** */ private internalreleaseManagedRefsOnRow(a: Archetype, c: Component, r: number): void {\n this.componentAccess.releaseManagedRefsOnRow(a, c, r);\n }\n /** */ private internalrelationshipOnInsert(\n h: EntityHandle,\n c: Component,\n v: Record<string, unknown>,\n preparation?: unknown,\n ): Result<void, EcsError> {\n return this.componentAccess.relationshipOnInsert(h, c, v, preparation as never);\n }\n /** */ private internalprepareRelationshipInsert(\n c: Component,\n v: Record<string, unknown>,\n ): Result<unknown, EcsError> {\n return this.componentAccess.prepareRelationshipInsert(c, v);\n }\n /** */ private internalreleaseRelationshipPreparation(preparation: unknown): void {\n this.componentAccess.releaseRelationshipPreparation(preparation as never);\n }\n /** */ private internalrelationshipOnRemove(\n h: EntityHandle,\n c: Component,\n v: Record<string, unknown>,\n ): Result<void, EcsError> {\n return this.componentAccess.relationshipOnRemove(h, c, v);\n }\n\n // ──────────────────────────────────────────────────────────────────────────\n // Spawn\n // ──────────────────────────────────────────────────────────────────────────\n\n /**\n * Spawn an entity with one or more components.\n * Multi-component spawn directly targets the correct archetype (AC-06).\n *\n * @returns `Result<Entity, EcsError>` — `ok(Entity)` on success.\n * EntityIndexOverflowError still throws (build-time / infrastructure failure).\n *\n * @example\n * ```ts\n * const Position = defineComponent('Position', { x: 'f32', y: 'f32' });\n * const world = new World();\n * const r = world.spawn({ component: Position, data: { x: 0, y: 0 } });\n * if (!r.ok) { console.error(r.error.code); return; }\n * const entity = r.value;\n * ```\n */\n spawn<const SArr extends readonly ComponentSchema[]>(\n ...componentDatas: {\n [K in keyof SArr]: {\n component: Component<string, SArr[K]>;\n data: Partial<InputShapeOf<SArr[K]>>;\n };\n }\n ): Result<EntityHandle, EcsError>;\n spawn(...componentDatas: ComponentData[]): Result<EntityHandle, EcsError> {\n const target = componentDatas.find(\n (data) =>\n isRelationshipTarget(data.component) &&\n this.relationshipTargetPayloadWrites(data.data as Record<string, unknown>),\n );\n if (target !== undefined) return this.relationshipTargetWriteError(target.component, 'spawn');\n return spawnCore(this, componentDatas, false);\n }\n\n /**\n * Core implementation of `spawn` with reentry guard.\n *\n * @param internal — `true` when called from relationship maintenance\n * (lazy mirror create or exclusive reparent).\n */\n private internalspawnCore(\n componentDatas: ComponentData[],\n internal: boolean,\n ): Result<EntityHandle, EcsError> {\n return spawnCore(this, componentDatas, internal);\n }\n\n // ──────────────────────────────────────────────────────────────────────────\n // Despawn (D-08: generation retirement)\n // ──────────────────────────────────────────────────────────────────────────\n\n /**\n * Despawn an entity. Stale handles are silently ignored (E-01, AC-17).\n * Generation retirement: gen=255 → index permanently retired (D-08/E-08).\n *\n * @returns `Result<void, EcsError>` — `ok(void)` always (idempotent on stale handles).\n *\n * @example\n * ```ts\n * const Position = defineComponent('Position', { x: 'f32', y: 'f32' });\n * const world = new World();\n * const e = world.spawn({ component: Position, data: { x: 0, y: 0 } }).unwrap();\n * const r = world.despawn(e);\n * r.unwrap(); // idempotent: ok(void) even on stale handle\n * ```\n */\n despawn(entity: EntityHandle): Result<void, EcsError> {\n return despawnCore(this, entity, false);\n }\n\n /** Despawn every live entity through the normal lifecycle and ref cleanup path. */\n despawnAll(): Result<void, EcsError> {\n const entities: EntityHandle[] = [];\n for (let index = 0; index < this.records.length; index += 1) {\n const record = this.records[index];\n if (record !== undefined && record.archetypeId >= 0) {\n entities.push(encodeEntity(index, record.generation));\n }\n }\n for (const entity of entities) {\n const result = this.despawn(entity);\n if (!result.ok) return result;\n }\n return ok(undefined);\n }\n\n /**\n * Core implementation of `despawn` with reentry guard.\n *\n * @param internal — `true` when called from within linkedSpawn cascade.\n * Nested despawn skips relationship pruning after the parent is retired;\n * the linkedSpawn collection still walks the subtree so grandchildren\n * cascade correctly (tweak-20260714 M2, R-6).\n */\n private internaldespawnCore(entity: EntityHandle, internal: boolean): Result<void, EcsError> {\n return despawnCore(this, entity, internal);\n }\n\n // ──────────────────────────────────────────────────────────────────────────\n // Hierarchy facade — lifecycle orchestration lives in world-entity-lifecycle.\n // Component storage still owns typed relationship mutation primitives.\n // ──────────────────────────────────────────────────────────────────────────\n\n addChild<S extends ComponentSchema>(\n parent: EntityHandle,\n child: EntityHandle,\n component: Component<string, S>,\n data: Partial<InputShapeOf<S>>,\n ): Result<void, EcsError> {\n return worldAddChild(this, parent, child, component, data);\n }\n\n removeChild<S extends ComponentSchema>(\n parent: EntityHandle,\n child: EntityHandle,\n component: Component<string, S>,\n ): Result<void, EcsError> {\n return worldRemoveChild(this, parent, child, component);\n }\n\n reparent<S extends ComponentSchema>(\n child: EntityHandle,\n newParent: EntityHandle,\n component: Component<string, S>,\n data: Partial<InputShapeOf<S>>,\n ): Result<void, EcsError> {\n return worldReparent(this, child, newParent, component, data);\n }\n\n iterAncestors(entity: EntityHandle): Iterable<EntityHandle> {\n return worldIterAncestors(this, entity);\n }\n\n iterDescendants(entity: EntityHandle): Iterable<EntityHandle> {\n return worldIterDescendants(this, entity);\n }\n}\n\n/** Freeze the detached POD produced by World.inspect(). */\nfunction detachWorldInspection<T extends object>(snapshot: T): Readonly<T> {\n return freezeInspection(snapshot);\n}\n\nfunction freezeInspection<T>(value: T): Readonly<T> {\n if (value === null || (typeof value !== 'object' && typeof value !== 'function')) {\n return value as Readonly<T>;\n }\n for (const key of Reflect.ownKeys(value as object)) {\n const child = (value as Record<PropertyKey, unknown>)[key];\n if (child !== null && (typeof child === 'object' || typeof child === 'function')) {\n freezeInspection(child);\n }\n }\n return Object.freeze(value) as Readonly<T>;\n}\n","/**\n * @module @forgeax/engine-ecs\n *\n * Archetype ECS with Result-based mutation errors and poisoned-frame recovery:\n *\n * 1. **Layer 1 (World methods)** — every mutation (`get`/`set`/`spawn`/`despawn`/\n * `addComponent`/`removeComponent`) returns `Result<T, EcsError>`.\n * Use `.unwrap()` for quick-and-dirty or `if (!r.ok) ... r.error ...` for programmatic branching.\n *\n *\n * AI users: import types from this module — `.d.ts` signatures expose\n * `Result<T, EcsError>` on all World methods, making error paths discoverable\n * without reading source. Switch on `.code` for programmatic error branching.\n *\n * **Warning — Result propagation in system bodies**: TypeScript lacks Rust's `?`\n * operator. Handle every Result branch explicitly or return the failure from\n * the system so the frame poison boundary can stop the host.\n */\n\n// Layered exports: core API first (World / defineComponent / Entity / Query),\n// then Result + error types, then advanced API (Schedule / CommandBuffer),\n// then errors, then constants. AI users reading .d.ts see high-frequency\n// APIs at the top of the file (charter V1 proposition 1).\n\n// ────────────────────────────────────────────────────────────────────────────\n// Result type — the return type of all World mutation methods\n// ────────────────────────────────────────────────────────────────────────────\n\n/**\n * Discriminated union result type: `ResultOk<T>` or `ResultErr<E>`.\n * All World mutation methods return `Result<T, EcsError>`. The discriminant\n * is `.ok: boolean`; the success branch carries `.value: T`, the failure\n * branch carries `.error: E`. Method chain: `.unwrap()` / `.unwrapOr(d)`.\n *\n * @example\n * ```ts\n * // Plain field-access idiom (charter proposition 5 consistent abstraction):\n * const r = world.get(entity, Position);\n * if (!r.ok) { console.error(r.error.code, r.error.hint); return; }\n * const data = r.value; // ShapeOf<S>\n *\n * // Method-chain idiom (`.unwrap()` throws the original EcsError on err):\n * const data2 = world.get(entity, Position).unwrap();\n *\n * // Defaulted-fallback idiom (charter proposition 4 explicit-failure\n * // boundary — `unwrapOr` silently drops the error):\n * const data3 = world.get(entity, Position).unwrapOr({ x: 0, y: 0 });\n * ```\n */\n\nimport { isComponentDefinitionOrderValid } from './component';\n// ────────────────────────────────────────────────────────────────────────────\n// Essential-id forced registration (feat-20260602 M1 / w1; plan-strategy\n// D-1 / D-6b; feat-20260611 D-9 SSOT switch to ESSENTIAL_COMPONENT_IDS).\n//\n// The `Entity` component MUST be the first `defineComponent` evaluated in the\n// process so the owner identity assigns it id=0. ESM\n// evaluates import bindings in source order before any other statement, so this\n// import -- placed textually first among the barrel's module imports -- forces\n// `entity.ts` (and thus `defineComponent('Entity', ...)`) to run ahead of\n// every downstream component module. The fail-fast assertion below converts\n// an import-order regression from a silent runtime mis-id into a structured\n// startup throw (charter P3).\n//\n// The assertion reads `ESSENTIAL_COMPONENT_IDS` (the SSOT for which ids must\n// be present and where) rather than hard-coding a token property so adding a\n// future essential component requires updating exactly one place.\n//\n// `Entity` is re-exported from the barrel as a value (the id=0 component\n// token). The matching type-space handle type is `EntityHandle`, re-exported\n// from `./entity-handle` -- the two no longer share a name (feat-20260611 I-1;\n// renamed from `./entity` to `./entity-handle` in tweak-20260611-M3 to make\n// the file's role explicit; tweak-20260612 then lifted the Entity component\n// from the historical `components/entity.ts` back into `./entity` since that\n// slot was free).\nimport { Disabled, Entity, ESSENTIAL_COMPONENT_IDS, foldEssentials } from './entity';\n\nif (\n !isComponentDefinitionOrderValid() ||\n ESSENTIAL_COMPONENT_IDS.length !== 1 ||\n ESSENTIAL_COMPONENT_IDS[0] !== 0\n) {\n throw new Error(\n 'forgeax-engine-ecs: ESSENTIAL_COMPONENT_IDS invariant violated ' +\n `(expected [0], got [${ESSENTIAL_COMPONENT_IDS.join(', ')}]). ` +\n 'A defineComponent() call evaluated before the @forgeax/engine-ecs barrel forced the id counter ' +\n 'past 0. Ensure no module defines a component at import time before importing from the barrel.',\n );\n}\n\n/**\n * Branded-number handle type identifying a row (24-bit index + 8-bit\n * generation). The `Entity` component token (value-space, id=0) and the\n * `EntityHandle` type (type-space) are deliberately separate names since\n * feat-20260611 -- a single shared name caused repeated AI-user confusion in\n * `: Entity` annotations.\n */\nexport type { EntityHandle } from './entity-handle';\nexport type { EcsErrorCode } from './errors';\nexport { SharedRefStaleError, UniqueRefStaleError } from './errors';\nexport {\n createWorldContext,\n worldPlugin,\n} from './plugin-service';\nexport {\n defineRelationship,\n type RelationshipTargetComponent,\n} from './relationship-index';\nexport {\n FixedUpdate,\n type ScheduleName,\n type ScheduleToken,\n Update,\n} from './schedule-token';\nexport {\n FixedTime,\n type FixedTimeResource,\n Time,\n type TimePolicy,\n type TimeResource,\n type WorldOptions,\n} from './time';\n/**\n * Union of all EcsError types returned by World methods via Result.\n * Switch on `.code` for programmatic branching (e.g. `error.code === 'stale-entity'`).\n */\nexport type { EcsError } from './world';\n/**\n * The id=0 essential `Entity` component token. The matching type-space handle\n * type (the branded number returned by `world.spawn` and accepted by every\n * World method that takes an entity argument) is `EntityHandle`, exported\n * separately from this barrel.\n *\n * @example Handle type + spawn:\n * ```ts\n * const e: EntityHandle = world.spawn({ component: Position, data: { x: 0, y: 0 } }).unwrap();\n * ```\n * @example Read the handle off its own column / probe liveness:\n * ```ts\n * world.get(e, Entity).unwrap().self === e;\n * ```\n */\nexport { Disabled, Entity, ESSENTIAL_COMPONENT_IDS, foldEssentials };\n\n// ────────────────────────────────────────────────────────────────────────────\n// Core API — the 80% surface most users need\n// ────────────────────────────────────────────────────────────────────────────\n\n/**\n * Two-axis phantom-branded handle: `Handle<TargetTag, Mode>`.\n *\n * - `Mode = 'unique'` — released by ECS on despawn / removeComponent / set\n * (e.g. derived from schema vocab `ref<T>`).\n * - `Mode = 'shared'` — external owner manages release; ECS treats as\n * plain id (e.g. derived from schema vocab `handle<T>`,\n * `MeshFilter.assetHandle: Handle<'MeshAsset','shared'>`).\n *\n * Cross-mode and cross-target assignment is a TS error (AC-02).\n *\n * The handle type is owned by `@forgeax/engine-types`; ECS schema fields\n * consume it but the ECS barrel does not forward the type.\n *\n * @example\n * ```ts\n * import type { Handle } from '@forgeax/engine-types';\n *\n * declare const mesh: Handle<'MeshAsset', 'shared'>;\n * // const mat: Handle<'MaterialAsset', 'shared'> = mesh; // TS error\n * ```\n */\n/**\n * Opaque component token carrying name + schema type information.\n *\n * Prefer letting `defineComponent` infer the type — both the literal name `N`\n * and schema `S` flow through, enabling typed `QueryRow.get` / `QueryRow.mut`\n * access without `as` assertions.\n *\n * @example\n * ```ts\n * // Recommended — infer both N and S:\n * const Pos = defineComponent('Pos', { x: 'f32', y: 'f32' });\n * // ^? Component<'Pos', { x: 'f32'; y: 'f32' }>\n *\n * // Only annotate when you must — and use both type parameters:\n * const Vel: Component<'Vel', { dx: 'f32'; dy: 'f32' }> =\n * defineComponent('Vel', { dx: 'f32', dy: 'f32' });\n * ```\n */\nexport type {\n Component,\n ComponentSchema,\n FieldReflection,\n InputShapeOf,\n SchemaOf,\n ShapeOf,\n} from './component';\n/**\n * Declare a component schema. Returns a frozen opaque token with `.name`, `.fields`, `.storage`.\n *\n * @example\n * ```ts\n * const Position = defineComponent('Position', { x: 'f32', y: 'f32' });\n * ```\n */\nexport { defineComponent } from './component';\n/**\n * Query descriptor for With/Without archetype filtering.\n *\n * @example\n * ```ts\n * const desc: QueryDescriptor = { with: [Position, Velocity], without: [Static] };\n * ```\n */\nexport type {\n Query,\n QueryCreationError,\n QueryDescriptor,\n QueryRow,\n QuerySpan,\n} from './query/query';\n/**\n * ECS-aware refcount-tracked handle store (M3). Owns the lifecycle of every\n * `Handle<T, 'shared'>` derived from `shared<T>` schema fields. The producer\n * (typically AssetRegistry) calls `alloc` once (alloc-grant rc=1); each\n * additional holder retains; release decrements; rc 1 -> 0 drops the slot\n * and publishes structured release evidence. Payload disposal belongs to the\n * renderer/assets/plugin owner; ECS invokes no user callback.\n *\n * D-15: the store manages ONLY user-tier slots (`>= BUILTIN_BASE`); builtin\n * asset payloads are process-static in their authoring package\n * (@forgeax/engine-runtime) and never reference-counted. Passing a builtin\n * slot fails fast with `BuiltinSlotNotOwnedError`.\n *\n * `World` owns one `SharedRefStore` per instance, exposed as\n * `world.sharedRefs`. The schema-field write barrier (retain on spawn / set,\n * release on despawn / removeComponent) short-circuits on builtin slots.\n *\n * @example\n * ```ts\n * const world = new World();\n * const handle = world.allocSharedRef('MaterialAsset', payload);\n * const M = defineComponent('M', { asset: 'shared<MaterialAsset>' });\n * world.spawn({ component: M, data: { asset: handle } });\n * // the SharedRefStore publishes release evidence at rc=0.\n * ```\n */\nexport type { SharedRefReleaseEvidence } from './shared-ref-store';\n\n/**\n * ECS-managed handle store (M1). Owns the lifecycle of every\n * `Handle<T, 'unique'>` derived from `ref<T>` schema fields - World hooks\n * `despawn` / `removeComponent` / `set` into `release(handle)`.\n *\n * `World` owns one `UniqueRefStore` per instance, constructed eagerly in the\n * `World` constructor (always-on since feat-20260515-string-managed-collapse).\n * Production code rarely touches the store directly - schema-vocab `ref<T>`\n * fields make `world.get(e, C).<refField>` the canonical access path.\n *\n * @example\n * ```ts\n * const Material = defineComponent('Material', { handle: 'unique<MaterialPayload>' });\n * const world = new World();\n * // World owns the UniqueRefStore internally; AI users do not wire it.\n * ```\n */\n\n/**\n * Component data bundle for spawn/addComponent: pairs a component token with initial values.\n *\n * @example\n * ```ts\n * const data: ComponentData = { component: Position, data: { x: 1, y: 2 } };\n * ```\n */\nexport type { ComponentData } from './world';\n/**\n * Top-level ECS container. Owns entities, archetypes, systems, and resources.\n *\n * @example\n * ```ts\n * const world = new World();\n * const e = world.spawn({ component: Position, data: { x: 0, y: 0 } });\n * world.update();\n * ```\n */\nexport { World } from './world';\n\n// ────────────────────────────────────────────────────────────────────────────\n// Advanced API — system scheduling, commands, resources, inspection\n// ────────────────────────────────────────────────────────────────────────────\n\n/**\n * Deferred command buffer passed to system functions. Queues structural changes\n * (spawn/despawn/addComponent/removeComponent) for end-of-frame flush.\n *\n * @example\n * ```ts\n * fn: (world, results, commands) => {\n * const e = commands.spawn({ component: Bullet, data: { dmg: 10 } });\n * commands.despawn(oldEntity);\n * }\n * ```\n */\nexport type { CommandBuffer } from './commands';\n/**\n * System descriptor for `world.addSystem()`. Declares queries, execution function,\n * and optional before/after ordering constraints.\n *\n * @example\n * ```ts\n * world.addSystem(Update, {\n * name: 'movement',\n * queries: [{ with: [Position, Velocity] }],\n * fn: (world, results, commands) => { ... },\n * });\n * ```\n */\n/**\n * SystemSet nominal branded token type. Use {@link defineSystemSet} to create\n * a token; never construct manually. The {@link SystemSet.__forgeaxSystemSet}\n * brand prevents plain-object assignment.\n *\n * @example\n * ```ts\n * import type { SystemSet } from '@forgeax/engine-ecs';\n * const set: SystemSet = defineSystemSet({ name: 'gameplay' });\n * ```\n */\nexport type {\n SystemDescriptor,\n SystemHandle,\n SystemSet,\n} from './schedule';\n/**\n * Define a frozen system token. Executable registration is World-local through\n * `world.addSystem`.\n *\n * @example\n * ```ts\n * const Move = defineSystem({\n * name: 'movement',\n * queries: [{ with: [Position, Velocity] }],\n * fn: (world, results) => { ... },\n * });\n * world.addSystem(Move);\n * ```\n */\n/**\n * Define a frozen system-set token. Membership is World-local.\n *\n * @example\n * ```ts\n * const GameplaySet = defineSystemSet({ name: 'gameplay', runIf: (w) => !w.getResource<boolean>('paused') });\n * const OrderedSet = defineSystemSet({ name: 'ordered', chained: true });\n * ```\n */\nexport {\n defineSystem,\n defineSystemSet,\n} from './schedule';\n\n/**\n * Inspection snapshot returned by `world.inspect()`. Contains entity count,\n * archetype info, active components, system count, and resource keys.\n *\n * @example\n * ```ts\n * const info = world.inspect();\n * console.log(info.entityCount, info.archetypeCount);\n * ```\n */\n\n// ────────────────────────────────────────────────────────────────────────────\n// Entity encoding utilities\n// ────────────────────────────────────────────────────────────────────────────\n\n/**\n * Encode/decode entity handles for serialization or debugging.\n *\n * @example\n * ```ts\n * const { index, generation } = decodeEntity(entity);\n * const rebuilt = encodeEntity(index, generation);\n * ```\n */\n\n// ────────────────────────────────────────────────────────────────────────────\n// Query engine utilities\n// ────────────────────────────────────────────────────────────────────────────\n\n// ────────────────────────────────────────────────────────────────────────────\n// Component internals (for advanced use: custom storage, tooling)\n// ────────────────────────────────────────────────────────────────────────────\n\n// ────────────────────────────────────────────────────────────────────────────\n// Layer-3 default-value SSOT helper (feat-20260517-spawn-default-fallback / M1)\n// ────────────────────────────────────────────────────────────────────────────\n\n// ────────────────────────────────────────────────────────────────────────────\n\n// ────────────────────────────────────────────────────────────────────────────\n// Constants\n// ────────────────────────────────────────────────────────────────────────────\n\n// Component policy and metadata are an explicit schema projection, not fields\n// on the token or a process-global registry. Owners that need these facts must\n// receive the token's projection through this seam.\nexport { componentDefinition } from './component-schema';\nexport { ENTITY_MAX_GENERATION, ENTITY_MAX_INDEX, ENTITY_NULL_RAW } from './entity-handle';\n\n// w8: Inspector contributor (registerEcsInspector + RegisterEcsInspectorResult)\n// deleted — routing layer (Registry / sandbox) is removed; eval is the sole\n// command channel.\n// w9: ECS_MUTATING_METHODS export deleted — sandbox dismantled; mutating-methods.ts removed.\n"]}
1
+ {"version":3,"sources":["../src/component-schema.ts","../src/errors/query-and-component-errors.ts","../src/errors/relationship-errors.ts","../src/errors/sprite-and-shared-errors.ts","../src/errors/validation-errors.ts","../src/world-internal.ts","../src/execution/shared-kernel.ts","../src/errors.ts","../src/component.ts","../src/entity.ts","../src/plugin-service.ts","../src/relationship-index.ts","../src/schedule-token.ts","../src/time.ts","../src/buffer-pool.ts","../src/entity-handle.ts","../src/component-default-fallback.ts","../src/component-value-validate.ts","../src/internal.ts","../src/storage/archetype.ts","../src/storage/column.ts","../src/storage/table.ts","../src/storage/archetype-graph.ts","../src/storage/change-detection.ts","../src/query/derived-range-writer.ts","../src/query/query.ts","../src/resource.ts","../src/commands.ts","../src/schedule.ts","../src/shared-ref-store.ts","../src/storage/structural-evidence.ts","../src/unique-ref-store.ts","../src/world-entity-lifecycle.ts","../src/world-read.ts","../src/world-scheduling.ts","../src/world-storage-primitives.ts","../src/world.ts","../src/index.ts"],"names":["roles","resourceName","id","buffer","view","ok","err","tableRow","HAS_TRANSFER","INITIAL_CAPACITY","metaKey","scalarType","componentId","target","relationshipSource","MAX_SLOT","pack","unwrapHandle","handleSlot","handleGeneration","isRetiredSlot","component","componentNames","systems","targetRecord","toUnique","BUILTIN_BASE","toShared"],"mappings":";;;;;;AAmCA,IAAM,kBAAA,mBAAqB,MAAA,CAAO,GAAA,CAAI,+BAA+B,CAAA;AAIrE,IAAM,aAAA,GAAgB,UAAA;AACtB,IAAM,WAAA,GACH,aAAA,CAAc,kBAAkB,CAAA,IAAA,CAChC,MAAM;AACL,EAAA,MAAM,QAAA,GAA8B,EAAE,WAAA,kBAAa,IAAI,SAAqC,EAAE;AAC9F,EAAA,aAAA,CAAc,kBAAkB,CAAA,GAAI,QAAA;AACpC,EAAA,OAAO,QAAA;AACT,CAAA,GAAG;AAEE,SAAS,2BAAA,CACd,WACA,UAAA,EACM;AACN,EAAA,WAAA,CAAY,WAAA,CAAY,GAAA,CAAI,SAAA,EAAW,UAAU,CAAA;AACnD;AAGO,SAAS,oBAAoB,SAAA,EAA2C;AAC7E,EAAA,MAAM,UAAA,GAAa,WAAA,CAAY,WAAA,CAAY,GAAA,CAAI,SAAS,CAAA;AACxD,EAAA,IA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sourcesContent":["import type { Component, FieldReflection, SchemaFieldType } from './component';\n\n/** The complete storage placement vocabulary owned by ECS schema. */\nexport type ComponentStorageKind = 'table' | 'sparse';\n\n/** The stable public facts needed to describe a component schema offline. */\nexport interface ComponentSchemaDefinition {\n readonly name: string;\n readonly fields: Readonly<Record<string, SchemaFieldType>>;\n readonly storage: ComponentStorageKind;\n}\n\n/**\n * Serialization facts owned beside schema registration, not carried by the\n * public component token. Queries and storage only need the token's schema\n * vocabulary; domain validation and lifecycle belong to their owners.\n */\nexport interface ComponentPolicy {\n readonly transient: boolean;\n readonly meta: Record<string, unknown>;\n /** Components that are materialized whenever this component is added. */\n readonly requires: readonly Component[];\n}\n\n/** Immutable schema reflection plus non-token policy projection. */\nexport interface ComponentDefinition {\n readonly fields: Readonly<Record<string, FieldReflection>>;\n readonly defaults: Readonly<Record<string, unknown>> | undefined;\n readonly policy: ComponentPolicy;\n}\n\n// Component tokens can cross independently bundled ECS entry points. Share\n// the owner registry through globalThis rather than attaching a hidden symbol\n// to each token; `Reflect.ownKeys(token)` must remain exactly the three public\n// facts name/fields/storage.\nconst COMPONENT_REGISTRY = Symbol.for('forgeax.ecs.componentRegistry');\ninterface ComponentRegistry {\n readonly definitions: WeakMap<object, ComponentDefinition>;\n}\nconst globalSymbols = globalThis as typeof globalThis & { [key: symbol]: unknown };\nconst definitions =\n (globalSymbols[COMPONENT_REGISTRY] as ComponentRegistry | undefined) ??\n (() => {\n const registry: ComponentRegistry = { definitions: new WeakMap<object, ComponentDefinition>() };\n globalSymbols[COMPONENT_REGISTRY] = registry;\n return registry;\n })();\n\nexport function registerComponentDefinition(\n component: Component,\n definition: ComponentDefinition,\n): void {\n definitions.definitions.set(component, definition);\n}\n\n/** Read the definition-time schema/policy projection for a component token. */\nexport function componentDefinition(component: Component): ComponentDefinition {\n const definition = definitions.definitions.get(component);\n if (definition === undefined) {\n throw new Error(`Component definition missing for '${component.name}'.`);\n }\n return definition;\n}\n\n/** Read the generic structural requirements declared by one component. */\nexport function componentRequirements(component: Component): readonly Component[] {\n // Keep invalid/foreign tokens on the ordinary preflight error path. The\n // expansion helper runs before validation, so it must not turn a structured\n // `component-not-defined` Result into an uncaught registry exception.\n return definitions.definitions.get(component)?.policy.requires ?? [];\n}\n\ntype ComponentDataLike = {\n readonly component: Component;\n readonly data: Partial<Record<string, unknown>>;\n};\n\n/**\n * Expand component requirements once at the structural boundary.\n *\n * Explicit component data wins and is never duplicated. Requirements are\n * appended in declaration order, and the same identity set also terminates a\n * malformed dependency cycle without a per-frame scan.\n */\nexport function expandComponentRequirements<T extends ComponentDataLike>(\n componentDatas: readonly T[],\n): T[] {\n let hasRequirements = false;\n for (const entry of componentDatas) {\n if (componentRequirements(entry.component).length !== 0) {\n hasRequirements = true;\n break;\n }\n }\n // Most structural operations use components without dependencies. Preserve\n // that path without copying or allocating a Set; callers only consume the\n // returned list and never mutate it.\n if (!hasRequirements) return componentDatas as T[];\n\n const expanded = [...componentDatas];\n const seen = new Set<Component>(expanded.map((entry) => entry.component));\n for (let index = 0; index < expanded.length; index++) {\n const component = expanded[index]?.component;\n if (component === undefined) continue;\n for (const required of componentRequirements(component)) {\n if (seen.has(required)) continue;\n seen.add(required);\n expanded.push({ component: required, data: {} } as T);\n }\n }\n return expanded;\n}\n\n/**\n * Freeze a schema value recursively. Component descriptors are authored data,\n * so nested defaults and enum label maps must not become mutation channels.\n */\nexport function deepFreeze<T>(value: T): Readonly<T> {\n if (value === null || (typeof value !== 'object' && typeof value !== 'function')) {\n return value as Readonly<T>;\n }\n // Non-empty TypedArrays reject Object.freeze and their indexed elements\n // remain writable even when the wrapper is frozen. Treat binary views as\n // immutable leaf projections; the authored descriptor around them is still\n // recursively frozen by this function.\n if (ArrayBuffer.isView(value) || value instanceof ArrayBuffer) {\n return value as Readonly<T>;\n }\n const object = value as object;\n for (const key of Reflect.ownKeys(object)) {\n const child = (object as Record<PropertyKey, unknown>)[key];\n if (child !== null && (typeof child === 'object' || typeof child === 'function')) {\n deepFreeze(child);\n }\n }\n return Object.freeze(value) as Readonly<T>;\n}\n\nexport function assertComponentStorage(value: string): asserts value is ComponentStorageKind {\n if (value !== 'table' && value !== 'sparse') {\n throw new Error(`Unsupported component storage '${value}'. Expected 'table' or 'sparse'.`);\n }\n}\n","/**\n * Returned via `Result.err` from `world.removeComponent` when the caller tries\n * to remove an essential (undeletable) component\n * (feat-20260602-archetype-stores-full-packed-entity M1 / w3, plan-strategy\n * D-3). The only essential component today is the id=0 `Entity` component: every\n * archetype carries it unconditionally as the row's own packed handle, so\n * removing it is structurally meaningless. The code name is deliberately\n * generic (`remove-essential-component`, not entity-specific) so a future second\n * essential component reuses it without a rename.\n *\n * `.code = 'remove-essential-component'`\n * `.detail = { componentName }`\n * `.hint` — names the essential component + states it cannot be removed.\n */\nexport class RemoveEssentialComponentError extends Error {\n override readonly name = 'RemoveEssentialComponentError';\n readonly code = 'remove-essential-component' as const;\n readonly hint: string;\n readonly expected: string;\n readonly detail: { readonly componentName: string };\n\n constructor(componentName: string) {\n const hint = `Component \"${componentName}\" is essential (every entity carries it unconditionally) and cannot be removed. Despawn the entity instead if you want to retire it.`;\n const expected = 'non-essential component';\n super(\n `removeComponent: essential component cannot be removed.\\n` +\n ` code: remove-essential-component\\n` +\n ` component: ${componentName}\\n` +\n ` expected: ${expected}\\n` +\n ` hint: ${hint}`,\n );\n this.hint = hint;\n this.expected = expected;\n this.detail = { componentName };\n }\n}\n\n/**\n * Returned via the `Result` err branch when `instantiate` encounters a\n * SceneAsset entity whose `components` map references a component name that was\n * never passed to `defineComponent`.\n *\n * `.code = 'component-not-defined'`\n * `.detail.name` — the offending component name.\n *\n * Promoting this to a class (rather than a bare object literal) keeps the\n * scene-instantiate failure surface inside the `EcsError` class union, so the\n * documented two-level narrow `cause instanceof EcsError` actually matches it\n * (docs/feedbacks/2026-06-03 §6.2 Tier 4.2). `expected` / `hint` accept\n * per-call overrides because the parent-passthrough (ChildOf) site needs a\n * distinct message from the generic entity-component site.\n */\nexport class ComponentNotDefinedError extends Error {\n override readonly name = 'ComponentNotDefinedError';\n readonly code = 'component-not-defined' as const;\n readonly hint: string;\n readonly expected: string;\n readonly detail: { readonly name: string };\n\n constructor(componentName: string, opts?: { expected?: string; hint?: string }) {\n const expected = opts?.expected ?? `component '${componentName}' defined before instantiate`;\n const hint =\n opts?.hint ??\n `define the component via defineComponent('${componentName}', ...) before instantiating this SceneAsset`;\n super(\n `instantiate: component not defined.\\n` +\n ` code: component-not-defined\\n` +\n ` component: ${componentName}\\n` +\n ` expected: ${expected}\\n` +\n ` hint: ${hint}`,\n );\n this.hint = hint;\n this.expected = expected;\n this.detail = { name: componentName };\n }\n}\n\n/**\n * Returned via `Result.err` from `world.spawn` / `world.addComponent` /\n * `world.instantiateScene` / `Commands.spawn` when the caller-supplied\n * data payload carries a key that is not declared in the target component's\n * schema. The pre-fix behaviour silently dropped unknown keys inside\n * `fillComponentDefaults` (which walked schema keys, never raw keys), so a\n * typo like `MeshRenderer { material: h }` (singular legacy field name; the\n * current schema has `materials: array<...>`) produced an empty-defaults row\n * + an invisible / mid-grey entity downstream. Surfacing the typo at the\n * spawn boundary collapses a class of \"renders wrong, looks like a graphics\n * bug\" reports into a single explicit error.\n *\n * `.code = 'spawn-data-unknown-field'`\n * `.detail = { component, field, knownFields }`\n * `.hint` — names the offending field and lists the schema's known fields.\n */\nexport class SpawnDataUnknownFieldError extends Error {\n override readonly name = 'SpawnDataUnknownFieldError';\n readonly code = 'spawn-data-unknown-field' as const;\n readonly hint: string;\n readonly expected: string;\n readonly detail: {\n readonly component: string;\n readonly field: string;\n readonly knownFields: readonly string[];\n };\n\n constructor(componentName: string, fieldName: string, knownFields: readonly string[]) {\n const sortedKnown = [...knownFields].sort();\n const expected = `field name in {${sortedKnown.join(', ')}}`;\n const hint =\n `'${fieldName}' is not a schema field of '${componentName}'. ` +\n `Known fields: ${sortedKnown.join(', ')}. ` +\n `Check for a typo or a stale single-vs-plural rename (e.g. 'material' vs 'materials').`;\n super(\n `${componentName}: spawn data carries unknown field.\\n` +\n ` code: spawn-data-unknown-field\\n` +\n ` component: ${componentName}\\n` +\n ` field: ${fieldName}\\n` +\n ` expected: ${expected}\\n` +\n ` hint: ${hint}`,\n );\n this.hint = hint;\n this.expected = expected;\n this.detail = { component: componentName, field: fieldName, knownFields: sortedKnown };\n }\n}\nexport type QuerySpanUnavailableReason =\n | 'optional-data'\n | 'sparse-component'\n | 'relationship-component';\n\nexport class QueryDescriptorConflictError extends Error {\n override readonly name = 'QueryDescriptorConflictError';\n readonly code = 'query-descriptor-conflict' as const;\n readonly expected = 'each component occupies one descriptor role';\n readonly hint: string;\n readonly detail: { readonly componentName: string; readonly roles: readonly string[] };\n\n constructor(componentName: string, roles: readonly string[]) {\n const hint = `Remove ${componentName} from all but one of: ${roles.join(', ')}.`;\n super(`Query descriptor roles conflict for ${componentName}.\\n hint: ${hint}`);\n this.hint = hint;\n this.detail = { componentName, roles };\n }\n}\n\nexport class QueryDataRequiresFieldsError extends Error {\n override readonly name = 'QueryDataRequiresFieldsError';\n readonly code = 'query-data-requires-fields' as const;\n readonly expected = 'a component with at least one data field';\n readonly hint: string;\n readonly detail: { readonly componentName: string };\n\n constructor(componentName: string) {\n const hint = `Move tag ${componentName} to with or without.`;\n super(`Query data access requires fields on ${componentName}.\\n hint: ${hint}`);\n this.hint = hint;\n this.detail = { componentName };\n }\n}\n\nexport class QuerySpanUnavailableError extends Error {\n override readonly name = 'QuerySpanUnavailableError';\n readonly code = 'query-span-unavailable' as const;\n readonly expected = 'a descriptor whose rows form contiguous table ranges';\n readonly hint = 'Use row iteration or split the query.';\n readonly detail: { readonly reason: QuerySpanUnavailableReason };\n\n constructor(reason: QuerySpanUnavailableReason) {\n super(`Query spans are unavailable: ${reason}.\\n hint: Use row iteration or split the query.`);\n this.detail = { reason };\n }\n}\n\nexport class QueryIterationInvalidatedError extends Error {\n override readonly name = 'QueryIterationInvalidatedError';\n readonly code = 'query-iteration-invalidated' as const;\n readonly expected: string;\n readonly hint = 'Use deferred Commands for structural mutation, then restart iteration.';\n readonly detail: {\n readonly expectedStructureEpoch: number;\n readonly actualStructureEpoch: number;\n };\n\n constructor(expectedStructureEpoch: number, actualStructureEpoch: number) {\n const expected = `structure epoch ${expectedStructureEpoch}`;\n super(\n `Query iteration was invalidated by structure epoch ${actualStructureEpoch}.\\n hint: ${'Use deferred Commands for structural mutation, then restart iteration.'}`,\n );\n this.expected = expected;\n this.detail = { expectedStructureEpoch, actualStructureEpoch };\n }\n}\n\nexport class QueryIterationActiveError extends Error {\n override readonly name = 'QueryIterationActiveError';\n readonly code = 'query-iteration-active' as const;\n readonly expected = 'one active iterator per Query';\n readonly hint = 'Complete the active iterator or create an independent Query.';\n readonly detail = {};\n\n constructor() {\n super('Query already has an active iterator.\\n hint: Complete it before iterating again.');\n }\n}\n","// ────────────────────────────────────────────────────────────────────────────\n// feat-20260531-ecs-relationship-abstraction-bidirectional-sync M2 — closed-\n// union evolution +4 (plan-strategy D-5). Adds 4 `relationship-*` kebab codes\n// (27 -> 31, add-only minor per AGENTS.md Error model evolution contract):\n//\n// - relationship-self-cycle (cycle / ancestor walk hit)\n// - relationship-mirror-component-not-registered (defineComponent gate a)\n// - relationship-mirror-field-type-mismatch (defineComponent gate b)\n// - relationship-detach-mismatch (removeChild parent arg mismatch)\n//\n// `relationship-exclusive-violation` is intentionally NOT a member: exclusive\n// re-add is an automatic reparent (a success path, D-1 style), not an error.\n// Every detail object is a discriminated payload narrowed via EcsErrorDetail.\n// ────────────────────────────────────────────────────────────────────────────\n\n/**\n * Returned via `Result.err` from `world.addChild` / `world.reparent` (M3) when\n * a hierarchy write would form a cycle — either the child is its own parent\n * (self-loop) or the proposed parent is already a descendant of the child\n * (ancestor-walk hit). The `.detail` carries both the offending child entity\n * and the ancestor entity that closed the cycle so AI users can locate the\n * loop without re-walking the graph.\n *\n * `.code = 'relationship-self-cycle'`\n * `.detail = { component, entity, ancestor }`\n * `.hint` — names the child + ancestor that would close the cycle.\n */\nexport class RelationshipSelfCycleError extends Error {\n override readonly name = 'RelationshipSelfCycleError';\n readonly code = 'relationship-self-cycle' as const;\n readonly hint: string;\n readonly expected: string;\n readonly detail: {\n readonly component: string;\n readonly entity: number;\n readonly ancestor: number;\n };\n\n constructor(component: string, entity: number, ancestor: number) {\n const hint = `Linking entity ${entity} via \"${component}\" would close a cycle through ancestor ${ancestor}. Reparent to an entity that is not a descendant of ${entity}.`;\n const expected = 'acyclic parent chain';\n super(\n `relationship: cycle detected.\\n` +\n ` code: relationship-self-cycle\\n` +\n ` component: ${component}\\n` +\n ` entity: ${entity}\\n` +\n ` ancestor: ${ancestor}\\n` +\n ` expected: ${expected}\\n` +\n ` hint: ${hint}`,\n );\n this.hint = hint;\n this.expected = expected;\n this.detail = { component, entity, ancestor };\n }\n}\n\n/**\n * Thrown by `defineComponent` (feat-20260602 M2) when a component declares a\n * `relationship.mirror` naming a component that has not yet been defined\n * (AC-09). AI users defineComponent the mirror before the holder (mirror-then-\n * holder order).\n *\n * The `.code` literal `relationship-mirror-component-not-registered` is kept\n * unchanged across the M2 migration (deliberate terminology trade-off:\n * external `.code` stability over wording precision); only the `.hint` text\n * drops the register/registered phrasing in favour of defineComponent ordering\n * guidance.\n *\n * `.code = 'relationship-mirror-component-not-registered'`\n * `.detail = { component, mirror }`\n * `.hint` — names the holder + the undefined mirror component.\n */\nexport class RelationshipMirrorComponentNotRegisteredError extends Error {\n override readonly name = 'RelationshipMirrorComponentNotRegisteredError';\n readonly code = 'relationship-mirror-component-not-registered' as const;\n readonly hint: string;\n readonly expected: string;\n readonly detail: { readonly component: string; readonly mirror: string };\n\n constructor(component: string, mirror: string) {\n const hint = `Component \"${component}\" declares relationship.mirror = \"${mirror}\", but \"${mirror}\" has not been defined yet. defineComponent the mirror component before the holder (define them in mirror-then-holder order).`;\n const expected = `mirror component \"${mirror}\" registered`;\n super(\n `relationship: mirror component not registered.\\n` +\n ` code: relationship-mirror-component-not-registered\\n` +\n ` component: ${component}\\n` +\n ` mirror: ${mirror}\\n` +\n ` expected: ${expected}\\n` +\n ` hint: ${hint}`,\n );\n this.hint = hint;\n this.expected = expected;\n this.detail = { component, mirror };\n }\n}\n\n/**\n * Thrown by `defineComponent` (feat-20260602 M2) when the\n * `relationship.field` on the mirror component is missing or its schema type\n * is not the only legal back-reference storage shape `array<entity>`\n * (AC-11 b). AI users declare the mirror field as `'array<entity>'`.\n *\n * `.code = 'relationship-mirror-field-type-mismatch'`\n * `.detail = { component, mirror, field, actualType }`\n * `.hint` — names the holder + mirror field + the type observed.\n */\nexport class RelationshipMirrorFieldTypeMismatchError extends Error {\n override readonly name = 'RelationshipMirrorFieldTypeMismatchError';\n readonly code = 'relationship-mirror-field-type-mismatch' as const;\n readonly hint: string;\n readonly expected: string;\n readonly detail: {\n readonly component: string;\n readonly mirror: string;\n readonly field: string;\n readonly actualType: string;\n };\n\n constructor(component: string, mirror: string, field: string, actualType: string) {\n const hint = `Component \"${component}\" mirror \"${mirror}\".${field} has type \"${actualType}\"; the reverse-list field must be declared as 'array<entity>'.`;\n const expected = \"mirror field type === 'array<entity>'\";\n super(\n `relationship: mirror field type mismatch.\\n` +\n ` code: relationship-mirror-field-type-mismatch\\n` +\n ` component: ${component}\\n` +\n ` mirror: ${mirror}\\n` +\n ` field: ${field}\\n` +\n ` actualType: ${actualType}\\n` +\n ` expected: ${expected}\\n` +\n ` hint: ${hint}`,\n );\n this.hint = hint;\n this.expected = expected;\n this.detail = { component, mirror, field, actualType };\n }\n}\n\n/**\n * Returned via `Result.err` from `world.removeChild` (M3) when the `parent`\n * argument does not match the child's current relationship parent (the child\n * lacks the relationship component, or it points at a different parent). The\n * `.detail` carries the expected (argument) parent + the actual current parent\n * so AI users can reconcile their model.\n *\n * `.code = 'relationship-detach-mismatch'`\n * `.detail = { component, child, expectedParent, actualParent }`\n * `actualParent === ENTITY_NULL_RAW` (0) signals the child has no relationship.\n * `.hint` — names the child + the parent mismatch.\n */\nexport class RelationshipDetachMismatchError extends Error {\n override readonly name = 'RelationshipDetachMismatchError';\n readonly code = 'relationship-detach-mismatch' as const;\n readonly hint: string;\n readonly expected: string;\n readonly detail: {\n readonly component: string;\n readonly child: number;\n readonly expectedParent: number;\n readonly actualParent: number;\n };\n\n constructor(component: string, child: number, expectedParent: number, actualParent: number) {\n const hint = `removeChild(${expectedParent}, ${child}) via \"${component}\": child's current parent is ${actualParent}, not ${expectedParent}. Detach from the actual parent or re-read the current relationship.`;\n const expected = `child's \"${component}\" parent === ${expectedParent}`;\n super(\n `relationship: detach parent mismatch.\\n` +\n ` code: relationship-detach-mismatch\\n` +\n ` component: ${component}\\n` +\n ` child: ${child}\\n` +\n ` expectedParent: ${expectedParent}\\n` +\n ` actualParent: ${actualParent}\\n` +\n ` expected: ${expected}\\n` +\n ` hint: ${hint}`,\n );\n this.hint = hint;\n this.expected = expected;\n this.detail = { component, child, expectedParent, actualParent };\n }\n}\n\n/** Returned when callers attempt to mutate an engine-maintained target list. */\nexport class RelationshipTargetReadonlyError extends Error {\n override readonly name = 'RelationshipTargetReadonlyError';\n readonly code = 'component-field-invalid-value' as const;\n readonly expected = 'relationship source mutation';\n readonly hint: string;\n readonly detail: {\n readonly component: string;\n readonly operation: string;\n };\n\n constructor(component: string, operation: string) {\n const hint = `Component \"${component}\" is an engine-maintained relationship target. Mutate its source component instead of ${operation}.`;\n super(`[RelationshipTargetReadonlyError component-field-invalid-value] ${hint}`);\n this.hint = hint;\n this.detail = { component, operation };\n }\n}\n","/**\n * feat-20260713-mount-override-component-add-and-shared-ref-round M2 / w9 —\n * `.code = 'shared-field-invalid-value'`.\n *\n * A `shared<T>` scalar / `array<shared<T>>` element must be a resolved numeric\n * Handle. A raw GUID string / `{ guid }` / `{ kind }` object (the\n * pre-resolution shape a sidecar hands an AI user) used to be silently coerced\n * to the all-zero sentinel by the column packer / scalar write path, so a\n * mis-bound reference read back as `0` / `[0,0,0,0]` and rendered blank with no\n * error. `validateComponentDataKeys` only checks key NAMES, not value types;\n * this error closes the value-type gap at all three write entries\n * (spawn / addComponent / set). `.detail.field` + `.detail.fieldType` name the\n * offending field; `.detail.index` locates the array element (undefined for the\n * scalar form).\n *\n * `.detail = { component, field, fieldType, actualValue, index? }`\n * `.hint` — names the field and points at `AssetRegistry.load + allocSharedRef`.\n */\nexport class SharedFieldInvalidValueError extends Error {\n override readonly name = 'SharedFieldInvalidValueError';\n readonly code = 'shared-field-invalid-value' as const;\n readonly hint: string;\n readonly expected: string;\n readonly detail: {\n readonly component: string;\n readonly field: string;\n readonly fieldType: string;\n readonly actualValue: unknown;\n readonly index?: number;\n };\n\n constructor(\n componentName: string,\n fieldName: string,\n fieldType: string,\n actualValue: unknown,\n index?: number,\n ) {\n const at = index === undefined ? '' : `[${index}]`;\n const expected = `a resolved numeric Handle for shared field '${fieldName}${at}'`;\n const hint =\n `'${fieldName}${at}' on '${componentName}' is a ${fieldType} reference; ` +\n `got ${typeof actualValue} (${JSON.stringify(actualValue)}). ` +\n `Resolve the GUID to a handle first: AssetRegistry.load(guid, kind) then allocSharedRef(...), ` +\n `and bind the returned numeric handle — not the raw GUID / sidecar object.`;\n super(\n `${componentName}.${fieldName}${at}: shared field bound to a non-handle value.\\n` +\n ` code: shared-field-invalid-value\\n` +\n ` component: ${componentName}\\n` +\n ` field: ${fieldName}${at}\\n` +\n ` fieldType: ${fieldType}\\n` +\n ` expected: ${expected}\\n` +\n ` hint: ${hint}`,\n );\n this.hint = hint;\n this.expected = expected;\n this.detail =\n index === undefined\n ? { component: componentName, field: fieldName, fieldType, actualValue }\n : { component: componentName, field: fieldName, fieldType, actualValue, index };\n }\n}\n\n// ────────────────────────────────────────────────────────────────────────────\n// feat-20260625-sprite-instances-and-tilemap-terrain-static-batch M1 / w2 —\n// closed-union evolution +3 for the SpriteInstances primitive + tilemap\n// terrain static-batch path. AGENTS.md §Error model evolution contract: minor\n// (add member only).\n//\n// All 3 codes are DECLARED here (M1) but FIRED at the render-system-extract\n// QueryRow loop (M3 w13) — plan-strategy D-6 \"fail-fast at the render\n// domain entry, not at ECS spawn-time (avoids reverse dep ECS -> AssetRegistry\n// to look up MaterialAsset.shadingModel)\". M1 carries class declarations only;\n// the `_routeError` call sites land in M3.\n//\n// Three codes, three failure shapes:\n// - 'sprite-instances-count-mismatch' — transforms.length / 16 !==\n// regions.length / 4 (stride contract; cf. instance-transforms-stride-\n// mismatch which guards Instances stride 16).\n// - 'sprite-instances-requires-sprite-shader' — the entity's MaterialAsset's\n// first pass shader is not 'forgeax::sprite' (extract-time check; AI users\n// using SpriteInstances must pick a sprite-shaded material).\n// - 'sprite-instances-mutually-exclusive-with-instances' — the same entity\n// carries both Instances + SpriteInstances (the two primitives are peers;\n// SpriteInstances supersedes Instances when per-instance UV region is\n// needed).\n//\n// .hint follows charter P3: each contains the literal repair step AI users\n// can paste back into spawn code (transforms/regions stride math; shading\n// model field write; component removal).\n// ────────────────────────────────────────────────────────────────────────────\n\n/**\n * Thrown / returned via Layer-3 error route when `SpriteInstances.transforms`\n * (stride 16 — column-major mat4 per instance) and `SpriteInstances.regions`\n * (stride 4 — per-instance UV vec4) instance counts disagree at render-system-\n * extract entry.\n *\n * `.code = 'sprite-instances-count-mismatch'`\n * `.detail = { transformsLength, regionsLength, expectedStride: { transforms: 16, regions: 4 } }`\n * `.hint` — instructs the AI user to enforce\n * `transforms.length / 16 === regions.length / 4`.\n */\nexport class SpriteInstancesCountMismatchError extends Error {\n override readonly name = 'SpriteInstancesCountMismatchError';\n readonly code = 'sprite-instances-count-mismatch' as const;\n readonly hint: string;\n readonly expected: string;\n readonly detail: {\n readonly code: 'sprite-instances-count-mismatch';\n readonly transformsLength: number;\n readonly regionsLength: number;\n readonly expectedStride: { readonly transforms: 16; readonly regions: 4 };\n };\n\n constructor(transformsLength: number, regionsLength: number) {\n const hint =\n 'SpriteInstances.transforms (stride 16) and SpriteInstances.regions (stride 4) ' +\n 'must describe the same instance count: ensure transforms.length / 16 === regions.length / 4 ' +\n 'at the spawn / set site (resize both arrays together).';\n const expected = 'transforms.length / 16 === regions.length / 4';\n super(\n `SpriteInstances: per-instance count mismatch between transforms and regions.\\n` +\n ` code: sprite-instances-count-mismatch\\n` +\n ` transformsLength: ${transformsLength} (count = ${transformsLength / 16})\\n` +\n ` regionsLength: ${regionsLength} (count = ${regionsLength / 4})\\n` +\n ` expected: ${expected}\\n` +\n ` hint: ${hint}`,\n );\n this.hint = hint;\n this.expected = expected;\n this.detail = {\n code: 'sprite-instances-count-mismatch',\n transformsLength,\n regionsLength,\n expectedStride: { transforms: 16, regions: 4 },\n };\n }\n}\n\n/**\n * Thrown / returned via Layer-3 error route when an entity carrying\n * `SpriteInstances` references a MaterialAsset whose first pass shader is not\n * `'forgeax::sprite'`. Detected at render-system-extract entry (M3 w13).\n *\n * `.code = 'sprite-instances-requires-sprite-shader'`\n * `.detail = { entityId, observedMaterialShaderId }`\n * `.hint` — instructs the AI user to bind a MaterialAsset whose first pass\n * `shader` is `'forgeax::sprite'` or `'forgeax::sprite-lit'`.\n *\n * feat-20260624-sprite-lit-shading-model-pure-2d-lighting M1' / t6:\n * sprite-lit walks the same per-instance UV region vertex path as sprite\n * (VsOut byte-identical, paramSchema mirror); both shader ids are accepted.\n */\nexport class SpriteInstancesRequiresSpriteShaderError extends Error {\n override readonly name = 'SpriteInstancesRequiresSpriteShaderError';\n readonly code = 'sprite-instances-requires-sprite-shader' as const;\n readonly hint: string;\n readonly expected: string;\n readonly detail: {\n readonly code: 'sprite-instances-requires-sprite-shader';\n readonly entityId: number;\n readonly observedMaterialShaderId: string;\n };\n\n constructor(entityId: number, observedMaterialShaderId: string) {\n const hint =\n \"bind a MaterialAsset whose first pass `shader` is 'forgeax::sprite' \" +\n \"or 'forgeax::sprite-lit' to this entity's MeshRenderer (SpriteInstances \" +\n 'requires a sprite-family shader so the per-instance UV region is consumed ' +\n 'by the sprite vertex shader path).';\n const expected =\n \"MaterialAsset.passes[0].shader === 'forgeax::sprite' || 'forgeax::sprite-lit'\";\n super(\n `SpriteInstances: entity ${entityId} requires a sprite-shaded MaterialAsset.\\n` +\n ` code: sprite-instances-requires-sprite-shader\\n` +\n ` entityId: ${entityId}\\n` +\n ` observedMaterialShaderId: ${observedMaterialShaderId}\\n` +\n ` expected: ${expected}\\n` +\n ` hint: ${hint}`,\n );\n this.hint = hint;\n this.expected = expected;\n this.detail = {\n code: 'sprite-instances-requires-sprite-shader',\n entityId,\n observedMaterialShaderId,\n };\n }\n}\n\n/**\n * Thrown / returned via Layer-3 error route when the same entity carries both\n * `Instances` (3D per-instance mat4) and `SpriteInstances` (2D per-instance\n * mat4 + UV region). The two primitives are peers — pick one. Detected at\n * render-system-extract entry (M3 w13).\n *\n * `.code = 'sprite-instances-mutually-exclusive-with-instances'`\n * `.detail = { entityId }`\n * `.hint` — instructs the AI user to remove one of the two components.\n */\nexport class SpriteInstancesMutuallyExclusiveWithInstancesError extends Error {\n override readonly name = 'SpriteInstancesMutuallyExclusiveWithInstancesError';\n readonly code = 'sprite-instances-mutually-exclusive-with-instances' as const;\n readonly hint: string;\n readonly expected: string;\n readonly detail: {\n readonly code: 'sprite-instances-mutually-exclusive-with-instances';\n readonly entityId: number;\n };\n\n constructor(entityId: number) {\n const hint =\n 'remove Instances or replace with SpriteInstances; SpriteInstances supersedes ' +\n 'Instances when per-instance region is needed.';\n const expected = 'entity carries Instances XOR SpriteInstances (not both)';\n super(\n `SpriteInstances: entity ${entityId} carries both Instances and SpriteInstances.\\n` +\n ` code: sprite-instances-mutually-exclusive-with-instances\\n` +\n ` entityId: ${entityId}\\n` +\n ` expected: ${expected}\\n` +\n ` hint: ${hint}`,\n );\n this.hint = hint;\n this.expected = expected;\n this.detail = {\n code: 'sprite-instances-mutually-exclusive-with-instances',\n entityId,\n };\n }\n}\n","import type { Component, ComponentSchema, FieldReflection } from '../component';\nimport { componentDefinition } from '../component-schema';\n\nexport class TimeDeltaInvalidError extends Error {\n override readonly name = 'TimeDeltaInvalidError';\n readonly code = 'time-delta-invalid' as const;\n readonly expected = 'a finite delta greater than or equal to 0';\n readonly hint = 'Call world.update(deltaSeconds) with a finite non-negative delta.';\n readonly detail: { readonly received: number };\n\n constructor(received: number) {\n super(\n `Invalid world.update delta: ${received}.\\n expected: a finite delta greater than or equal to 0\\n hint: Call world.update(deltaSeconds) with a finite non-negative delta.`,\n );\n this.detail = { received };\n }\n}\n\nexport class TimeConfigInvalidError extends Error {\n override readonly name = 'TimeConfigInvalidError';\n readonly code = 'time-config-invalid' as const;\n readonly expected: string;\n readonly hint = 'Increase maxDeltaSeconds or decrease maxStepsPerUpdate or fixedDeltaSeconds.';\n readonly detail: {\n readonly fixedDeltaSeconds: number;\n readonly maxStepsPerUpdate: number;\n readonly maxDeltaSeconds: number;\n };\n\n constructor(detail: TimeConfigInvalidError['detail']) {\n const expected = 'maxDeltaSeconds >= (maxStepsPerUpdate + 1) * fixedDeltaSeconds';\n super(\n `Invalid World time policy.\\n expected: ${expected}\\n hint: Increase maxDeltaSeconds or decrease maxStepsPerUpdate or fixedDeltaSeconds.`,\n );\n this.expected = expected;\n this.detail = detail;\n }\n}\n\nexport class ScheduleScopeMismatchError extends Error {\n override readonly name = 'ScheduleScopeMismatchError';\n readonly code = 'schedule-scope-mismatch' as const;\n readonly expected: string;\n readonly hint: string;\n readonly detail: {\n readonly sourceSchedule: string;\n readonly targetSchedule: string;\n readonly reference?: string;\n };\n\n constructor(sourceSchedule: string, targetSchedule: string, reference?: string) {\n const expected = `a reference owned by ${sourceSchedule}`;\n const hint = `The referenced item belongs to ${targetSchedule}; register and order it in ${sourceSchedule}.`;\n super(`Schedule scope mismatch.\\n expected: ${expected}\\n hint: ${hint}`);\n this.expected = expected;\n this.hint = hint;\n this.detail = { sourceSchedule, targetSchedule, ...(reference ? { reference } : {}) };\n }\n}\n\n/**\n * Returned when a closed enum field receives a value outside its reflected\n * labels. The write owner runs this before any archetype or column mutation.\n */\nexport class ComponentFieldInvalidValueError extends Error {\n override readonly name = 'ComponentFieldInvalidValueError';\n readonly code = 'component-field-invalid-value' as const;\n readonly hint: string;\n readonly expected: string;\n readonly detail: {\n readonly entity: number | undefined;\n readonly component: string;\n readonly field: string;\n readonly received: unknown;\n readonly allowedValues: Readonly<Record<string, number>>;\n };\n\n constructor(\n entity: number | undefined,\n component: string,\n field: string,\n received: unknown,\n allowedValues: Readonly<Record<string, number>>,\n ) {\n const entries = Object.entries(allowedValues)\n .map(([label, value]) => `${label}=${value}`)\n .join(', ');\n const expected = `${component}.${field} in { ${entries} }`;\n const hint = `Set ${component}.${field} to one of the reflected enum values: ${entries}`;\n super(\n `${component}.${field} received an invalid enum value.\\n` +\n ` code: component-field-invalid-value\\n` +\n ` component: ${component}\\n` +\n ` field: ${field}\\n` +\n ` received: ${String(received)}\\n` +\n ` expected: ${expected}\\n` +\n ` hint: ${hint}`,\n );\n this.hint = hint;\n this.expected = expected;\n this.detail = { entity, component, field, received, allowedValues };\n }\n}\n\nexport class ComponentNumericValueInvalidError extends Error {\n override readonly name = 'ComponentNumericValueInvalidError';\n readonly code = 'component-numeric-value-invalid' as const;\n readonly expected = 'a numeric value other than NaN';\n readonly hint: string;\n readonly detail: {\n readonly entity: number | undefined;\n readonly component: string;\n readonly field: string;\n readonly received: number;\n readonly index?: number;\n };\n\n constructor(\n entity: number | undefined,\n component: string,\n field: string,\n received: number,\n index?: number,\n ) {\n const location =\n index === undefined ? `${component}.${field}` : `${component}.${field}[${index}]`;\n const hint = `Replace NaN at ${location} with an authored numeric value; Number.POSITIVE_INFINITY remains valid where the component domain permits it.`;\n super(\n `${location} received NaN.\\n` +\n ` code: component-numeric-value-invalid\\n` +\n ` expected: a numeric value other than NaN\\n` +\n ` hint: ${hint}`,\n );\n this.hint = hint;\n this.detail = {\n entity,\n component,\n field,\n received,\n ...(index === undefined ? {} : { index }),\n };\n }\n}\n\nconst NUMERIC_FIELD_TYPES = new Set(['f32', 'f64', 'i32', 'u32', 'i16', 'u16', 'i8', 'u8', 'enum']);\n\nexport function validateNumericFieldValues<S extends ComponentSchema>(\n component: Component<string, S>,\n raw: Partial<Record<string, unknown>> | undefined,\n entity?: number,\n): ComponentNumericValueInvalidError | null {\n if (raw === undefined) return null;\n const fields = componentDefinition(component).fields as Readonly<Record<string, FieldReflection>>;\n const rawValues = raw as Record<string, unknown>;\n for (const fieldName of Object.keys(rawValues)) {\n const reflection = fields[fieldName];\n if (reflection === undefined) continue;\n const value = rawValues[fieldName];\n if (NUMERIC_FIELD_TYPES.has(reflection.type)) {\n if (typeof value === 'number' && Number.isNaN(value)) {\n return new ComponentNumericValueInvalidError(entity, component.name, fieldName, value);\n }\n continue;\n }\n if (\n reflection.arrayMeta === undefined ||\n !NUMERIC_FIELD_TYPES.has(reflection.arrayMeta.elementType)\n ) {\n continue;\n }\n const length =\n Array.isArray(value) || ArrayBuffer.isView(value)\n ? (value as { readonly length?: number }).length\n : undefined;\n if (length === undefined) continue;\n const values = value as ArrayLike<unknown>;\n for (let index = 0; index < length; index++) {\n const received = values[index];\n if (typeof received === 'number' && Number.isNaN(received)) {\n return new ComponentNumericValueInvalidError(\n entity,\n component.name,\n fieldName,\n received,\n index,\n );\n }\n }\n }\n return null;\n}\n\n/**\n * Returned before an ECS write when a managed `array<T>` field receives a\n * value that the storage boundary cannot interpret as an array payload. The\n * old column writer treated arbitrary objects as an empty payload, which\n * silently changed the row while retaining no evidence of the caller error.\n */\nexport class ManagedArrayInvalidValueError extends Error {\n override readonly name = 'ManagedArrayInvalidValueError';\n readonly code = 'managed-array-invalid-value' as const;\n readonly expected = 'an Array or TypedArray payload (or null/undefined to clear it)';\n readonly hint: string;\n readonly detail: {\n readonly component: string;\n readonly field: string;\n readonly fieldType: string;\n readonly actualValue: unknown;\n };\n\n constructor(componentName: string, fieldName: string, fieldType: string, actualValue: unknown) {\n const hint =\n `Set ${componentName}.${fieldName} to a plain array or TypedArray matching ` +\n `${fieldType}; use null or undefined to clear the managed value.`;\n super(\n `${componentName}.${fieldName}: managed array received an invalid value.\\n` +\n ` code: managed-array-invalid-value\\n` +\n ` fieldType: ${fieldType}\\n` +\n ` expected: an Array or TypedArray payload (or null/undefined to clear it)\\n` +\n ` hint: ${hint}`,\n );\n this.hint = hint;\n this.detail = { component: componentName, field: fieldName, fieldType, actualValue };\n }\n}\n\n/**\n * Validate the closed enum fields present in a write payload. Enums without\n * labels remain open numeric fields for compatibility with existing schemas.\n */\nexport function validateEnumFieldValues<S extends ComponentSchema>(\n component: Component<string, S>,\n raw: Partial<Record<string, unknown>> | undefined,\n entity?: number,\n): ComponentFieldInvalidValueError | null {\n if (raw === undefined) return null;\n const fields = componentDefinition(component).fields as Readonly<Record<string, FieldReflection>>;\n const rawValues = raw as Record<string, unknown>;\n for (const fieldName of Object.keys(rawValues)) {\n const reflection = fields[fieldName];\n if (reflection?.type !== 'enum' || reflection.labels === undefined) continue;\n const value = rawValues[fieldName];\n const allowedValues = Object.values(reflection.labels);\n if (typeof value !== 'number' || !Number.isInteger(value) || !allowedValues.includes(value)) {\n return new ComponentFieldInvalidValueError(\n entity,\n component.name,\n fieldName,\n value,\n reflection.labels,\n );\n }\n }\n return null;\n}\n\n// ────────────────────────────────────────────────────────────────────────────\n// feat-20260519-light-casters-point-spot-pbr w2 — closed-union evolution +1.\n//\n// Adds 1 new member 'spawn-light-invalid-bounds' to EcsErrorCode (23 -> 24).\n// AGENTS.md section Error model evolution contract: minor (add member only).\n// Triggered by PointLight / SpotLight spawn-time payload validation\n// (plan-strategy D-S3 a). detail.field three-branch\n// ('range' | 'innerOuter' | 'outerNinety') keeps the four bound-violation\n// shapes under one error code so callers narrow first on `.code` then on\n// `.detail.field` (charter P3 progressive disclosure).\n// ────────────────────────────────────────────────────────────────────────────\n\n/**\n * Returned via `Result.err` from `world.spawn` when a PointLight or SpotLight\n * payload field is out of the documented bound. Four bound violations share\n * one `.code` and discriminate via `.detail.field`:\n *\n * - `range` — PointLight / SpotLight `range < 0` or `Number.isNaN(range)`.\n * Use `Number.POSITIVE_INFINITY` for an unlimited range or a non-negative\n * meter value.\n * - `innerOuter` — SpotLight `outerConeDeg <= innerConeDeg`. Inner cone is\n * the saturated bright region; outer cone is the falloff edge.\n * - `outerNinety` — SpotLight `outerConeDeg > 90`. KHR_lights_punctual upper\n * bound. A spot light cone wider than 90 degrees becomes a point light;\n * use PointLight instead.\n * - `direction` — DirectionalLight / SpotLight `direction` is missing or a\n * zero vector `[0, 0, 0]`. Direction has no default (there is no universal\n * default direction): omitting it lands the array layer-3 all-zero, which is\n * the same illegal state as an explicit zero vector. Supply a non-zero\n * direction (feat-20260709 M2 / D-1, add-only union member).\n *\n * `.code = 'spawn-light-invalid-bounds'`\n * `.detail.field` is derived from `keyof typeof SPAWN_LIGHT_INVALID_BOUNDS_POLICY`;\n * `.detail.got` is `number | readonly number[]`.\n * `.hint` — names the offending field plus the valid replacement form.\n */\nconst SPAWN_LIGHT_INVALID_BOUNDS_POLICY = {\n intensity: {\n expected: 'intensity is finite and >= 0',\n hint: (componentName: string, got: number | readonly number[]) =>\n `${componentName}.intensity must be a finite non-negative number (got ${got})`,\n },\n color: {\n expected: 'color is a finite non-negative [r, g, b] vector',\n hint: (componentName: string, got: number | readonly number[]) =>\n `${componentName}.color must contain three finite non-negative channels (got ${JSON.stringify(got)})`,\n },\n width: {\n expected: 'width is finite and > 0',\n hint: (componentName: string, got: number | readonly number[]) =>\n `${componentName}.width must be a finite positive meter value (got ${got})`,\n },\n height: {\n expected: 'height is finite and > 0',\n hint: (componentName: string, got: number | readonly number[]) =>\n `${componentName}.height must be a finite positive meter value (got ${got})`,\n },\n irradiance: {\n expected: 'irradiance is a finite 27-value SH vector',\n hint: (componentName: string, got: number | readonly number[]) =>\n `${componentName}.irradiance must contain 27 finite SH values (got ${JSON.stringify(got)})`,\n },\n radius: {\n expected: 'radius is finite and >= R_MIN',\n hint: (componentName: string, got: number | readonly number[]) =>\n `${componentName}.radius must be a finite value >= R_MIN (got ${got})`,\n },\n range: {\n expected: 'range >= 0 or Number.POSITIVE_INFINITY',\n hint: (componentName: string, got: number | readonly number[]) =>\n `${componentName}.range = ${got} is invalid; use Number.POSITIVE_INFINITY for unlimited range, or a non-negative meter value`,\n },\n innerOuter: {\n expected: 'outerConeDeg > innerConeDeg',\n hint: (componentName: string, got: number | readonly number[]) =>\n `${componentName}.outerConeDeg <= innerConeDeg (got ${got}); inner cone is the saturated bright region, outer cone is the falloff edge; outerConeDeg > innerConeDeg required`,\n },\n outerNinety: {\n expected: 'outerConeDeg <= 90 (KHR_lights_punctual upper bound)',\n hint: (componentName: string, got: number | readonly number[]) =>\n `${componentName}.outerConeDeg = ${got} > 90; a spot light cone wider than 90 degrees becomes a point light; use PointLight instead`,\n },\n direction: {\n expected: 'direction is a non-zero [x, y, z] vector',\n hint: (componentName: string, got: number | readonly number[]) =>\n `${componentName}.direction is missing or a zero vector (got ${JSON.stringify(got)}); direction has no default, provide a non-zero direction, e.g. [-0.5, -1, -0.3]`,\n },\n} satisfies Record<\n string,\n {\n readonly expected: string;\n readonly hint: (componentName: string, got: number | readonly number[]) => string;\n }\n>;\n\nexport class SpawnLightInvalidBoundsError extends Error {\n override readonly name = 'SpawnLightInvalidBoundsError';\n readonly code = 'spawn-light-invalid-bounds' as const;\n readonly hint: string;\n readonly expected: string;\n readonly detail: {\n readonly field: keyof typeof SPAWN_LIGHT_INVALID_BOUNDS_POLICY;\n readonly got: number | readonly number[];\n };\n\n constructor(\n componentName: string,\n field: keyof typeof SPAWN_LIGHT_INVALID_BOUNDS_POLICY,\n got: number | readonly number[],\n ) {\n const policy = SPAWN_LIGHT_INVALID_BOUNDS_POLICY[field];\n const hint = policy.hint(componentName, got);\n const expectedStr = policy.expected;\n super(\n `${componentName}: spawn payload bound violation.\\n` +\n ` code: spawn-light-invalid-bounds\\n` +\n ` component: ${componentName}\\n` +\n ` field: ${field}\\n` +\n ` got: ${got}\\n` +\n ` expected: ${expectedStr}\\n` +\n ` hint: ${hint}`,\n );\n this.hint = hint;\n this.expected = expectedStr;\n this.detail = { field, got };\n }\n}\n\n/**\n * Returned via `Result.err` from resource-setter helpers (e.g.\n * `setTransparentSortConfig`) when a numeric payload field violates the\n * closed bound declared by the resource contract. The first consumer is\n * `TransparentSortConfig.mode ∈ {0, 1, 2}` (plan-strategy D-4); future\n * resource validators with the same shape reuse this code by routing\n * through `.detail.receivedKey` to disambiguate which resource validator\n * surfaced the failure.\n *\n * Closed-set kebab code consistent with `spawn-light-invalid-bounds`\n * (feat-20260519 / w2); AI users consume via `switch (err.code)` exhaustive\n * narrows + `err.detail.receivedMode` (or `err.detail.receivedKey` /\n * `err.expected`) property access — never string-parse the message.\n *\n * `.code = 'resource-invalid-value'`\n * `.detail = { receivedMode: number; receivedKey?: string }`\n * `.hint` — direct copy-paste recovery (e.g. \"0=layer-z, 1=layer-y,\n * 2=layer-yz\" for the sort-config case).\n * `.expected` — the bound contract literal (e.g. \"mode ∈ {0, 1, 2}\").\n *\n * @reuses RhiError structured shape — same `.code / .expected / .hint /\n * .detail` quadruple AI users consume across rhi + ecs.\n */\nexport class ResourceInvalidValueError extends Error {\n override readonly name = 'ResourceInvalidValueError';\n readonly code = 'resource-invalid-value' as const;\n readonly hint: string;\n readonly expected: string;\n readonly detail: { readonly receivedMode: number; readonly receivedKey?: string };\n\n constructor(\n expected: string,\n hint: string,\n detail: { readonly receivedMode: number; readonly receivedKey?: string },\n ) {\n const keyClause = detail.receivedKey === undefined ? '' : ` key: ${detail.receivedKey}\\n`;\n super(\n `resource: invalid value.\\n` +\n ` code: resource-invalid-value\\n` +\n keyClause +\n ` receivedMode: ${detail.receivedMode}\\n` +\n ` expected: ${expected}\\n` +\n ` hint: ${hint}`,\n );\n this.hint = hint;\n this.expected = expected;\n this.detail = detail;\n }\n}\n\n// ────────────────────────────────────────────────────────────────────────────\n// feat-20260521-sprite-atlas-animation M1 T-05 — closed-union evolution +1.\n//\n// Adds 1 new member 'sprite-animation-invalid' to EcsErrorCode (25 -> 26).\n// AGENTS.md §Error model evolution contract: minor (add member only).\n// Same-shape add-only mirror of SpawnLightInvalidBoundsError (feat-20260519\n// w2 line 736-776) and ResourceInvalidValueError (feat-20260520 w13 line\n// 862) — the kebab `'<noun>-invalid-...'` series keeps `switch (err.code)`\n// exhaustive narrows visually consistent (charter P4 consistent abstraction;\n// research F-7 candidate A).\n//\n// Triggered by `spriteAnimationTickSystem` (packages/runtime/src/systems/\n// sprite-animation-tick.ts, landed in M4 T-23) when an entity's\n// `SpriteAnimation` row violates one of two runtime invariants:\n//\n// - field='regions-length' -> `regions.length !== frameCount * 4`\n// - field='frame-duration' -> `frameDuration <= 0`\n//\n// `.detail.field` two-branch (charter P3: AI users branch once on\n// `err.code` and once on `err.detail.field` to reach the recovery hint\n// without parsing the message). Plan-strategy section 2 D-1 binds the\n// detail field shape; M4 T-19 / T-20 / T-21 cover the runtime fail-fast\n// paths end-to-end.\n// ────────────────────────────────────────────────────────────────────────────\n\n/**\n * Returned via `Result.err` from `spriteAnimationTickSystem` (M4 T-23) when\n * an entity's `SpriteAnimation` row violates a runtime invariant.\n * Two invariants share one `.code` and discriminate via `.detail.field`:\n *\n * - `regions-length` — `SpriteAnimation.regions.length !== frameCount * 4`.\n * `regions` packs `[uMin, vMin, uW, vH]` per frame so the length must be\n * exactly `frameCount * 4`. Detail carries the offending `regionsLength`\n * alongside the declared `frameCount` so the hint can spell the exact\n * delta in callsite-friendly numbers.\n * - `frame-duration` — `SpriteAnimation.frameDuration <= 0` (covers both\n * `frameDuration === 0` and `frameDuration < 0`; T-21 binds the negative\n * case to the same arm so AI users handle both via a single\n * `if (err.detail.field === 'frame-duration')` branch — charter P4\n * consistent abstraction).\n *\n * `.code = 'sprite-animation-invalid'`\n * `.detail = { field: 'regions-length', regionsLength, frameCount } |\n * { field: 'frame-duration', frameDuration }`\n *\n * Two top-level detail variants give each `.field` branch its own\n * required sub-field shape so AI users get strong narrowing inside\n * `switch (err.detail.field)` without optional sub-fields bleeding\n * across branches (mirrors `SpawnLightInvalidBoundsError`'s shared\n * `got: number` shape but adapted because regions-length /\n * frame-duration carry different sub-field counts).\n *\n * `.hint` — names the offending invariant plus the valid replacement form.\n */\nexport class SpriteAnimationInvalidError extends Error {\n override readonly name = 'SpriteAnimationInvalidError';\n readonly code = 'sprite-animation-invalid' as const;\n readonly hint: string;\n readonly expected: string;\n readonly detail:\n | {\n readonly field: 'regions-length';\n readonly regionsLength: number;\n readonly frameCount: number;\n }\n | {\n readonly field: 'frame-duration';\n readonly frameDuration: number;\n };\n\n private static resolvePolicy(detail: SpriteAnimationInvalidError['detail']): {\n readonly expected: string;\n readonly hint: string;\n } {\n switch (detail.field) {\n case 'regions-length':\n return {\n expected: 'SpriteAnimation.regions.length === frameCount * 4',\n hint: `SpriteAnimation.regions.length = ${detail.regionsLength} does not match frameCount * 4 = ${detail.frameCount * 4}; pack 4 floats [uMin, vMin, uW, vH] per frame (see <name>.atlas.meta.json sidecar 'regions' map)`,\n };\n case 'frame-duration':\n return {\n expected: 'SpriteAnimation.frameDuration > 0',\n hint: `SpriteAnimation.frameDuration = ${detail.frameDuration} is invalid; use a positive seconds-per-frame value (e.g. 0.1 = 10 fps)`,\n };\n }\n }\n\n constructor(detail: SpriteAnimationInvalidError['detail']) {\n const policy = SpriteAnimationInvalidError.resolvePolicy(detail);\n super(\n `SpriteAnimation: invariant violated.\\n` +\n ` code: sprite-animation-invalid\\n` +\n ` field: ${detail.field}\\n` +\n ` expected: ${policy.expected}\\n` +\n ` hint: ${policy.hint}`,\n );\n this.hint = policy.hint;\n this.expected = policy.expected;\n this.detail = detail;\n }\n}\n","/**\n * ECS package-internal World seam.\n *\n * This module is intentionally not re-exported by the package entry points.\n * It keeps implementation access out of World's discoverable API while\n * retaining direct bound calls for the hot query and structural paths.\n */\n// Bundled ECS entry points (`index` and `projection`) each include this module\n// in their own closure. A plain Symbol() therefore gives World and projection\n// different property keys at runtime even though their source imports agree.\n// The registry is package-private by convention: no root/advanced export\n// exposes this key, while Symbol.for keeps source/dist and split bundles on\n// one identity.\nimport type { Result } from '@forgeax/engine-types';\nimport type { BufferPool } from './buffer-pool';\nimport type { Component, ComponentSchema, ShapeOf } from './component';\nimport type { EntityHandle } from './entity-handle';\nimport type { WorldExecutionFault } from './execution/shared-kernel';\nimport type { ResourceStore } from './resource';\nimport type { Schedule } from './schedule';\nimport type { ScheduleToken } from './schedule-token';\nimport type { SharedRefStore } from './shared-ref-store';\nimport type { Archetype } from './storage/archetype';\nimport type { ArchetypeGraph } from './storage/archetype-graph';\nimport type { ChangeTicks } from './storage/change-detection';\nimport type { StructuralEvidenceRing } from './storage/structural-evidence';\nimport type { Table } from './storage/table';\nimport type { ClockWriter } from './time';\nimport type { ComponentData, EcsError, EntityRecord } from './world';\n\n/** @internal Package-private identity; absent from the public export map. */\nexport const worldInternal: unique symbol = Symbol.for(\n 'forgeax.ecs.worldInternal',\n) as unknown as typeof worldInternal;\n\n/**\n * The one package-internal capability surface owned by World.\n *\n * Every member is explicit so an extraction cannot silently widen the seam or\n * leak an untyped state bag. The symbol itself remains package-private and is\n * the only route used by query, commands, and lifecycle helpers.\n */\n/** @internal Raw ECS owner seam; source-relative consumers only. */\nexport interface WorldInternal {\n readonly allocatePendingEntity: () => EntityHandle;\n readonly cancelPendingEntity: (entity: EntityHandle) => void;\n readonly getArrayView: (\n entity: EntityHandle,\n component: Component,\n fieldName: string,\n ) => ArrayLike<number> | undefined;\n readonly getBufferPool: () => BufferPool;\n readonly getClockWriter: () => ClockWriter;\n readonly getComponentChange: (\n entity: EntityHandle,\n componentId: number,\n ) => ChangeTicks | undefined;\n readonly getComponentMutationEpochs: () => readonly number[];\n readonly getEntityArchetype: (entity: EntityHandle) => Archetype | undefined;\n readonly getFixedAccumulator: () => number;\n readonly getGraph: () => ArchetypeGraph;\n readonly getMutationEpoch: () => number;\n readonly getQueryRow: (\n entity: EntityHandle,\n component: Component,\n ) => Result<Record<string, unknown>, EcsError>;\n readonly getRecords: () => EntityRecord[];\n readonly getRelationshipEpoch: (component: Component) => number;\n readonly getRelationshipTargetEntities: (\n component: Component,\n target: EntityHandle,\n ) => readonly EntityHandle[];\n readonly getResources: () => ResourceStore;\n readonly getSchedule: (token: ScheduleToken) => Schedule | undefined;\n readonly getSchedules: () => ReadonlyMap<ScheduleToken, Schedule>;\n readonly getSharedRefs: () => SharedRefStore;\n readonly getStructureEpoch: () => number;\n readonly getStructuralEvidence: () => StructuralEvidenceRing;\n readonly lookupAlive: (\n entity: EntityHandle,\n operation: string,\n component?: string,\n ) => Result<EntityRecord, EcsError>;\n readonly markComponentChanged: (entity: EntityHandle, componentId: number) => void;\n readonly markComponentRangeChanged: (\n table: Table,\n componentId: number,\n rowStart: number,\n rowCount: number,\n ) => void;\n readonly materializeEntity: (\n entity: EntityHandle,\n componentDatas: ComponentData[],\n ) => Result<void, EcsError>;\n readonly materializePendingEntity: (\n entity: EntityHandle,\n componentDatas: ComponentData[],\n ) => Result<void, EcsError>;\n readonly nextMutationEpoch: () => number;\n readonly poisonExecution: (fault: WorldExecutionFault) => void;\n readonly publishDerivedRange: (\n table: Table,\n componentId: number,\n rowStart: number,\n rowCount: number,\n epoch: number,\n ) => void;\n readonly preflightComponentData: (\n holder: EntityHandle | null,\n componentData: ComponentData,\n pendingEntities?: ReadonlySet<number>,\n unavailableEntities?: ReadonlySet<number>,\n ) => Result<void, EcsError>;\n readonly readRow: <S extends ComponentSchema>(\n archetype: Archetype,\n component: Component<string, S>,\n row: number,\n ) => ShapeOf<S>;\n readonly recordIsLive: (\n record: EntityRecord | undefined,\n generation: number,\n ) => record is EntityRecord;\n readonly routeError: (error: unknown, context?: { readonly systemName: string }) => void;\n readonly restoreMutationEpoch: (epoch: number) => void;\n readonly setFixedAccumulator: (value: number) => void;\n readonly setQueryRow: (\n entity: EntityHandle,\n component: Component,\n value: Record<string, unknown>,\n ) => Result<void, EcsError>;\n}\n","import type { Component, SchemaFieldType } from '../component';\nimport { componentId, componentSchema } from '../component';\nimport type { QueryDescriptor, QuerySpan } from '../query/query';\nimport type { SystemHandle } from '../schedule';\nimport { worldInternal } from '../world-internal';\n\nexport const SHARED_KERNEL_EXECUTOR_RESOURCE_KEY = 'SharedKernelExecutor';\n\nexport interface KernelDispatchResult {\n readonly mode: 'forced-inline' | 'shared';\n readonly dispatched: number;\n readonly completed: number;\n readonly waitMs: number;\n}\n\nexport interface KernelDispatchFailure {\n readonly cause: unknown;\n readonly dispatched: number;\n readonly completed: number;\n readonly partialWrite: boolean;\n}\n\nexport interface KernelDispatchSpan {\n readonly queryIndex: number;\n readonly span: QuerySpan;\n}\n\nexport interface SharedKernelExecutor {\n warmup?(kernel: SharedKernelDispatch): void;\n execute(\n kernel: SharedKernelDispatch,\n spans: readonly KernelDispatchSpan[],\n ): KernelDispatchResult | KernelDispatchFailure;\n}\n\nexport function isKernelDispatchFailure(\n value: KernelDispatchResult | KernelDispatchFailure,\n): value is KernelDispatchFailure {\n return 'cause' in value;\n}\n\nexport const SHARED_KERNEL_ELIGIBILITY_REASONS = [\n 'callback-not-module-function',\n 'dom-access',\n 'missing-access-declaration',\n 'descriptor-conflict',\n 'object-field',\n 'span-unavailable',\n] as const;\nexport type SharedKernelEligibilityReason = (typeof SHARED_KERNEL_ELIGIBILITY_REASONS)[number];\n\nexport type WorldExecutionHealth = 'healthy' | 'poisoned';\n\nexport interface WorldExecutionFault {\n readonly code: 'shared-kernel-failed';\n readonly kernelName: string;\n readonly cause: unknown;\n readonly partialWrite: boolean;\n readonly retryable: false;\n}\n\nexport interface WorldExecutionState {\n readonly identity: string;\n readonly health: WorldExecutionHealth;\n readonly fault: WorldExecutionFault | null;\n}\n\nlet nextWorldIdentity = 1;\n\nexport function createWorldIdentity(): string {\n const identity = `world-${nextWorldIdentity}`;\n nextWorldIdentity += 1;\n return identity;\n}\n\nexport function healthyWorldExecutionState(identity: string): WorldExecutionState {\n return Object.freeze({ identity, health: 'healthy', fault: null });\n}\n\nexport function poisonedWorldExecutionState(\n identity: string,\n fault: WorldExecutionFault,\n): WorldExecutionState {\n return Object.freeze({ identity, health: 'poisoned', fault: Object.freeze(fault) });\n}\n\nexport interface SharedKernelDefinition<Qs extends readonly QueryDescriptor[]> {\n readonly name: string;\n readonly queries: Qs;\n readonly run: (spans: readonly QuerySpan[]) => void;\n readonly minimumRows?: number;\n readonly before?: readonly (string | import('../schedule-token').ScheduleToken)[];\n readonly after?: readonly (string | import('../schedule-token').ScheduleToken)[];\n}\n\nexport interface SharedKernelDispatch<\n Qs extends readonly QueryDescriptor[] = readonly QueryDescriptor[],\n> {\n readonly kind: 'shared-kernel';\n readonly moduleUrl: string;\n readonly name: string;\n readonly minimumRows: number;\n readonly queries: Qs;\n readonly run: (spans: readonly QuerySpan[]) => void;\n}\n\nexport interface SharedKernelHandle<\n Qs extends readonly QueryDescriptor[] = readonly QueryDescriptor[],\n> extends SystemHandle<Qs>,\n SharedKernelDispatch<Qs> {}\n\nexport class SharedKernelEligibilityError extends Error {\n readonly code = 'shared-kernel-ineligible' as const;\n readonly expected =\n 'a module-loadable named kernel with one or more numeric QuerySpan read/write declarations';\n readonly hint =\n 'export a named function from the kernel module and use only dense numeric QuerySpan columns';\n readonly detail: { readonly kernelName: string; readonly reason: SharedKernelEligibilityReason };\n\n constructor(kernelName: string, reason: SharedKernelEligibilityReason) {\n super(`Shared kernel \"${kernelName}\" is ineligible: ${reason}.`);\n this.name = 'SharedKernelEligibilityError';\n this.detail = { kernelName, reason };\n }\n}\n\nexport class SharedKernelFailureError extends Error {\n readonly code = 'shared-kernel-failed' as const;\n readonly expected = 'every dispatched shard completes without a possible partial write';\n readonly hint =\n 'do not retry this World; inspect detail.cause and rebuild with a new World identity';\n readonly detail: {\n readonly kernelName: string;\n readonly worldIdentity: string;\n readonly cause: unknown;\n readonly partialWrite: boolean;\n readonly retryable: false;\n };\n\n constructor(kernelName: string, worldIdentity: string, cause: unknown, partialWrite: boolean) {\n super(`Shared kernel \"${kernelName}\" failed; World ${worldIdentity} is poisoned.`);\n this.name = 'SharedKernelFailureError';\n this.detail = { kernelName, worldIdentity, cause, partialWrite, retryable: false };\n }\n}\n\nexport class WorldPoisonedError extends Error {\n readonly code = 'world-poisoned' as const;\n readonly expected = 'World health is healthy before update';\n readonly hint = 'stop scheduling this World and explicitly bootstrap a new World identity';\n readonly detail: { readonly worldIdentity: string; readonly fault: unknown };\n\n constructor(worldIdentity: string, fault: unknown) {\n super(`World ${worldIdentity} is poisoned and cannot update.`);\n this.name = 'WorldPoisonedError';\n this.detail = { worldIdentity, fault };\n }\n}\n\nconst NUMERIC_FIELDS = new Set<SchemaFieldType>([\n 'f32',\n 'f64',\n 'i32',\n 'u32',\n 'i16',\n 'u16',\n 'i8',\n 'u8',\n 'bool',\n 'enum',\n 'ref',\n 'entity',\n]);\n\nfunction components(descriptor: QueryDescriptor): readonly Component[] {\n return [\n ...(descriptor.read ?? []),\n ...(descriptor.write ?? []),\n ...(descriptor.optional ?? []),\n ...(descriptor.with ?? []),\n ...(descriptor.without ?? []),\n ...(descriptor.changed ?? []),\n ...(descriptor.added ?? []),\n ];\n}\n\nfunction descriptorReason(descriptor: QueryDescriptor): SharedKernelEligibilityReason | undefined {\n if ((descriptor.read?.length ?? 0) + (descriptor.write?.length ?? 0) === 0) {\n return 'missing-access-declaration';\n }\n if (\n (descriptor.optional?.length ?? 0) > 0 ||\n (descriptor.changed?.length ?? 0) > 0 ||\n (descriptor.added?.length ?? 0) > 0\n ) {\n return 'span-unavailable';\n }\n const seen = new Set<number>();\n for (const component of components(descriptor)) {\n if (seen.has(componentId(component))) return 'descriptor-conflict';\n seen.add(componentId(component));\n if (component.storage === 'sparse') return 'span-unavailable';\n if (Object.values(componentSchema(component)).some((field) => !NUMERIC_FIELDS.has(field))) {\n return 'object-field';\n }\n }\n return undefined;\n}\n\nexport function sharedKernelEligibility(\n moduleUrl: string,\n definition: SharedKernelDefinition<readonly QueryDescriptor[]>,\n): SharedKernelEligibilityReason | undefined {\n try {\n new URL(moduleUrl);\n } catch {\n return 'callback-not-module-function';\n }\n const source = Function.prototype.toString.call(definition.run);\n if (definition.run.name.length === 0 || source.includes('=>')) {\n return 'callback-not-module-function';\n }\n if (/\\b(?:document|window|globalThis|HTMLElement|GPUDevice|AudioContext)\\b/u.test(source)) {\n return 'dom-access';\n }\n for (const query of definition.queries) {\n const reason = descriptorReason(query);\n if (reason !== undefined) return reason;\n }\n return undefined;\n}\n\nexport function defineSharedKernel<const Qs extends readonly QueryDescriptor[]>(\n moduleUrl: string,\n definition: SharedKernelDefinition<Qs>,\n): SharedKernelHandle<Qs> {\n const reason = sharedKernelEligibility(moduleUrl, definition);\n if (reason !== undefined) throw new SharedKernelEligibilityError(definition.name, reason);\n\n const handle: SharedKernelHandle<Qs> = Object.freeze({\n kind: 'shared-kernel' as const,\n moduleUrl,\n name: definition.name,\n queries: definition.queries,\n minimumRows: definition.minimumRows ?? 16_384,\n run: definition.run,\n ...(definition.before !== undefined ? { before: definition.before } : {}),\n ...(definition.after !== undefined ? { after: definition.after } : {}),\n fn: (world: import('../world').World, queries: Parameters<SystemHandle<Qs>['fn']>[1]) => {\n const dispatchSpans: KernelDispatchSpan[] = [];\n for (const [queryIndex, query] of queries.entries()) {\n const result = query.spans();\n if (!result.ok) throw new SharedKernelEligibilityError(definition.name, 'span-unavailable');\n for (const span of result.value) dispatchSpans.push({ queryIndex, span });\n }\n const spans = dispatchSpans.map((entry) => entry.span);\n const totalRows = spans.reduce((sum, span) => sum + span.length, 0);\n try {\n if (\n totalRows < (definition.minimumRows ?? 16_384) ||\n !world.hasResource(SHARED_KERNEL_EXECUTOR_RESOURCE_KEY)\n ) {\n definition.run(spans);\n return;\n }\n const executor = world.getResource<SharedKernelExecutor>(\n SHARED_KERNEL_EXECUTOR_RESOURCE_KEY,\n );\n const result = executor.execute(handle, dispatchSpans);\n if (isKernelDispatchFailure(result)) {\n if (!result.partialWrite) {\n definition.run(spans);\n return;\n }\n world[worldInternal].poisonExecution({\n code: 'shared-kernel-failed',\n kernelName: definition.name,\n cause: result.cause,\n partialWrite: result.partialWrite,\n retryable: false,\n });\n throw new SharedKernelFailureError(\n definition.name,\n world.execution.identity,\n result.cause,\n result.partialWrite,\n );\n }\n } catch (cause) {\n if (world.execution.health !== 'poisoned') {\n world[worldInternal].poisonExecution({\n code: 'shared-kernel-failed',\n kernelName: definition.name,\n cause,\n partialWrite: true,\n retryable: false,\n });\n }\n if (cause instanceof SharedKernelFailureError) throw cause;\n throw new SharedKernelFailureError(definition.name, world.execution.identity, cause, true);\n }\n },\n });\n return handle;\n}\n\nexport type SharedFieldView =\n | Float32Array\n | Float64Array\n | Int32Array\n | Uint32Array\n | Int16Array\n | Uint16Array\n | Int8Array\n | Uint8Array;\n\nexport interface SharedSpanBinding {\n readonly entities: Readonly<Uint32Array>;\n readonly length: number;\n readonly read: Readonly<Record<string, Readonly<Record<string, SharedFieldView>>>>;\n readonly write: Readonly<Record<string, Readonly<Record<string, SharedFieldView>>>>;\n}\n\nfunction sliceFields(\n fields: Readonly<Record<string, SharedFieldView>>,\n start: number,\n end: number,\n): Readonly<Record<string, SharedFieldView>> {\n return Object.fromEntries(\n Object.entries(fields).map(([name, view]) => [name, view.subarray(start, end)]),\n );\n}\n\nexport function bindSharedSpan(\n kernel: SharedKernelDispatch,\n span: QuerySpan,\n queryIndex: number,\n): SharedSpanBinding {\n const descriptor = kernel.queries[queryIndex];\n if (descriptor === undefined) throw new Error(`Missing query descriptor ${queryIndex}.`);\n const read = Object.fromEntries(\n (descriptor.read ?? []).map((component) => [\n component.name,\n span.get(component) as unknown as Record<string, SharedFieldView>,\n ]),\n );\n const write = Object.fromEntries(\n (descriptor.write ?? []).map((component) => [\n component.name,\n span.mut(component) as unknown as Record<string, SharedFieldView>,\n ]),\n );\n return { entities: span.entities, length: span.length, read, write };\n}\n\nexport function splitSharedSpan(\n binding: SharedSpanBinding,\n shardCount: number,\n): readonly SharedSpanBinding[] {\n if (binding.length === 0 || shardCount <= 0) return [];\n const count = Math.min(binding.length, shardCount);\n const shards: SharedSpanBinding[] = [];\n for (let index = 0; index < count; index += 1) {\n const start = Math.floor((binding.length * index) / count);\n const end = Math.floor((binding.length * (index + 1)) / count);\n shards.push({\n entities: binding.entities.subarray(start, end),\n length: end - start,\n read: Object.fromEntries(\n Object.entries(binding.read).map(([component, fields]) => [\n component,\n sliceFields(fields, start, end),\n ]),\n ),\n write: Object.fromEntries(\n Object.entries(binding.write).map(([component, fields]) => [\n component,\n sliceFields(fields, start, end),\n ]),\n ),\n });\n }\n return shards;\n}\n\nexport function isSharedSpan(binding: SharedSpanBinding): boolean {\n if (typeof SharedArrayBuffer === 'undefined') return false;\n if (!(binding.entities.buffer instanceof SharedArrayBuffer)) return false;\n return [...Object.values(binding.read), ...Object.values(binding.write)].every((fields) =>\n Object.values(fields).every((view) => view.buffer instanceof SharedArrayBuffer),\n );\n}\n","// @forgeax/engine-ecs — typed error class collection.\n//\n// Typed error classes covering all boundary conditions. Each follows progressive\n// disclosure format: one-line summary → context fields → hint fix suggestion.\n// Each exposes a `.hint` readonly property for programmatic extraction.\n\nimport type { QuerySpanUnavailableReason } from './errors/query-and-component-errors';\n\n// ────────────────────────────────────────────────────────────────────────────\n// Re-exports from split error sub-files (w3-b — package cohesion split)\n// ────────────────────────────────────────────────────────────────────────────\n\nexport {\n ComponentNotDefinedError,\n QueryDataRequiresFieldsError,\n QueryDescriptorConflictError,\n QueryIterationActiveError,\n QueryIterationInvalidatedError,\n QuerySpanUnavailableError,\n type QuerySpanUnavailableReason,\n RemoveEssentialComponentError,\n SpawnDataUnknownFieldError,\n} from './errors/query-and-component-errors';\n\nexport {\n RelationshipDetachMismatchError,\n RelationshipMirrorComponentNotRegisteredError,\n RelationshipMirrorFieldTypeMismatchError,\n RelationshipSelfCycleError,\n RelationshipTargetReadonlyError,\n} from './errors/relationship-errors';\nexport {\n SharedFieldInvalidValueError,\n SpriteInstancesCountMismatchError,\n SpriteInstancesMutuallyExclusiveWithInstancesError,\n SpriteInstancesRequiresSpriteShaderError,\n} from './errors/sprite-and-shared-errors';\nexport {\n ComponentFieldInvalidValueError,\n ComponentNumericValueInvalidError,\n ManagedArrayInvalidValueError,\n ResourceInvalidValueError,\n ScheduleScopeMismatchError,\n SpawnLightInvalidBoundsError,\n SpriteAnimationInvalidError,\n TimeConfigInvalidError,\n TimeDeltaInvalidError,\n validateEnumFieldValues,\n validateNumericFieldValues,\n} from './errors/validation-errors';\n\nexport {\n SharedKernelEligibilityError,\n SharedKernelFailureError,\n WorldPoisonedError,\n} from './execution/shared-kernel';\n\n/**\n * Thrown when an attempt is made to encode an entity index that does not fit\n * in 24 bits (i.e. >= 2^24 = 16_777_216).\n *\n * `.code = 'entity-index-overflow'`\n * `.hint` — suggests reducing entity count or investigating leaks.\n */\nexport class EntityIndexOverflowError extends RangeError {\n override readonly name = 'EntityIndexOverflowError';\n readonly code = 'entity-index-overflow' as const;\n readonly hint: string;\n\n constructor(index: number) {\n const hint =\n 'Entity index exceeds 24-bit max (16777215). Reduce simultaneous entity count or investigate entity leaks.';\n super(\n `Entity index ${index} exceeds 24-bit max (16777215).\\n` +\n ` index: ${index}\\n` +\n ` hint: ${hint}`,\n );\n this.hint = hint;\n }\n}\n\n/**\n * Thrown when `defineComponent` is given a field type that is not in the\n * supported scalar field type set.\n *\n * `.code = 'schema-unsupported-field'`\n * `.hint` — lists all supported scalar field types.\n */\nexport class SchemaUnsupportedFieldError extends Error {\n override readonly name = 'SchemaUnsupportedFieldError';\n readonly code = 'schema-unsupported-field' as const;\n readonly hint: string;\n\n constructor(fieldName: string, fieldType: string) {\n let hint = 'Supported types: f32 / f64 / i32 / u32 / i16 / u16 / i8 / u8 / bool / enum / ref.';\n // feat-20260614 M1 / M5: explicit migration hints for the two\n // retired schema-vocab keyword families. Both renames preserve brand\n // and storage layout (u32 column); only the keyword + dispatch arm\n // changed. AI users hitting either literal land directly on the new\n // keyword instead of grepping for the rename note (charter F1\n // single-entry indexability).\n if (fieldType.startsWith('handle<') && fieldType.endsWith('>')) {\n const tag = fieldType.slice(7, -1);\n hint = `'handle<${tag}>' was removed in feat-20260614 M5; use 'shared<${tag}>' instead. The brand and storage layout are unchanged; only the keyword + write-barrier dispatch (SharedRefStore retain/release) is new.`;\n } else if (fieldType.startsWith('ref<') && fieldType.endsWith('>')) {\n const tag = fieldType.slice(4, -1);\n hint = `'ref<${tag}>' was renamed in feat-20260614 M1; use 'unique<${tag}>' instead. The brand and storage layout are unchanged; the dispatch still routes through UniqueRefStore (single-holder direct release).`;\n }\n super(\n `Schema field \"${fieldName}\" has unsupported type \"${fieldType}\".\\n` +\n ` field: ${fieldName}\\n` +\n ` type: ${fieldType}\\n` +\n ` hint: ${hint}`,\n );\n this.hint = hint;\n }\n}\n\nexport class SparseStorageRequiresTagError extends Error {\n override readonly name = 'SparseStorageRequiresTagError';\n readonly code = 'sparse-storage-requires-tag' as const;\n readonly expected = 'sparse components have an empty schema and no relationship metadata';\n readonly hint = 'remove all fields and relationship metadata, or use storage: table';\n readonly detail: { readonly componentName: string };\n\n constructor(componentName: string) {\n super(\n `Sparse component \"${componentName}\" must be a zero-field, non-relationship tag.\\n` +\n ` component: ${componentName}\\n` +\n ` hint: remove all fields and relationship metadata, or use storage: table`,\n );\n this.detail = { componentName };\n }\n}\n\n/**\n * Thrown (or returned via the `Result` err branch — `r.ok === false`, `r.error`)\n * when get/set/addComponent/removeComponent is called on an entity that has\n * been despawned (stale handle).\n *\n * `.code = 'stale-entity'`\n * `.hint` — includes operation name, expected/actual generation, and component name.\n * Enhanced fields: `.component`, `.operation`, `.expectedGeneration`, `.actualGeneration`.\n */\nexport class StaleEntityError extends Error {\n override readonly name = 'StaleEntityError';\n readonly code = 'stale-entity' as const;\n readonly hint: string;\n\n /** Component name involved in the operation (undefined when the operation does not target a specific component). */\n readonly component: string | undefined;\n /** The component-level operation that triggered this error (e.g. 'get' / 'set' / 'add' / 'remove'). Entity-level operations like `despawn` are not surfaced here — see `EntityHandle` lifecycle errors. */\n readonly operation: string | undefined;\n /** The generation the caller expected (from the entity handle). */\n readonly expectedGeneration: number | undefined;\n /**\n * The actual generation found in the entity pool. `-1` is the sentinel\n * value for entities never allocated (slot was never occupied), as opposed\n * to allocated-then-despawned entities which carry a real (incremented)\n * generation number.\n */\n readonly actualGeneration: number | undefined;\n\n constructor(\n entityId: number,\n index: number,\n generation: number,\n enhanced?: {\n component?: string;\n operation: string;\n expectedGeneration: number;\n actualGeneration: number;\n },\n ) {\n const hint = enhanced\n ? `Entity was despawned. Operation \"${enhanced.operation}\" on entity ${entityId}` +\n (enhanced.component ? ` (component: ${enhanced.component})` : '') +\n ` expected generation ${enhanced.expectedGeneration}, found ${enhanced.actualGeneration}.` +\n ' Check entity lifecycle before access.'\n : 'Entity was despawned. Check entity lifecycle before access.';\n super(\n `Operation on stale entity handle.\\n` +\n ` entity: ${entityId} (index=${index}, generation=${generation})\\n` +\n (enhanced ? ` operation: ${enhanced.operation}\\n` : '') +\n (enhanced?.component ? ` component: ${enhanced.component}\\n` : '') +\n ` hint: ${hint}`,\n );\n this.hint = hint;\n this.component = enhanced?.component;\n this.operation = enhanced?.operation;\n this.expectedGeneration = enhanced?.expectedGeneration;\n this.actualGeneration = enhanced?.actualGeneration;\n }\n}\n\n/**\n * Returned via the `Result` err branch (`r.ok === false`, `r.error`) when\n * addComponent tries to add a component that the entity already possesses.\n *\n * `.code = 'component-already-present'`\n * `.hint` — suggests using `set()` to update values instead.\n */\nexport class ComponentAlreadyPresentError extends Error {\n override readonly name = 'ComponentAlreadyPresentError';\n readonly code = 'component-already-present' as const;\n readonly hint: string;\n\n constructor(entityId: number, componentName: string) {\n const hint = 'Entity already has this component. Use set() to update values.';\n super(\n `Entity ${entityId} already has component \"${componentName}\".\\n` +\n ` entity: ${entityId}\\n` +\n ` component: ${componentName}\\n` +\n ` hint: ${hint}`,\n );\n this.hint = hint;\n }\n}\n\n/**\n * Returned via the `Result` err branch (`r.ok === false`, `r.error`) when\n * removeComponent / set is called for a component the entity does not possess.\n *\n * `.code = 'component-not-present'`\n * `.hint` — suggests checking with query or inspect().\n */\nexport class ComponentNotPresentError extends Error {\n override readonly name = 'ComponentNotPresentError';\n readonly code = 'component-not-present' as const;\n readonly hint: string;\n\n constructor(entityId: number, componentName: string) {\n const hint = 'Entity does not have this component. Check with query or inspect().';\n super(\n `Entity ${entityId} does not have component \"${componentName}\".\\n` +\n ` entity: ${entityId}\\n` +\n ` component: ${componentName}\\n` +\n ` hint: ${hint}`,\n );\n this.hint = hint;\n }\n}\n\n/**\n * Thrown when DAG Schedule detects a cyclic dependency among systems.\n *\n * `.code = 'cyclic-dependency'`\n * `.hint` — includes the cycle path and suggests removing one constraint.\n * `.detail` — `{ code: 'cyclic-dependency'; cycle: readonly string[] }` contains the\n * structured cycle path for programmatic consumption.\n */\nexport class CyclicDependencyError extends Error {\n override readonly name = 'CyclicDependencyError';\n readonly code = 'cyclic-dependency' as const;\n readonly expected = 'the schedule dependency graph is acyclic';\n readonly hint: string;\n /** Structured cycle path — programmatic consumers read this, not the message. */\n readonly detail: { readonly code: 'cyclic-dependency'; readonly cycle: readonly string[] };\n\n constructor(cycle: readonly string[]) {\n const cycleStr = cycle.join(' -> ');\n const hint = `Cycle path: ${cycleStr}. Remove one ordering constraint to break the cycle.`;\n super(`DAG Schedule has a cyclic dependency.\\n cycle: ${cycleStr}\\n hint: ${hint}`);\n this.hint = hint;\n this.detail = { code: 'cyclic-dependency' as const, cycle };\n }\n}\n\n/**\n * Returned via `Result.err` from `world.addSystems`\n * when a SystemSet token fails local structural validation.\n *\n * The sole public invalid-token error type (D-2a). Covers all rejection\n * scenarios: plain-object cast, unregistered name, stale token after\n * overwrite, and cross-realm copies.\n *\n * `.code = 'system-set-not-registered'`\n * `.expected` — the name of the unregistered token.\n * `.hint` — suggests passing the current token to the owning World schedule.\n * `.detail` — `{ code, name, registered }` where `registered` is a deterministic snapshot\n * of the current World-local schedule keys.\n */\nexport class SystemSetNotRegisteredError extends Error {\n override readonly name = 'SystemSetNotRegisteredError';\n readonly code = 'system-set-not-registered' as const;\n /** The name carried by the rejected token. */\n readonly expected: string;\n readonly hint: string;\n /** Deterministic snapshot of the current World-local schedule for repair. */\n readonly detail: {\n readonly code: 'system-set-not-registered';\n readonly name: string;\n readonly registered: readonly string[];\n };\n\n constructor(name: string, registered: readonly string[]) {\n const hint =\n `SystemSet \"${name}\" is not valid for the current World schedule. ` +\n `Pass a non-empty SystemSet token owned by this World schedule.`;\n const message =\n `SystemSet \"${name}\" is not registered.\\n` +\n ` expected: ${name}\\n` +\n ` registered: [${registered.join(', ')}]\\n` +\n ` hint: ${hint}`;\n super(message);\n this.expected = name;\n this.hint = hint;\n this.detail = { code: 'system-set-not-registered' as const, name, registered };\n }\n}\n\n/**\n * Factory for {@link SystemSetNotRegisteredError}. Consumed by\n * {@link validateSystemSetTokens} (w4) and the two mutation entry points.\n */\nexport function systemSetNotRegistered(\n name: string,\n registered: readonly string[],\n): SystemSetNotRegisteredError {\n return new SystemSetNotRegisteredError(name, registered);\n}\n\n/**\n * Closed-set ScheduleMutationError code union (M2 — plan-strategy D-3).\n *\n * Schedule add-only API (`removeSystem` / `replaceSystem`) returns\n * `Result<void, ScheduleMutationError>` carrying one of these codes. The\n * `@forgeax/engine-remote` layer (M3) bridges these strings to JSON-RPC\n * `RemoteErrorCode` 1:1 — keeping ECS free of console / wire dependencies.\n *\n * - `system-before-unknown` — name argument does not match any registered system.\n * - `system-name-conflict` — reserved for the M3 inject path; surfaced from\n * schedule when callers inject a name that already exists.\n * - `cyclic-injection` — schedule build detected a cycle introduced by\n * the mutation; carries the cycle path in `.detail.cycle`.\n */\nexport type ScheduleMutationErrorCode = 'system-before-unknown';\n\nexport interface ScheduleMutationErrorDetail {\n readonly cycle?: readonly string[];\n readonly candidates?: readonly string[];\n}\n\n/**\n * Returned via `Result.err` from `world.removeSystem` / `world.replaceSystem`.\n *\n * `.code` is the closed-set string SSOT consumed by the M3 console bridge;\n * `.hint` carries an AI-friendly self-repair suggestion; `.detail` is the\n * discriminated payload (cycle path for `cyclic-injection`, candidate list\n * for `system-before-unknown`).\n */\nexport class ScheduleMutationError extends Error {\n override readonly name = 'ScheduleMutationError';\n readonly code: ScheduleMutationErrorCode;\n readonly hint: string;\n readonly detail: ScheduleMutationErrorDetail;\n\n constructor(\n code: ScheduleMutationErrorCode,\n message: string,\n hint: string,\n detail: ScheduleMutationErrorDetail = {},\n ) {\n super(`${message}\\n code: ${code}\\n hint: ${hint}`);\n this.code = code;\n this.hint = hint;\n this.detail = detail;\n }\n}\n\n/**\n * Thrown when getResource is called with a key that does not exist.\n *\n * `.code = 'resource-not-found'`\n * `.hint` — suggests using `world.insertResource()` first.\n */\nexport class ResourceNotFoundError extends Error {\n override readonly name = 'ResourceNotFoundError';\n readonly code = 'resource-not-found' as const;\n readonly hint: string;\n\n constructor(key: string) {\n const hint = `Resource \"${key}\" not found. Insert with world.insertResource() first.`;\n super(`Resource \"${key}\" not found.\\n` + ` key: ${key}\\n` + ` hint: ${hint}`);\n this.hint = hint;\n }\n}\n\nexport class ChangeEpochExhaustedError extends Error {\n override readonly name = 'ChangeEpochExhaustedError';\n readonly code = 'change-epoch-exhausted' as const;\n readonly expected = 'mutationEpoch < Number.MAX_SAFE_INTEGER';\n readonly hint = 'Rebuild the World before performing another mutation.';\n readonly detail: { readonly epoch: number };\n\n constructor(epoch: number) {\n super(`World mutation epoch is exhausted at ${epoch}.\\n hint: Rebuild the World.`);\n this.detail = { epoch };\n }\n}\n\nexport class DerivedRangeOutOfBoundsError extends Error {\n override readonly name = 'DerivedRangeOutOfBoundsError';\n readonly code = 'derived-range-out-of-bounds' as const;\n readonly expected = 'a non-negative span-relative range with start + count <= span.length';\n readonly hint =\n 'check start and count against the QuerySpan length, then retry without changing World state';\n readonly detail: { readonly start: number; readonly count: number; readonly spanLength: number };\n\n constructor(start: number, count: number, spanLength: number) {\n super(`Derived range [${start}, ${start + count}) exceeds QuerySpan length ${spanLength}.`);\n this.detail = { start, count, spanLength };\n }\n}\n\n/**\n * Thrown when insertResource/removeResource is called on a World-owned\n * protected resource (Time or FixedTime).\n *\n * `.code = 'resource-protected'`\n * `.hint` — suggests using `world.update(delta)` or reading the resource.\n * `.expected` — the resource name that was rejected.\n */\nexport class ProtectedResourceError extends Error {\n override readonly name = 'ProtectedResourceError';\n readonly code = 'resource-protected' as const;\n readonly hint: string;\n readonly expected: string;\n\n constructor(resourceName: string, operation: 'insert' | 'remove') {\n const hint =\n operation === 'insert'\n ? `\"${resourceName}\" is a World-owned protected resource. It is advanced by world.update(delta); read it via world.getResource(${resourceName}).`\n : `\"${resourceName}\" is a World-owned protected resource. It is owned by the World scheduler and cannot be removed.`;\n const expected = `a user-owned resource key (not ${resourceName})`;\n super(\n `Protected resource \"${resourceName}\" cannot be ${operation}ed.\\n` +\n ` code: resource-protected\\n` +\n ` resource: ${resourceName}\\n` +\n ` expected: ${expected}\\n` +\n ` hint: ${hint}`,\n );\n this.hint = hint;\n this.expected = expected;\n }\n}\n\n// ────────────────────────────────────────────────────────────────────────────\n// w5 — managed-* closed-union extension (M0).\n//\n// Four error classes covering the managed-* family:\n//\n// managed-* : UniqueRefStore + BufferPool runtime fail-fast.\n// Returned via Result.err from M1 / M2 storage paths.\n//\n// `.code` uses lowercase-kebab literals consistent with `ScheduleMutationErrorCode`\n// (the prior closed-set convention). The 9 legacy errors keep their\n// SCREAMING_SNAKE_CASE codes — codes are append-only per the evolution contract.\n// `EcsErrorCode` (declared at the foot of this file) merges all literal codes\n// into one closed union; downstream `switch (err.code)` is exhaustive.\n//\n// Every detail object is a discriminated payload — narrowed per `.code` via\n// `EcsErrorDetail` (also at foot of file).\n// ────────────────────────────────────────────────────────────────────────────\n\n/**\n * Thrown / returned via `Result.err` when UniqueRefStore.alloc encounters a\n * slot whose refcount has already dropped to zero (sentinel for a released\n * slot reused without re-init).\n *\n * `.code = 'unique-ref-released'`\n * `.detail = { handle, target }`\n * `.hint` — recommends checking handle lifetime against owner despawn.\n */\nexport class UniqueRefReleasedError extends Error {\n override readonly name = 'UniqueRefReleasedError';\n readonly code = 'unique-ref-released' as const;\n readonly hint: string;\n readonly expected: string;\n readonly detail: { readonly handle: number; readonly target: string };\n\n constructor(handle: number, target: string) {\n const hint = `Handle ${handle} (target ${target}) was released before this access. Re-acquire via the producing system or re-spawn the asset before reading.`;\n const expected = 'live (refcount >= 1) managed handle';\n super(\n `UniqueRefStore: handle is already released.\\n` +\n ` code: unique-ref-released\\n` +\n ` handle: ${handle}\\n` +\n ` target: ${target}\\n` +\n ` expected: ${expected}\\n` +\n ` hint: ${hint}`,\n );\n this.hint = hint;\n this.expected = expected;\n this.detail = { handle, target };\n }\n}\n\n/**\n * Thrown / returned via `Result.err` when UniqueRefStore.release is called on\n * a handle whose refcount is already zero (double-free).\n *\n * `.code = 'unique-ref-double-release'`\n * `.detail = { handle, target }`\n * `.hint` — recommends auditing the release-loop entry points (set / removeComponent / despawn).\n */\nexport class UniqueRefDoubleReleaseError extends Error {\n override readonly name = 'UniqueRefDoubleReleaseError';\n readonly code = 'unique-ref-double-release' as const;\n readonly hint: string;\n readonly expected: string;\n readonly detail: { readonly handle: number; readonly target: string };\n\n constructor(handle: number, target: string) {\n const hint = `Handle ${handle} (target ${target}) was released twice. Only one of {despawn / removeComponent / set} should release a managed handle per lifecycle.`;\n const expected = 'first release of a managed handle (refcount transition 1 -> 0)';\n super(\n `UniqueRefStore: double release on handle.\\n` +\n ` code: unique-ref-double-release\\n` +\n ` handle: ${handle}\\n` +\n ` target: ${target}\\n` +\n ` expected: ${expected}\\n` +\n ` hint: ${hint}`,\n );\n this.hint = hint;\n this.expected = expected;\n this.detail = { handle, target };\n }\n}\n\n// ────────────────────────────────────────────────────────────────────────────\n// feat-20260614-ecs-shared-component-and-unique-rename M3 — SharedRefStore\n// closed-union extension (+2). Mirrors the UniqueRef* pair — `'shared-ref-released'`\n// covers resolve-after-release / retain-after-release; `'shared-ref-double-release'`\n// covers release-when-rc-already-zero. Both are Result.err returns (not throws);\n// AI users branch on `.code` and read `.detail.handle` for the offending slot.\n//\n// Detail field shape mirrors UniqueRef* with one addition (`rc`) so AI users\n// debugging a double-release see the exact rc transition that surfaced the\n// failure (charter P3 progressive disclosure). Empty `target` handled the\n// same way as UniqueRef* — runtime-erased phantom, surfaced as '<unknown>'.\n// ────────────────────────────────────────────────────────────────────────────\n\n/**\n * Thrown / returned via `Result.err` when SharedRefStore.resolve / .retain is\n * called on a handle whose refcount has already dropped to zero (slot released).\n *\n * `.code = 'shared-ref-released'`\n * `.detail = { handle, target }`\n * `.hint` — recommends checking handle lifetime against owner / consumer release.\n */\nexport class SharedRefReleasedError extends Error {\n override readonly name = 'SharedRefReleasedError';\n readonly code = 'shared-ref-released' as const;\n readonly hint: string;\n readonly expected: string;\n readonly detail: { readonly handle: number; readonly target: string };\n\n constructor(handle: number, target: string) {\n const hint = `Handle ${handle} (target ${target}) was released (refcount reached 0). Re-acquire via the producing system or re-spawn the asset before reading.`;\n const expected = 'live (refcount >= 1) shared handle';\n super(\n `SharedRefStore: handle is already released.\\n` +\n ` code: shared-ref-released\\n` +\n ` handle: ${handle}\\n` +\n ` target: ${target}\\n` +\n ` expected: ${expected}\\n` +\n ` hint: ${hint}`,\n );\n this.hint = hint;\n this.expected = expected;\n this.detail = { handle, target };\n }\n}\n\n/**\n * Thrown / returned via `Result.err` when SharedRefStore.release is called on\n * a handle whose refcount is already zero (double-release). Distinct from the\n * UniqueRef family because shared release is rc--, not direct slot drop —\n * AI users debug this by reading `.detail.rc` (always 0 here) alongside the\n * payload-presence signal.\n *\n * `.code = 'shared-ref-double-release'`\n * `.detail = { handle, target, rc }`\n * `.hint` — recommends auditing the producer / consumer release pairs.\n */\nexport class SharedRefDoubleReleaseError extends Error {\n override readonly name = 'SharedRefDoubleReleaseError';\n readonly code = 'shared-ref-double-release' as const;\n readonly hint: string;\n readonly expected: string;\n readonly detail: { readonly handle: number; readonly target: string; readonly rc: number };\n\n constructor(handle: number, target: string, rc: number) {\n const hint = `Handle ${handle} (target ${target}) released with rc=${rc}. Each shared handle must have a matching alloc/retain for every release; audit the producer / consumer release pairs.`;\n const expected = 'rc >= 1 before release';\n super(\n `SharedRefStore: double release on handle.\\n` +\n ` code: shared-ref-double-release\\n` +\n ` handle: ${handle}\\n` +\n ` target: ${target}\\n` +\n ` rc: ${rc}\\n` +\n ` expected: ${expected}\\n` +\n ` hint: ${hint}`,\n );\n this.hint = hint;\n this.expected = expected;\n this.detail = { handle, target, rc };\n }\n}\n\n/** Raised before SharedRefStore mutates slot state for a nullish payload. */\nexport class SharedRefPayloadInvalidError extends Error {\n override readonly name = 'SharedRefPayloadInvalidError';\n readonly code = 'shared-ref-payload-invalid' as const;\n readonly expected = 'a non-null, non-undefined shared payload';\n readonly hint = 'Allocate a concrete payload and let its owning effect dispose it.';\n readonly detail: { readonly target: string; readonly actual: 'null' | 'undefined' };\n\n constructor(target: string, actual: 'null' | 'undefined') {\n super(`SharedRefStore: ${actual} payload is not a valid shared reference for ${target}.`);\n this.detail = { target, actual };\n }\n}\n\n/**\n * Returned via `Result.err` when a builtin-tier slot (`slot < BUILTIN_BASE`)\n * is passed to SharedRefStore.alloc / retain / release / resolve\n * (feat-20260614 M6 D-15). The SharedRefStore manages ONLY user-tier slots\n * (`>= BUILTIN_BASE`); builtin asset payloads are process-static and owned by\n * the package that authored their builtin handle, never reference-counted by\n * this World store.\n *\n * `.code = 'builtin-slot-not-owned'`\n * `.detail = { slot }`\n * `.hint` — points the caller back to the builtin handle owner.\n */\nexport class BuiltinSlotNotOwnedError extends Error {\n override readonly name = 'BuiltinSlotNotOwnedError';\n readonly code = 'builtin-slot-not-owned' as const;\n readonly hint: string;\n readonly expected: string;\n readonly detail: { readonly slot: number };\n\n constructor(slot: number) {\n const hint = `Slot ${slot} is a builtin-tier handle (< BUILTIN_BASE). World.sharedRefs manages only user-tier handles (>= BUILTIN_BASE). Obtain the builtin payload from the package that authored the handle; builtin payloads are process-static and never reference-counted by this World.`;\n const expected = 'user-tier slot (>= BUILTIN_BASE)';\n super(\n `SharedRefStore: builtin slot is not owned by this store.\\n` +\n ` code: builtin-slot-not-owned\\n` +\n ` slot: ${slot}\\n` +\n ` expected: ${expected}\\n` +\n ` hint: ${hint}`,\n );\n this.hint = hint;\n this.expected = expected;\n this.detail = { slot };\n }\n}\n\n// ────────────────────────────────────────────────────────────────────────────\n// feat-20260623-asset-handle-generation M4 — stale error classes (+2).\n//\n// Two error classes covering gen-based staleness detection in SharedRefStore\n// and UniqueRefStore. Distinguish from the existing `*-ref-released` codes\n// (slot empty / never allocated) — `*-ref-stale` means the slot has been\n// released AND re-allocated, so the caller's handle generation no longer\n// matches the store's current generation. AI users pick different recovery\n// strategies: released -> re-load the asset; stale -> re-acquire the handle\n// from AssetRegistry (charter P3 explicit failure, two semantics two\n// recovery paths).\n//\n// `.detail` carries { slot, expectedGeneration, actualGeneration } aligned\n// with StaleEntityError field names (AC-11). Codes are add-only minor\n// members of EcsErrorCode (AC-10) and detail shapes extend EcsErrorDetail\n// discriminator.\n// ────────────────────────────────────────────────────────────────────────────\n\n/**\n * Returned via `Result.err` when SharedRefStore.resolve / .retain / .release\n * is called with a handle whose generation no longer matches the store's\n * current generation for that slot — the slot was released and re-allocated\n * to a different payload. Distinct from `'shared-ref-released'` (slot empty,\n * never re-allocated): stale means the slot IS live but belongs to a newer\n * allocation.\n *\n * `.code = 'shared-ref-stale'`\n * `.detail = { slot, expectedGeneration, actualGeneration }`\n * `.hint` — recommends re-acquiring the handle from AssetRegistry.\n */\nexport class SharedRefStaleError extends Error {\n override readonly name = 'SharedRefStaleError';\n readonly code = 'shared-ref-stale' as const;\n readonly hint: string;\n readonly expected: string;\n readonly detail: {\n readonly slot: number;\n readonly expectedGeneration: number;\n readonly actualGeneration: number;\n };\n\n constructor(slot: number, expectedGeneration: number, actualGeneration: number) {\n const hint = `Handle for slot ${slot} is stale: expected generation ${expectedGeneration}, but the store has generation ${actualGeneration} (slot was released and re-allocated). Re-acquire the handle from AssetRegistry.`;\n const expected = `generation === ${actualGeneration} (current store generation)`;\n super(\n `SharedRefStore: stale handle.\\n` +\n ` code: shared-ref-stale\\n` +\n ` slot: ${slot}\\n` +\n ` expectedGeneration: ${expectedGeneration}\\n` +\n ` actualGeneration: ${actualGeneration}\\n` +\n ` expected: ${expected}\\n` +\n ` hint: ${hint}`,\n );\n this.hint = hint;\n this.expected = expected;\n this.detail = { slot, expectedGeneration, actualGeneration };\n }\n}\n\n/**\n * Returned via `Result.err` when UniqueRefStore.resolve / .release is\n * called with a handle whose generation no longer matches the store's\n * current generation for that slot — the slot was released and re-allocated.\n * Distinct from `'unique-ref-released'` (slot empty). UniqueRefStore has\n * no retain method; the stale surface is resolve + release only.\n *\n * `.code = 'unique-ref-stale'`\n * `.detail = { slot, expectedGeneration, actualGeneration }`\n * `.hint` — recommends re-acquiring the handle from the producing system.\n */\nexport class UniqueRefStaleError extends Error {\n override readonly name = 'UniqueRefStaleError';\n readonly code = 'unique-ref-stale' as const;\n readonly hint: string;\n readonly expected: string;\n readonly detail: {\n readonly slot: number;\n readonly expectedGeneration: number;\n readonly actualGeneration: number;\n };\n\n constructor(slot: number, expectedGeneration: number, actualGeneration: number) {\n const hint = `Handle for slot ${slot} is stale: expected generation ${expectedGeneration}, but the store has generation ${actualGeneration} (slot was released and re-allocated). Re-acquire the handle via the producing system or re-spawn the asset.`;\n const expected = `generation === ${actualGeneration} (current store generation)`;\n super(\n `UniqueRefStore: stale handle.\\n` +\n ` code: unique-ref-stale\\n` +\n ` slot: ${slot}\\n` +\n ` expectedGeneration: ${expectedGeneration}\\n` +\n ` actualGeneration: ${actualGeneration}\\n` +\n ` expected: ${expected}\\n` +\n ` hint: ${hint}`,\n );\n this.hint = hint;\n this.expected = expected;\n this.detail = { slot, expectedGeneration, actualGeneration };\n }\n}\n\n/**\n * Thrown / returned via `Result.err` when BufferPool indexing reads or writes\n * an offset outside the slot's `[0, size)` byte range. Triggers are limited\n * to the `buffer:<N>` and managed-array-element-buffer paths; the\n * `'string'` schema vocab no longer routes through this code (collapsed onto\n * the managed-ref dispatch by feat-20260515-string-managed-collapse — JS\n * string capacity is bounded by the host runtime, not by BufferPool buckets).\n *\n * `.code = 'managed-buffer-out-of-bounds'`\n * `.detail = { index, size }`\n * `.hint` — points at the field's `'buffer'` / `buffer<N>` schema declaration.\n */\nexport class ManagedBufferOutOfBoundsError extends RangeError {\n override readonly name = 'ManagedBufferOutOfBoundsError';\n readonly code = 'managed-buffer-out-of-bounds' as const;\n readonly hint: string;\n readonly expected: string;\n readonly detail: { readonly index: number; readonly size: number };\n\n constructor(index: number, size: number) {\n const hint = `Index ${index} is outside [0, ${size}). Check the field's 'buffer' / 'buffer<N>' declaration matches the access pattern.`;\n const expected = `index in [0, ${size})`;\n super(\n `BufferPool: index out of bounds.\\n` +\n ` code: managed-buffer-out-of-bounds\\n` +\n ` index: ${index}\\n` +\n ` size: ${size}\\n` +\n ` expected: ${expected}\\n` +\n ` hint: ${hint}`,\n );\n this.hint = hint;\n this.expected = expected;\n this.detail = { index, size };\n }\n}\n\n/**\n * Thrown / returned via `Result.err` when BufferPool resize is asked to shrink\n * a slot below its current allocated size — the pool only grows.\n *\n * `.code = 'managed-buffer-shrink-not-supported'`\n * `.detail = { requested, current }`\n * `.hint` — directs callers to allocate a fresh slot if a smaller buffer is needed.\n */\nexport class ManagedBufferShrinkNotSupportedError extends Error {\n override readonly name = 'ManagedBufferShrinkNotSupportedError';\n readonly code = 'managed-buffer-shrink-not-supported' as const;\n readonly hint: string;\n readonly expected: string;\n readonly detail: { readonly requested: number; readonly current: number };\n\n constructor(requested: number, current: number) {\n const hint = `BufferPool only grows. Requested ${requested} bytes < current ${current}; allocate a fresh slot if a smaller buffer is required.`;\n const expected = `requested >= ${current}`;\n super(\n `BufferPool: shrink not supported.\\n` +\n ` code: managed-buffer-shrink-not-supported\\n` +\n ` requested: ${requested}\\n` +\n ` current: ${current}\\n` +\n ` expected: ${expected}\\n` +\n ` hint: ${hint}`,\n );\n this.hint = hint;\n this.expected = expected;\n this.detail = { requested, current };\n }\n}\n\n// ────────────────────────────────────────────────────────────────────────────\n// feat-20260515-buffer-array-vocab-collapse w11 — closed-union evolution.\n//\n// 4 managed-array-* error classes deleted (replaced by the 4 collapsed-vocab\n// codes below); ManagedArrayElementTypeNotAllowedError preserved (still\n// surfaced from defineComponent's schema parser).\n//\n// 2 surviving error classes:\n// - FixedSizeMismatchError ('fixed-size-mismatch')\n// - InstanceTransformsStrideMismatchError ('instance-transforms-stride-mismatch')\n//\n// Naming-prefix orthogonality (plan-strategy §2.5):\n// fixed- element-type or capacity contract violations on fixed shape\n// array- operation failures (pop on empty) on the array vocab keyword\n// instance- GPU-render component-specific stride contract (Instances.transforms)\n//\n// The array element-wise facade was removed; only write-shape and render\n// stride errors remain on this boundary. The\n// `instance-transforms-stride-mismatch` member is the plan-strategy §2.4\n// evolution surfaced from `packages/runtime/src/render-system-extract.ts`\n// defensive entry (consumed by w15 in M3, but the error class lives here so\n// the EcsErrorCode union closure is owned by ECS — RhiError is not extended\n// per plan-strategy §2.4 decision).\n// ────────────────────────────────────────────────────────────────────────────\n\n/**\n * Returned via `Result.err` from `world.set` when a `buffer<N>` field is\n * written with a `Uint8Array` whose `byteLength` does not equal the\n * schema-declared fixed size `N`. AI users resize their payload to exactly\n * `N` bytes (zero-pad or truncate at the producer) before calling `world.set`.\n *\n * `.code = 'fixed-size-mismatch'`\n * `.detail = { expected, actual }`\n * `.hint` — points at the producer's payload sizing.\n */\nexport class FixedSizeMismatchError extends Error {\n override readonly name = 'FixedSizeMismatchError';\n readonly code = 'fixed-size-mismatch' as const;\n readonly hint: string;\n readonly expected: string;\n readonly detail: { readonly expected: number; readonly actual: number };\n\n constructor(fieldName: string, expected: number, actual: number) {\n const hint = `buffer<${expected}> set with byteLength ${actual} (expected ${expected}); resize your Uint8Array to exactly ${expected} bytes before world.set`;\n const expectedStr = `byteLength === ${expected}`;\n super(\n `buffer<N>: fixed-size mismatch.\\n` +\n ` code: fixed-size-mismatch\\n` +\n ` field: ${fieldName}\\n` +\n ` expected: ${expected}\\n` +\n ` actual: ${actual}\\n` +\n ` hint: ${hint}`,\n );\n this.hint = hint;\n this.expected = expectedStr;\n this.detail = { expected, actual };\n }\n}\n\n/**\n * Surfaced via the Layer-3 ErrorHandler from\n * `packages/runtime/src/render-system-extract.ts` defensive entry when an\n * `Instances.transforms` array<f32> length violates the column-major mat4\n * stride contract (`length % 16 === 0`). Locates the failure adjacent to the\n * extract pipeline rather than at GPU upload (plan-strategy §2.4 D-P2 +\n * §8.3 hint SSOT).\n *\n * `.code = 'instance-transforms-stride-mismatch'`\n * `.detail = { actualLength, expectedStride: 16 }`\n * `.hint` — names the stride invariant + the call sites to audit.\n */\nexport class InstanceTransformsStrideMismatchError extends Error {\n override readonly name = 'InstanceTransformsStrideMismatchError';\n readonly code = 'instance-transforms-stride-mismatch' as const;\n readonly hint: string;\n readonly expected: string;\n readonly detail: { readonly actualLength: number; readonly expectedStride: 16 };\n\n constructor(actualLength: number) {\n const hint = `Instances.transforms length ${actualLength} violates stride 16 (mat4); ensure transforms.length % 16 === 0 before render frame; verify world.set / world.push call sites`;\n const expectedStr = 'actualLength % 16 === 0';\n super(\n `Instances.transforms: stride mismatch.\\n` +\n ` code: instance-transforms-stride-mismatch\\n` +\n ` actualLength: ${actualLength}\\n` +\n ` expectedStride: 16\\n` +\n ` hint: ${hint}`,\n );\n this.hint = hint;\n this.expected = expectedStr;\n this.detail = { actualLength, expectedStride: 16 };\n }\n}\n\n/**\n * Thrown by `defineComponent` when an `array<T>` / `array<T,N>` schema field\n * carries an element type outside the legal whitelist (scalars + entity).\n * Forms like `array<ref<X>>` / `array<handle<X>>` / `array<buffer:N>` /\n * `array<array<...>>` are rejected (AC-03 runtime fail-safe). The TS layer\n * blocks these forms at compile time; this error is the runtime backstop for\n * `as unknown as SchemaFieldType` casts.\n *\n * `.code = 'managed-array-element-type-not-allowed'`\n * `.detail = { fieldName, elementType, hint }`\n * `.hint` — lists the whitelist of legal element types.\n */\nexport class ManagedArrayElementTypeNotAllowedError extends Error {\n override readonly name = 'ManagedArrayElementTypeNotAllowedError';\n readonly code = 'managed-array-element-type-not-allowed' as const;\n readonly hint: string;\n readonly expected: string;\n readonly detail: {\n readonly fieldName: string;\n readonly elementType: string;\n readonly hint: string;\n };\n\n constructor(fieldName: string, elementType: string) {\n const hint = `array<T> element type must be a scalar (f32/f64/i32/u32/i16/u16/i8/u8/bool/enum/ref) or entity. ref<X> / handle<X> / buffer:N / nested array<...> are forbidden on field \"${fieldName}\".`;\n const expected = 'element type in {scalar | entity}';\n super(\n `managed-array: element type not allowed.\\n` +\n ` code: managed-array-element-type-not-allowed\\n` +\n ` field: ${fieldName}\\n` +\n ` elementType: ${elementType}\\n` +\n ` expected: ${expected}\\n` +\n ` hint: ${hint}`,\n );\n this.hint = hint;\n this.expected = expected;\n this.detail = { fieldName, elementType, hint };\n }\n}\n\n// ────────────────────────────────────────────────────────────────────────────\n// EcsErrorCode closed union (w5)\n//\n// Merges every `.code` literal across the EcsError family. Downstream\n// `switch (err.code)` blocks become exhaustive; `assertNever(code)` catches\n// any future code addition without a matching case at compile time.\n//\n// Order is grouped (legacy SCREAMING_SNAKE first, then closed-set kebab) but\n// not load-bearing — TS unions are unordered.\n// ────────────────────────────────────────────────────────────────────────────\n\n/** Closed union of every `.code` literal carried by EcsError instances. */\nexport type EcsErrorCode =\n // Legacy SCREAMING_SNAKE codes (7, carried unchanged; the two\n // registration codes COMPONENT_ALREADY_REGISTERED / COMPONENT_NOT_REGISTERED\n // were dropped by feat-20260602 along with the per-World register concept).\n | 'stale-entity'\n | 'component-already-present'\n | 'component-not-present'\n | 'cyclic-dependency'\n | 'resource-not-found'\n // ECS time and schedule-scope errors (M2 w16, approved 43 -> 46 baseline; verify hotfix +1 → 47).\n | 'time-delta-invalid'\n | 'time-config-invalid'\n | 'schedule-scope-mismatch'\n // ScheduleMutationError closed-set kebab code.\n | ScheduleMutationErrorCode\n // w5 managed-* kebab codes (4).\n | 'unique-ref-released'\n | 'unique-ref-double-release'\n // feat-20260614-ecs-shared-component-and-unique-rename M3 — SharedRefStore\n // closed-union extension (+2). `'shared-ref-released'` covers resolve / retain\n // on rc=0; `'shared-ref-double-release'` covers release on rc=0.\n | 'shared-ref-released'\n | 'shared-ref-double-release'\n | 'shared-ref-payload-invalid'\n // feat-20260614-ecs-shared-component-and-unique-rename M6 D-15 (+1).\n // SharedRefStore manages ONLY user-tier slots (>= BUILTIN_BASE); a builtin\n // slot (< BUILTIN_BASE) passed to alloc/retain/release/resolve is a caller\n // error -> `'builtin-slot-not-owned'` (the authoring package owns the payload).\n | 'builtin-slot-not-owned'\n // feat-20260623-asset-handle-generation M4 — stale error codes (+2).\n // `'shared-ref-stale'` / `'unique-ref-stale'` cover gen mismatch on resolve /\n // retain / release after slot re-allocation. Add-only minor per AGENTS.md\n // Error model evolution contract; distinct from the existing `*-ref-released`\n // codes (slot empty vs slot re-allocated).\n | 'shared-ref-stale'\n | 'unique-ref-stale'\n | 'managed-buffer-out-of-bounds'\n | 'managed-buffer-shrink-not-supported'\n // managed-array-* kebab codes — surviving member from feat-20260514;\n // the other 4 (`managed-array-{index-out-of-bounds, pop-empty,\n // shrink-not-supported, stride-mismatch}`) were dropped by\n // feat-20260515-buffer-array-vocab-collapse w11 in favour of the 4 new\n // collapsed-vocab codes below. Kept here because `defineComponent`'s schema\n // parser still surfaces it for illegal `array<...>` element types.\n // feat-20260515-buffer-array-vocab-collapse w11 collapsed-vocab codes (4,\n // plan-strategy §2.4 + §2.5 four-prefix taxonomy).\n | 'fixed-size-mismatch'\n // feat-20260519-light-casters-point-spot-pbr w2 — PointLight / SpotLight\n // spawn-time payload bound violation (plan-strategy D-S3 a). 23 -> 24\n // minor evolution per AGENTS.md Error model evolution contract.\n // feat-20260520-2d-sprite-layer-mvp M-2 w13 — resource-setter bound\n // validation (plan-strategy D-4). 25 -> 26 minor evolution; first\n // consumer is `setTransparentSortConfig` (mode ∈ {0, 1, 2}).\n // feat-20260521-sprite-atlas-animation M1 T-05 — spriteAnimationTickSystem\n // runtime invariant violation (plan-strategy D-1). 26 -> 27 minor evolution\n // per AGENTS.md §Error model evolution contract; same-shape mirror of\n // 'spawn-light-invalid-bounds' (feat-20260519 w2) and 'resource-invalid-\n // value' (feat-20260520 w13) — the `<noun>-invalid-...` kebab series keeps\n // switch (err.code) narrows visually consistent for AI users (charter P4).\n // feat-20260531-ecs-relationship-abstraction-bidirectional-sync M2 —\n // relationship bidirectional sync + defineComponent relationship validation +\n // addChild/reparent cycle detection + removeChild detach guard\n // (plan-strategy D-5). 27 -> 31 minor evolution per AGENTS.md Error model\n // evolution contract. `relationship-exclusive-violation` is NOT a member:\n // exclusive re-add is an automatic reparent (success path), not an error.\n | 'relationship-self-cycle'\n | 'relationship-detach-mismatch'\n // feat-20260602-drop-component-registration w16-a — scene instantiate\n // fail-fast when a SceneAsset entity names a component that was never defined\n // via defineComponent (the per-World register concept was dropped; a\n // component becomes globally usable the moment defineComponent runs). 30 ->\n // 31 minor evolution per AGENTS.md Error model evolution contract. Replaces\n // the deleted COMPONENT_NOT_REGISTERED code at the scene-instance producer\n // sites (research Finding 5 missed these 3 producers; human escalation-\n // response authorized this scope-amendment).\n // feat-20260602-archetype-stores-full-packed-entity M1 / w3 — removeComponent\n // rejection when the target is an essential (undeletable) component. The only\n // essential component is the id=0 `Entity` (plan-strategy D-3). Net +1 minor\n // evolution per AGENTS.md §Error model evolution contract.\n | 'remove-essential-component'\n // feat-20260608-scene-nesting-ecs-fication M1 / w9 — setSceneOverride\n // type-mismatch fail-fast (plan-strategy D-9). 30 -> 31 minor evolution per\n // AGENTS.md §Error model evolution contract. Surfaced from\n // `world.setSceneOverride(root, member, comp, field, value)` when `value`'s\n // runtime type does not match the per-component schema field type (the\n // override apply path never silently coerces — value writes are typed at the\n // ECS layer; requirements §Edge cases table last row, reviewer Issue 1).\n // bug-20260615-spawn-data-unknown-field-fail-fast — spawn / addComponent /\n // SceneAsset.instantiate / Commands.spawn fail-fast when the caller-supplied\n // payload carries a key that is not declared in the component schema. Pre-\n // fix the unknown key was silently dropped by `fillComponentDefaults`\n // (which iterated only over schema keys), routing typos like\n // `MeshRenderer { material }` (singular legacy name) into the empty-default\n // path and producing invisible / mid-grey entities downstream. AI users\n // narrow on `.code` then read `.detail.field` for the offending key and\n // `.detail.knownFields` for the valid field whitelist.\n | 'spawn-data-unknown-field'\n // feat-20260625-sprite-instances-and-tilemap-terrain-static-batch M1 / w2 —\n // SpriteInstances primitive + tilemap terrain static-batch path. Three\n // codes declared together; fire path lands in M3 w13 at the\n // render-system-extract QueryRow loop. Minor evolution +3 per\n // AGENTS.md §Error model evolution contract; plan-strategy D-6 keeps the\n // detection in the render domain (not the ECS spawn path) to avoid an\n // ECS -> AssetRegistry reverse dep for the shader-id lookup.\n // feat-20260713-mount-override-component-add-and-shared-ref-round M2 / w9 —\n // P3 shared-field value gate. A `shared<T>` scalar or `array<shared<T>>`\n // element must be a resolved numeric Handle; a raw GUID string / `{ guid }` /\n // `{ kind }` object (the pre-resolution shape an AI user gets from a sidecar)\n // was silently coerced to the all-zero sentinel by the column packer\n // (`typed[i] = typeof val === 'number' ? val : 0`) / scalar write, so a\n // mis-bound reference read back as `0` / `[0,0,0,0]` and rendered blank with\n // no error. `validateComponentDataKeys` only checks key names, not value\n // types — this code closes the value-type gap at all three write entries\n // (spawn / addComponent / set). AI users resolve a GUID via\n // `AssetRegistry.load(guid, kind) + allocSharedRef` first; passing the raw GUID now fails fast.\n // Minor evolution +1 per AGENTS.md §Error model evolution contract.\n | 'shared-field-invalid-value'\n // feat-20260714-bevy-style-system-sets M1 / w3 — sole invalid-SystemSet\n // error code. Surfaced from world.addSystems when a\n // token fails identity validation (brand bypass + registry identity check).\n // Minor evolution +1 per AGENTS.md §Error model evolution contract.\n | 'system-set-not-registered'\n // Closed enum field writes fail before archetype or column mutation.\n | 'component-field-invalid-value'\n | 'component-numeric-value-invalid'\n | 'managed-array-invalid-value'\n | 'shared-kernel-ineligible'\n | 'shared-kernel-failed'\n | 'world-poisoned'\n // World.update terminal failures. These remain in the same closed union as\n // structural errors so consumers never need a second error discriminator.\n | 'command-failed'\n | 'system-failed';\n\n/**\n * Discriminated `.detail` payload per `.code`.\n *\n * Narrowed via `switch (err.code)` against `EcsErrorCode`. Empty-detail entries\n * (legacy errors without `.detail`) are intentionally omitted from this map —\n * only the w5 family + `cyclic-injection` carry structured payloads today.\n */\nexport type EcsErrorDetail =\n | {\n readonly code: 'shared-kernel-ineligible';\n readonly kernelName: string;\n readonly reason: string;\n }\n | {\n readonly code: 'shared-kernel-failed';\n readonly kernelName: string;\n readonly worldIdentity: string;\n readonly cause: unknown;\n readonly partialWrite: boolean;\n readonly retryable: false;\n }\n | { readonly code: 'world-poisoned'; readonly worldIdentity: string; readonly fault: unknown }\n | { readonly code: 'sparse-storage-requires-tag'; readonly componentName: string }\n | {\n readonly code: 'query-descriptor-conflict';\n readonly componentName: string;\n readonly roles: readonly string[];\n }\n | { readonly code: 'query-data-requires-fields'; readonly componentName: string }\n | { readonly code: 'query-span-unavailable'; readonly reason: QuerySpanUnavailableReason }\n | {\n readonly code: 'query-iteration-invalidated';\n readonly expectedStructureEpoch: number;\n readonly actualStructureEpoch: number;\n }\n | { readonly code: 'query-iteration-active' }\n | { readonly code: 'change-epoch-exhausted'; readonly epoch: number }\n | { readonly code: 'unique-ref-released'; readonly handle: number; readonly target: string }\n | {\n readonly code: 'unique-ref-double-release';\n readonly handle: number;\n readonly target: string;\n }\n // feat-20260614 M3 — SharedRefStore detail variants (+2).\n | { readonly code: 'shared-ref-released'; readonly handle: number; readonly target: string }\n | {\n readonly code: 'shared-ref-double-release';\n readonly handle: number;\n readonly target: string;\n readonly rc: number;\n }\n | {\n readonly code: 'shared-ref-payload-invalid';\n readonly target: string;\n readonly actual: 'null' | 'undefined';\n }\n // feat-20260614 M6 D-15 — builtin-slot fail-fast detail variant (+1).\n | { readonly code: 'builtin-slot-not-owned'; readonly slot: number }\n // feat-20260623-asset-handle-generation M4 — stale error detail variants (+2).\n | {\n readonly code: 'shared-ref-stale';\n readonly slot: number;\n readonly expectedGeneration: number;\n readonly actualGeneration: number;\n }\n | {\n readonly code: 'unique-ref-stale';\n readonly slot: number;\n readonly expectedGeneration: number;\n readonly actualGeneration: number;\n }\n | { readonly code: 'managed-buffer-out-of-bounds'; readonly index: number; readonly size: number }\n | {\n readonly code: 'managed-buffer-shrink-not-supported';\n readonly requested: number;\n readonly current: number;\n }\n // feat-20260514 surviving managed-array-* discriminated detail variant (1).\n | {\n readonly code: 'managed-array-element-type-not-allowed';\n readonly fieldName: string;\n readonly elementType: string;\n readonly hint: string;\n }\n // feat-20260515-buffer-array-vocab-collapse w11 collapsed-vocab detail\n // variants (4). Per-code field names are SSOT-anchored at AC-07 + plan-\n // strategy §2.4 §detail-list (NOT renamed for \"consistency\" — name follows\n // semantics).\n | {\n readonly code: 'fixed-size-mismatch';\n readonly expected: number;\n readonly actual: number;\n }\n | {\n readonly code: 'instance-transforms-stride-mismatch';\n readonly actualLength: number;\n readonly expectedStride: 16;\n }\n // feat-20260519-light-casters-point-spot-pbr w2 — light and local probe\n // spawn-time payload bound violation (plan-strategy D-S3 a). detail.field\n // names the validated scalar or RGB payload while one code keeps the\n // recovery surface closed; AI users narrow on `.detail.field` after the\n // outer `switch (err.code)` to pick the specific recovery hint.\n | {\n readonly code: 'spawn-light-invalid-bounds';\n readonly field:\n | 'direction'\n | 'intensity'\n | 'color'\n | 'width'\n | 'height'\n | 'irradiance'\n | 'radius'\n | 'range'\n | 'innerOuter'\n | 'outerNinety';\n readonly got: number | readonly number[];\n }\n // feat-20260520-2d-sprite-layer-mvp M-2 w13 — resource-setter bound\n // violation (plan-strategy D-4). receivedMode carries the rejected\n // payload number; receivedKey is optional so future resource\n // validators can share the same code while disambiguating which\n // resource produced the failure.\n | {\n readonly code: 'resource-invalid-value';\n readonly receivedMode: number;\n readonly receivedKey?: string;\n }\n // feat-20260521-sprite-atlas-animation M1 T-05 — sprite-animation tick\n // runtime invariant violation (plan-strategy D-1 + section 5 AC-09).\n // detail.field two-branch keeps the regions-length / frame-duration\n // invariants under one code; AI users narrow on `.detail.field` after\n // the outer `switch (err.code)` to pick the specific recovery hint\n // (charter P3 + P4). Two top-level variants give each `.field` branch\n // its own required sub-field shape so AI users get strong narrowing\n // inside `switch (err.detail.field)` without optional sub-fields\n // bleeding across branches.\n | {\n readonly code: 'sprite-animation-invalid';\n readonly field: 'regions-length';\n readonly regionsLength: number;\n readonly frameCount: number;\n }\n | {\n readonly code: 'sprite-animation-invalid';\n readonly field: 'frame-duration';\n readonly frameDuration: number;\n }\n // feat-20260531-ecs-relationship-abstraction-bidirectional-sync M2 — the 4\n // relationship-* discriminated detail variants (plan-strategy D-5). Each\n // carries the component name + the entities involved so AI users narrow on\n // `.code` then read `.detail` to locate the offending relationship surface.\n | {\n readonly code: 'relationship-self-cycle';\n readonly component: string;\n readonly entity: number;\n readonly ancestor: number;\n }\n | {\n readonly code: 'relationship-mirror-component-not-registered';\n readonly component: string;\n readonly mirror: string;\n }\n | {\n readonly code: 'relationship-mirror-field-type-mismatch';\n readonly component: string;\n readonly mirror: string;\n readonly field: string;\n readonly actualType: string;\n }\n | {\n readonly code: 'relationship-detach-mismatch';\n readonly component: string;\n readonly child: number;\n readonly expectedParent: number;\n readonly actualParent: number;\n }\n // feat-20260602-drop-component-registration w16-a — scene instantiate\n // unknown-component fail-fast (30 -> 31). `.detail.name` carries the\n // component name that was never defined via defineComponent.\n | {\n readonly code: 'component-not-defined';\n readonly name: string;\n }\n // feat-20260602-archetype-stores-full-packed-entity M1 / w3 — removeComponent\n // essential-component rejection. `.detail.componentName` carries the essential\n // component name (the id=0 `Entity`).\n | {\n readonly code: 'remove-essential-component';\n readonly componentName: string;\n }\n // feat-20260608-scene-nesting-ecs-fication M1 / w9 — setSceneOverride\n // value-type rejection (plan-strategy D-9; requirements §Edge cases last\n // row + reviewer Issue 1). `.detail.comp` / `.detail.field` locate the\n // override target; `.detail.expectedType` carries the schema-declared\n // type literal (e.g. 'f32', 'bool', 'string'); `.detail.actualType`\n // carries the runtime `typeof value` (typed `unknown` because the\n // override write is not coerced — fail-fast surfaces the mismatch).\n | {\n readonly code: 'scene-override-type-mismatch';\n readonly comp: string;\n readonly field: string;\n readonly expectedType: string;\n readonly actualType: unknown;\n }\n // bug-20260615-spawn-data-unknown-field-fail-fast — spawn-data unknown-key\n // fail-fast. `.detail.component` names the schema's component, `.detail.field`\n // is the offending raw key, `.detail.knownFields` is the schema's full field\n // whitelist (sorted, used by AI users / hint formatters to surface \"did you\n // mean\" suggestions without round-tripping to the schema).\n | {\n readonly code: 'spawn-data-unknown-field';\n readonly component: string;\n readonly field: string;\n readonly knownFields: readonly string[];\n }\n // feat-20260625-sprite-instances-and-tilemap-terrain-static-batch M1 / w2 —\n // 3 discriminated detail variants for the SpriteInstances primitive\n // (declared in M1, fired at render-system-extract entry in M3).\n | {\n readonly code: 'sprite-instances-count-mismatch';\n readonly transformsLength: number;\n readonly regionsLength: number;\n readonly expectedStride: { readonly transforms: 16; readonly regions: 4 };\n }\n | {\n readonly code: 'sprite-instances-requires-sprite-shader';\n readonly entityId: number;\n readonly observedMaterialShaderId: string;\n }\n | {\n readonly code: 'sprite-instances-mutually-exclusive-with-instances';\n readonly entityId: number;\n }\n // feat-20260713-mount-override-component-add-and-shared-ref-round M2 / w9 —\n // shared-field value gate. `.detail.component` / `.detail.field` locate the\n // shared reference field; `.detail.fieldType` is the schema-declared type\n // literal (`shared<T>` scalar or `array<shared<T>>`); `.detail.actualValue`\n // is the offending non-handle value (typed `unknown` — a raw GUID string /\n // `{ guid }` / `{ kind }` object is not coerced, the fail-fast surfaces it);\n // `.detail.index` is the array element index for the array form (undefined for\n // the scalar form). AI users read `.detail.field` + `.detail.fieldType` to see\n // which reference needs `AssetRegistry.load(guid, kind) + allocSharedRef` before binding.\n | {\n readonly code: 'shared-field-invalid-value';\n readonly component: string;\n readonly field: string;\n readonly fieldType: string;\n readonly actualValue: unknown;\n readonly index?: number;\n }\n // feat-20260714-bevy-style-system-sets M1 / w3 — invalid-SystemSet detail.\n // `.detail.name` is the rejected token name; `.detail.registered` is a\n // deterministic snapshot of the current registry keys.\n | {\n readonly code: 'system-set-not-registered';\n readonly name: string;\n readonly registered: readonly string[];\n }\n | {\n readonly code: 'component-field-invalid-value';\n readonly entity: number | undefined;\n readonly component: string;\n readonly field: string;\n readonly received: unknown;\n readonly allowedValues: Readonly<Record<string, number>>;\n }\n | {\n readonly code: 'component-numeric-value-invalid';\n readonly entity: number | undefined;\n readonly component: string;\n readonly field: string;\n readonly received: number;\n readonly index?: number;\n }\n | {\n readonly code: 'managed-array-invalid-value';\n readonly component: string;\n readonly field: string;\n readonly fieldType: string;\n readonly actualValue: unknown;\n }\n // feat-20260714-bevy-style-system-sets M2 / w12 — structured cyclic-dependency\n // detail. `.detail.cycle` is the ordered cycle path array; consumers read\n // this instead of parsing the message string.\n | {\n readonly code: 'cyclic-dependency';\n readonly cycle: readonly string[];\n }\n | {\n readonly code: 'command-failed';\n readonly systemName: string;\n readonly schedule: string;\n readonly commandIndex: number;\n readonly commandKind: CommandKind;\n readonly cause: unknown;\n }\n | {\n readonly code: 'system-failed';\n readonly systemName: string;\n readonly schedule: string;\n readonly cause: unknown;\n readonly lastCommittedCommand: CommandCommitEvidence | null;\n };\n\n/**\n * Layer-3 error envelope routed through managed-storage callbacks. Callers\n * narrow `detail` through the source-owned `EcsErrorDetail` union.\n */\nexport interface ManagedArrayErrorEnvelope {\n readonly code: EcsErrorCode;\n readonly hint: string;\n readonly expected: string;\n readonly detail: unknown;\n}\n\nexport type CommandKind = 'spawn' | 'despawn' | 'addComponent' | 'removeComponent';\n\nexport interface CommandCommitEvidence {\n readonly index: number;\n readonly kind: CommandKind;\n}\n\n/** Expected command preflight failure, with the exact batch location. */\nexport class CommandFailedError extends Error {\n override readonly name = 'CommandFailedError';\n readonly code = 'command-failed' as const;\n readonly expected = 'all deferred commands pass preflight before commit';\n readonly hint =\n 'Inspect detail.cause, repair the command at detail.commandIndex, and run the World again.';\n override readonly cause: unknown;\n readonly detail: {\n readonly systemName: string;\n readonly schedule: string;\n readonly commandIndex: number;\n readonly commandKind: CommandKind;\n readonly cause: unknown;\n };\n\n constructor(\n systemName: string,\n schedule: string,\n commandIndex: number,\n commandKind: CommandKind,\n cause: unknown,\n ) {\n super(\n `Deferred command failed before commit in ${schedule}/${systemName} ` +\n `at command ${commandIndex} (${commandKind}).`,\n );\n this.cause = cause;\n this.detail = { systemName, schedule, commandIndex, commandKind, cause };\n }\n}\n\n/** Unknown system failure. The World is poisoned because row writes may exist. */\nexport class SystemFailedError extends Error {\n override readonly name = 'SystemFailedError';\n readonly code = 'system-failed' as const;\n readonly expected = 'a system completes without throwing or returning a failed Result';\n readonly hint =\n 'Inspect detail.cause, stop using this poisoned World, and rebuild it from the owning App.';\n override readonly cause: unknown;\n readonly detail: {\n readonly systemName: string;\n readonly schedule: string;\n readonly cause: unknown;\n readonly lastCommittedCommand: CommandCommitEvidence | null;\n };\n\n constructor(\n systemName: string,\n schedule: string,\n cause: unknown,\n lastCommittedCommand: CommandCommitEvidence | null = null,\n ) {\n super(`System ${schedule}/${systemName} failed; World is poisoned.`);\n this.cause = cause;\n this.detail = { systemName, schedule, cause, lastCommittedCommand };\n }\n}\n","// @forgeax/engine-ecs — Component schema + opaque token.\n//\n// `defineComponent(name, fields, options?)` returns a frozen token carrying\n// only the three runtime facts needed by callers:\n// - `.name`: component name string\n// - `.fields`: frozen field descriptors (the schema SSOT)\n// - `.storage`: table or sparse placement\n// Numeric identity, flat schema projections, and default maps live in the ECS\n// owner tables below rather than on the public token.\n//\n// ComponentId is used by archetype storage, bitmask matching, and edges cache.\n\nimport { err, type Handle, ok, type Result } from '@forgeax/engine-types';\nimport {\n assertComponentStorage,\n deepFreeze,\n registerComponentDefinition,\n} from './component-schema';\nimport type { EntityHandle } from './entity-handle';\nimport {\n ManagedArrayElementTypeNotAllowedError,\n SchemaUnsupportedFieldError,\n SparseStorageRequiresTagError,\n} from './errors';\nimport type { ManagedColumnReader } from './storage/column';\n\n// The internal package subpath reuses this owner module so the source budget\n// does not grow a second forwarding module. Root exports remain curated in\n// index.ts; this re-export is only reached through `@forgeax/engine-ecs/internal`.\nexport { componentDefinition } from './component-schema';\n\n// ────────────────────────────────────────────────────────────────────────────\n// Field types — schema vocab keywords (AC-01).\n//\n// Two-tier vocabulary:\n//\n// 1. Legacy scalar set: 11 keywords backed by TypedArray storage. Concrete\n// byte-sizes + TypedArray constructors are internal constants consumed by\n// `scalarRow()` to build TYPE_METADATA rows (see M4 §FIELD_SIZE_BYTES / VIEW_CTORS).\n//\n// 2. Schema-vocab keywords: 7 template-literal patterns expressing\n// ECS-managed types whose storage is owned by separate subsystems:\n// * `buffer:<bytes>` — fixed-byte managed Uint8Array, stored by BufferPool\n// * `ref<T>` — managed Handle<T,'unique'>, released by UniqueRefStore\n// * `shared<T>` — rc-tracked Handle<T,'shared'>, lifecycle owned by SharedRefStore\n// * `entity` — Entity reference (Entity | null)\n// * `string` — utf-8 string payload, allocated as a managed handle via UniqueRefStore\n// * `array<T,N>` — fixed-capacity typed view; elements inline in stride-N column (feat-20260602)\n// * `array<T>` — variable-capacity typed view over BufferPool slot bytes\n//\n// The retired `array<entity>` predecessor (closed out by this feat) is no\n// longer a valid schema field type — the union has narrowed it out.\n// ────────────────────────────────────────────────────────────────────────────\n\n/** Bytes per element for each scalar field type. */\nconst FIELD_SIZE_BYTES = {\n f32: 4,\n f64: 8,\n i32: 4,\n u32: 4,\n i16: 2,\n u16: 2,\n i8: 1,\n u8: 1,\n bool: 1,\n enum: 4,\n ref: 4,\n} as const;\n\n/** Numeric scalar field types backed by TypedArray storage (legacy tier). */\nexport type ScalarFieldType = keyof typeof FIELD_SIZE_BYTES;\n\n/**\n * Legal element-type whitelist for the `array<T,N>` / `array<T>` vocab\n * keywords (AC-03). T must be a scalar field type, `entity`, or a\n * `shared\\<X\\>` template with a non-empty tag; reference / buffer / nested\n * array element types are forbidden (OOS-08 / OOS-03).\n *\n * feat-20260614 M5 / w23: the historical `handle\\<X\\>` element family was\n * deleted in favor of `shared\\<X\\>` (rc-tracked, lifecycle owned by\n * SharedRefStore). The `MANAGED_ARRAY_ELEMENT_TYPES` Set remains\n * static-scalar + entity only (D-8); dynamic `shared\\<X\\>` templates are\n * validated by `isValidArrayElementType` at parse time.\n *\n * Legal: every member of `ScalarFieldType` plus `entity` plus\n * `shared\\<X\\>` (non-empty tag). The `ref` legacy scalar keyword (a u32\n * column placeholder) is in the whitelist; the parametric `unique<T>` /\n * `shared<T>` scalars are rejected as array element types by AC-03.\n */\nexport type ManagedArrayElementType = ScalarFieldType | 'entity' | `shared<${string}>`;\n\n/**\n * Schema-vocab keywords beyond the legacy scalar tier (AC-01).\n *\n * Each pattern is a template-literal type so a literal schema like\n * `{ mat: 'unique<MaterialAsset>' }` types the value as\n * `Handle<'MaterialAsset','unique'>` end-to-end. Runtime acceptance is\n * gated by the internal `isSchemaVocabKeyword` check — the SSOT for parser fail-fast.\n *\n * The legacy `'buffer:<N>'` literal is retired one-cut by\n * feat-20260515-buffer-array-vocab-collapse w4: replaced by the\n * angle-bracket generic shapes `'buffer'` (variable byte slot) and\n * `'buffer<N>'` (fixed byte slot). With `'array<T>'` / `'array<T, N>'` they\n * form a 4-keyword closed surface across two orthogonal axes (element-type\n * x capacity contract).\n */\nexport type SchemaVocabKeyword =\n | 'string'\n | 'buffer'\n | `buffer<${number}>`\n | `unique<${string}>`\n | `shared<${string}>`\n | 'entity'\n | `array<${ManagedArrayElementType}, ${number}>`\n | `array<${ManagedArrayElementType}>`;\n\n/**\n * Closed union of every keyword `defineComponent` accepts for a schema field.\n * Combines the legacy scalar tier with the schema-vocab tier.\n *\n * `ComponentSchema` is keyed against this union; `defineComponent` rejects\n * any field value not satisfying it (compile-time) or matching it\n * (runtime).\n */\nexport type SchemaFieldType = ScalarFieldType | SchemaVocabKeyword;\n\n/**\n * Producer-owned semantic shape tags for authoring/schema consumers.\n *\n * The ECS storage vocabulary remains the source of truth for bytes and\n * runtime values. These tags capture the semantic shape that storage alone\n * cannot express (for example an optional entity reference or a nested\n * unique payload). The tag is deliberately closed so downstream consumers\n * can exhaustively handle the representative field-shape vocabulary without\n * creating a second component registry.\n */\nexport type FieldShapeKind =\n | 'scalar'\n | 'boolean'\n | 'enum'\n | 'vector'\n | 'quaternion'\n | 'optional'\n | 'nested'\n | 'array'\n | 'asset-ref';\n\n/**\n * Normalize any field-type keyword to its TYPE_METADATA key.\n *\n * The 11 legacy scalars round-trip their own key. The 6 vocab families normalize\n * their parametric shapes to the family key:\n * - `unique<T>` / `shared<T>` — strip `<T>` → `'ref'` / `'shared'`\n * - `buffer<N>` — strip `<N>` → `'buffer'`\n * - `array<T>` / `array<T,N>` — strip `<...>` → `'array'`\n * - `entity` / `string` / `buffer` are identity.\n *\n * Returns `null` for an unrecognised keyword so callers can skip column\n * allocation (same semantics as the retired `storageFieldType`).\n */\nexport function fieldTypeToMetaKey(fieldType: string): string | null {\n if (fieldType === 'entity' || fieldType === 'string' || fieldType === 'buffer') {\n return fieldType;\n }\n if (fieldType.startsWith('unique<') && fieldType.endsWith('>')) return 'ref';\n if (fieldType.startsWith('shared<') && fieldType.endsWith('>')) return 'shared';\n if (fieldType.startsWith('buffer<') && fieldType.endsWith('>')) return 'buffer';\n if (fieldType.startsWith('array<') && fieldType.endsWith('>')) return 'array';\n // Legacy scalar — the 11 types are keys in TYPE_METADATA.\n if (TYPE_METADATA[fieldType] !== undefined) return fieldType;\n return null;\n}\n\n/**\n * `true` when the schema field type is a managed-store slot - i.e. should be\n * routed through `UniqueRefStore` (or `SharedRefStore` for `'shared<T>'`)\n * for alloc / resolve / release. Derived from TYPE_METADATA[].isManaged\n * column (feat-20260611-ecs-storage-naming-ssot D-3).\n *\n * Naming note (D-6 whitelist): `managed = ECS-tracked`. The prefix here is\n * about column-side lifecycle ownership (the ECS releases the slot on\n * despawn / overwrite), not the retired `'managed' | 'unmanaged'` Handle\n * brand. Both `'unique<T>'` and `'shared<T>'` schema fields satisfy\n * `isManagedField` because both are ECS-tracked; the dispatcher in\n * `releaseManagedFieldOnRow` picks the right store per field type.\n */\nexport function isManagedField(fieldType: string): boolean {\n return TYPE_METADATA[fieldTypeToMetaKey(fieldType) ?? '']?.isManaged ?? false;\n}\n\n/**\n * `true` when the schema field type is a managed-buffer slot - i.e. should be\n * released by the M2 BufferPool release loop. Derived from\n * TYPE_METADATA[].isBuffer column (feat-20260611-ecs-storage-naming-ssot D-3/D-4).\n *\n * D-4 semantic widening accepted: `buffer<abc>` resolves to metaKey 'buffer'\n * (isBuffer=true) while the old regex-based impl rejected the non-integer N.\n * This is a dead path — `defineComponent` rejects `buffer<abc>` via\n * `isSchemaVocabKeyword` before the predicate fires.\n *\n * Naming note (D-6 whitelist): `managed = ECS-tracked`. Same semantic as\n * `isManagedField` — the variable `'buffer'` keyword is one whose\n * BufferPool slot the ECS releases at despawn / overwrite time.\n */\nexport function isManagedBufferField(fieldType: string): boolean {\n return TYPE_METADATA[fieldTypeToMetaKey(fieldType) ?? '']?.isBuffer ?? false;\n}\n\n/**\n * `true` when the schema field type is the single-entity reference keyword\n * `'entity'`. Derived from TYPE_METADATA[].isEntityRef column\n * (feat-20260611-ecs-storage-naming-ssot D-3).\n */\nexport function isEntityField(fieldType: string): boolean {\n return TYPE_METADATA[fieldTypeToMetaKey(fieldType) ?? '']?.isEntityRef ?? false;\n}\n\n/**\n * `true` when the schema field type is an `array<T,N>` / `array<T>` vocab\n * keyword. Derived from TYPE_METADATA[].isArray column\n * (feat-20260611-ecs-storage-naming-ssot D-3).\n *\n * Naming note (D-6 whitelist): `managed = ECS-tracked`. Variable\n * `array<T>` storage routes through BufferPool (slot lifecycle owned by\n * the ECS); fixed `array<T,N>` is inline stride-N and has no separate\n * slot to release, but both share this predicate as they share the\n * `'array'` meta key.\n */\nexport function isManagedArrayField(fieldType: string): boolean {\n return TYPE_METADATA[fieldTypeToMetaKey(fieldType) ?? '']?.isArray ?? false;\n}\n\n/**\n * Set of legal element types for the `array<T,N>` / `array<T>` keywords\n * (AC-03). Runtime mirror of `ManagedArrayElementType`.\n *\n * Naming note (D-6 whitelist): `MANAGED_ARRAY_ELEMENT_TYPES` keeps the\n * `MANAGED` prefix because `managed = ECS-tracked` here — the Set is the\n * static-whitelist arm of `isValidArrayElementType`, which gates which\n * element types the ECS array dispatch knows how to retain / release.\n * The `'shared<X>'` template family rides the `startsWith('shared<')`\n * special case (D-8) rather than living in this Set.\n */\nexport const MANAGED_ARRAY_ELEMENT_TYPES: ReadonlySet<ManagedArrayElementType> =\n new Set<ManagedArrayElementType>([\n 'f32',\n 'f64',\n 'i32',\n 'u32',\n 'i16',\n 'u16',\n 'i8',\n 'u8',\n 'bool',\n 'enum',\n 'ref',\n 'entity',\n ]);\n\n/**\n * Return `true` when `elementType` is a legal array element type\n * (static-whitelist scalar | entity, or a `shared\\<X\\>` template with a\n * non-empty tag). The empty-tag form `shared\\<\\>` is rejected\n * (plan-strategy §2 D-1 / R-NEW-1).\n *\n * @internal\n */\nfunction isValidArrayElementType(elementType: string): elementType is ManagedArrayElementType {\n if (MANAGED_ARRAY_ELEMENT_TYPES.has(elementType as ManagedArrayElementType)) return true;\n // feat-20260614 D-8: `shared<X>` is a legal element-type via the\n // startsWith special case; `MANAGED_ARRAY_ELEMENT_TYPES` Set deliberately\n // does NOT carry a `'shared'` entry (D-8 keeps the static-whitelist Set\n // free of the new family; runtime validation through the special case\n // here pairs with the independent `'shared'` TYPE_METADATA row that\n // routes element retain/release semantics in M4).\n if (elementType.startsWith('shared<') && elementType.endsWith('>') && elementType.length > 9)\n return true;\n return false;\n}\n\n/**\n * Parse an `array<T,N>` / `array<T>` schema string into its element type and\n * optional fixed length. Returns `null` if the string is not a managed-array\n * keyword or its element type is not in the whitelist (AC-03 runtime\n * fail-safe).\n *\n * Examples:\n * parseManagedArraySchema('array<entity>') => { elementType: 'entity', length: undefined }\n * parseManagedArraySchema('array<f32, 16>') => { elementType: 'f32', length: 16 }\n * parseManagedArraySchema('array<shared<MaterialAsset>>') => { elementType: 'shared<MaterialAsset>', length: undefined }\n * parseManagedArraySchema('array<shared<>>') => null (empty tag rejection)\n * parseManagedArraySchema('array<unique<X>>') => null (illegal element)\n * parseManagedArraySchema('array<array<f32,4>>') => null (nested rejected)\n *\n * Naming note (D-6 whitelist): `parseManagedArraySchema` keeps the\n * `Managed` infix because `managed = ECS-tracked` — every legal output\n * shape this parser returns is one whose lifecycle the ECS knows how to\n * retain / release on overwrite, despawn, or archetype migration.\n */\nexport function parseManagedArraySchema(\n fieldType: string,\n): { readonly elementType: ManagedArrayElementType; readonly length: number | undefined } | null {\n if (!fieldType.startsWith('array<') || !fieldType.endsWith('>')) return null;\n const inner = fieldType.slice(6, -1);\n const commaIdx = inner.indexOf(',');\n if (commaIdx === -1) {\n // Variable-capacity: inner must be a bare element-type keyword or\n // handle<X> template.\n if (!isValidArrayElementType(inner)) return null;\n return { elementType: inner as ManagedArrayElementType, length: undefined };\n }\n // Fixed-capacity: split at first comma; element-type before, integer length\n // after. Reject any further '<' / ':' / ',' to keep the form unambiguous.\n const head = inner.slice(0, commaIdx).trim();\n const tail = inner.slice(commaIdx + 1).trim();\n if (!isValidArrayElementType(head)) return null;\n if (!/^[1-9]\\d*$/.test(tail)) return null;\n return { elementType: head as ManagedArrayElementType, length: Number.parseInt(tail, 10) };\n}\n\n/**\n * Parse the byte count out of a `buffer<N>` schema keyword. Returns NaN if\n * the input does not match the keyword pattern - callers that already gated\n * via `isManagedBufferField` get a guaranteed-positive integer for the\n * fixed-byte form. The bare `'buffer'` keyword (variable byte capacity)\n * returns NaN and callers must check `fieldType === 'buffer'` separately.\n */\nexport function bufferFieldByteLength(fieldType: string): number {\n if (!fieldType.startsWith('buffer<') || !fieldType.endsWith('>')) return Number.NaN;\n const tail = fieldType.slice(7, -1);\n if (!/^[1-9]\\d*$/.test(tail)) return Number.NaN;\n return Number.parseInt(tail, 10);\n}\n\n/**\n * Runtime check for a schema-vocab keyword (the tier-2 surface).\n *\n * Pure-function regex match — kept off the hot path; only invoked by\n * `defineComponent` once per field at registration time. The match patterns\n * are the runtime mirror of `SchemaVocabKeyword` template literals.\n *\n * - `'string'` is exact-match (bare literal, no `<>`).\n * - `'buffer'` is exact-match (variable-byte capacity).\n * - `buffer<N>` requires `N` to be a positive base-10 integer (`/^[1-9]\\d*$/`).\n * Forms like `buffer<abc>` / `buffer<0>` / `buffer<>` are rejected.\n * - `unique<T>` / `shared<T>` require a non-empty target tag (`/^\\w+$/`).\n * - `entity` is exact-match.\n * - `array<T,N>` / `array<T>` accept only the whitelist element types\n * (`MANAGED_ARRAY_ELEMENT_TYPES`); illegal inner types fall through and\n * the caller surfaces `managed-array-element-type-not-allowed`.\n */\nexport function isSchemaVocabKeyword(s: string): s is SchemaVocabKeyword {\n if (s === 'string') return true;\n if (s === 'entity') return true;\n if (s === 'buffer') return true;\n if (s.startsWith('buffer<') && s.endsWith('>')) {\n const tail = s.slice(7, -1);\n return /^[1-9]\\d*$/.test(tail);\n }\n if (s.startsWith('unique<') && s.endsWith('>')) {\n return /^\\w+$/.test(s.slice(7, -1));\n }\n if (s.startsWith('shared<') && s.endsWith('>')) {\n return /^\\w+$/.test(s.slice(7, -1));\n }\n if (s.startsWith('array<') && s.endsWith('>')) {\n return parseManagedArraySchema(s) !== null;\n }\n return false;\n}\n\n/**\n * JS value-shape per managed-array element type. `entity` maps to `Entity`\n * (branded number), every scalar maps to `number` (bool is stored as a 0/1\n * byte and read back as 0 or 1).\n */\nexport type ManagedArrayElementValue<T extends ManagedArrayElementType> = T extends 'entity'\n ? EntityHandle\n : number;\n\n/**\n * Maps each field-type keyword to the JS value type read/written by it.\n *\n * Tier-1 (legacy scalars) widens to `boolean | number`; tier-2 (schema-vocab)\n * resolves to the corresponding handle / entity / buffer / array / string\n * shape via the `infer T` template-literal extraction pattern. Conditional\n * types resolve top-down --- the `'string'` arm sits BEFORE the array<...> /\n * `buffer<N>` arms so the precise literal wins template-literal resolution\n * (R-P5: prevents `'string'` from being shadowed by a wider template-literal\n * pattern). The fixed-capacity `array<T,N>` arm matches before the\n * variable-capacity `array<T>` arm by the same rule.\n *\n * The 4 buffer/array keywords (`'buffer'` / `'buffer<N>'` / `'array<T>'` /\n * `'array<T, N>'`) all resolve directly to a concrete TypedArray (or\n * Uint8Array for the byte-only buffer family). At the public `world.get`\n * boundary, a relationship-target `array<entity>` is a detached `Uint32Array`\n * snapshot. Other public array fields retain their existing transient live\n * TypedArray alias: fixed `buffer<N>` / `array<T,N>` values alias the inline\n * column buffer (feat-20260602), while variable `buffer` / `array<T>` values\n * alias the BufferPool slot bytes. Internal `readRow`, `_getArrayView`, and\n * `materializeArrayView` paths always use the live zero-copy alias. Mutation\n * flows through `world.set` / `world.push` / `world.pop`, not direct\n * assignment to a returned TypedArray.\n *\n * The `'string'` arm resolves to a native JS `string` (D-R1 / AC-13): the\n * dispatch routes the column u32 through `UniqueRefStore.resolve(handle)`\n * which returns the immutable string payload by reference.\n */\nexport type FieldValueType<T extends SchemaFieldType> = T extends 'bool'\n ? boolean\n : T extends 'entity'\n ? EntityHandle | null\n : T extends 'string'\n ? string\n : T extends 'buffer'\n ? Uint8Array\n : T extends `buffer<${number}>`\n ? Uint8Array\n : T extends `array<shared<${infer Target}>, ${number}>`\n ? readonly Handle<Target, 'shared'>[]\n : T extends `array<shared<${infer Target}>>`\n ? readonly Handle<Target, 'shared'>[]\n : T extends `array<${infer Elem extends ManagedArrayElementType}, ${number}>`\n ? TypedArrayFor<Elem extends 'entity' ? 'u32' : Elem>\n : T extends `array<${infer Elem extends ManagedArrayElementType}>`\n ? TypedArrayFor<Elem extends 'entity' ? 'u32' : Elem>\n : T extends `unique<${infer Target}>`\n ? Handle<Target, 'unique'>\n : T extends `shared<${infer Target}>`\n ? Handle<Target, 'shared'>\n : T extends ScalarFieldType\n ? number\n : never;\n\n/**\n * Input-side counterpart of {@link FieldValueType} for write paths\n * (`world.spawn` / `world.addComponent` / `world.set`).\n *\n * Asymmetric on `array<scalar, N>` / `array<scalar>` ONLY: the read side\n * surfaces zero-copy `Float32Array` / `Uint32Array` / etc views; the write\n * side ALSO accepts `readonly number[]` because writeArrayField copies bytes\n * verbatim from either shape (TypedArray subarray() OR per-element pack via\n * DataView). Plain literals like `times: [0.5]` reach the same code path\n * with no Float32Array wrapper boilerplate at the call site, and short\n * prefixes pad the row tail with zero (writeArrayField D-3 contract).\n *\n * Asymmetric on `buffer` / `buffer<N>`: the read side returns `Uint8Array`,\n * but the write side accepts any `AllowSharedBufferSource` (Float32Array /\n * ArrayBuffer / Uint8Array / any TypedArray). The ECS buffer-write ingestion\n * point (`World.writeRow` / `World.set`) normalizes any view to `Uint8Array`\n * over its raw bytes before storing (feat-20260621 V2 / AC-A4). This lets AI\n * users write typed param payloads directly, e.g.\n * `world.set(e, PostProcessParams, { data: Float32Array.of(exposure,0,0,0) })`,\n * without manual byte-reinterpret boilerplate at the call site.\n *\n * Every other arm matches FieldValueType verbatim (no widening): handles\n * are already arrays-of-handle, scalars stay number, etc.\n */\nexport type FieldInputType<T extends SchemaFieldType> = T extends 'bool'\n ? boolean\n : T extends 'entity'\n ? EntityHandle | null\n : T extends 'string'\n ? string\n : T extends 'buffer'\n ? AllowSharedBufferSource\n : T extends `buffer<${number}>`\n ? AllowSharedBufferSource\n : T extends `array<shared<${infer Target}>, ${number}>`\n ? readonly Handle<Target, 'shared'>[]\n : T extends `array<shared<${infer Target}>>`\n ? readonly Handle<Target, 'shared'>[]\n : T extends `array<${infer Elem extends ManagedArrayElementType}, ${number}>`\n ? TypedArrayFor<Elem extends 'entity' ? 'u32' : Elem> | readonly number[]\n : T extends `array<${infer Elem extends ManagedArrayElementType}>`\n ? TypedArrayFor<Elem extends 'entity' ? 'u32' : Elem> | readonly number[]\n : T extends `unique<${infer Target}>`\n ? Handle<Target, 'unique'>\n : T extends `shared<${infer Target}>`\n ? Handle<Target, 'shared'>\n : T extends ScalarFieldType\n ? number\n : never;\n\n/**\n * Maps a SchemaFieldType to its zero-copy query-column view type.\n *\n * Three storage shapes share the keyword space:\n *\n * 1. Scalar / fixed-inline columns -- the column buffer is the data, written\n * in place. The bundle entry is a concrete writable TypedArray of the\n * correct ctor (`f32` -> `Float32Array`, `'buffer<N>'` -> `Uint8Array`,\n * `'array<T,N>'` -> the T-typed array). Direct index assignment is\n * fine -- the column owns the bytes.\n *\n * 2. `shared\\<X\\>` (rc-tracked AssetRegistry reference) -- the column carries\n * a u32 handle id; SharedRefStore owns the rc lifecycle. The bundle\n * entry is a `ManagedColumnReader<T>` (D-4 / D-7) -- read-only, walk\n * via `.get(i)`. Consumers route through `assets.get(handle)` to\n * materialise the asset payload.\n *\n * 3. The 4 managed-vocab keywords -- `'string'` / `` `ref<T>` `` / variable\n * `'buffer'` / variable `` `array<T>` `` -- the column carries a u32 slot\n * id; the payload lives in `UniqueRefStore` / `BufferPool`. The bundle\n * entry is a `ManagedColumnReader<T>` (D-4 / D-7) -- read-only by\n * construction, no index signature. Mutation MUST flow through the\n * public dispatch (`world.set` / `world.push` / `world.allocUniqueRef`).\n *\n * The `extends SchemaFieldType` upper bound matches `ComponentSchema[K]`\n * so query bundle types do not have to pre-filter.\n */\nexport type TypedArrayFor<T extends SchemaFieldType> = T extends 'f32'\n ? Float32Array\n : T extends 'f64'\n ? Float64Array\n : T extends 'i32'\n ? Int32Array\n : T extends 'u32' | 'enum' | 'ref' | 'entity'\n ? Uint32Array\n : T extends 'i16'\n ? Int16Array\n : T extends 'u16'\n ? Uint16Array\n : T extends 'i8'\n ? Int8Array\n : T extends 'u8' | 'bool'\n ? Uint8Array\n : T extends 'string'\n ? ManagedColumnReader<'string'>\n : T extends `unique<${string}>`\n ? ManagedColumnReader<T>\n : T extends `shared<${string}>`\n ? ManagedColumnReader<T>\n : T extends 'buffer'\n ? ManagedColumnReader<'buffer'>\n : T extends `buffer<${number}>`\n ? Uint8Array\n : T extends `array<${infer Elem extends ManagedArrayElementType}, ${number}>`\n ? TypedArrayFor<\n Elem extends 'entity' | `shared<${string}>` ? 'u32' : Elem\n >\n : T extends `array<${string}>`\n ? ManagedColumnReader<T>\n : never;\n\n/**\n * Relationship metadata (feat-20260531 M2 / plan-strategy D-5). Declares this\n * component as the holder side of a Bevy-style bidirectional relationship: the\n * holder carries a single `entity` field (the target), and the engine mirrors\n * the reverse reference into `mirror`.`field` (an `array<entity>` on the target\n * entity) at add / remove / despawn time.\n *\n * - `mirror` — the mirror component's string NAME (not a type reference, so\n * `engine-ecs` never imports the mirror component type; AC-29). The mirror\n * component is a derived runtime view rebuilt by the relationship owner, so\n * it MUST declare `transient: true` — otherwise scene collect serializes it\n * and `instantiateScene` double-writes (serialized copy + owner rebuild).\n * - `field` — the `array<entity>` field on the mirror component that holds the\n * reverse list. Validated to be exactly `'array<entity>'` at `defineComponent` time.\n * - `exclusive` — when `true`, re-adding the holder component with a new target\n * auto-reparents (clears the old mirror entry, then appends the new one)\n * instead of returning `ComponentAlreadyPresentError` (AC-12).\n * - `linkedSpawn` — when `true`, despawning the target recursively despawns the\n * holders in its mirror list. Default `false` (D-1): despawn only prunes the\n * mirror entry, the holder entity survives.\n */\n/** A schema is a record of field-name → field-type keyword. */\nexport type ComponentSchema = Record<string, SchemaFieldType>;\n\n/** Derive the JS value-shape from a schema (read side; zero-copy views). */\nexport type ShapeOf<S extends ComponentSchema> = {\n [K in keyof S]: FieldValueType<S[K]>;\n};\n\n/**\n * Derive the input-side value-shape from a schema (write side; widens\n * `array<scalar>` to also accept `readonly number[]` plus the strict\n * TypedArray view). Used by `world.spawn` / `world.addComponent` /\n * `world.set` `data` so AI users can write `times: [0.5]` instead of the\n * `new Float32Array([0.5])` boilerplate. writeArrayField walks both shapes\n * via the same byte-copy path so runtime semantics are identical.\n */\nexport type InputShapeOf<S extends ComponentSchema> = {\n [K in keyof S]: FieldInputType<S[K]>;\n};\n\n// ────────────────────────────────────────────────────────────────────────────\n// ComponentId\n// ────────────────────────────────────────────────────────────────────────────\n\n/**\n * Numeric identity is an ECS-owner fact, not component authoring data. Keep it\n * out of the token's own enumerable surface so reflection sees only\n * `name`/`fields`/`storage`.\n */\n/** Component owner identity shared by independently bundled ECS entry points. */\nconst COMPONENT_OWNER_REGISTRY = Symbol.for('forgeax.ecs.componentOwnerRegistry');\ninterface ComponentOwnerRegistry {\n nextId: number;\n readonly ids: WeakMap<object, ComponentId>;\n readonly schemas: WeakMap<object, Readonly<Record<string, SchemaFieldType>>>;\n}\nconst ownerSymbols = globalThis as typeof globalThis & { [key: symbol]: unknown };\nconst ownerRegistry =\n (ownerSymbols[COMPONENT_OWNER_REGISTRY] as ComponentOwnerRegistry | undefined) ??\n (() => {\n const registry: ComponentOwnerRegistry = {\n nextId: 1,\n ids: new WeakMap<object, ComponentId>(),\n schemas: new WeakMap<object, Readonly<Record<string, SchemaFieldType>>>(),\n };\n ownerSymbols[COMPONENT_OWNER_REGISTRY] = registry;\n return registry;\n })();\n\nlet entityDefinitionSeen = false;\nlet componentDefinedBeforeEntity = false;\n\n/** @internal Barrel-only check for the id=0 Entity import-order invariant. */\nexport function isComponentDefinitionOrderValid(): boolean {\n return !componentDefinedBeforeEntity;\n}\n\n/** @internal Read the owner-assigned identity for storage/archetype code. */\nexport function componentId(component: Component): ComponentId {\n const id = ownerRegistry.ids.get(component);\n if (id === undefined) throw new Error(`Component identity missing for '${component.name}'.`);\n return id;\n}\n\n/** @internal Derive the flat type map from the fields SSOT. */\nexport function componentSchema<const C extends Component>(component: C): Readonly<SchemaOf<C>> {\n const schema = ownerRegistry.schemas.get(component);\n if (schema === undefined) throw new Error(`Component schema missing for '${component.name}'.`);\n return schema as Readonly<SchemaOf<C>>;\n}\n\n/** Numeric identifier for a component type, used by bitmask matching and archetype edges. */\nexport type ComponentId = number;\nexport type ComponentStorage = 'table' | 'sparse';\n\n// ────────────────────────────────────────────────────────────────────────────\n// Token\n// ────────────────────────────────────────────────────────────────────────────\n\ndeclare const __componentBrand: unique symbol;\n\n/**\n * Opaque component token. Carries the component name `N` as a string-literal\n * type parameter (lifted from the `defineComponent` call site via `<const N>`)\n * and the schema-shape `S` as a phantom brand so `world.get(e, Comp)` can\n * return `Result<ShapeOf<S>, EcsError>` precisely.\n *\n * The `N` parameter defaults to `string` to keep existing single-parameter\n * `Component<S>` annotations source-compatible. When inferred from a\n * `defineComponent('Position', ...)` call, `N` is the literal `'Position'`,\n * which lets query row/span mapped types resolve `{ [K in N]: ... }` to a\n * concrete keyed object instead of a degraded index signature (KD-1).\n */\nexport interface Component<N extends string = string, S extends ComponentSchema = ComponentSchema> {\n readonly name: N;\n /** The one schema projection: type, default, and enum labels per field. */\n readonly fields: Readonly<Record<keyof S & string, FieldReflection>>;\n readonly storage: ComponentStorage;\n readonly [__componentBrand]: ShapeOf<S>;\n}\n\n// ────────────────────────────────────────────────────────────────────────────\n// TypedArray constructors — internal; consumed by `scalarRow()` to build\n// TYPE_METADATA rows (feat-20260602 M4, w12).\n// ────────────────────────────────────────────────────────────────────────────\n\n/** TypedArray constructor for each scalar field type. */\nconst VIEW_CTORS: Readonly<\n Record<\n ScalarFieldType,\n | Float32ArrayConstructor\n | Float64ArrayConstructor\n | Int32ArrayConstructor\n | Uint32ArrayConstructor\n | Int16ArrayConstructor\n | Uint16ArrayConstructor\n | Int8ArrayConstructor\n | Uint8ArrayConstructor\n >\n> = {\n f32: Float32Array,\n f64: Float64Array,\n i32: Int32Array,\n u32: Uint32Array,\n i16: Int16Array,\n u16: Uint16Array,\n i8: Int8Array,\n u8: Uint8Array,\n bool: Uint8Array,\n enum: Uint32Array,\n ref: Uint32Array,\n};\n\n// ────────────────────────────────────────────────────────────────────────────\n// TYPE_METADATA — global per-type metadata table (feat-20260602 M1 / D-A6)\n//\n// Converges the 12 scattered type-intrinsic structures (3 tables + 9\n// predicate / tool functions) into a single per-type authoritative table.\n// Exports FIELD_SIZE_BYTES / VIEW_CTORS / isSchemaVocabKeyword /\n// managedArrayElementBytes / SUPPORTED_FIELD_TYPES / storageFieldType were\n// deleted M4 (w12); internal FIELD_SIZE_BYTES + VIEW_CTORS constants remain as\n// build inputs for scalarRow(). All former consumers now read TYPE_METADATA:\n// storage routing via fieldTypeToMetaKey() + TYPE_METADATA[key].storage,\n// scalar checks via TYPE_METADATA[key]?.isScalar.\n//\n// Mixed key granularity (D-5): the 11 scalars are keyed by their concrete\n// type (`f32` ... `ref`); the 6 vocab families are keyed by family (`entity`\n// / `string` / `buffer` / `ref` / `handle` / `array`). The `array` row's T/N\n// parameters are NOT table columns — they are parsed per-field into\n// `arrayMeta` (see FieldDescriptor below). The vocab `ref` family row and\n// the scalar `ref` row share the `'ref'` key intentionally: the scalar is a\n// u32 column placeholder and the vocab `ref<T>` form maps to the same\n// managed-ref storage, so one row carries both (isScalar + isManaged both\n// true). tweak-20260612-ecs-concept-compression dropped redundant columns:\n// `isVocabKeyword` (zero production consumers), the per-vocab managed-\n// ref predicate column (100% duplicate of `isManaged`), and the YAGNI\n// `fixedByteLength` placeholder;\n// `isLegacyScalar` was renamed `isScalar` (the \"legacy\" prefix labelled the\n// historical M2-introduction tense; the 11 scalars are first-class).\n// ────────────────────────────────────────────────────────────────────────────\n\n/**\n * One row of the global type-metadata table. Carries the type-intrinsic\n * properties a field type has regardless of which component declares it.\n *\n * - `byteSize` — element byte width for the column-storage scalar; `undefined`\n * for families whose storage byte size is not a fixed per-type constant\n * (variable buffer / array slot ids are u32-stored, surfaced via `storage`).\n * - `viewCtor` — TypedArray constructor for the column storage; `undefined`\n * for families without a direct TypedArray column.\n * - `storage` — the column-storage scalar type this field routes to (every\n * vocab family stores a u32 slot id / handle).\n * - `isScalar` — member of the 11 concrete scalar types\n * (`f32`/`f64`/`i32`/`u32`/`i16`/`u16`/`i8`/`u8`/`bool`/`enum`/`ref`).\n * - `isManaged` — routed through `UniqueRefStore` (string / ref<T>).\n * - `isBuffer` — a `buffer` / `buffer<N>` managed-byte slot.\n * - `isEntityRef` — the single-entity `entity` reference keyword.\n * - `isArray` — an `array<T>` / `array<T,N>` keyword.\n */\nexport interface TypeMetadataRow {\n readonly byteSize: number | undefined;\n readonly viewCtor:\n | Float32ArrayConstructor\n | Float64ArrayConstructor\n | Int32ArrayConstructor\n | Uint32ArrayConstructor\n | Int16ArrayConstructor\n | Uint16ArrayConstructor\n | Int8ArrayConstructor\n | Uint8ArrayConstructor\n | undefined;\n readonly storage: ScalarFieldType;\n readonly isScalar: boolean;\n readonly isManaged: boolean;\n readonly isBuffer: boolean;\n readonly isEntityRef: boolean;\n readonly isArray: boolean;\n}\n\n/** Build a scalar row from the concrete scalar type. */\nfunction scalarRow(t: ScalarFieldType): TypeMetadataRow {\n return {\n byteSize: FIELD_SIZE_BYTES[t],\n viewCtor: VIEW_CTORS[t],\n storage: t,\n isScalar: true,\n // The scalar `ref` shares its key with the vocab `ref<T>` family; mark\n // it as managed so the single row covers both.\n isManaged: t === 'ref',\n isBuffer: false,\n isEntityRef: false,\n isArray: false,\n };\n}\n\n/**\n * Global per-type metadata table. Keyed by concrete scalar type (11) plus\n * vocab family (6 — `entity` / `string` / `buffer` / `ref` / `handle` /\n * `array`). The `ref` key is shared by the legacy scalar and the vocab family\n * (see header). Every vocab family stores a u32 slot id / handle.\n *\n * Built once at module load; frozen so downstream consumers (column.ts /\n * archetype.ts / world.ts, migrated M2) read a stable single source.\n */\nexport const TYPE_METADATA: Readonly<Record<string, TypeMetadataRow>> = Object.freeze({\n f32: scalarRow('f32'),\n f64: scalarRow('f64'),\n i32: scalarRow('i32'),\n u32: scalarRow('u32'),\n i16: scalarRow('i16'),\n u16: scalarRow('u16'),\n i8: scalarRow('i8'),\n u8: scalarRow('u8'),\n bool: scalarRow('bool'),\n enum: scalarRow('enum'),\n ref: scalarRow('ref'),\n entity: {\n byteSize: 4,\n viewCtor: Uint32Array,\n storage: 'u32',\n isScalar: false,\n isManaged: false,\n isBuffer: false,\n isEntityRef: true,\n isArray: false,\n },\n string: {\n byteSize: 4,\n viewCtor: Uint32Array,\n storage: 'u32',\n isScalar: false,\n isManaged: true,\n isBuffer: false,\n isEntityRef: false,\n isArray: false,\n },\n buffer: {\n byteSize: 4,\n viewCtor: Uint32Array,\n storage: 'u32',\n isScalar: false,\n isManaged: false,\n isBuffer: true,\n isEntityRef: false,\n isArray: false,\n },\n // feat-20260614-ecs-shared-component-and-unique-rename M3 (plan-strategy\n // D-3): independent `'shared'` row, NOT a reuse of the `'ref'` (post-M2:\n // `'unique<T>'` family) row. `isManaged: true` so write-barrier dispatch\n // routes shared<T> fields through release on despawn / removeComponent /\n // set-overwrite, but the M4 sub-dispatch in releaseManagedFieldOnRow will\n // separate shared (rc--) from unique (direct slot drop) using the\n // fieldType.startsWith('shared<') predicate. Keeping the meta key\n // independent preserves the \"meta key = release semantics\" invariant\n // (architecture-principles.md #1 SSOT).\n shared: {\n byteSize: 4,\n viewCtor: Uint32Array,\n storage: 'u32',\n isScalar: false,\n isManaged: true,\n isBuffer: false,\n isEntityRef: false,\n isArray: false,\n },\n array: {\n byteSize: 4,\n viewCtor: Uint32Array,\n storage: 'u32',\n isScalar: false,\n isManaged: false,\n isBuffer: false,\n isEntityRef: false,\n isArray: true,\n },\n});\n\n// ────────────────────────────────────────────────────────────────────────────\n// FieldDescriptor — input field-descriptor object + per-field reflection\n// (feat-20260602 M1 / D-A1 / D-A3)\n// ────────────────────────────────────────────────────────────────────────────\n\n/**\n * Pre-parsed `array<T>` / `array<T,N>` reflection. Bare length sentinel\n * (D-A1 user ruling): `length` present => fixed-capacity, `length === undefined`\n * => variable-capacity. No `isVariable` / `kind` field — both are losslessly\n * derivable from `length` presence (architecture-principles.md #2 Derive). This\n * is exactly the existing `parseManagedArraySchema` return shape (zero shape\n * change).\n */\nexport interface ArrayMeta {\n readonly elementType: ManagedArrayElementType;\n readonly length?: number;\n}\n\n/**\n * Input field-descriptor object (D-A3). The second `defineComponent` argument\n * may declare each field either as a bare type keyword (legacy flat form,\n * still accepted through M2; migrated repo-wide in M3) or as a descriptor\n * object aggregating `type` + `default` + semantic `shape` + field-level\n * `meta`.\n *\n * - `type` — the schema field-type keyword (a parametrized string such as\n * `'array<f32,3>'` / `'unique<MaterialAsset>'` is used verbatim, D-A2).\n * - `default` — layer-2 default value; retained in the field reflection row.\n * - `shape` — producer-owned semantic shape tag for schema consumers; it does\n * not change ECS storage or runtime value semantics.\n * - `meta` — field-level open namespace; aggregated into `component.meta`. The\n * infra gives no key special meaning (open map, OOS-1).\n * - `transient` — when `true`, scene collect skips this field (D-5). Same word,\n * same meaning as the component-level `transient` flag, with granularity sunk\n * to the field level: a field that is derived/reconstructable (e.g. a resolved\n * world mat4) is excluded from serialization while its component's persisted\n * fields still round-trip. Absent (the common case) means the field is\n * serialized.\n * - `labels` — for an `enum` field ONLY: the label→numeric-value map (e.g.\n * `{ static: 0, dynamic: 1, kinematic: 2 }`). An `enum` field stores a bare\n * `u32` variant index; the human-readable names historically lived in a\n * SEPARATE per-package const map (`RigidBodyTypeValue`) + comment table, so no\n * schema consumer could read them and the two could drift. Declaring `labels`\n * attaches that map to the field itself (SSOT-adjacent): it is aggregated into\n * `component.fields[field].labels` and surfaced by reflection consumers (the\n * editor's `describeComponent`, inspector UIs, validation hints) so a\n * docs-only user learns the legal variants + their integers from the schema\n * alone. Pass the EXISTING `*Value` const map here (Derive, don't Duplicate —\n * one object, two consumers). Absent for non-enum fields / enums that opt out.\n */\nexport interface FieldDescriptor<T extends SchemaFieldType = SchemaFieldType> {\n readonly type: T;\n readonly default?: FieldValueType<T>;\n /** Semantic authoring shape; storage still follows `type`. */\n readonly shape?: FieldShapeKind;\n readonly meta?: Readonly<Record<string, unknown>>;\n readonly transient?: boolean;\n readonly labels?: Readonly<Record<string, number>>;\n}\n\n/**\n * Per-field reflection produced at registration time and read off\n * `component.fields[fieldName]` (D-A3). Carries the pre-parsed facts: the\n * field `type`, its `default` (if any), semantic `shape` (if declared), — for\n * `array<...>` fields only — the pre-parsed `arrayMeta` (parse happens once at\n * registration, AC-03c), and the field-level `transient` flag (D-5) when\n * declared.\n *\n * `transient` mirrors the component-level `Component.transient` (same word,\n * same meaning): scene collect skips a `transient` field just as it skips a\n * `transient` component. Granularity is sunk to the field level so a component\n * can persist most of its fields while excluding a derived/reconstructable one\n * (e.g. `GlobalTransform.world`). Absent means the field participates in\n * serialization.\n */\nexport interface FieldReflection {\n readonly type: SchemaFieldType;\n readonly default?: unknown;\n /** Producer-declared semantic shape, when storage type alone is insufficient. */\n readonly shape?: FieldShapeKind;\n readonly arrayMeta?: ArrayMeta;\n readonly transient?: boolean;\n /**\n * For an `enum` field: the label→numeric-value map declared on the field\n * descriptor (see `FieldDescriptor.labels`). Lets a schema consumer resolve a\n * variant name ↔ its stored `u32` index without a separate const map. Absent\n * for non-enum fields / enums that did not declare labels.\n */\n readonly labels?: Readonly<Record<string, number>>;\n}\n\n/**\n * One input field-spec value: either the bare type keyword (legacy flat form)\n * or a field-descriptor object. Accepting both keeps the ~44 flat-string\n * call-sites + ~55 test files green through M1/M2 while the field-descriptor\n * form is migrated in repo-wide in M3 (D-A7 / D-A8 shrink the migration\n * surface to the input side only).\n */\nexport type FieldSpec<T extends SchemaFieldType = SchemaFieldType> = T | FieldDescriptor<T>;\n\n/** An input field-spec map: field-name -> bare keyword | field-descriptor. */\nexport type FieldsInput = Record<string, FieldSpec>;\n\n/**\n * Project an input field-spec map down to its flat `ComponentSchema` shape\n * (field-name -> type keyword). A bare-keyword spec maps to itself (identity,\n * so existing flat-string call-sites infer exactly as before); a descriptor\n * spec maps to its `type`. This keeps `Component<N, SchemaOf<F>>` driving every\n * downstream type (ShapeOf / query row/span projection / TypedArrayFor) unchanged.\n */\nexport type SchemaOf<F extends FieldsInput | Component> =\n F extends Component<string, infer S>\n ? S\n : F extends FieldsInput\n ? {\n [K in keyof F]: F[K] extends FieldDescriptor<infer T>\n ? T\n : F[K] extends SchemaFieldType\n ? F[K]\n : never;\n }\n : never;\n\n// ────────────────────────────────────────────────────────────────────────────\n// defineComponent\n// ────────────────────────────────────────────────────────────────────────────\n\n/** Optional configuration for `defineComponent` (w4, M3 consumer; w21 layer-2 defaults). */\nexport interface DefineComponentOptions {\n readonly storage?: ComponentStorage;\n /**\n * When `true`, the component is skipped by scene collect\n * (rootsToSceneAsset). The component stays in archetype columns and\n * participates normally in queries / world.get at runtime.\n *\n * Default: `false`. Mirror targets of relationship components should\n * declare `transient: true` so they are not serialized (their state is\n * rebuilt by the mirror hook after instantiateScene).\n */\n readonly transient?: boolean;\n /**\n * Components materialized automatically when this component is added.\n * Explicit data for a required component wins; the ECS appends only missing\n * identities at the spawn/add boundary, never from a frame system.\n */\n readonly requires?: readonly Component[];\n /**\n * Component-level open metadata namespace. Entries are copied into\n * `Component.meta` at registration; the ECS core assigns no meaning to any\n * key. Component-level entries win over field-level entries with the same\n * key, and consumers may extend the mutable map after registration.\n */\n readonly meta?: Readonly<Record<string, unknown>>;\n}\n\n/**\n * Extract the bare field-type keyword from a field-spec (bare keyword | field-\n * descriptor object), fail-fast if a descriptor object is missing its `type`.\n * The throw carries the field name + expected shape (charter P3 / OOS-6: this\n * is a programmer error caught at registration time, no new EcsErrorCode).\n */\nfunction fieldSpecType(fieldName: string, spec: FieldSpec): SchemaFieldType {\n if (typeof spec === 'string') return spec as SchemaFieldType;\n const t = (spec as FieldDescriptor).type;\n if (typeof t !== 'string') {\n throw new SchemaUnsupportedFieldError(\n fieldName,\n `<field-descriptor missing 'type'> (expected { type, default?, meta? })`,\n );\n }\n return t as SchemaFieldType;\n}\n\n/**\n * Define a component. Returns a frozen opaque token with exactly three runtime\n * facts: `.name`, `.fields`, and `.storage`. Numeric identity, flat schema,\n * and defaults are owner projections held outside the token.\n *\n * The second argument accepts each field either as a bare type keyword\n * ('f32', 'array<entity>', ...) or as a field-descriptor object\n * `{ type, default?, meta? }` (D-A3). The single `FieldsInput` overload\n * handles both forms — bare keywords are identity through `SchemaOf<F>`.\n *\n * The `<const N>` modifier lifts `name` to its string-literal type so the\n * returned `Component<N, SchemaOf<S>>` drives precise key-based mapped types\n * downstream (for example QueryRow and QuerySpan projections). At runtime `name` is a plain\n * string.\n *\n * Schema-field validation accepts both the legacy scalar tier\n * (`ScalarFieldType`, 11 keywords) and the schema-vocab tier\n * (`SchemaVocabKeyword`, 8 patterns including `array<T,N>` / `array<T>` /\n * `buffer` / `buffer<N>`). Mismatched values raise\n * `SchemaUnsupportedFieldError`. Illegal `array<...>` element types\n * (e.g. `array<ref<X>>`) raise `ManagedArrayElementTypeNotAllowedError`\n * (AC-03 runtime fail-safe).\n *\n * Relationship roles are declared through `defineRelationship`; component\n * definitions contain only schema vocabulary and no mirror metadata.\n *\n * @throws SchemaUnsupportedFieldError for any field type not in the supported\n * set, or a field-descriptor object missing its `type`.\n * @throws ManagedArrayElementTypeNotAllowedError when an `array<...>`\n * keyword carries an illegal element type.\n * @throws RelationshipMirrorComponentNotRegisteredError when\n * `relationship.mirror` names a component not yet defined.\n * @throws RelationshipMirrorFieldTypeMismatchError when the mirror's\n * `relationship.field` is missing or not typed `'array<entity>'`.\n */\n// Single signature post-M4 (w12) — bare-keyword field specs are valid\n// FieldSpec<T> values (identity through SchemaOf<F>), so flat-string schemas\n// work without a separate overload. tweak-20260612-ecs-concept-compression\n// dropped the redundant byte-identical overload declaration.\nexport function defineComponent<const N extends string, const S extends FieldsInput>(\n name: N,\n fields: S,\n options?: DefineComponentOptions,\n): Component<N, SchemaOf<S>> {\n const storage = options?.storage ?? 'table';\n assertComponentStorage(storage);\n if (storage === 'sparse' && Object.keys(fields).length !== 0) {\n throw new SparseStorageRequiresTagError(name);\n }\n const schema: Record<string, SchemaFieldType> = {};\n const reflectedFields: Record<string, FieldReflection> = {};\n const collectedMeta: Record<string, unknown> = {};\n const collectedDefaults: Record<string, unknown> = {};\n\n for (const fieldName of Object.keys(fields)) {\n const spec = fields[fieldName] as FieldSpec;\n const fieldType = fieldSpecType(fieldName, spec);\n\n // Validate the field type — same fail-fast as before, now over the\n // normalized keyword.\n let arrayMeta: ArrayMeta | undefined;\n if (TYPE_METADATA[fieldType]?.isScalar === true) {\n // legacy scalar — ok\n } else if (fieldType === 'string') {\n // string vocab — ok\n } else if (fieldType.startsWith('array<') && fieldType.endsWith('>')) {\n const parsed = parseManagedArraySchema(fieldType);\n if (parsed === null) {\n const elementType = fieldType.slice(6, -1);\n throw new ManagedArrayElementTypeNotAllowedError(fieldName, elementType);\n }\n // Pre-parse once at registration (AC-03c): array fields cache arrayMeta.\n // Bare length sentinel {elementType, length?} (D-A1): drop `length` when\n // variable so the row is byte-identical to the parse return shape.\n arrayMeta = deepFreeze(\n parsed.length === undefined\n ? { elementType: parsed.elementType }\n : { elementType: parsed.elementType, length: parsed.length },\n );\n } else if (!isSchemaVocabKeyword(fieldType)) {\n throw new SchemaUnsupportedFieldError(fieldName, fieldType);\n }\n\n schema[fieldName] = fieldType;\n\n // Per-field reflection row — only attach arrayMeta / default when present\n // (exactOptionalPropertyTypes: never set an explicit `undefined`).\n const row: {\n type: string;\n default?: unknown;\n shape?: FieldShapeKind;\n arrayMeta?: ArrayMeta;\n transient?: boolean;\n labels?: Readonly<Record<string, number>>;\n } = {\n type: fieldType,\n };\n if (typeof spec !== 'string') {\n const desc = spec as FieldDescriptor;\n if ('default' in desc) {\n row.default = desc.default;\n collectedDefaults[fieldName] = desc.default;\n }\n if (desc.shape !== undefined) row.shape = desc.shape;\n if (desc.meta !== undefined) {\n Object.assign(collectedMeta, desc.meta);\n }\n // exactOptionalPropertyTypes: only attach `transient` when declared.\n if (desc.transient !== undefined) row.transient = desc.transient;\n // enum label→value map (see FieldDescriptor.labels). Frozen so the\n // reflected row exposes a stable read-only map. Only enum fields declare it.\n if (desc.labels !== undefined) row.labels = deepFreeze({ ...desc.labels });\n }\n if (arrayMeta !== undefined) row.arrayMeta = arrayMeta;\n reflectedFields[fieldName] = Object.freeze(row) as FieldReflection;\n }\n\n if (name === 'Entity') {\n entityDefinitionSeen = true;\n } else if (!entityDefinitionSeen) {\n componentDefinedBeforeEntity = true;\n }\n const id = name === 'Entity' ? 0 : ownerRegistry.nextId++;\n\n // Derived defaults projection (D-A8): pure from `fields[k].default`.\n // No longer merged with a removed `options.defaults` input — strict single-entry\n // means the only way to set a layer-2 default is through the field descriptor.\n const frozenDefaults =\n Object.keys(collectedDefaults).length === 0\n ? undefined\n : (deepFreeze(collectedDefaults) as Readonly<Partial<ShapeOf<SchemaOf<S>>>>);\n\n // Keep the component token immutable while leaving its open metadata map\n // extensible for higher-level consumers after registration.\n if (options?.meta !== undefined) {\n Object.assign(collectedMeta, options.meta);\n }\n const frozenSchema = deepFreeze(schema);\n const frozenFields = deepFreeze(reflectedFields);\n const meta = collectedMeta;\n const token = Object.freeze({ name, fields: frozenFields, storage }) as Component<N, SchemaOf<S>>;\n ownerRegistry.ids.set(token, id);\n ownerRegistry.schemas.set(token, frozenSchema);\n registerComponentDefinition(token, {\n fields: frozenFields,\n defaults: frozenDefaults,\n policy: {\n transient: options?.transient ?? false,\n meta,\n requires: Object.freeze([...(options?.requires ?? [])]),\n },\n });\n return Object.freeze(token);\n}\n\nexport class ComponentInUseError extends Error {\n override readonly name = 'ComponentInUseError';\n readonly code = 'component-in-use' as const;\n readonly expected = 'the component to have no live entity or scheduled-system references';\n readonly hint =\n 'Remove owning systems and component values before disposing the registration lease.';\n readonly detail: { readonly componentName: string };\n\n constructor(componentName: string) {\n super(`Component ${componentName} is still in use.`);\n this.detail = { componentName };\n }\n}\n\nexport class ComponentNameConflictError extends Error {\n override readonly name = 'ComponentNameConflictError';\n readonly code = 'component-name-conflict' as const;\n readonly expected = 'one component token per name in a World';\n readonly hint =\n 'Use the token already registered in this World or choose a distinct component name.';\n readonly detail: { readonly componentName: string };\n\n constructor(componentName: string) {\n super(`Component ${componentName} is already registered with a different token.`);\n this.detail = { componentName };\n }\n}\n\nexport type ComponentCatalogError = ComponentInUseError | ComponentNameConflictError;\n\nexport interface ComponentLease {\n readonly component: Component;\n dispose(): Result<void, ComponentInUseError>;\n}\n\ninterface ComponentRegistration {\n readonly component: Component;\n owners: number;\n}\n\n/** World-local discovery and ownership boundary for plugin-installed component vocabulary. */\nexport class ComponentCatalog {\n private readonly registrations = new Map<string, ComponentRegistration>();\n\n constructor(private readonly inUse: (component: Component) => boolean) {}\n\n register(component: Component): Result<ComponentLease, ComponentNameConflictError> {\n const current = this.registrations.get(component.name);\n if (current !== undefined && current.component !== component) {\n return err(new ComponentNameConflictError(component.name));\n }\n if (current === undefined) {\n this.registrations.set(component.name, { component, owners: 1 });\n } else {\n current.owners += 1;\n }\n\n let active = true;\n return ok({\n component,\n dispose: () => {\n if (!active) return ok(undefined);\n const registration = this.registrations.get(component.name);\n if (registration === undefined || registration.component !== component) {\n active = false;\n return ok(undefined);\n }\n if (registration.owners > 1) {\n registration.owners -= 1;\n active = false;\n return ok(undefined);\n }\n if (this.inUse(component)) return err(new ComponentInUseError(component.name));\n this.registrations.delete(component.name);\n active = false;\n return ok(undefined);\n },\n });\n }\n\n resolve(name: string): Component | undefined {\n return this.registrations.get(name)?.component;\n }\n\n entries(): ReadonlyMap<string, Component> {\n return new Map(\n [...this.registrations].map(([name, registration]) => [name, registration.component]),\n );\n }\n}\n","// @forgeax/engine-ecs - Entity component (feat-20260602-archetype-stores-full-packed-entity M1 / w1).\n//\n// Entity identity is modelled as a real id=0 ECS component `Entity`, whose sole\n// field `self` stores the full 32-bit packed entity handle (generation << 24 |\n// index). Every archetype carries this column unconditionally (it is essential\n// and cannot be removed), so an entity's own handle is read through the exact\n// same query / read path as Transform / MeshRenderer columns:\n//\n// const query = world.query({ read: [Transform] }).unwrap();\n// for (const row of query) row.entity;\n// world.get(e, Entity).unwrap().self === e\n//\n// This retires the \"entity is an archetype side-array + three-step rebuild\"\n// implementation detail (index slot -> generation lookup -> encodeEntity) in\n// favour of a single uniform column read.\n//\n// id=0 structural guarantee: `Entity` MUST be the first `defineComponent`\n// evaluated in the process so the owner identity assigns it 0. The package\n// barrel (packages/ecs/src/index.ts) force-evaluates this module before any\n// other component-defining module and asserts the invariant fail-fast.\n// See plan-strategy D-1 / D-6b (LP-1): the hard-coded 0 + barrel forced\n// registration + startup throw is the locked design; no UECS-style runtime\n// token lookup is introduced (the hot-path archetype column key stays a numeric\n// owner-assigned component identity).\n//\n// charter mapping: P4 (consistent abstraction -- reading the entity handle is\n// reading any other column) + P3 (id=0 drift surfaces as a structured startup\n// throw, never a silent runtime mis-id) + P1 (single top-level import surface).\n\nimport type { ComponentId } from './component';\nimport { componentId, defineComponent } from './component';\n\n/**\n * The id=0 essential `Entity` component. Its single `self` field carries the\n * full packed entity handle for the row it sits on (written at spawn time).\n *\n * Naming convention (feat-20260611-ecs-storage-naming-ssot):\n *\n * - Value-space `Entity` (this const) is the id=0 component token. It is\n * looked up by name (`'Entity'`) at component-registration time and used\n * as a value (`world.spawn`, `world.get(entity, Entity)`).\n * - Type-space `EntityHandle` (the branded number, exported from `../entity`)\n * is the row-identifier handle type. It is used in `: EntityHandle`\n * annotations.\n *\n * The two no longer share a name -- the prior intentional coexistence (a\n * single `Entity` symbol carrying both meanings via TS namespace merging) was\n * dropped because two-roles-one-name created repeated AI-user confusion when\n * reading `: Entity` annotations (is this the handle or the token?). The id=0\n * component token's name (the literal string `'Entity'`) is preserved for\n * runtime stability; only the type-space alias was renamed.\n *\n * @example Read an entity's own handle through a query:\n * const query = world.query({ read: [Transform] }).unwrap();\n * for (const row of query) {\n * const handle = row.entity;\n * }\n *\n * @example Use `world.get` as a general liveness probe:\n * const r = world.get(e, Entity);\n * if (!r.ok) { // r.error.code === 'stale-entity' for a despawned handle\n * }\n */\nexport const Entity = defineComponent('Entity', {\n // Layer-2 default is never observed: `world.spawn` always overwrites `self`\n // with the freshly encoded handle for the row. `null` is the type-correct\n // \"no handle yet\" placeholder (`'entity'` decodes to `EntityHandle | null`).\n self: { type: 'entity', default: null },\n});\n\n/**\n * Marks an entity as disabled.\n *\n * Queries exclude this tag by default. Add `Disabled` to a query's `with`\n * tuple when the query must inspect or re-enable disabled entities.\n */\nexport const Disabled = defineComponent('Disabled', {});\n\n/**\n * SSOT for component ids that are essential to every archetype. Every archetype\n * carries the columns named by these ids unconditionally (they cannot be added\n * or removed via `addComponent` / `removeComponent`). Currently only `Entity`\n * is essential -- the row-identity column that lets every entity read its own\n * packed handle (`world.get(e, Entity).self === e`) through the same column\n * path as any other component (feat-20260602 / charter P4).\n *\n * Frozen so consumers cannot mutate the SSOT. The barrel\n * (`packages/ecs/src/index.ts`) re-exports this constant so the AI-facing\n * `import { ESSENTIAL_COMPONENT_IDS } from '@forgeax/engine-ecs'` works.\n *\n * Physical location is `packages/ecs/src/entity.ts` -- the module that owns\n * the `defineComponent('Entity', ...)` call, so reading the owner identity\n * immediately after registration is well-defined. tweak-20260612-ecs-concept-\n * compression lifted this file back from the historical `components/entity.ts`\n * after `entity-handle.ts` freed up the `entity.ts` slot.\n */\nexport const ESSENTIAL_COMPONENT_IDS: ReadonlyArray<ComponentId> = Object.freeze([\n componentId(Entity),\n]);\n\n/**\n * Fold the essential component ids (currently `[componentId(Entity)]`) into a caller-\n * supplied id list. Returns a NEW array; never mutates the input.\n *\n * - If `ids` already contains every essential id, returns a deduped copy\n * (idempotent under repeated folding).\n * - Otherwise, returns `[...essential, ...ids]` with duplicates of the\n * essential ids removed.\n *\n * The empty input maps to `[componentId(Entity)]` -- the bare-archetype shape that a\n * `world.spawn()` (no components) materialises.\n *\n * Single SSOT consumed by both `archetypeKey` (string-key fold) and\n * `createArchetype` (column-build fold) so the two sites can never disagree\n * on which ids are essential. Hot-path correctness is on `createArchetype`'s\n * side: misalignment between key and columns silently drops fields.\n *\n * @example\n * foldEssentials([2, 5, 7]) // [componentId(Entity), 2, 5, 7]\n * foldEssentials([componentId(Entity), 2, 5]) // [componentId(Entity), 2, 5]\n * foldEssentials([componentId(Entity), componentId(Entity)]) // [componentId(Entity)]\n * foldEssentials([]) // [componentId(Entity)]\n */\nexport function foldEssentials(ids: ReadonlyArray<ComponentId>): ComponentId[] {\n const seen = new Set<ComponentId>();\n const out: ComponentId[] = [];\n for (const essential of ESSENTIAL_COMPONENT_IDS) {\n if (!seen.has(essential)) {\n seen.add(essential);\n out.push(essential);\n }\n }\n for (const id of ids) {\n if (!seen.has(id)) {\n seen.add(id);\n out.push(id);\n }\n }\n return out;\n}\n","import { Context, type Plugin } from '@forgeax/engine-plugin';\n\nimport type { World } from './world';\n\ndeclare module '@forgeax/engine-plugin' {\n interface EngineContextServices {\n world: World;\n }\n}\n\nexport function worldPlugin(world: World): Plugin {\n return {\n name: 'world',\n provide: 'world',\n apply(ctx) {\n ctx.provide('world', world);\n },\n };\n}\n\n/** Create one Cordis realm whose root service is the ECS World. */\nexport async function createWorldContext(\n world: World,\n plugins: readonly Plugin[] = [],\n): Promise<Context> {\n const ctx = new Context();\n try {\n await ctx.plugin(worldPlugin(world));\n for (const plugin of plugins) await ctx.plugin(plugin);\n return ctx;\n } catch (error) {\n await ctx.fiber.dispose();\n throw error;\n }\n}\n","import {\n type Component,\n type ComponentSchema,\n defineComponent,\n type FieldsInput,\n} from './component';\nimport type { EntityHandle } from './entity-handle';\n\ndeclare const relationshipTargetBrand: unique symbol;\n\n/** A relationship target is a read projection, never a structural-write token. */\nexport type RelationshipTargetComponent<C extends Component = Component> = C & {\n readonly [relationshipTargetBrand]: true;\n};\n\n/** The two immutable roles produced by one relationship declaration. */\nexport interface RelationshipDefinition {\n readonly source: Component<string, ComponentSchema>;\n readonly target: RelationshipTargetComponent<Component<string, ComponentSchema>>;\n}\n\nexport interface RelationshipOptions {\n readonly sourceName: string;\n readonly sourceField: string;\n readonly targetName: string;\n readonly targetField: string;\n /**\n * Components materialized with the writable source side. This is the\n * relationship equivalent of `defineComponent(..., { requires })`: the\n * dependency is resolved once at the structural boundary, never by a frame\n * system. It applies only to the source; the reverse target remains an\n * engine-owned projection.\n */\n readonly sourceRequires?: readonly Component[];\n readonly exclusive?: boolean;\n readonly linkedSpawn?: boolean;\n /** Allow a source to point at its own holder (e.g. self-animated entities). */\n readonly allowSelf?: boolean;\n}\n\nexport type RelationshipRole =\n | {\n readonly kind: 'source';\n readonly target: Component<string, ComponentSchema>;\n readonly sourceField: string;\n readonly targetField: string;\n readonly exclusive: boolean;\n readonly linkedSpawn: boolean;\n readonly allowSelf: boolean;\n }\n | {\n readonly kind: 'target';\n readonly source: Component<string, ComponentSchema>;\n readonly sourceField: string;\n readonly targetField: string;\n };\n\nconst roles = new WeakMap<Component, RelationshipRole>();\n\n/**\n * Declare both sides of a relationship in one closed operation. The source is\n * the only writable relationship component; its target is a materialized,\n * engine-maintained reverse list.\n */\nexport function defineRelationship<\n const S extends string,\n const SF extends string,\n const T extends string,\n const TF extends string,\n>(\n options: RelationshipOptions & {\n readonly sourceName: S;\n readonly sourceField: SF;\n readonly targetName: T;\n readonly targetField: TF;\n },\n): {\n readonly source: Component<S, { [K in SF]: 'entity' }>;\n readonly target: RelationshipTargetComponent<Component<T, { [K in TF]: 'array<entity>' }>>;\n} {\n const targetFields: FieldsInput = {\n [options.targetField]: { type: 'array<entity>', transient: true },\n };\n const target = defineComponent(options.targetName, targetFields);\n const sourceFields: FieldsInput = { [options.sourceField]: { type: 'entity' } };\n const source = defineComponent(\n options.sourceName,\n sourceFields,\n options.sourceRequires === undefined ? undefined : { requires: options.sourceRequires },\n );\n\n roles.set(source, {\n kind: 'source',\n target,\n sourceField: options.sourceField,\n targetField: options.targetField,\n exclusive: options.exclusive ?? true,\n linkedSpawn: options.linkedSpawn ?? false,\n allowSelf: options.allowSelf ?? false,\n });\n roles.set(target, {\n kind: 'target',\n source,\n sourceField: options.sourceField,\n targetField: options.targetField,\n });\n return { source: source as never, target: target as never };\n}\n\nexport function relationshipRole(component: Component): RelationshipRole | undefined {\n return roles.get(component);\n}\n\n/** Return the materialized target token owned by a source relationship. */\nexport function relationshipMirror(component: Component): Component | undefined {\n const role = roles.get(component);\n return role?.kind === 'source' ? role.target : undefined;\n}\n\n/** Return the source token owned by a materialized relationship target. */\nexport function relationshipSource(component: Component): Component | undefined {\n const role = roles.get(component);\n return role?.kind === 'target' ? role.source : undefined;\n}\n\nexport function isRelationshipTarget(component: Component): boolean {\n return roles.get(component)?.kind === 'target';\n}\n\n/**\n * Backpointer index for the materialized reverse lists stored by World.\n * The target component array is the one authoritative read list; this index\n * stores only source-to-target locations for O(1) swap-remove bookkeeping.\n */\nexport class RelationshipIndex {\n private readonly slots = new Map<number, { target: number; slot: number }>();\n private epochValue = 0;\n\n get epoch(): number {\n return this.epochValue;\n }\n\n attach(source: EntityHandle, target: EntityHandle, slot: number): number {\n this.slots.set(source as number, { target: target as number, slot });\n this.epochValue++;\n return slot;\n }\n\n detach(source: EntityHandle): boolean {\n if (!this.slots.delete(source as number)) return false;\n this.epochValue++;\n return true;\n }\n\n reparent(source: EntityHandle, target: EntityHandle, slot: number): number {\n return this.attach(source, target, slot);\n }\n\n slotOf(source: EntityHandle): number | undefined {\n return this.slots.get(source as number)?.slot;\n }\n\n targetOf(source: EntityHandle): EntityHandle | undefined {\n return this.slots.get(source as number)?.target as EntityHandle | undefined;\n }\n\n /** Bind the source that swap-remove moved into `slot`. */\n updateSlot(source: EntityHandle, target: EntityHandle, slot: number): void {\n const location = this.slots.get(source as number);\n if (location === undefined) return;\n location.target = target as number;\n location.slot = slot;\n this.epochValue++;\n }\n\n /** Cold recovery path only: rebuild from R source records. */\n recover(records: Iterable<readonly [EntityHandle, EntityHandle]>): void {\n this.slots.clear();\n const nextSlots = new Map<number, number>();\n for (const [source, target] of records) {\n const slot = nextSlots.get(target as number) ?? 0;\n nextSlots.set(target as number, slot + 1);\n this.attach(source, target, slot);\n }\n this.epochValue++;\n }\n}\n","/**\n * Nominal label for one of the World-owned schedules.\n *\n * Worlds expose the built-in tokens below. A token is both a registration\n * scope and, for FixedUpdate, the intrinsic Update ordering anchor.\n */\nexport interface ScheduleToken {\n readonly name: string;\n}\n\nexport type ScheduleName = 'Update' | 'FixedUpdate';\n\nfunction createScheduleToken(name: ScheduleName): ScheduleToken {\n // The Engine Worker loads its runtime and an execution bootstrap as separate\n // Vite bundles. Keep the two built-in tokens physically shared across those\n // bundles so a plugin's `Update` reference still addresses the owning World\n // schedule instead of becoming an accidental cross-scope edge.\n const registry = globalThis as typeof globalThis & {\n readonly [key: symbol]: ScheduleToken | undefined;\n };\n const key = Symbol.for(`forgeax.ecs.schedule-token.${name}`);\n const existing = registry[key];\n if (existing !== undefined) return existing;\n const token = Object.freeze({ name });\n Object.defineProperty(registry, key, {\n configurable: false,\n enumerable: false,\n value: token,\n writable: false,\n });\n return token;\n}\n\n/** Variable-rate World schedule. */\nexport const Update = createScheduleToken('Update');\n/** Fixed-rate World schedule and the intrinsic Update ordering anchor. */\nexport const FixedUpdate = createScheduleToken('FixedUpdate');\nexport function isScheduleToken(value: unknown): value is ScheduleToken {\n return value === Update || value === FixedUpdate;\n}\n","export interface TimeResource {\n readonly delta: number;\n readonly elapsed: number;\n readonly maxDeltaSeconds: number;\n}\n\nexport interface FixedTimeResource {\n readonly delta: number;\n readonly maxStepsPerUpdate: number;\n readonly tick: number;\n /** Seconds accumulated toward the next fixed update. */\n readonly overstep: number;\n readonly droppedSeconds: number;\n readonly droppedUpdates: number;\n}\n\nexport type MutableTimeResource = { -readonly [K in keyof TimeResource]: TimeResource[K] };\nexport type MutableFixedTimeResource = {\n -readonly [K in keyof FixedTimeResource]: FixedTimeResource[K];\n};\n\n/** Scheduler-only mutable clock capability; World never exposes this publicly. */\nexport interface ClockWriter {\n readonly time: MutableTimeResource;\n readonly fixed: MutableFixedTimeResource;\n}\n\nexport interface WorldClock {\n readonly time: TimeResource;\n readonly fixed: FixedTimeResource;\n readonly writer: ClockWriter;\n}\n\ninterface ResourceToken<T> {\n readonly name: string;\n readonly __resourceType?: T;\n}\n\nexport type ResourceValue<Key> = Key extends ResourceToken<infer Value> ? Value : never;\n\nexport interface TimePolicy {\n readonly fixedDeltaSeconds?: number;\n readonly maxStepsPerUpdate?: number;\n readonly maxDeltaSeconds?: number;\n}\n\nexport interface WorldOptions {\n readonly time?: TimePolicy;\n /** SAB-backed dense numeric columns for a SharedKernel-capable Engine Realm. */\n readonly storage?: 'local' | 'shared';\n}\n\n/** World-owned variable-rate clock resource key. */\nexport const Time = Object.freeze({ name: 'Time' }) as ResourceToken<TimeResource> & TimeResource;\n/** World-owned fixed-rate clock, policy, and catch-up metric resource key. */\nexport const FixedTime = Object.freeze({ name: 'FixedTime' }) as ResourceToken<FixedTimeResource> &\n FixedTimeResource;\n\nexport const TIME_RESOURCE_KEY = Time.name;\nexport const FIXED_TIME_RESOURCE_KEY = FixedTime.name;\n\nexport const DEFAULT_TIME_POLICY: Required<TimePolicy> = {\n fixedDeltaSeconds: 1 / 60,\n maxStepsPerUpdate: 4,\n maxDeltaSeconds: 0.1,\n};\n\nexport function createTimeResource(policy: Required<TimePolicy>): TimeResource {\n return { delta: 0, elapsed: 0, maxDeltaSeconds: policy.maxDeltaSeconds };\n}\n\nexport function createFixedTimeResource(policy: Required<TimePolicy>): FixedTimeResource {\n return {\n delta: policy.fixedDeltaSeconds,\n maxStepsPerUpdate: policy.maxStepsPerUpdate,\n tick: 0,\n overstep: 0,\n droppedSeconds: 0,\n droppedUpdates: 0,\n };\n}\n\nexport function createWorldClock(policy: Required<TimePolicy>): WorldClock {\n const time = createTimeResource(policy) as MutableTimeResource;\n const fixed = createFixedTimeResource(policy) as MutableFixedTimeResource;\n const timeView: TimeResource = Object.freeze({\n get delta() {\n return time.delta;\n },\n get elapsed() {\n return time.elapsed;\n },\n get maxDeltaSeconds() {\n return time.maxDeltaSeconds;\n },\n });\n const fixedView: FixedTimeResource = Object.freeze({\n get delta() {\n return fixed.delta;\n },\n get maxStepsPerUpdate() {\n return fixed.maxStepsPerUpdate;\n },\n get tick() {\n return fixed.tick;\n },\n get overstep() {\n return fixed.overstep;\n },\n get droppedSeconds() {\n return fixed.droppedSeconds;\n },\n get droppedUpdates() {\n return fixed.droppedUpdates;\n },\n });\n return {\n time: timeView,\n fixed: fixedView,\n writer: { time, fixed },\n };\n}\n","// World-owned managed array storage. Small fields use eight radix-4 free\n// lists; larger fields allocate dedicated buffers and drop them on release.\n// Pooling policy never limits a field to the largest pooled class. Slot IDs\n// remain private to ECS and survive archetype migration and growth.\n\nimport { err, ok, type Result } from '@forgeax/engine-types';\nimport { ManagedBufferOutOfBoundsError, ManagedBufferShrinkNotSupportedError } from './errors';\n\n/**\n * Size-class bucket boundaries in bytes (D-5, radix 4). Frozen tuple - the\n * order is load-bearing: bucket index = ascending position in the array.\n *\n * `alloc(byteLength)` rounds up to `SIZE_CLASSES[i]` for the smallest `i`\n * with `byteLength <= SIZE_CLASSES[i]`. byteLength === 0 is the special path\n * (no bucket); larger requests use dedicated, unpooled allocations.\n */\nexport const SIZE_CLASSES: readonly number[] = Object.freeze([\n 16, 64, 256, 1024, 4096, 16384, 65536, 262144,\n]);\n\n/** Result envelope for a fresh alloc - id + initial view. */\nexport interface BufferAllocResult {\n /** Stable slot id; archetype columns store this u32 in their `buffer:<N>` field. */\n readonly id: number;\n /** Live Uint8Array view of length `byteLength` (D-5 rounding visible only via `view.buffer.byteLength`). */\n readonly view: Uint8Array;\n}\n\n/**\n * Module-level cache for `ArrayBuffer.prototype.transfer` support.\n *\n * Mirrors `column.ts` HAS_TRANSFER probe: ES2024 transfer is the zero-copy\n * fast path on Node 22+ / dawn-node / modern browsers; the fallback re-allocs\n * + byte-copies. Both paths preserve the byte-equal carry-over invariant\n * (AC-07).\n */\nconst HAS_TRANSFER: boolean =\n typeof (ArrayBuffer.prototype as { transfer?: unknown }).transfer === 'function';\n\ninterface SlotState {\n /** Bucket index, SIZE_CLASSES.length for dedicated storage, or -1 for zero length. */\n sizeClassIdx: number;\n /** Underlying ArrayBuffer for the slot's current bucket (zero-length for sizeClassIdx === -1). */\n buffer: ArrayBuffer;\n /** Live view; sliced to `byteLength <= buffer.byteLength`. */\n view: Uint8Array;\n /** Logical byteLength (== view.byteLength). */\n byteLength: number;\n /** false when the slot has been released and its id is parked on the free-list. */\n live: boolean;\n}\n\n/**\n * Round `byteLength` up to a bucket index. Returns -1 for the legal zero\n * path; returns `SIZE_CLASSES.length` (out-of-range) for byteLength larger\n * than the top bucket so the caller can use a dedicated allocation.\n */\nfunction bucketIndex(byteLength: number): number {\n if (byteLength === 0) return -1;\n for (let i = 0; i < SIZE_CLASSES.length; i++) {\n const b = SIZE_CLASSES[i];\n if (b !== undefined && byteLength <= b) return i;\n }\n return SIZE_CLASSES.length;\n}\n\n/**\n * Per-(slot id) managed Uint8Array store backing the `buffer:<bytes>` schema\n * vocab keyword. Eight size-class free-lists (radix 4); cross-bucket growth\n * uses `ArrayBuffer.transfer` when available with a copy fallback for older\n * runtimes.\n *\n * AI users do not interact with `BufferPool` directly - it sits behind\n * `world.get(e, C).<bufferField>` and the M4 carry-over migrate path. The\n * pool is exposed as a class so World can hold one instance per\n * `new World()` (D-2 per-World lifecycle).\n */\nexport class BufferPool {\n private readonly slots = new Map<number, SlotState>();\n /**\n * Per-bucket free-lists: `freeBuckets[i]` is a LIFO stack of slot ids\n * whose backing buffer is parked on bucket `i`. Released slots stay on\n * their original bucket's free-list - v1 never moves a slot between\n * buckets on release (D-7 no trim).\n */\n private readonly freeBuckets: number[][] = SIZE_CLASSES.map(() => [] as number[]);\n private nextId = 1;\n\n /**\n * Allocate a managed buffer slot of at least `byteLength` bytes.\n *\n * Routes:\n * - invalid byteLength -> structured out-of-bounds error.\n * - byteLength == 0 -> ok({ id, view: zero-length Uint8Array }) (no bucket).\n * - byteLength <= 262144 -> ok({ id, view }), bucket = smallest >= byteLength.\n * - byteLength > 262144 -> a dedicated allocation; allocation failure is structured.\n *\n * D-5: size classes are radix-4 (16 / 64 / 256 / 1K / 4K / 16K / 64K / 256K).\n * Free-list pop reuses the most recently released slot id at the same bucket;\n * miss falls through to a fresh allocation.\n */\n alloc(byteLength: number): Result<BufferAllocResult, ManagedBufferOutOfBoundsError> {\n if (byteLength === 0) {\n const id = this.nextId++;\n const buffer = new ArrayBuffer(0);\n const view = new Uint8Array(buffer);\n this.slots.set(id, { sizeClassIdx: -1, buffer, view, byteLength: 0, live: true });\n return ok({ id, view });\n }\n if (!Number.isSafeInteger(byteLength) || byteLength < 0) {\n return err(new ManagedBufferOutOfBoundsError(byteLength, 0));\n }\n const idx = bucketIndex(byteLength);\n if (idx === SIZE_CLASSES.length) {\n // Large fields are dedicated allocations, not permanently retained\n // pool buckets. Small fields keep exactly the existing allocation cost.\n try {\n const buffer = new ArrayBuffer(byteLength);\n const view = new Uint8Array(buffer);\n const id = this.nextId++;\n this.slots.set(id, { sizeClassIdx: idx, buffer, view, byteLength, live: true });\n return ok({ id, view });\n } catch {\n return err(new ManagedBufferOutOfBoundsError(byteLength, 0));\n }\n }\n const bucketBytes = SIZE_CLASSES[idx];\n /* istanbul ignore next -- bucketIndex returns < SIZE_CLASSES.length here */\n if (bucketBytes === undefined) {\n return err(new ManagedBufferOutOfBoundsError(byteLength, 0));\n }\n // Free-list reuse path: pop the most recently released slot of this bucket.\n const free = this.freeBuckets[idx];\n if (free !== undefined && free.length > 0) {\n const id = free.pop() as number;\n const slot = this.slots.get(id);\n /* istanbul ignore next -- freeBuckets only carries ids that exist in slots */\n if (slot === undefined) {\n return err(new ManagedBufferOutOfBoundsError(byteLength, 0));\n }\n // Re-slice the parked buffer to the new logical length; bucket buffer\n // is reused as-is (D-7 no realloc on release).\n slot.byteLength = byteLength;\n slot.view = new Uint8Array(slot.buffer, 0, byteLength);\n slot.live = true;\n // Defensively clear bytes so AI users never see stale data from the\n // prior tenant of the slot.\n new Uint8Array(slot.buffer).fill(0);\n return ok({ id, view: slot.view });\n }\n // Fresh allocation: bucket bytes (rounded up) -> sliced view of byteLength.\n const id = this.nextId++;\n const buffer = new ArrayBuffer(bucketBytes);\n const view = new Uint8Array(buffer, 0, byteLength);\n this.slots.set(id, {\n sizeClassIdx: idx,\n buffer,\n view,\n byteLength,\n live: true,\n });\n return ok({ id, view });\n }\n\n /**\n * Grow slot `id` to `newBytes`. Returns the post-grow Uint8Array view.\n *\n * Routes (D-6 / D-7):\n * - newBytes < current -> err(managed-buffer-shrink-not-supported).\n * - newBytes == current -> ok(current view) (no-op, identity preserved).\n * - newBytes > current && same bucket -> ok(re-sliced view) (no transfer).\n * - newBytes > current && cross bucket -> ok(new view) backed by a fresh\n * bucket buffer; the prior ArrayBuffer is detached via transfer (ES2024)\n * or replaced via allocate-and-copy fallback. Old `view`s captured by\n * the caller become detached / orphaned - callers must use `pool.view(id)`\n * after grow to read the refreshed view (the `release` loop refreshes\n * automatically).\n * - newBytes beyond the last pooled class -> dedicated allocation.\n */\n grow(\n id: number,\n newBytes: number,\n ): Result<Uint8Array, ManagedBufferShrinkNotSupportedError | ManagedBufferOutOfBoundsError> {\n const slot = this.slots.get(id);\n if (slot === undefined) {\n // Treat unknown id as out-of-bounds against a 0-byte slot (closes the\n // surface; AI users hit this only on use-after-release of a slot id).\n return err(new ManagedBufferOutOfBoundsError(newBytes, 0));\n }\n if (newBytes < slot.byteLength) {\n return err(new ManagedBufferShrinkNotSupportedError(newBytes, slot.byteLength));\n }\n if (newBytes === slot.byteLength) {\n return ok(slot.view);\n }\n if (!Number.isSafeInteger(newBytes) || newBytes < 0) {\n return err(new ManagedBufferOutOfBoundsError(newBytes, slot.buffer.byteLength));\n }\n const newIdx = bucketIndex(newBytes);\n if (newBytes <= slot.buffer.byteLength) {\n // Same bucket: re-slice the existing backing ArrayBuffer to the new\n // logical length. No transfer; old view stays valid until next grow.\n slot.byteLength = newBytes;\n slot.view = new Uint8Array(slot.buffer, 0, newBytes);\n return ok(slot.view);\n }\n // Cross-bucket: detach old buffer + carry old bytes into the new bucket.\n const newBucketBytes = SIZE_CLASSES[newIdx] ?? Math.max(newBytes, slot.buffer.byteLength * 2);\n const oldByteLength = slot.byteLength;\n let nextBuffer: ArrayBuffer;\n try {\n if (HAS_TRANSFER) {\n // ES2024 transfer: copy contents into a fresh ArrayBuffer of the new\n // bucket size and detach the source. The transferred buffer keeps the\n // old prefix bytes intact.\n nextBuffer = (\n slot.buffer as unknown as { transfer(newByteLength: number): ArrayBuffer }\n ).transfer(newBucketBytes);\n } /* istanbul ignore next -- fallback only on runtimes without ES2024 transfer() */ else {\n nextBuffer = new ArrayBuffer(newBucketBytes);\n new Uint8Array(nextBuffer).set(new Uint8Array(slot.buffer, 0, oldByteLength));\n }\n } catch {\n return err(new ManagedBufferOutOfBoundsError(newBytes, slot.buffer.byteLength));\n }\n slot.sizeClassIdx = newIdx;\n slot.buffer = nextBuffer;\n slot.byteLength = newBytes;\n slot.view = new Uint8Array(nextBuffer, 0, newBytes);\n return ok(slot.view);\n }\n\n /**\n * Release slot `id` back to its bucket's free-list. Releasing an unknown id\n * is a no-op - World's release loop drives this and idempotency keeps the\n * despawn chain free of bookkeeping noise. Bucket free-lists are NEVER\n * trimmed in v1 (D-7 no trim).\n */\n release(id: number): Result<void, never> {\n const slot = this.slots.get(id);\n if (slot === undefined) return ok(undefined);\n if (!slot.live) return ok(undefined);\n slot.live = false;\n if (slot.sizeClassIdx >= 0 && slot.sizeClassIdx < SIZE_CLASSES.length) {\n const bucket = this.freeBuckets[slot.sizeClassIdx];\n if (bucket !== undefined) bucket.push(id);\n } else {\n // Zero-length or dedicated slot: drop the slot record entirely so\n // the id is not retained.\n this.slots.delete(id);\n }\n return ok(undefined);\n }\n\n /**\n * Return the live view for slot `id`. Used by World after `grow` to\n * refresh the column's stored view reference. Returns a zero-length view\n * for unknown / released ids so callers never crash on use-after-release.\n */\n view(id: number): Uint8Array {\n const slot = this.slots.get(id);\n if (slot === undefined || !slot.live) return new Uint8Array(0);\n return slot.view;\n }\n\n /**\n * Return the bucket-rounded byte capacity for slot `id` --- i.e.\n * `SIZE_CLASSES[slot.sizeClassIdx]`. Used by managed-buffer view callers\n * (D-4 no-cache: re-queried per accessor). Returns `0` for the zero-length\n * (`alloc(0)`) slot; returns `0` for unknown / released ids (mirrors\n * `view(id)` use-after-release semantics).\n */\n byteCapacity(id: number): number {\n const slot = this.slots.get(id);\n if (slot === undefined || !slot.live) return 0;\n if (slot.sizeClassIdx < 0) return 0;\n return slot.buffer.byteLength;\n }\n\n /**\n * Reset the logical byteLength of slot `id` to `newByteLength` while\n * keeping the same bucket allocation (no transfer, no release). Only\n * legal when `newByteLength <= bucketBytes`; the slot's bucket index\n * does not move (D-7 v1 forbids cross-bucket shrink). Used by managed-\n * buffer clear paths so the slot retains its `byteCapacity` while the\n * live view becomes zero-length. Bytes past the new logical length are\n * zero-filled defensively.\n *\n * Returns `err(ManagedBufferShrinkNotSupportedError)` when called on a\n * `sizeClassIdx === -1` slot (alloc(0)) with `newByteLength > 0`, or\n * when `newByteLength` exceeds the bucket capacity.\n */\n setLogicalLength(\n id: number,\n newByteLength: number,\n ): Result<Uint8Array, ManagedBufferShrinkNotSupportedError | ManagedBufferOutOfBoundsError> {\n const slot = this.slots.get(id);\n if (slot === undefined) {\n return err(new ManagedBufferOutOfBoundsError(newByteLength, 0));\n }\n if (slot.sizeClassIdx < 0) {\n // alloc(0) slot has no bucket; only newByteLength === 0 is legal.\n if (newByteLength === 0) {\n slot.byteLength = 0;\n slot.view = new Uint8Array(slot.buffer);\n return ok(slot.view);\n }\n return err(new ManagedBufferOutOfBoundsError(newByteLength, 0));\n }\n const bucketBytes = slot.buffer.byteLength;\n if (newByteLength > bucketBytes) {\n return err(new ManagedBufferOutOfBoundsError(newByteLength, bucketBytes));\n }\n // Zero-fill the prefix bytes that fall past the new logical length so\n // AI users never see stale tail bytes through a future grow.\n if (newByteLength < slot.byteLength) {\n new Uint8Array(slot.buffer, newByteLength, slot.byteLength - newByteLength).fill(0);\n }\n slot.byteLength = newByteLength;\n slot.view = new Uint8Array(slot.buffer, 0, newByteLength);\n return ok(slot.view);\n }\n\n /** @internal Diagnostic count of live slots. Exposed for tests + inspector. */\n _liveCount(): number {\n let n = 0;\n for (const s of this.slots.values()) if (s.live) n += 1;\n return n;\n }\n}\n","// @forgeax/engine-ecs — Entity handle.\n//\n// Encoding: u32 = (generation << 24) | (index & 0xFFFFFF)\n// - index: 24 bits — supports up to 16_777_215 simultaneous entities.\n// - generation: 8 bits — retirement when gen exceeds 255 (gen 255 usable);\n// index permanently retired when bumped generation would reach 256.\n//\n// Key difference from @forgeax/engine-ecs: generation does NOT wrap 255 → 0.\n// When generation would exceed 255 (256), the index is permanently retired\n// from the free list to prevent handle aliasing (D-08).\n//\n// feat-20260623-asset-handle-generation M2 / w4: encodeEntity/decodeEntity/\n// entityIndex/entityGeneration are now thin wrappers over the shared gen-slot\n// codec in @forgeax/engine-types (pack / unpackSlot / unpackGen). The\n// `EntityIndexOverflowError` throw and `ENTITY_NULL_RAW` sentinel stay in ecs\n// (D-1). Constants re-export codec values for backward-compatible names.\n\nimport { MAX_GEN, MAX_SLOT, pack, unpackGen, unpackSlot } from '@forgeax/engine-types';\nimport { EntityIndexOverflowError } from './errors';\n\n/**\n * Branded `number` representing an Entity handle. Stored as a JS `number` but\n * holds the u32 bit pattern (generation << 24) | index.\n *\n * The phantom `__entity` brand prevents accidental mixing with other numbers.\n *\n * Naming: the type-space alias is `EntityHandle` (the branded number that\n * identifies a row). The same-named value-space `Entity` re-exported from the\n * package barrel is the id=0 component token (see `./entity`).\n */\nexport type EntityHandle = number & { readonly __entity: unique symbol };\n\n/** Maximum representable entity index (2^24 - 1 = 16_777_215). Re-exports codec MAX_SLOT. */\nexport const ENTITY_MAX_INDEX = MAX_SLOT;\n\n/** Maximum representable generation (2^8 - 1 = 255). Re-exports codec MAX_GEN. */\nexport const ENTITY_MAX_GENERATION = MAX_GEN;\n\n/**\n * Sentinel u32 value reserved for the \"null entity\" slot in `entity`-typed\n * component fields.\n *\n * The encoding `(gen << 24) | index` yields `0xFFFFFFFF` only at the very\n * last valid (gen=255, index=0xFFFFFF) entity, which retires permanently on\n * its first despawn (D-08). Carving out this single bit pattern as the null\n * sentinel costs at most one slot at the far edge of the entity space.\n *\n * Stored u32 column reads compare against `ENTITY_NULL_RAW` first; the\n * column-level `Entity | null` decode lives in `world.readRow`.\n *\n * Scene-as-World-Blueprint anchor (feat-20260514 w12, R-8 lockdown):\n * This module (`packages/ecs/src/entity.ts`) is the canonical export site\n * for the entity null sentinel. Downstream consumers (M2 instantiate\n * layer 3 fallback for `'entity'`-typed component fields, w22) must import\n * from the package barrel:\n *\n * import { ENTITY_NULL_RAW } from '@forgeax/engine-ecs'\n *\n * The raw `0xFFFFFFFF` literal MUST NOT be duplicated at consumer sites\n * (charter proposition 1: SSOT lives here). The decoded JS-side value is\n * `null` (returned by `world.get(e, C).<entityField>`). Layer 3 default\n * for `'entity'` keyword fields stores `ENTITY_NULL_RAW` into the u32\n * column, which decodes back to `null` on read. ecs-managed-buffer feat\n * export verification (w12 grep): see `packages/ecs/src/index.ts` line\n * re-exporting this constant alongside `ENTITY_MAX_GENERATION /\n * ENTITY_MAX_INDEX`. No add-only fallback re-export is required at this\n * time.\n */\nexport const ENTITY_NULL_RAW = 0xffffffff;\n\n/**\n * Encode (index, generation) into a u32 entity handle.\n *\n * Delegates to shared codec `pack(index, generation)` after ecs-specific\n * overflow validation. The `>>> 0` anti-ToInt32 guard is inherited from the\n * codec (D-7 hard constraint).\n *\n * @throws EntityIndexOverflowError when `index > ENTITY_MAX_INDEX` or `index < 0`.\n */\nexport function encodeEntity(index: number, generation: number): EntityHandle {\n if (index < 0 || index > ENTITY_MAX_INDEX) {\n throw new EntityIndexOverflowError(index);\n }\n return pack(index, generation) as EntityHandle;\n}\n\n/** Decode a u32 entity handle into its (index, generation) pair via shared codec. */\nexport function decodeEntity(entity: EntityHandle): { index: number; generation: number } {\n const e = entity as unknown as number;\n return {\n index: unpackSlot(e),\n generation: unpackGen(e),\n };\n}\n\n/** Extract just the index slot from an entity handle via shared codec. */\nexport function entityIndex(entity: EntityHandle): number {\n return unpackSlot(entity as unknown as number);\n}\n\n/** Extract just the generation slot from an entity handle via shared codec. */\nexport function entityGeneration(entity: EntityHandle): number {\n return unpackGen(entity as unknown as number);\n}\n","// @forgeax/engine-ecs - Layer-3 default-value SSOT helper (feat-20260517-\n// spawn-default-fallback / M1).\n//\n// AI users: this file is the SINGLE PHYSICAL LOCATION of the layer-3\n// `typeDefault(fieldType)` table. Three runtime paths consume it (D-2\n// / plan-strategy §2.1 / AC-05):\n//\n// - `world.spawn(...)` (M2 — t9)\n// - `world.addComponent(...)` (M2 — t9, ComponentData<S> shared)\n//\n// Two-layer split (D-3 / plan-strategy §2.2 — DELIBERATELY NOT MERGED):\n//\n// layer-3 (this file)\n// \"raw value fallback\" — fills missing schema fields with the\n// spawn-data raw shape: 0 / false / ENTITY_NULL_RAW / [] / 0 (slot\n// id placeholder). The output is the input shape `world.spawn`\n// receives (`Partial<ShapeOf<S>>` -> `Record<string, unknown>` with\n// all schema keys present).\n//\n// layer-4 (silent fallback inside writeRow / write{Buffer,Array,\n// UniqueRef}Field)\n// \"column-store value fallback\" — when raw === 0 hits a managed-\n// family arm (string / unique<T> / buffer / buffer<N> / array<T> for\n// T != entity), the column store routes 0 to \"empty slot\" semantics\n// (UniqueRefStore handle 0 / BufferPool slot 0 / array slot\n// length === 0). The two layers are NEVER merged — layer-3 stays\n// pure / unaware of column physics; layer-4 stays inside writeRow\n// where the column instance is in scope.\n//\n// The 14-vocab x default-value table (AC-06 closed table, grep-gate t2\n// keyword \"layer-3 typeDefault table\"):\n//\n// ScalarFieldType (11 arms):\n// f32 / f64 / i32 / u32 / i16 / u16 / i8 / u8 -> 0\n// bool -> false\n// enum / ref (legacy scalar) -> 0\n//\n// SchemaVocabKeyword (8 arms; one \"buffer\" + one \"buffer<N>\"; one\n// \"ref<T>\" + one \"handle<T>\"; one \"entity\" + one \"string\"; two array\n// variants — array<T,N> / array<T> — collapse to two table arms:\n// 'string' -> 0 (uniqueRefs handle slot;\n// resolved payload '' on read)\n// 'entity' -> ENTITY_NULL_RAW (NULL_ENTITY u32\n// = 0xffffffff)\n// 'array<entity>' -> [] (THE ONLY array<T> arm with []\n// — entity[] runtime shape is a\n// JS array of Entity, not a\n// BufferPool slot id)\n// 'array<T>' (T != entity) -> 0 (BufferPool slot id; layer-4\n// writeArrayField bottoms out to\n// empty slot — D-2 asymmetric;\n// SceneAsset byte-equivalence,\n// OOS-6 letter)\n// 'array<T, N>' (any T) -> 0 (inline stride-N column,\n// feat-20260602; fallback writes the\n// zeroed row, not a slot id)\n// 'buffer' -> 0 (BufferPool slot id; variable\n// byte capacity)\n// 'buffer<N>' -> 0 (inline stride-N u8 column,\n// feat-20260602; fallback writes the\n// zeroed row, not a slot id)\n// 'unique<T>' -> 0 (UniqueRefStore handle slot)\n// 'handle<T>' -> 0 (unmanaged handle phantom u32;\n// schema-level nullable -> NULL\n// sentinel 0)\n//\n// Brand-class semantics (AC-10 / requirements §A-3 reframe round 2):\n// `handle<T>` and `ref<T>` are SCHEMA-LEVEL nullable. Spawn `data: {}`\n// is legal; layer-3 fills 0 (NULL sentinel for unmanaged handles) /\n// 0 (uniqueRefs handle slot, '' payload). SceneAsset.instantiate\n// produces byte-equivalent column state.\n//\n// Anchors:\n// - requirements §AC-05 (helper SSOT) + §AC-06 (closed 14-vocab table)\n// + §AC-09 (SceneAsset byte-equiv) + §AC-10 (brand-class nullable)\n// - plan-strategy §2.1 (helper file location decision)\n// §2.2 (two-layer split JSDoc declaration)\n// §2.3 (array<T> T!=entity asymmetric raw 0)\n// §3.1 (helper node in component graph)\n// §8.2 (naming rules: fillComponentDefaults / typeDefault)\n// §8.4 (head JSDoc as discovery anchor)\n\nimport type { Component, ComponentSchema } from './component';\nimport { componentSchema } from './component';\nimport { componentDefinition } from './component-schema';\nimport { ENTITY_NULL_RAW } from './entity-handle';\nimport { SpawnDataUnknownFieldError } from './errors';\n\n/**\n * Layer-3 silent default for a single schema field type. Returned when\n * the spawn-data raw input (layer 1) and the owner definition defaults\n * map (layer 2) both omit a known schema field.\n *\n * Pure function — runs once per missing field per (component, spawn /\n * instantiate) call. No `BufferPool` / `UniqueRefStore` / `World`\n * dependency: the helper hands back raw column-shape values (u32 / bool\n * / number array literal); the layer-4 silent fallback inside\n * `writeRow` / `write{Buffer,Array,UniqueRef}Field` turns raw `0` into\n * the live column-store value (unique-ref handle 0 / BufferPool slot\n * id 0 / array slot length 0).\n *\n * Mapping is the same closed table the head-JSDoc table documents.\n *\n * @internal — helper-private; AI users call `fillComponentDefaults`.\n */\nfunction typeDefault(fieldType: string): unknown {\n // bool is the only scalar arm with a non-zero default.\n if (fieldType === 'bool') return false;\n // 'entity' uses the runtime NULL_ENTITY sentinel (0xffffffff).\n if (fieldType === 'entity') return ENTITY_NULL_RAW;\n // 'array<entity>' is the only array<T> arm whose layer-3 default is a\n // JS array literal — entity[] runtime shape is a JS Array<Entity>,\n // not a BufferPool slot id (D-2 asymmetric pivot).\n if (fieldType === 'array<entity>') return [];\n // every other vocab keyword (incl. 'string' / 'unique<T>' / 'handle<T>'\n // / 'buffer' / 'buffer<N>' / 'array<T>' (T!=entity) / 'array<T, N>')\n // and every remaining ScalarFieldType (f* / i* / u* / enum / ref)\n // defaults to numeric 0 at the spawn-data raw surface. Layer-4\n // silent fallback inside writeRow turns 0 into the empty-slot\n // shape on the column-store side when applicable.\n return 0;\n}\n\n/**\n * Fill missing schema fields on a partial spawn-data raw with their\n * layer-2 / layer-3 defaults. Public surface used by:\n *\n * - `World.spawn` (writeRow entry, M2)\n * - `World.addComponent` (writeRow entry, M2)\n *\n * Resolution order (matches scene-instance-container.ts JSDoc):\n *\n * layer 1 — explicit raw value (caller passed `data[field] = v`).\n * Carrier: the raw input itself; not handled by this\n * helper — copied through the `if (key in raw)` branch.\n * SceneAsset.instantiate additionally remaps `entity` /\n * `array<entity>` LocalEntityId values BEFORE handing the raw\n * to the helper (the entity-remap layer is NOT this\n * helper's responsibility).\n *\n * layer 2 — owner definition defaults (declared via\n * `defineComponent(name, schema, { defaults })`). Layer-2\n * defaults beat layer-3.\n *\n * layer 3 — `typeDefault(fieldType)` (this file's private dispatch).\n *\n * Returns a fresh `Record<string, unknown>` carrying every schema\n * field. The output is column-shape raw — the caller's writeRow path\n * walks it field-by-field and applies layer-4 silent fallback when a\n * raw `0` lands on a managed-family arm.\n *\n * Pure: no World / store side effect. Thread-safety irrelevant (single-\n * thread JS engine), but the helper allocates one `Object.create(null)`\n * per call so repeated invocations cannot share a mutable record.\n *\n * @param token Component token (name + schema + optional defaults).\n * @param raw Partial spawn-data raw — caller's `Partial<ShapeOf<S>>`.\n * Keys not present in the schema are passed through\n * unchanged (the spawn write path will emit a write-time\n * error if applicable; helper does not validate keys).\n * @returns Record with every schema field populated by layer-1 /\n * layer-2 / layer-3 defaults in that order.\n */\nexport function fillComponentDefaults<S extends ComponentSchema>(\n token: Component<string, S>,\n raw: Partial<Record<string, unknown>> | undefined,\n): Record<string, unknown> {\n const schema = componentSchema(token) as Record<string, string>;\n const layer2 = componentDefinition(token).defaults;\n const out: Record<string, unknown> = Object.create(null);\n const rawObj = (raw as Record<string, unknown> | undefined) ?? undefined;\n for (const fieldName of Object.keys(schema)) {\n const fieldType = schema[fieldName];\n if (fieldType === undefined) continue;\n // layer 1 — explicit raw value (caller may pass undefined to mean\n // \"use default\"; mirror the existing scene-instance-container\n // behaviour where the gate is `fieldName in raw`).\n if (rawObj !== undefined && fieldName in rawObj) {\n out[fieldName] = rawObj[fieldName];\n continue;\n }\n // layer 2 — component-level defaults map.\n if (layer2 !== undefined && fieldName in layer2) {\n out[fieldName] = layer2[fieldName];\n continue;\n }\n // layer 3 — TS type defaults (silent — no error code).\n out[fieldName] = typeDefault(fieldType);\n }\n return out;\n}\n\n// Re-export the private dispatch for unit-test introspection (t1\n// keyword pin — every vocab arm gets a one-liner it() block). The\n// helper-private arity is preserved at callers via the\n// `fillComponentDefaults` boundary.\nexport { typeDefault };\n\n/**\n * Validate that every key in `raw` is a declared schema field on `token`.\n *\n * Returned as a `SpawnDataUnknownFieldError` on the FIRST offending key\n * (deterministic for AI users; subsequent unknown keys surface on the next\n * spawn after the first is fixed). Pre-fix the unknown key was silently\n * dropped inside `fillComponentDefaults` (which iterates only schema keys),\n * routing typos like `MeshRenderer { material }` (singular legacy field name)\n * into the empty-default path and producing invisible / mid-grey entities\n * downstream.\n *\n * Pure: no World / store side effect; allocates no closure on the hot path\n * (early-returns null when raw is undefined / empty).\n *\n * Call order at every spawn / addComponent / SceneAsset.instantiate /\n * Commands.spawn site: validate FIRST, then `fillComponentDefaults`. The\n * split keeps `fillComponentDefaults` pure (charter P3 SSOT — a fill helper\n * never validates) while every layer-1 raw key reaches one validator gate.\n *\n * @param token Component token (name + schema).\n * @param raw Caller's `Partial<ShapeOf<S>>` — raw spawn payload.\n * @returns `null` on success; `SpawnDataUnknownFieldError` on the first\n * key not declared in `componentSchema(token)`.\n */\nexport function validateComponentDataKeys<S extends ComponentSchema>(\n token: Component<string, S>,\n raw: Partial<Record<string, unknown>> | undefined,\n): SpawnDataUnknownFieldError | null {\n if (raw === undefined) return null;\n const schema = componentSchema(token) as Record<string, unknown>;\n const rawObj = raw as Record<string, unknown>;\n for (const fieldName of Object.keys(rawObj)) {\n if (!(fieldName in schema)) {\n return new SpawnDataUnknownFieldError(token.name, fieldName, Object.keys(schema));\n }\n }\n return null;\n}\n","// feat-20260713-mount-override-component-add-and-shared-ref-round M2 / w9 —\n// P3 shared-field value gate.\n//\n// `validateComponentDataKeys` (component-default-fallback.ts) checks that every\n// key in a spawn / addComponent / set payload is a declared schema field. It\n// does NOT check value TYPES. A `shared<T>` scalar / `array<shared<T>>` element\n// must be a resolved numeric Handle; a raw GUID string / `{ guid }` / `{ kind }`\n// object (the pre-resolution shape a sidecar hands an AI user) was silently\n// coerced to the all-zero sentinel by the column packer\n// (`typed[i] = typeof val === 'number' ? val : 0`) / scalar write path, so a\n// mis-bound reference read back as `0` / `[0,0,0,0]` and rendered blank with no\n// error.\n//\n// This module closes that value-type gap. It is a pure validator (no World /\n// store side effect) invoked at all three write entries (spawn / addComponent /\n// set) BEFORE any archetype mutation, mirroring the validate-first ordering of\n// `validateComponentDataKeys`. §2.5: it depends only on the schema field-type\n// SHAPE (`shared<...>` / `array<shared<...>>`), never on any GUID / asset\n// concretion — the GUID domain stays sealed in assets-runtime; ecs only sees a\n// numeric handle vs a non-handle.\n\nimport type { Component, ComponentSchema } from './component';\nimport { componentSchema } from './component';\nimport { componentDefinition } from './component-schema';\nimport { ManagedArrayInvalidValueError, SharedFieldInvalidValueError } from './errors';\n\n/** A resolved shared handle is a plain number (the branded Handle bit pattern). */\nfunction isNumericHandle(v: unknown): boolean {\n return typeof v === 'number';\n}\n\n/** `shared<T>` scalar field type. */\nfunction isSharedScalarType(fieldType: string): boolean {\n return fieldType.startsWith('shared<') && fieldType.endsWith('>');\n}\n\n/**\n * `array<shared<T>>` / `array<shared<T>, N>` field type. The inner element type\n * is a `shared<...>` template; we test the array wrapper and the `shared<`\n * infix rather than fully re-parsing (parseManagedArraySchema owns the strict\n * grammar — here we only need the coarse \"is this an array of shared refs\"\n * discriminant).\n */\nfunction isSharedArrayType(fieldType: string): boolean {\n if (!fieldType.startsWith('array<') || !fieldType.endsWith('>')) return false;\n const inner = fieldType.slice(6, -1);\n const head = inner.indexOf(',') === -1 ? inner : inner.slice(0, inner.indexOf(',')).trim();\n return head.startsWith('shared<') && head.endsWith('>');\n}\n\nfunction isArrayPayload(value: unknown): boolean {\n if (Array.isArray(value)) return true;\n // DataView and ArrayBuffer are views/buffers without an element `length`;\n // the storage writer cannot interpret them as a managed array payload.\n return ArrayBuffer.isView(value) && typeof (value as { length?: unknown }).length === 'number';\n}\n\n/**\n * Validate the outer value shape for every managed `array<T>` field present in\n * a write payload. This is deliberately a preflight-only check: element\n * coercion remains owned by the column writer, while arbitrary objects are\n * rejected before any row, buffer slot, retain, or epoch mutation can occur.\n */\nexport function validateManagedArrayValues<S extends ComponentSchema>(\n token: Component<string, S>,\n raw: Partial<Record<string, unknown>> | undefined,\n): ManagedArrayInvalidValueError | null {\n if (raw === undefined) return null;\n const fields = componentDefinition(token).fields as Readonly<\n Record<string, { readonly type: string; readonly arrayMeta?: unknown }>\n >;\n const rawObj = raw as Record<string, unknown>;\n for (const fieldName of Object.keys(rawObj)) {\n const reflection = fields[fieldName];\n if (reflection?.arrayMeta === undefined) continue;\n const value = rawObj[fieldName];\n // `fillComponentDefaults` deliberately uses numeric zero as the layer-3\n // raw sentinel for every non-entity array vocabulary. The column writer\n // owns translating that sentinel into an empty variable slot or a\n // zero-filled fixed row, so it must pass this preflight just like an\n // omitted/null value. Other scalar/object values remain invalid.\n if (value === 0) continue;\n if (value === undefined || value === null || isArrayPayload(value)) continue;\n return new ManagedArrayInvalidValueError(token.name, fieldName, reflection.type, value);\n }\n return null;\n}\n\n/**\n * Validate that every `shared<T>` scalar / `array<shared<T>>` element present in\n * `raw` is a resolved numeric Handle. Returns the FIRST offending field's\n * `SharedFieldInvalidValueError` (deterministic for AI users), or `null` on\n * success.\n *\n * Pure: no World / store side effect. Only fields PRESENT in `raw` are checked\n * (an omitted shared field takes its schema default — a numeric sentinel — via\n * `fillComponentDefaults`, so it is never a non-handle). `undefined` / `null`\n * values are treated as \"omitted\" (the write path routes them to the sentinel\n * intentionally); only a concrete non-numeric value (string / object) is a\n * mis-bound GUID and fails fast.\n *\n * @param token Component token (name + schema).\n * @param raw Caller's raw payload (spawn / addComponent / set value).\n * @returns `null` on success; `SharedFieldInvalidValueError` on the first\n * shared field bound to a non-handle value.\n */\nexport function validateSharedFieldValues<S extends ComponentSchema>(\n token: Component<string, S>,\n raw: Partial<Record<string, unknown>> | undefined,\n): SharedFieldInvalidValueError | null {\n if (raw === undefined) return null;\n const schema = componentSchema(token) as Record<string, string>;\n const rawObj = raw as Record<string, unknown>;\n for (const fieldName of Object.keys(rawObj)) {\n const fieldType = schema[fieldName];\n if (fieldType === undefined) continue; // key validation owns unknown keys.\n const value = rawObj[fieldName];\n if (value === undefined || value === null) continue; // omitted -> sentinel default.\n if (isSharedScalarType(fieldType)) {\n if (!isNumericHandle(value)) {\n return new SharedFieldInvalidValueError(token.name, fieldName, fieldType, value);\n }\n } else if (isSharedArrayType(fieldType)) {\n if (!Array.isArray(value)) continue; // non-array raw for an array field: write path no-ops.\n for (let i = 0; i < value.length; i++) {\n const el = value[i];\n if (el === undefined || el === null) continue;\n if (!isNumericHandle(el)) {\n return new SharedFieldInvalidValueError(token.name, fieldName, fieldType, el, i);\n }\n }\n }\n }\n return null;\n}\n","// @forgeax/engine-ecs/internal — package-owner seams that are intentionally\n// absent from the public ECS barrel.\n//\n// This entry keeps the existing component-owner imports stable and adds the\n// typed symbol used by scene propagation. A symbol avoids putting a derived\n// writer method on the discoverable Query contract while still letting the\n// owning package share the exact query implementation without a private path\n// import or an untyped cast at each consumer.\n\n// Keep this entry limited to package-owner metadata and the derived writer.\n// Raw World storage stays source-private; semantic World reads live behind the\n// separate `./world-read` entry.\nexport { componentId, componentSchema } from './component';\nexport { componentDefinition } from './component-schema';\n\nimport type { Result } from '@forgeax/engine-types';\nimport type { Component } from './component';\nimport type { QuerySpanUnavailableError } from './errors';\nimport type { DerivedRangeWriter } from './query/derived-range-writer';\nimport type { Query } from './query/query';\n\n/** Internal identity for the ECS-owned derived range writer accessor. */\nexport const DERIVED_WRITER: unique symbol = Symbol.for(\n 'forgeax.ecs.query.derivedWriter',\n) as unknown as typeof DERIVED_WRITER;\n\ntype DerivedWriterQuery<\n R extends readonly Component[],\n W extends readonly Component[],\n O extends readonly Component[],\n> = Query<R, W, O> & {\n readonly [DERIVED_WRITER]: <C extends W[number]>(\n component: C,\n ) => Result<DerivedRangeWriter<R[number], C>, QuerySpanUnavailableError>;\n};\n\n/**\n * Resolve the ECS-owned derived writer through its internal symbol seam.\n * Consumers of this module retain the component/query type relationship while\n * the public Query and QuerySpan surfaces remain read/write-only contracts.\n */\nexport function getDerivedWriter<\n R extends readonly Component[],\n W extends readonly Component[],\n O extends readonly Component[],\n C extends W[number],\n>(\n query: Query<R, W, O>,\n component: C,\n): Result<DerivedRangeWriter<R[number], C>, QuerySpanUnavailableError> {\n const internalQuery = query as DerivedWriterQuery<R, W, O>;\n return internalQuery[DERIVED_WRITER](component);\n}\n\nexport type {\n DerivedColumnBinding,\n DerivedRangeCursor,\n DerivedRangeRowCommit,\n DerivedRangeRowProbe,\n DerivedRangeWriter,\n} from './query/derived-range-writer';\n","import type { Component, ComponentId } from '../component';\nimport { componentId } from '../component';\nimport { foldEssentials } from '../entity';\nimport type { TableId } from './table';\n\nconst INITIAL_CAPACITY = 64;\n\nexport type ArchetypeId = number;\n\nexport interface Archetype {\n readonly id: ArchetypeId;\n readonly key: string;\n readonly components: ReadonlyArray<Component>;\n readonly tableId: TableId;\n rows: Uint32Array;\n size: number;\n capacity: number;\n addEdges: Map<ComponentId, ArchetypeId>;\n removeEdges: Map<ComponentId, ArchetypeId>;\n}\n\nexport function archetypeKey(componentIds: ReadonlyArray<ComponentId>): string {\n return [...foldEssentials(componentIds)].sort((a, b) => a - b).join('+');\n}\n\nexport function createArchetype(\n components: ReadonlyArray<Component>,\n id: ArchetypeId,\n tableId: TableId,\n): Archetype {\n const byId = new Map<ComponentId, Component>();\n for (const component of components) byId.set(componentId(component), component);\n const sorted = [...byId.values()].sort((a, b) => componentId(a) - componentId(b));\n return {\n id,\n key: archetypeKey(sorted.map((component) => componentId(component))),\n components: sorted,\n tableId,\n rows: new Uint32Array(INITIAL_CAPACITY),\n size: 0,\n capacity: INITIAL_CAPACITY,\n addEdges: new Map(),\n removeEdges: new Map(),\n };\n}\n\nexport function appendArchetypeRow(archetype: Archetype, tableRow: number): number {\n if (archetype.size === archetype.capacity) growArchetype(archetype, archetype.capacity * 2);\n const row = archetype.size;\n archetype.rows[row] = tableRow;\n archetype.size = row + 1;\n return row;\n}\n\nexport function removeArchetypeRow(\n archetype: Archetype,\n row: number,\n): { movedTableRow: number; newRow: number } | null {\n const lastRow = archetype.size - 1;\n if (row === lastRow) {\n archetype.size = lastRow;\n return null;\n }\n const movedTableRow = archetype.rows[lastRow] ?? 0;\n archetype.rows[row] = movedTableRow;\n archetype.size = lastRow;\n return { movedTableRow, newRow: row };\n}\n\nexport function growArchetype(archetype: Archetype, targetCapacity: number): void {\n let capacity = archetype.capacity;\n while (capacity < targetCapacity) capacity *= 2;\n if (capacity === archetype.capacity) return;\n const rows = new Uint32Array(capacity);\n rows.set(archetype.rows);\n archetype.rows = rows;\n archetype.capacity = capacity;\n}\n","// @forgeax/engine-ecs — per-field independent buffer column storage (D-01).\n//\n// Each component field gets its own ArrayBuffer/SharedArrayBuffer + TypedArray view.\n// This enables independent per-column transfer() expansion and\n// supports dynamic column add/remove during archetype migration.\n//\n// `array<T>` (variable-capacity) fields take TWO columns in archetype layout\n// (D-3): the primary u32 column carries the BufferPool slot id; a sidecar\n// column carries the live element count, named `<fieldName>:count` and\n// keyed by `arrayCountColumnName(fieldName)`. `array<T,N>` (fixed-capacity)\n// fields (feat-20260602) take a SINGLE inline stride-N column (arity = N) --\n// no BufferPool slot id, no sidecar count column. The elements live\n// contiguously per row. `buffer<N>` likewise takes a single stride-N u8\n// column. Variable `buffer` still uses a u32 BufferPool slot id column.\n// Capacity is never stored as an independent column: for variable-capacity\n// fields it is derived from `BufferPool.view(slotId).byteLength /\n// elementBytes`; for fixed-capacity fields the schema-declared N is the\n// capacity.\n\nimport { type ComponentSchema, type ScalarFieldType, TYPE_METADATA } from '../component';\n\n// ────────────────────────────────────────────────────────────────────────────\n// ManagedColumnReader — read-only view onto a managed-vocab column\n// (feat-20260614 M4 / D-4 / AC-08 / AC-09 / AC-10)\n// ────────────────────────────────────────────────────────────────────────────\n\n/**\n * Read-only access shape for the 4 managed-vocab column keywords --\n * `'string'` / `` `ref<T>` `` / variable `'buffer'` / variable `` `array<T>` ``.\n *\n * The column carries u32 slot ids (`UniqueRefStore` / `BufferPool`); direct\n * index assignment would corrupt the slot table. The reader exposes\n * `.length` + `.get(i): number` so consumers can walk row indices and\n * retrieve slot ids, then route through the public dispatch (`world.set`,\n * `world.push`, `world.allocUniqueRef`, etc.) for any mutation.\n *\n * Phantom brand `__managed` (D-7 / requirements-decisions q2): the\n * double-underscore + semantic-word pattern matches `Handle.__handle`. The\n * brand is a structural-typing safety net; the class name already\n * disambiguates against `Uint32Array` / `Uint8Array` / fixed inline views.\n *\n * Intentionally minimal -- no iterator, no `toArray`, no `slice`. Adding\n * those invites a \"cache the slot ids, mutate later\" anti-pattern that\n * silently desyncs from the live column on the next archetype migration\n * (charter P4 / plan-strategy §8.4).\n */\nexport interface ManagedColumnReader<T extends string> {\n readonly length: number;\n get(i: number): number;\n readonly __managed: T;\n}\n\n/**\n * Sidecar column name for the live `count` of an `array<T>` (variable-\n * capacity) field. Format `<fieldName>:count` keeps the suffix outside the\n * legal user-facing schema name space (the colon is forbidden in user\n * field names by convention) so the archetype Map can carry both columns\n * under one `Map<fieldName, Column>` keyed namespace without collision\n * (D-3 double-column allocation in M1 / w7).\n */\nexport function arrayCountColumnName(fieldName: string): string {\n return `${fieldName}:count`;\n}\n\n// ────────────────────────────────────────────────────────────────────────────\n// Column: one field's storage\n// ────────────────────────────────────────────────────────────────────────────\n\n/** TypedArray view types used by columns. */\nexport type FieldView =\n | Float32Array\n | Float64Array\n | Int32Array\n | Uint32Array\n | Int16Array\n | Uint16Array\n | Int8Array\n | Uint8Array;\n\ntype FieldViewConstructor = new (buffer: ArrayBufferLike) => FieldView;\n\nfunction createFieldView(\n Ctor: NonNullable<(typeof TYPE_METADATA)[string]['viewCtor']>,\n buffer: ArrayBufferLike,\n): FieldView {\n return new (Ctor as FieldViewConstructor)(buffer);\n}\n\nfunction isSharedBuffer(buffer: ArrayBufferLike): buffer is SharedArrayBuffer {\n return typeof SharedArrayBuffer !== 'undefined' && buffer instanceof SharedArrayBuffer;\n}\n\n/** A single column: one field's ArrayBuffer + TypedArray view. */\nexport interface Column {\n buffer: ArrayBuffer | SharedArrayBuffer;\n view: FieldView;\n capacity: number;\n fieldType: ScalarFieldType;\n /**\n * Number of elements per row (stride). Scalar and variable-capacity columns\n * default to 1 (one u32 slot id or one scalar value per row). Fixed-capacity\n * `array<T,N>` / `buffer<N>` inline columns (feat-20260602) have arity = N.\n *\n * For inline columns, the TypedArray view returned by `col.view.subarray()`\n * aliases the column buffer directly. The view is transient: `growColumn`\n * detaches the old `ArrayBuffer` via `transfer()`, so callers must re-fetch\n * the view after any structural change. See `packages/ecs/README.md`\n * Transient view contract section.\n */\n arity: number;\n}\n\n/**\n * Create a column for a single field with given capacity.\n *\n * @param fieldType - scalar storage type for the column view ctor\n * @param capacity - number of rows\n * @param arity - elements per row (stride); default 1 for scalar/variable columns\n */\nexport function createColumn(\n fieldType: ScalarFieldType,\n capacity: number,\n arity = 1,\n shared = false,\n): Column {\n const meta = TYPE_METADATA[fieldType];\n if (!meta) throw new Error(`Missing TYPE_METADATA entry for scalar field type ${fieldType}`);\n const bytesPerElement =\n // biome-ignore lint/style/noNonNullAssertion: ScalarFieldType rows always carry a byteSize\n meta.byteSize!;\n const buffer = shared\n ? new SharedArrayBuffer(bytesPerElement * capacity * arity)\n : new ArrayBuffer(bytesPerElement * capacity * arity);\n // biome-ignore lint/style/noNonNullAssertion: ScalarFieldType rows always carry a viewCtor\n const Ctor = meta.viewCtor!;\n const view = createFieldView(Ctor, buffer);\n return { buffer, view, capacity, fieldType, arity };\n}\n\n/**\n * Module-level cache for `ArrayBuffer.prototype.transfer` support (O-1).\n * Checked once at import time; avoids per-call feature detection overhead.\n *\n * Note: `transfer()` is ES2024. We use runtime feature detection + type cast\n * so that tsconfig does not need `lib: [\"es2024\"]`.\n */\nexport const HAS_TRANSFER: boolean =\n typeof (ArrayBuffer.prototype as { transfer?: unknown }).transfer === 'function';\n\n/**\n * Grow a column to a new capacity, preserving existing data.\n * Returns a new Column; the old column is not modified.\n *\n * When the runtime supports `ArrayBuffer.transfer()` (ES2024, Node 22+,\n * modern browsers), uses zero-copy buffer transfer. Otherwise falls back\n * to `new ArrayBuffer` + `Uint8Array.set` copy.\n *\n * Both paths produce data-equivalent results (O-1 acceptance criterion).\n */\nexport function growColumn(col: Column, newCapacity: number): Column {\n const meta = TYPE_METADATA[col.fieldType];\n if (!meta) throw new Error(`Missing TYPE_METADATA entry for scalar field type ${col.fieldType}`);\n const bytesPerElement =\n // biome-ignore lint/style/noNonNullAssertion: ScalarFieldType rows always carry a byteSize\n meta.byteSize!;\n const newByteLength = bytesPerElement * newCapacity * col.arity;\n // biome-ignore lint/style/noNonNullAssertion: ScalarFieldType rows always carry a viewCtor\n const Ctor = meta.viewCtor!;\n\n let buffer: ArrayBuffer | SharedArrayBuffer;\n if (isSharedBuffer(col.buffer)) {\n buffer = new SharedArrayBuffer(newByteLength);\n new Uint8Array(buffer).set(new Uint8Array(col.buffer));\n } else if (HAS_TRANSFER) {\n // Zero-copy path: transfer() resizes the underlying buffer in-place\n // and detaches the source. The old column's buffer becomes detached,\n // but we return a new Column object so callers never touch the old one.\n buffer = (col.buffer as unknown as { transfer(newByteLength: number): ArrayBuffer }).transfer(\n newByteLength,\n );\n } /* istanbul ignore next -- fallback for runtimes without ES2024 transfer() */ else {\n // Fallback path: allocate new buffer + byte-level copy.\n buffer = new ArrayBuffer(newByteLength);\n new Uint8Array(buffer).set(new Uint8Array(col.buffer));\n }\n\n const view = createFieldView(Ctor, buffer);\n return { buffer, view, capacity: newCapacity, fieldType: col.fieldType, arity: col.arity };\n}\n\n// ────────────────────────────────────────────────────────────────────────────\n// Buffer-write input normalization (feat-20260621 V2 / AC-A4)\n// ────────────────────────────────────────────────────────────────────────────\n\n/**\n * Normalize a `'buffer'` / `'buffer<N>'` write payload to a `Uint8Array` view\n * over its raw bytes. The write surface (`FieldInputType<'buffer'>`) accepts\n * any `AllowSharedBufferSource` (Float32Array / ArrayBuffer / Uint8Array / any\n * TypedArray); the column store and read side speak `Uint8Array` only. This is\n * the single ingestion point that bridges the two — a strict superset of the\n * prior Uint8Array-only behavior (an existing `Uint8Array` caller round-trips\n * through `new Uint8Array(buffer, byteOffset, byteLength)`, same bytes, same\n * length), so existing callers see zero behavior change.\n *\n * Returns `null` for non-buffer-source inputs (e.g. a forced cast feeding a\n * number) so callers keep their existing \"no-op / alloc(0)\" branch for raw\n * that is not a real buffer view.\n */\nexport function normalizeBufferWrite(raw: unknown): Uint8Array | null {\n if (raw instanceof Uint8Array) {\n return raw;\n }\n if (ArrayBuffer.isView(raw)) {\n return new Uint8Array(raw.buffer, raw.byteOffset, raw.byteLength);\n }\n if (raw instanceof ArrayBuffer) {\n return new Uint8Array(raw);\n }\n if (typeof SharedArrayBuffer !== 'undefined' && raw instanceof SharedArrayBuffer) {\n return new Uint8Array(raw);\n }\n return null;\n}\n\n// ────────────────────────────────────────────────────────────────────────────\n// Hot/cold classification\n// ────────────────────────────────────────────────────────────────────────────\n\n/**\n * Determine if a schema is \"hot\" (all fields are scalar → TypedArray SoA).\n * Returns true if all fields are in the scalar field type set.\n * Empty schema (tag component) returns true by convention (vacuously true).\n *\n * Schema-vocab keywords (`buffer:<N>` / `ref<T>` / `handle<T>` / `entity` /\n * `array<T,N>` / `array<T>`) are explicitly cold — their storage is owned by\n * separate subsystems (UniqueRefStore / BufferPool), not the column SoA path. The keyword check uses an unsafe narrowing because\n * `SchemaFieldType` is wider than the set's `ScalarFieldType` element type;\n * the `has` test is the runtime gate.\n */\nexport function isHotSchema(schema: ComponentSchema): boolean {\n for (const fieldType of Object.values(schema)) {\n if (!TYPE_METADATA[fieldType]?.isScalar) {\n return false;\n }\n }\n return true;\n}\n","import {\n bufferFieldByteLength,\n type Component,\n type ComponentId,\n componentId,\n componentSchema,\n fieldTypeToMetaKey,\n isManagedBufferField,\n parseManagedArraySchema,\n type ScalarFieldType,\n TYPE_METADATA,\n} from '../component';\nimport { Entity, foldEssentials } from '../entity';\nimport type { EntityHandle } from '../entity-handle';\nimport {\n type ComponentEpochColumns,\n copyComponentEpoch,\n createComponentEpochColumns,\n growComponentEpochColumns,\n} from './change-detection';\nimport { arrayCountColumnName, type Column, createColumn, growColumn } from './column';\n\nconst INITIAL_CAPACITY = 64;\n\nexport type TableId = number;\n\nexport interface TableComponentStorage {\n readonly component: Component;\n fields: Map<string, Column>;\n epochs: ComponentEpochColumns;\n}\n\nexport interface Table {\n readonly id: TableId;\n readonly key: string;\n readonly components: ReadonlyArray<Component>;\n storage: Map<ComponentId, TableComponentStorage>;\n size: number;\n capacity: number;\n version: number;\n}\n\nexport function tableKey(componentIds: ReadonlyArray<ComponentId>): string {\n return [...foldEssentials(componentIds)].sort((a, b) => a - b).join('+');\n}\n\nexport function canonicalComponents(components: ReadonlyArray<Component>): Component[] {\n const byId = new Map<ComponentId, Component>();\n byId.set(componentId(Entity), Entity as unknown as Component);\n for (const component of components) byId.set(componentId(component), component);\n return [...byId.values()].sort((a, b) => componentId(a) - componentId(b));\n}\n\nexport function createTable(\n components: ReadonlyArray<Component>,\n id: TableId,\n shared = false,\n): Table {\n const sortedComponents = canonicalComponents(components);\n const capacity = INITIAL_CAPACITY;\n const storage = new Map<ComponentId, TableComponentStorage>();\n for (const component of sortedComponents) {\n const fields = new Map<string, Column>();\n for (const [fieldName, fieldType] of Object.entries(componentSchema(component))) {\n const arrayMeta = parseManagedArraySchema(fieldType);\n if (arrayMeta !== null && arrayMeta.length !== undefined) {\n const metaKey = fieldTypeToMetaKey(arrayMeta.elementType);\n const scalarType: ScalarFieldType | null =\n metaKey === null ? null : (TYPE_METADATA[metaKey]?.storage ?? null);\n if (scalarType !== null) {\n fields.set(fieldName, createColumn(scalarType, capacity, arrayMeta.length, shared));\n }\n continue;\n }\n if (isManagedBufferField(fieldType) && fieldType !== 'buffer') {\n fields.set(\n fieldName,\n createColumn('u8', capacity, bufferFieldByteLength(fieldType), shared),\n );\n continue;\n }\n const metaKey = fieldTypeToMetaKey(fieldType);\n const scalarType: ScalarFieldType | null =\n metaKey === null ? null : (TYPE_METADATA[metaKey]?.storage ?? null);\n if (scalarType === null) continue;\n fields.set(fieldName, createColumn(scalarType, capacity, 1, shared));\n if (arrayMeta !== null && arrayMeta.length === undefined) {\n fields.set(arrayCountColumnName(fieldName), createColumn('u32', capacity, 1, shared));\n }\n }\n storage.set(componentId(component), {\n component,\n fields,\n epochs: createComponentEpochColumns(capacity),\n });\n }\n return {\n id,\n key: tableKey(sortedComponents.map((component) => componentId(component))),\n components: sortedComponents,\n storage,\n size: 0,\n capacity,\n version: 0,\n };\n}\n\nexport function appendTableRow(table: Table, entity: EntityHandle): number {\n if (table.size === table.capacity) growTable(table, table.capacity * 2);\n const row = table.size;\n const self = table.storage.get(componentId(Entity))?.fields.get('self');\n if (self !== undefined) self.view[row] = entity as number;\n table.size = row + 1;\n return row;\n}\n\nexport function removeTableRow(\n table: Table,\n row: number,\n): { movedEntity: EntityHandle; newRow: number } | null {\n const lastRow = table.size - 1;\n if (row === lastRow) {\n table.size = lastRow;\n return null;\n }\n const movedEntity = (table.storage.get(componentId(Entity))?.fields.get('self')?.view[lastRow] ??\n 0) as EntityHandle;\n for (const componentStorage of table.storage.values()) {\n for (const column of componentStorage.fields.values()) {\n const arity = column.arity;\n column.view.set(column.view.subarray(lastRow * arity, lastRow * arity + arity), row * arity);\n }\n copyComponentEpoch(componentStorage.epochs, lastRow, componentStorage.epochs, row);\n }\n table.size = lastRow;\n return { movedEntity, newRow: row };\n}\n\nexport function growTable(table: Table, targetCapacity: number): void {\n let capacity = table.capacity;\n while (capacity < targetCapacity) capacity *= 2;\n if (capacity === table.capacity) return;\n for (const componentStorage of table.storage.values()) {\n const fields = new Map<string, Column>();\n for (const [fieldName, column] of componentStorage.fields) {\n fields.set(fieldName, growColumn(column, capacity));\n }\n componentStorage.fields = fields;\n componentStorage.epochs = growComponentEpochColumns(componentStorage.epochs, capacity);\n }\n table.capacity = capacity;\n table.version += 1;\n}\n","// @forgeax/engine-ecs — ArchetypeGraph: manages archetype creation and edge caching.\n//\n// O(1) archetype migration lookup via cached edges (D-02 / Finding 2).\n// Global `generation` counter incremented on each new archetype creation\n// (ArchetypeGeneration for query cache incremental update).\n\nimport type { Component, ComponentId } from '../component';\nimport * as componentOwner from '../component';\nimport { type Archetype, type ArchetypeId, archetypeKey, createArchetype } from './archetype';\nimport { createSparseTagSet, type SparseTagSet } from './change-detection';\nimport { canonicalComponents, createTable, type Table, type TableId, tableKey } from './table';\n\n/**\n * The ArchetypeGraph owns all archetypes and their edge caches.\n *\n * `archetypes` is the SSOT: a dense array indexed by `ArchetypeId` (the id is\n * allocated as the next array slot, so `archetypes[id].id === id`).\n * `dedupByKey` is a derived index `key → ArchetypeId` used only at archetype\n * creation to dedupe; consumers always read through `archetypes[id]`\n * (architecture-principles.md §1 SSOT, §2 Derive — replaces the historical\n * `byKey: Map<string, Archetype>` / `byId: Archetype[]` pair which carried two\n * full Archetype refs per row).\n */\nexport interface ArchetypeGraph {\n /** SSOT: dense array indexed by `ArchetypeId` (id == array slot). */\n archetypes: Archetype[];\n /** Derived dedup index: canonical-key string → ArchetypeId. */\n dedupByKey: Map<string, ArchetypeId>;\n /** Global generation counter. Incremented on each new archetype. */\n generation: number;\n tables: Table[];\n tableDedupByKey: Map<string, TableId>;\n tableGeneration: number;\n sparseTags: Map<ComponentId, SparseTagSet>;\n readonly shared: boolean;\n}\n\n/**\n * Create a fresh ArchetypeGraph.\n */\nexport function createArchetypeGraph(shared = false): ArchetypeGraph {\n return {\n archetypes: [],\n dedupByKey: new Map(),\n generation: 0,\n tables: [],\n tableDedupByKey: new Map(),\n tableGeneration: 0,\n sparseTags: new Map(),\n shared,\n };\n}\n\nexport function getTable(graph: ArchetypeGraph, id: TableId): Table {\n const table = graph.tables[id];\n if (table === undefined) throw new Error(`Table ${id} does not exist.`);\n return table;\n}\n\nexport function getOrCreateTable(\n graph: ArchetypeGraph,\n components: ReadonlyArray<Component>,\n): Table {\n const tableComponents = canonicalComponents(\n components.filter((component) => component.storage === 'table'),\n );\n const key = tableKey(tableComponents.map((component) => componentOwner.componentId(component)));\n const existingId = graph.tableDedupByKey.get(key);\n if (existingId !== undefined) return getTable(graph, existingId);\n const table = createTable(tableComponents, graph.tables.length, graph.shared);\n graph.tables.push(table);\n graph.tableDedupByKey.set(key, table.id);\n graph.tableGeneration += 1;\n return table;\n}\n\nexport function getOrCreateSparseTagSet(graph: ArchetypeGraph, component: Component): SparseTagSet {\n const current = graph.sparseTags.get(componentOwner.componentId(component));\n if (current !== undefined) return current;\n const set = createSparseTagSet(component);\n graph.sparseTags.set(componentOwner.componentId(component), set);\n return set;\n}\n\n/**\n * Get or create an archetype for the given component set.\n * ComponentIds are sorted to produce a canonical key.\n */\nexport function getOrCreateArchetype(\n graph: ArchetypeGraph,\n componentIds: ReadonlyArray<ComponentId>,\n components: ReadonlyArray<Component>,\n): Archetype {\n const key = archetypeKey(componentIds);\n const existingId = graph.dedupByKey.get(key);\n if (existingId !== undefined) {\n // biome-ignore lint/style/noNonNullAssertion: dedupByKey only ever holds ids that were pushed into archetypes[].\n return graph.archetypes[existingId]!;\n }\n\n const fullComponents = canonicalComponents(components);\n const table = getOrCreateTable(graph, fullComponents);\n const archId = graph.archetypes.length;\n const arch = createArchetype(fullComponents, archId, table.id);\n graph.archetypes.push(arch);\n graph.dedupByKey.set(key, archId);\n graph.generation += 1;\n return arch;\n}\n\n/**\n * Get the target archetype after adding `componentId` to `src`.\n * Caches the edge for O(1) subsequent lookups.\n */\nexport function getAddEdge(\n graph: ArchetypeGraph,\n src: Archetype,\n componentId: ComponentId,\n component: Component,\n): Archetype {\n const cached = src.addEdges.get(componentId);\n if (cached !== undefined) {\n const target = graph.archetypes[cached];\n if (target) {\n return target;\n }\n }\n\n // Compute target archetype: src components + new component.\n const newIds = [...src.components.map((c) => componentOwner.componentId(c)), componentId];\n const newComponents = [...src.components, component];\n const target = getOrCreateArchetype(graph, newIds, newComponents);\n src.addEdges.set(componentId, target.id);\n return target;\n}\n\n/**\n * Get the target archetype after removing `componentId` from `src`.\n * Caches the edge for O(1) subsequent lookups.\n *\n * Component list is derived from `src.components.filter(c => componentOwner.componentId(c) !== componentId)`\n * (no separate componentRegistry — feat-20260611 AC-09).\n */\nexport function getRemoveEdge(\n graph: ArchetypeGraph,\n src: Archetype,\n componentId: ComponentId,\n): Archetype {\n const cached = src.removeEdges.get(componentId);\n if (cached !== undefined) {\n const target = graph.archetypes[cached];\n if (target) {\n return target;\n }\n }\n\n // Compute target archetype: src components minus removed component.\n // Derive componentIds from src.components (single-field Archetype).\n const newIds = src.components\n .map((c) => componentOwner.componentId(c))\n .filter((id) => id !== componentId);\n const newComponents = src.components.filter((c) => componentOwner.componentId(c) !== componentId);\n const target = getOrCreateArchetype(graph, newIds, newComponents);\n src.removeEdges.set(componentId, target.id);\n return target;\n}\n","// @forgeax/engine-ecs — per-entity and per-resource change ticks.\n\nimport type { Component } from '../component';\nimport * as componentOwner from '../component';\nimport { type EntityHandle, entityIndex } from '../entity-handle';\n\nimport type { ArchetypeGraph } from './archetype-graph';\nimport { getOrCreateSparseTagSet } from './archetype-graph';\n\nconst INITIAL_SPARSE_CAPACITY = 64;\n\nexport interface ComponentEpochColumns {\n added: Float64Array;\n changed: Float64Array;\n}\n\nexport function createComponentEpochColumns(capacity: number): ComponentEpochColumns {\n return { added: new Float64Array(capacity), changed: new Float64Array(capacity) };\n}\n\nexport function growComponentEpochColumns(\n columns: ComponentEpochColumns,\n capacity: number,\n): ComponentEpochColumns {\n const added = new Float64Array(capacity);\n const changed = new Float64Array(capacity);\n added.set(columns.added);\n changed.set(columns.changed);\n return { added, changed };\n}\n\nexport function copyComponentEpoch(\n source: ComponentEpochColumns,\n sourceRow: number,\n target: ComponentEpochColumns,\n targetRow: number,\n): void {\n target.added[targetRow] = source.added[sourceRow] ?? 0;\n target.changed[targetRow] = source.changed[sourceRow] ?? 0;\n}\n\nexport interface SparseTagSet {\n readonly component: Component;\n sparse: Int32Array;\n dense: Uint32Array;\n added: Float64Array;\n changed: Float64Array;\n size: number;\n}\n\nexport function createSparseTagSet(component: Component): SparseTagSet {\n const sparse = new Int32Array(INITIAL_SPARSE_CAPACITY);\n sparse.fill(-1);\n return {\n component,\n sparse,\n dense: new Uint32Array(INITIAL_SPARSE_CAPACITY),\n added: new Float64Array(INITIAL_SPARSE_CAPACITY),\n changed: new Float64Array(INITIAL_SPARSE_CAPACITY),\n size: 0,\n };\n}\n\nexport function sparseTagIndex(set: SparseTagSet, entity: EntityHandle): number {\n const denseIndex = set.sparse[entityIndex(entity)] ?? -1;\n return denseIndex >= 0 && set.dense[denseIndex] === (entity as number) ? denseIndex : -1;\n}\n\nexport function sparseTagHas(set: SparseTagSet, entity: EntityHandle): boolean {\n return sparseTagIndex(set, entity) >= 0;\n}\n\nexport function insertSparseTag(set: SparseTagSet, entity: EntityHandle, epoch: number): number {\n const present = sparseTagIndex(set, entity);\n if (present >= 0) {\n set.changed[present] = epoch;\n return present;\n }\n growSparseSlots(set, entityIndex(entity) + 1);\n if (set.size === set.dense.length) growSparseDense(set, set.size + 1);\n const denseIndex = set.size;\n set.dense[denseIndex] = entity as number;\n set.added[denseIndex] = epoch;\n set.changed[denseIndex] = epoch;\n set.sparse[entityIndex(entity)] = denseIndex;\n set.size += 1;\n return denseIndex;\n}\n\nexport function removeSparseTag(set: SparseTagSet, entity: EntityHandle): boolean {\n const denseIndex = sparseTagIndex(set, entity);\n if (denseIndex < 0) return false;\n const lastIndex = set.size - 1;\n set.sparse[entityIndex(entity)] = -1;\n if (denseIndex !== lastIndex) {\n const movedEntity = set.dense[lastIndex] as EntityHandle;\n set.dense[denseIndex] = movedEntity as number;\n set.added[denseIndex] = set.added[lastIndex] ?? 0;\n set.changed[denseIndex] = set.changed[lastIndex] ?? 0;\n set.sparse[entityIndex(movedEntity)] = denseIndex;\n }\n set.size = lastIndex;\n return true;\n}\n\nfunction growSparseSlots(set: SparseTagSet, targetCapacity: number): void {\n if (targetCapacity <= set.sparse.length) return;\n let capacity = set.sparse.length;\n while (capacity < targetCapacity) capacity *= 2;\n const sparse = new Int32Array(capacity);\n sparse.fill(-1);\n sparse.set(set.sparse);\n set.sparse = sparse;\n}\n\nfunction growSparseDense(set: SparseTagSet, targetCapacity: number): void {\n let capacity = set.dense.length;\n while (capacity < targetCapacity) capacity *= 2;\n const dense = new Uint32Array(capacity);\n dense.set(set.dense);\n set.dense = dense;\n const added = new Float64Array(capacity);\n added.set(set.added);\n set.added = added;\n const changed = new Float64Array(capacity);\n changed.set(set.changed);\n set.changed = changed;\n}\n\nexport interface ChangeTicks {\n added: number;\n changed: number;\n}\n\nexport const NEVER_CHANGED_TICK = -1;\n\nexport function createChangeTicks(tick: number): ChangeTicks {\n return { added: tick, changed: tick };\n}\n\ninterface EntityLocation {\n readonly archetypeId: number;\n readonly archetypeRow: number;\n}\n\nexport function readComponentChange(\n graph: ArchetypeGraph,\n location: EntityLocation,\n entity: EntityHandle,\n componentId: number,\n): ChangeTicks | undefined {\n const sparseSet = graph.sparseTags.get(componentId);\n if (sparseSet !== undefined) {\n const denseIndex = sparseTagIndex(sparseSet, entity);\n if (denseIndex < 0) return undefined;\n return {\n added: sparseSet.added[denseIndex] ?? 0,\n changed: sparseSet.changed[denseIndex] ?? 0,\n };\n }\n const archetype = graph.archetypes[location.archetypeId];\n if (archetype === undefined) return undefined;\n const epochs = graph.tables[archetype.tableId]?.storage.get(componentId)?.epochs;\n if (epochs === undefined) return undefined;\n const tableRow = archetype.rows[location.archetypeRow] ?? -1;\n return {\n added: epochs.added[tableRow] ?? 0,\n changed: epochs.changed[tableRow] ?? 0,\n };\n}\n\nexport function markComponentsAdded(\n graph: ArchetypeGraph,\n location: EntityLocation,\n entity: EntityHandle,\n componentIds: readonly number[],\n epoch: number,\n): void {\n const archetype = graph.archetypes[location.archetypeId];\n const table = archetype === undefined ? undefined : graph.tables[archetype.tableId];\n const tableRow = archetype?.rows[location.archetypeRow] ?? -1;\n for (const componentId of componentIds) {\n const component = archetype?.components.find(\n (candidate) => componentOwner.componentId(candidate) === componentId,\n );\n if (component?.storage === 'sparse') {\n insertSparseTag(getOrCreateSparseTagSet(graph, component), entity, epoch);\n continue;\n }\n const epochs = table?.storage.get(componentId)?.epochs;\n if (epochs === undefined) continue;\n epochs.added[tableRow] = epoch;\n epochs.changed[tableRow] = epoch;\n }\n}\n\nexport function markComponentChanged(\n graph: ArchetypeGraph,\n location: EntityLocation,\n entity: EntityHandle,\n componentId: number,\n epoch: () => number,\n): void {\n const sparseSet = graph.sparseTags.get(componentId);\n if (sparseSet !== undefined) {\n const denseIndex = sparseTagIndex(sparseSet, entity);\n if (denseIndex >= 0) sparseSet.changed[denseIndex] = epoch();\n return;\n }\n const archetype = graph.archetypes[location.archetypeId];\n if (archetype === undefined) return;\n const epochs = graph.tables[archetype.tableId]?.storage.get(componentId)?.epochs;\n if (epochs === undefined) return;\n const tableRow = archetype.rows[location.archetypeRow] ?? -1;\n epochs.changed[tableRow] = epoch();\n}\n","import { err, ok, type Result } from '@forgeax/engine-types';\nimport type { Component } from '../component';\nimport * as componentOwner from '../component';\nimport { componentId } from '../component';\nimport { Entity } from '../entity';\nimport type { EntityHandle } from '../entity-handle';\nimport {\n DerivedRangeOutOfBoundsError,\n SharedKernelFailureError,\n WorldPoisonedError,\n} from '../errors';\nimport type { Table } from '../storage/table';\nimport type { EcsError, World } from '../world';\nimport { worldInternal } from '../world-internal';\nimport type { MutableColumnShape, ReadonlyColumnShape } from './query';\n\n/** Package-internal whole-column storage owned by one dense query table. */\nexport interface DerivedColumnBinding<R extends Component, C extends Component> {\n /** Physical table identity for package-internal projection consumers. */\n readonly tableId: number;\n /** Whole entity column; every dense table carries the essential Entity row. */\n readonly entities: Readonly<Uint32Array>;\n readonly read: ReadonlyColumnShape<R>;\n readonly write: MutableColumnShape<C>;\n readonly rowCapacity: number;\n}\n\n/** Reusable identity cursor for O(1) dense-table lookup without a row facade. */\nexport interface DerivedRangeCursor {\n bindingIndex: number;\n row: number;\n}\n\nexport type DerivedRangeKernel<R extends Component, C extends Component> = (\n binding: DerivedColumnBinding<R, C>,\n base: number,\n start: number,\n count: number,\n context: unknown,\n) => void;\n\n/** Package-internal row probe used when the probe already has the derived value in scratch storage. */\nexport type DerivedRangeRowProbe<R extends Component, C extends Component> = (\n binding: DerivedColumnBinding<R, C>,\n row: number,\n context: unknown,\n) => boolean;\n\n/** Package-internal commit for a value prepared by a preceding row probe. */\nexport type DerivedRangeRowCommit<R extends Component, C extends Component> = (\n binding: DerivedColumnBinding<R, C>,\n row: number,\n context: unknown,\n) => void;\n\ninterface DerivedRangeBindingSource {\n readonly structureEpoch: () => number;\n readonly tables: () => readonly Table[];\n readonly readComponents: readonly Component[];\n readonly writeComponents: readonly Component[];\n}\n\nexport interface DerivedRangeAllocationTrace {\n subarrayCalls: number;\n shapeAllocations: number;\n closureAllocations: number;\n columnWindowAllocations: number;\n rowFacadeAllocations: number;\n proxyAllocations: number;\n rangeCacheAllocations: number;\n bindingRebuilds: number;\n}\n\nlet allocationTrace: DerivedRangeAllocationTrace | undefined;\n\nexport function beginDerivedRangeAllocationTrace(): void {\n allocationTrace = {\n subarrayCalls: 0,\n shapeAllocations: 0,\n closureAllocations: 0,\n columnWindowAllocations: 0,\n rowFacadeAllocations: 0,\n proxyAllocations: 0,\n rangeCacheAllocations: 0,\n bindingRebuilds: 0,\n };\n}\n\nexport function endDerivedRangeAllocationTrace(): DerivedRangeAllocationTrace {\n const trace = allocationTrace;\n allocationTrace = undefined;\n return (\n trace ?? {\n subarrayCalls: 0,\n shapeAllocations: 0,\n closureAllocations: 0,\n columnWindowAllocations: 0,\n rowFacadeAllocations: 0,\n proxyAllocations: 0,\n rangeCacheAllocations: 0,\n bindingRebuilds: 0,\n }\n );\n}\n\nfunction countAllocation(name: keyof DerivedRangeAllocationTrace): void {\n const trace = allocationTrace;\n if (trace !== undefined) trace[name] += 1;\n}\n\nexport interface DerivedRangeWriter<R extends Component, C extends Component> {\n readonly bindings: readonly DerivedColumnBinding<R, C>[];\n /** Locate a live entity in its bound table and return its physical row. */\n locateEntity(entity: EntityHandle, cursor: DerivedRangeCursor): boolean;\n /** Publish rows whose values were written directly into a derived column. */\n publishChangedRows(bindingIndex: number, changed: Uint8Array): Result<void, EcsError>;\n writeRange(\n bindingIndex: number,\n base: number,\n start: number,\n count: number,\n kernel: DerivedRangeKernel<R, C>,\n context: unknown,\n ): Result<void, EcsError>;\n /**\n * Probe and commit rows in one pass. The probe must only inspect the derived\n * value prepared in reusable scratch storage; the commit copies that value.\n * The writer publishes only contiguous changed runs and does not allocate in\n * the hot loop.\n */\n probeAndCommitRange(\n bindingIndex: number,\n base: number,\n start: number,\n count: number,\n probe: DerivedRangeRowProbe<R, C>,\n commit: DerivedRangeRowCommit<R, C>,\n context: unknown,\n ): Result<void, EcsError>;\n}\n\nexport function createDerivedRangeWriter<R extends Component, C extends Component>(\n world: World,\n component: C,\n source: DerivedRangeBindingSource,\n): DerivedRangeWriter<R, C> {\n let boundEpoch = -1;\n let bindingTables: readonly Table[] = [];\n let bindings: readonly DerivedColumnBinding<R, C>[] = [];\n let bindingByTable = new Map<number, number>();\n let runStartBuffers: readonly Int32Array[] = [];\n let runCountBuffers: readonly Int32Array[] = [];\n\n const rebind = (): void => {\n countAllocation('bindingRebuilds');\n const tables = source.tables();\n const nextBindings: DerivedColumnBinding<R, C>[] = [];\n const nextRunStartBuffers: Int32Array[] = [];\n const nextRunCountBuffers: Int32Array[] = [];\n for (const table of tables) {\n nextBindings.push({\n tableId: table.id,\n entities: (table.storage.get(componentId(Entity))?.fields.get('self')?.view ??\n new Uint32Array(0)) as Uint32Array,\n read: buildWholeColumnShape(table, source.readComponents) as ReadonlyColumnShape<R>,\n write: buildWholeColumnShape(table, source.writeComponents) as MutableColumnShape<C>,\n rowCapacity: table.size,\n });\n // A table with N rows can contain at most N changed runs. These buffers\n // are owned by the structural rebind and reused by every hot call.\n const runCapacity = Math.max(1, table.size);\n nextRunStartBuffers.push(new Int32Array(runCapacity));\n nextRunCountBuffers.push(new Int32Array(runCapacity));\n }\n bindingTables = tables;\n bindings = nextBindings;\n bindingByTable = new Map<number, number>();\n for (let index = 0; index < nextBindings.length; index += 1) {\n const binding = nextBindings[index];\n if (binding !== undefined) bindingByTable.set(binding.tableId, index);\n }\n runStartBuffers = nextRunStartBuffers;\n runCountBuffers = nextRunCountBuffers;\n boundEpoch = source.structureEpoch();\n };\n\n rebind();\n\n const writer: DerivedRangeWriter<R, C> = {\n get bindings() {\n if (boundEpoch !== source.structureEpoch()) rebind();\n return bindings;\n },\n locateEntity(entity, cursor) {\n if (world.execution.health === 'poisoned') return false;\n if (boundEpoch !== source.structureEpoch()) rebind();\n const archetype = world[worldInternal].getEntityArchetype(entity);\n if (archetype === undefined) return false;\n const bindingIndex = bindingByTable.get(archetype.tableId);\n if (bindingIndex === undefined) return false;\n const record = world[worldInternal].getRecords()[(entity as unknown as number) & 0x00ffffff];\n if (record === undefined || record.archetypeId !== archetype.id) return false;\n const row = archetype.rows[record.archetypeRow];\n const binding = bindings[bindingIndex];\n if (binding === undefined || row === undefined || row < 0 || row >= binding.rowCapacity) {\n return false;\n }\n cursor.bindingIndex = bindingIndex;\n cursor.row = row;\n return true;\n },\n publishChangedRows(bindingIndex, changed) {\n if (world.execution.health === 'poisoned') {\n return err(new WorldPoisonedError(world.identity, world.execution.fault));\n }\n if (boundEpoch !== source.structureEpoch()) rebind();\n const binding = bindings[bindingIndex];\n const table = bindingTables[bindingIndex];\n const runStarts = runStartBuffers[bindingIndex];\n const runCounts = runCountBuffers[bindingIndex];\n if (\n binding === undefined ||\n table === undefined ||\n runStarts === undefined ||\n runCounts === undefined ||\n !Number.isSafeInteger(bindingIndex) ||\n bindingIndex < 0 ||\n changed.length < binding.rowCapacity ||\n table.storage.get(componentOwner.componentId(component)) === undefined\n ) {\n return err(new DerivedRangeOutOfBoundsError(0, changed.length, binding?.rowCapacity ?? 0));\n }\n let runCount = 0;\n let runStart = -1;\n for (let row = 0; row < binding.rowCapacity; row += 1) {\n if ((changed[row] ?? 0) !== 0) {\n if (runStart < 0) runStart = row;\n } else if (runStart >= 0) {\n runStarts[runCount] = runStart;\n runCounts[runCount] = row - runStart;\n runCount += 1;\n runStart = -1;\n }\n }\n if (runStart >= 0) {\n runStarts[runCount] = runStart;\n runCounts[runCount] = binding.rowCapacity - runStart;\n runCount += 1;\n }\n if (runCount === 0) return ok(undefined);\n const previousEpoch = world[worldInternal].getMutationEpoch();\n let epoch: number;\n try {\n epoch = world[worldInternal].nextMutationEpoch();\n const componentIdentifier = componentOwner.componentId(component);\n for (let index = 0; index < runCount; index += 1) {\n world[worldInternal].publishDerivedRange(\n table,\n componentIdentifier,\n runStarts[index] ?? 0,\n runCounts[index] ?? 0,\n epoch,\n );\n }\n changed.fill(0, 0, binding.rowCapacity);\n return ok(undefined);\n } catch (cause) {\n world[worldInternal].restoreMutationEpoch(previousEpoch);\n world[worldInternal].poisonExecution({\n code: 'shared-kernel-failed',\n kernelName: `derived-range:${component.name}:publish`,\n cause,\n partialWrite: true,\n retryable: false,\n });\n return err(new SharedKernelFailureError(component.name, world.identity, cause, true));\n }\n },\n writeRange(bindingIndex, base, start, count, kernel, context) {\n if (world.execution.health === 'poisoned') {\n return err(new WorldPoisonedError(world.identity, world.execution.fault));\n }\n if (boundEpoch !== source.structureEpoch()) rebind();\n const binding = bindings[bindingIndex];\n const table = bindingTables[bindingIndex];\n if (\n binding === undefined ||\n table === undefined ||\n !Number.isSafeInteger(bindingIndex) ||\n !Number.isSafeInteger(base) ||\n !Number.isSafeInteger(start) ||\n !Number.isSafeInteger(count) ||\n bindingIndex < 0 ||\n base < 0 ||\n start < 0 ||\n count < 0 ||\n base + start + count > binding.rowCapacity ||\n table.storage.get(componentOwner.componentId(component)) === undefined\n ) {\n return err(new DerivedRangeOutOfBoundsError(start, count, binding?.rowCapacity ?? 0));\n }\n if (count === 0) return ok(undefined);\n\n const previousEpoch = world[worldInternal].getMutationEpoch();\n let epoch: number;\n try {\n epoch = world[worldInternal].nextMutationEpoch();\n } catch (cause) {\n return err(cause as EcsError);\n }\n try {\n kernel(binding, base, start, count, context);\n world[worldInternal].publishDerivedRange(\n table,\n componentOwner.componentId(component),\n base + start,\n count,\n epoch,\n );\n return ok(undefined);\n } catch (cause) {\n world[worldInternal].restoreMutationEpoch(previousEpoch);\n world[worldInternal].poisonExecution({\n code: 'shared-kernel-failed',\n kernelName: `derived-range:${component.name}`,\n cause,\n partialWrite: true,\n retryable: false,\n });\n return err(new SharedKernelFailureError(component.name, world.identity, cause, true));\n }\n },\n probeAndCommitRange(bindingIndex, base, start, count, probe, commit, context) {\n if (world.execution.health === 'poisoned') {\n return err(new WorldPoisonedError(world.identity, world.execution.fault));\n }\n if (boundEpoch !== source.structureEpoch()) rebind();\n const binding = bindings[bindingIndex];\n const table = bindingTables[bindingIndex];\n const runStarts = runStartBuffers[bindingIndex];\n const runCounts = runCountBuffers[bindingIndex];\n if (\n binding === undefined ||\n table === undefined ||\n runStarts === undefined ||\n runCounts === undefined ||\n !Number.isSafeInteger(bindingIndex) ||\n !Number.isSafeInteger(base) ||\n !Number.isSafeInteger(start) ||\n !Number.isSafeInteger(count) ||\n bindingIndex < 0 ||\n base < 0 ||\n start < 0 ||\n count < 0 ||\n base + start + count > binding.rowCapacity ||\n table.storage.get(componentOwner.componentId(component)) === undefined\n ) {\n return err(new DerivedRangeOutOfBoundsError(start, count, binding?.rowCapacity ?? 0));\n }\n if (count === 0) return ok(undefined);\n\n const previousEpoch = world[worldInternal].getMutationEpoch();\n let runCount = 0;\n let epoch = 0;\n let epochReserved = false;\n let runStart = -1;\n try {\n for (let offset = 0; offset < count; offset += 1) {\n const row = base + start + offset;\n const changed = probe(binding, row, context);\n if (changed) {\n if (!epochReserved) {\n try {\n epoch = world[worldInternal].nextMutationEpoch();\n epochReserved = true;\n } catch (cause) {\n // Nothing has been committed yet. Keep the World healthy and\n // preserve the source error so the caller can retry unchanged.\n return err(cause as EcsError);\n }\n }\n if (runStart < 0) runStart = row;\n commit(binding, row, context);\n } else if (runStart >= 0) {\n runStarts[runCount] = runStart;\n runCounts[runCount] = row - runStart;\n runCount += 1;\n runStart = -1;\n }\n }\n if (runStart >= 0) {\n runStarts[runCount] = runStart;\n runCounts[runCount] = base + start + count - runStart;\n runCount += 1;\n }\n\n // Every changed run in this call shares the epoch reserved immediately\n // before the first commit. Publication remains deferred until the\n // complete probe/commit pass has succeeded.\n if (runCount > 0) {\n const componentIdentifier = componentOwner.componentId(component);\n for (let index = 0; index < runCount; index += 1) {\n const runStartValue = runStarts[index] ?? 0;\n const runLength = runCounts[index] ?? 0;\n world[worldInternal].publishDerivedRange(\n table,\n componentIdentifier,\n runStartValue,\n runLength,\n epoch,\n );\n }\n }\n return ok(undefined);\n } catch (cause) {\n if (epochReserved) world[worldInternal].restoreMutationEpoch(previousEpoch);\n world[worldInternal].poisonExecution({\n code: 'shared-kernel-failed',\n kernelName: `derived-range:${component.name}:probe`,\n cause,\n partialWrite: true,\n retryable: false,\n });\n return err(new SharedKernelFailureError(component.name, world.identity, cause, true));\n }\n },\n };\n return writer;\n}\n\nfunction buildWholeColumnShape(\n table: Table,\n components: readonly Component[],\n): Record<string, unknown> {\n countAllocation('shapeAllocations');\n const shape: Record<string, unknown> = {};\n for (const component of components) {\n const fields = table.storage.get(componentOwner.componentId(component))?.fields;\n if (fields === undefined) continue;\n for (const [fieldName, column] of fields) shape[fieldName] = column.view;\n }\n return shape;\n}\n","import { err, ok, type Result } from '@forgeax/engine-types';\nimport {\n type Component,\n type ComponentId,\n type ComponentSchema,\n componentId,\n componentSchema,\n isManagedField,\n type ShapeOf,\n type TypedArrayFor,\n} from '../component';\nimport { Disabled, Entity } from '../entity';\nimport type { EntityHandle } from '../entity-handle';\nimport {\n QueryDataRequiresFieldsError,\n QueryDescriptorConflictError,\n QueryIterationActiveError,\n QueryIterationInvalidatedError,\n QuerySpanUnavailableError,\n type QuerySpanUnavailableReason,\n RelationshipTargetReadonlyError,\n} from '../errors';\nimport { DERIVED_WRITER } from '../internal';\nimport { isRelationshipTarget, relationshipRole } from '../relationship-index';\nimport type { Archetype, ArchetypeId } from '../storage/archetype';\nimport type { ArchetypeGraph } from '../storage/archetype-graph';\nimport { sparseTagIndex } from '../storage/change-detection';\nimport type { FieldView, ManagedColumnReader } from '../storage/column';\nimport type { Table } from '../storage/table';\nimport { type WorldInternal, worldInternal } from '../world-internal';\nimport { createDerivedRangeWriter, type DerivedRangeWriter } from './derived-range-writer';\n\nexport interface QueryDescriptor<\n R extends readonly Component[] = readonly Component[],\n W extends readonly Component[] = readonly Component[],\n O extends readonly Component[] = readonly Component[],\n> {\n readonly read?: R;\n readonly write?: W;\n readonly optional?: O;\n readonly with?: readonly Component[];\n readonly without?: readonly Component[];\n readonly changed?: readonly Component[];\n readonly added?: readonly Component[];\n}\n\nexport type ReadonlyRowShape<C> =\n C extends Component<string, infer S> ? Readonly<ShapeOf<S>> : never;\nexport type MutableRowShape<C> =\n C extends Component<string, infer S>\n ? { -readonly [K in keyof ShapeOf<S>]: ShapeOf<S>[K] }\n : never;\n\ntype ColumnShapeForSchema<S extends ComponentSchema> = {\n [K in keyof S]: TypedArrayFor<S[K]>;\n};\n\nexport type ReadonlyColumnShape<C> =\n C extends Component<string, infer S> ? Readonly<ColumnShapeForSchema<S>> : never;\nexport type MutableColumnShape<C> =\n C extends Component<string, infer S>\n ? { -readonly [K in keyof ColumnShapeForSchema<S>]: ColumnShapeForSchema<S>[K] }\n : never;\n\nexport interface QueryRow<\n R extends readonly Component[] = readonly Component[],\n W extends readonly Component[] = readonly Component[],\n O extends readonly Component[] = readonly Component[],\n> {\n readonly entity: EntityHandle;\n /** Test component presence without materialising its row object. */\n has(component: R[number] | W[number] | O[number]): boolean;\n get<C extends R[number]>(component: C): ReadonlyRowShape<C>;\n get<C extends O[number]>(component: C): ReadonlyRowShape<C> | undefined;\n mut<C extends W[number]>(component: C): MutableRowShape<C>;\n}\n\nexport interface QuerySpan<\n R extends readonly Component[] = readonly Component[],\n W extends readonly Component[] = readonly Component[],\n> {\n /** Packed entity identities for this contiguous table range. */\n readonly entities: Readonly<Uint32Array>;\n readonly length: number;\n get<C extends R[number]>(component: C): ReadonlyColumnShape<C>;\n mut<C extends W[number]>(component: C): MutableColumnShape<C>;\n}\n\nexport interface Query<\n R extends readonly Component[] = readonly Component[],\n W extends readonly Component[] = readonly Component[],\n O extends readonly Component[] = readonly Component[],\n> extends Iterable<QueryRow<R, W, O>> {\n /**\n * Read one known entity without iterating the query's matching tables.\n * Structural descriptor constraints are applied; temporal `changed` and\n * `added` filters are intentionally not evaluated because this is an\n * identity-addressed read, not a version scan.\n */\n at(entity: EntityHandle): QueryRow<R, W, O> | undefined;\n spans(): Result<Iterable<QuerySpan<R, W>>, QuerySpanUnavailableError>;\n combinations(k?: number): Iterable<readonly QueryRow<R, W, O>[]>;\n}\n\nexport type QueryCreationError = QueryDescriptorConflictError | QueryDataRequiresFieldsError;\n\ninterface WorldQueryAccess {\n readonly [worldInternal]: WorldInternal;\n}\n\ninterface CompiledDescriptor<\n R extends readonly Component[],\n W extends readonly Component[],\n O extends readonly Component[],\n> {\n readonly descriptor: QueryDescriptor<R, W, O>;\n readonly requiredIds: readonly ComponentId[];\n readonly withoutIds: readonly ComponentId[];\n readonly changedIds: readonly ComponentId[];\n readonly addedIds: readonly ComponentId[];\n readonly sparseRoute: boolean;\n}\n\ntype Role = 'read' | 'write' | 'optional' | 'with' | 'without';\n\nfunction compileDescriptor<\n const R extends readonly Component[],\n const W extends readonly Component[],\n const O extends readonly Component[],\n>(descriptor: QueryDescriptor<R, W, O>): Result<CompiledDescriptor<R, W, O>, QueryCreationError> {\n const read = descriptor.read ?? ([] as unknown as R);\n const write = descriptor.write ?? ([] as unknown as W);\n const optional = descriptor.optional ?? ([] as unknown as O);\n const withComponents = descriptor.with ?? [];\n const withoutComponents = [...(descriptor.without ?? [])];\n const roles = new Map<Component, Role[]>();\n const addRole = (component: Component, role: Role): void => {\n const current = roles.get(component);\n if (current === undefined) roles.set(component, [role]);\n else current.push(role);\n };\n for (const component of read) addRole(component, 'read');\n for (const component of write) addRole(component, 'write');\n for (const component of optional) addRole(component, 'optional');\n for (const component of withComponents) addRole(component, 'with');\n for (const component of withoutComponents) addRole(component, 'without');\n\n for (const [component, componentRoles] of roles) {\n if (componentRoles.length > 1) {\n return err(new QueryDescriptorConflictError(component.name, componentRoles));\n }\n }\n for (const component of [...read, ...write, ...optional]) {\n if (Object.keys(componentSchema(component)).length === 0) {\n return err(new QueryDataRequiresFieldsError(component.name));\n }\n }\n\n const required = [\n ...read,\n ...write,\n ...withComponents,\n ...(descriptor.changed ?? []),\n ...(descriptor.added ?? []),\n ];\n const requiredIds = [...new Set(required.map((component) => componentId(component)))];\n const withoutIds = [...new Set(withoutComponents.map((component) => componentId(component)))];\n if (!requiredIds.includes(componentId(Disabled)) && !withoutIds.includes(componentId(Disabled))) {\n withoutIds.push(componentId(Disabled));\n }\n return ok({\n descriptor,\n requiredIds,\n withoutIds,\n changedIds: [...new Set((descriptor.changed ?? []).map((component) => componentId(component)))],\n addedIds: [...new Set((descriptor.added ?? []).map((component) => componentId(component)))],\n sparseRoute: [\n ...required,\n ...withoutComponents,\n ...(descriptor.changed ?? []),\n ...(descriptor.added ?? []),\n ].some((component) => component.storage === 'sparse'),\n });\n}\n\nclass QueryRowFacade<\n R extends readonly Component[],\n W extends readonly Component[],\n O extends readonly Component[],\n> implements QueryRow<R, W, O>\n{\n entity = 0 as EntityHandle;\n private archetype: Archetype | undefined;\n\n constructor(private readonly world: WorldQueryAccess) {}\n\n bind(entity: EntityHandle, archetype: Archetype): this {\n this.entity = entity;\n this.archetype = archetype;\n return this;\n }\n\n snapshot(): QueryRowFacade<R, W, O> {\n if (this.archetype === undefined) throw new Error('Query row is not bound.');\n return new QueryRowFacade<R, W, O>(this.world).bind(this.entity, this.archetype);\n }\n\n has(component: R[number] | W[number] | O[number]): boolean {\n return (\n this.archetype?.components.some(\n (candidate) => componentId(candidate) === componentId(component),\n ) === true\n );\n }\n\n get<C extends R[number]>(component: C): ReadonlyRowShape<C>;\n get<C extends O[number]>(component: C): ReadonlyRowShape<C> | undefined;\n get(component: Component): Record<string, unknown> | undefined {\n if (\n !this.archetype?.components.some(\n (candidate) => componentId(candidate) === componentId(component),\n )\n ) {\n return undefined;\n }\n const result = this.world[worldInternal].getQueryRow(this.entity, component);\n if (!result.ok) throw result.error;\n return result.value;\n }\n\n mut<C extends W[number]>(component: C): MutableRowShape<C> {\n const current = this.get(component);\n if (current === undefined) throw new Error(`Query row lacks ${component.name}.`);\n if (isRelationshipTarget(component)) {\n throw new RelationshipTargetReadonlyError(component.name, 'query row');\n }\n // Relationship sources must let the owner validate before recording\n // authored evidence. A stale/cyclic target therefore has zero mutation\n // side effects, while ordinary components retain the existing eager\n // `mut()` evidence semantics.\n const relationshipSource = relationshipRole(component)?.kind === 'source';\n if (!relationshipSource) {\n this.world[worldInternal].markComponentChanged(this.entity, componentId(component));\n }\n return new Proxy(current, {\n set: (target, property, value) => {\n if (typeof property !== 'string') return false;\n const result = this.world[worldInternal].setQueryRow(this.entity, component, {\n [property]: value,\n });\n if (!result.ok) throw result.error;\n (target as Record<string, unknown>)[property] = value;\n return true;\n },\n }) as MutableRowShape<C>;\n }\n}\n\nclass QuerySpanFacade<R extends readonly Component[], W extends readonly Component[]>\n implements QuerySpan<R, W>\n{\n readonly entities: Readonly<Uint32Array>;\n\n constructor(\n private readonly world: WorldQueryAccess,\n private readonly table: Table,\n private readonly rowStart: number,\n readonly length: number,\n ) {\n const entityColumn = table.storage.get(componentId(Entity))?.fields.get('self');\n this.entities = (\n entityColumn === undefined\n ? new Uint32Array(0)\n : rowStart === 0 && length === entityColumn.view.length\n ? entityColumn.view\n : entityColumn.view.subarray(rowStart, rowStart + length)\n ) as Readonly<Uint32Array>;\n }\n\n get<C extends R[number]>(component: C): ReadonlyColumnShape<C> {\n return buildColumnShape(\n this.table,\n component,\n this.rowStart,\n this.length,\n ) as ReadonlyColumnShape<C>;\n }\n\n mut<C extends W[number]>(component: C): MutableColumnShape<C> {\n // A span exposes live column storage. Relationship source and target\n // columns must never obtain that raw write capability: source writes need\n // target-side maintenance and target writes are engine-owned projections.\n if (relationshipRole(component) !== undefined) {\n throw new RelationshipTargetReadonlyError(component.name, 'query span');\n }\n this.world[worldInternal].markComponentRangeChanged(\n this.table,\n componentId(component),\n this.rowStart,\n this.length,\n );\n return buildColumnShape(\n this.table,\n component,\n this.rowStart,\n this.length,\n ) as MutableColumnShape<C>;\n }\n}\n\nfunction makeManagedColumnReader(\n view: FieldView,\n length: number,\n fieldType: string,\n): ManagedColumnReader<string> {\n const slots = view.length === length ? view : view.subarray(0, length);\n return Object.freeze({\n length,\n get(i: number): number {\n return slots[i] ?? 0;\n },\n __managed: fieldType,\n });\n}\n\nfunction buildColumnShape(\n table: Table,\n component: Component,\n rowStart: number,\n rowCount: number,\n): Record<string, FieldView | ManagedColumnReader<string>> {\n const shape: Record<string, FieldView | ManagedColumnReader<string>> = {};\n const fields = table.storage.get(componentId(component))?.fields;\n if (fields === undefined) return shape;\n for (const [fieldName, column] of fields) {\n const start = rowStart * column.arity;\n const end = start + rowCount * column.arity;\n const view =\n start === 0 && end === column.view.length ? column.view : column.view.subarray(start, end);\n const fieldType = componentSchema(component)[fieldName];\n shape[fieldName] =\n fieldType !== undefined && isManagedField(fieldType)\n ? makeManagedColumnReader(view, view.length, fieldType)\n : view;\n }\n return shape;\n}\n\nclass ExecutableQuery<\n R extends readonly Component[],\n W extends readonly Component[],\n O extends readonly Component[],\n> implements Query<R, W, O>\n{\n private matchedArchetypes: ArchetypeId[] = [];\n private matchedTables: number[] = [];\n private matchedTableObjects: Table[] = [];\n private lastGraphGeneration = -1;\n private lastObservedEpoch = 0;\n private active = false;\n\n constructor(\n private readonly world: WorldQueryAccess,\n private readonly compiled: CompiledDescriptor<R, W, O>,\n ) {}\n\n [Symbol.iterator](): Iterator<QueryRow<R, W, O>> {\n this.beginIteration();\n this.refreshMatches();\n const structureEpoch = this.world[worldInternal].getStructureEpoch();\n const upperBound = this.world[worldInternal].getMutationEpoch();\n const row = new QueryRowFacade<R, W, O>(this.world);\n let archetypeIndex = 0;\n let tableIndex = 0;\n let rowIndex = 0;\n let finished = false;\n\n const close = (commit: boolean): void => {\n if (finished) return;\n finished = true;\n this.active = false;\n if (commit) this.lastObservedEpoch = upperBound;\n };\n\n return {\n next: (): IteratorResult<QueryRow<R, W, O>> => {\n if (finished) return { done: true, value: undefined };\n if (this.world[worldInternal].getStructureEpoch() !== structureEpoch) {\n close(false);\n throw new QueryIterationInvalidatedError(\n structureEpoch,\n this.world[worldInternal].getStructureEpoch(),\n );\n }\n if (!this.compiled.sparseRoute) {\n while (tableIndex < this.matchedTables.length) {\n const table =\n this.world[worldInternal].getGraph().tables[this.matchedTables[tableIndex] ?? -1];\n if (table === undefined || rowIndex >= table.size) {\n tableIndex += 1;\n rowIndex = 0;\n continue;\n }\n const currentTableRow = rowIndex++;\n const entityColumn = table.storage.get(componentId(Entity))?.fields.get('self');\n if (entityColumn === undefined) continue;\n const entity = (entityColumn.view[currentTableRow] ?? 0) as EntityHandle;\n if (!this.changeMatches(entity, table, currentTableRow, upperBound)) continue;\n const recordArchetype = this.world[worldInternal].getEntityArchetype(entity);\n if (recordArchetype === undefined) continue;\n return { done: false, value: row.bind(entity, recordArchetype) };\n }\n close(true);\n return { done: true, value: undefined };\n }\n while (archetypeIndex < this.matchedArchetypes.length) {\n const archetype =\n this.world[worldInternal].getGraph().archetypes[\n this.matchedArchetypes[archetypeIndex] ?? -1\n ];\n if (archetype === undefined || rowIndex >= archetype.size) {\n archetypeIndex += 1;\n rowIndex = 0;\n continue;\n }\n const currentArchetypeRow = rowIndex++;\n const currentTableRow = archetype.rows[currentArchetypeRow] ?? 0;\n const table = this.world[worldInternal].getGraph().tables[archetype.tableId];\n if (table === undefined) continue;\n const entityColumn = table.storage.get(componentId(Entity))?.fields.get('self');\n if (entityColumn === undefined) continue;\n const entity = (entityColumn.view[currentTableRow] ?? 0) as EntityHandle;\n if (!this.changeMatches(entity, table, currentTableRow, upperBound)) continue;\n return { done: false, value: row.bind(entity, archetype) };\n }\n close(true);\n return { done: true, value: undefined };\n },\n return: (): IteratorResult<QueryRow<R, W, O>> => {\n close(false);\n return { done: true, value: undefined };\n },\n };\n }\n\n at(entity: EntityHandle): QueryRow<R, W, O> | undefined {\n const archetype = this.world[worldInternal].getEntityArchetype(entity);\n if (archetype === undefined || !this.archetypeMatches(archetype)) return undefined;\n return new QueryRowFacade<R, W, O>(this.world).bind(entity, archetype).snapshot();\n }\n\n spans(): Result<Iterable<QuerySpan<R, W>>, QuerySpanUnavailableError> {\n const reason = this.spanUnavailableReason();\n if (reason !== undefined) return err(new QuerySpanUnavailableError(reason));\n const query = this;\n return ok({\n [Symbol.iterator](): Iterator<QuerySpan<R, W>> {\n query.beginIteration();\n query.refreshMatches();\n const structureEpoch = query.world[worldInternal].getStructureEpoch();\n const upperBound = query.world[worldInternal].getMutationEpoch();\n let tableIndex = 0;\n let rowIndex = 0;\n let finished = false;\n const close = (commit: boolean): void => {\n if (finished) return;\n finished = true;\n query.active = false;\n if (commit) query.lastObservedEpoch = upperBound;\n };\n return {\n next(): IteratorResult<QuerySpan<R, W>> {\n if (finished) return { done: true, value: undefined };\n if (query.world[worldInternal].getStructureEpoch() !== structureEpoch) {\n close(false);\n throw new QueryIterationInvalidatedError(\n structureEpoch,\n query.world[worldInternal].getStructureEpoch(),\n );\n }\n while (tableIndex < query.matchedTables.length) {\n const table =\n query.world[worldInternal].getGraph().tables[query.matchedTables[tableIndex] ?? -1];\n if (table === undefined || table.size === 0) {\n tableIndex += 1;\n rowIndex = 0;\n continue;\n }\n if (query.compiled.changedIds.length === 0 && query.compiled.addedIds.length === 0) {\n tableIndex += 1;\n rowIndex = 0;\n return {\n done: false,\n value: new QuerySpanFacade<R, W>(query.world, table, 0, table.size),\n };\n }\n while (\n rowIndex < table.size &&\n !query.denseChangeMatches(table, rowIndex, upperBound)\n ) {\n rowIndex += 1;\n }\n if (rowIndex >= table.size) {\n tableIndex += 1;\n rowIndex = 0;\n continue;\n }\n const start = rowIndex;\n rowIndex += 1;\n while (\n rowIndex < table.size &&\n query.denseChangeMatches(table, rowIndex, upperBound)\n ) {\n rowIndex += 1;\n }\n return {\n done: false,\n value: new QuerySpanFacade<R, W>(query.world, table, start, rowIndex - start),\n };\n }\n close(true);\n return { done: true, value: undefined };\n },\n return(): IteratorResult<QuerySpan<R, W>> {\n close(false);\n return { done: true, value: undefined };\n },\n };\n },\n });\n }\n\n [DERIVED_WRITER]<C extends W[number]>(\n component: C,\n ): Result<DerivedRangeWriter<R[number], C>, QuerySpanUnavailableError> {\n const reason = this.spanUnavailableReason();\n if (reason !== undefined) return err(new QuerySpanUnavailableError(reason));\n return ok(\n createDerivedRangeWriter<R[number], C>(\n this.world as unknown as import('../world').World,\n component,\n {\n structureEpoch: () => this.world[worldInternal].getStructureEpoch(),\n tables: () => {\n this.refreshMatches();\n return this.matchedTableObjects;\n },\n readComponents: this.compiled.descriptor.read ?? [],\n writeComponents: this.compiled.descriptor.write ?? [],\n },\n ),\n );\n }\n\n combinations(k = 2): Iterable<readonly QueryRow<R, W, O>[]> {\n const query = this;\n return {\n *[Symbol.iterator](): Iterator<readonly QueryRow<R, W, O>[]> {\n if (!Number.isInteger(k) || k < 1) return;\n const previousObservedEpoch = query.lastObservedEpoch;\n const structureEpoch = query.world[worldInternal].getStructureEpoch();\n const rows: QueryRow<R, W, O>[] = [];\n for (const row of query) {\n rows.push((row as QueryRowFacade<R, W, O>).snapshot());\n }\n query.active = true;\n let completed = false;\n try {\n if (k <= rows.length) {\n const indices = Array.from({ length: k }, (_, index) => index);\n while (true) {\n if (query.world[worldInternal].getStructureEpoch() !== structureEpoch) {\n throw new QueryIterationInvalidatedError(\n structureEpoch,\n query.world[worldInternal].getStructureEpoch(),\n );\n }\n yield indices.map((index) => rows[index] as QueryRow<R, W, O>);\n let pivot = k - 1;\n while (pivot >= 0 && (indices[pivot] ?? 0) === rows.length - k + pivot) pivot -= 1;\n if (pivot < 0) break;\n indices[pivot] = (indices[pivot] ?? 0) + 1;\n for (let index = pivot + 1; index < k; index++) {\n indices[index] = (indices[index - 1] ?? 0) + 1;\n }\n }\n }\n completed = true;\n } finally {\n query.active = false;\n if (!completed) query.lastObservedEpoch = previousObservedEpoch;\n }\n },\n };\n }\n\n private beginIteration(): void {\n if (this.active) throw new QueryIterationActiveError();\n this.active = true;\n }\n\n private refreshMatches(): void {\n const graph = this.world[worldInternal].getGraph() as ArchetypeGraph;\n if (this.lastGraphGeneration === graph.generation) return;\n this.matchedArchetypes = graph.archetypes\n .filter((archetype) => this.archetypeMatches(archetype))\n .map((archetype) => archetype.id);\n this.matchedTables = graph.tables\n .filter((table) => this.tableMatches(table))\n .map((table) => table.id);\n this.matchedTableObjects = this.matchedTables.flatMap((id) => {\n const table = graph.tables[id];\n return table === undefined ? [] : [table];\n });\n this.lastGraphGeneration = graph.generation;\n }\n\n private archetypeMatches(archetype: Archetype): boolean {\n for (const requiredId of this.compiled.requiredIds) {\n if (!archetype.components.some((component) => componentId(component) === requiredId))\n return false;\n }\n for (const excludedId of this.compiled.withoutIds) {\n if (archetype.components.some((component) => componentId(component) === excludedId))\n return false;\n }\n return true;\n }\n\n private tableMatches(table: Table): boolean {\n for (const componentId of this.compiled.requiredIds) {\n if (!table.storage.has(componentId)) return false;\n }\n for (const componentId of this.compiled.withoutIds) {\n if (table.storage.has(componentId)) return false;\n }\n return true;\n }\n\n private changeMatches(\n entity: EntityHandle,\n table: Table,\n row: number,\n upperBound: number,\n ): boolean {\n const graph = this.world[worldInternal].getGraph();\n for (const componentId of this.compiled.changedIds) {\n const sparseSet = graph.sparseTags.get(componentId);\n const denseIndex = sparseSet === undefined ? -1 : sparseTagIndex(sparseSet, entity);\n const epoch =\n denseIndex >= 0\n ? (sparseSet?.changed[denseIndex] ?? 0)\n : (table.storage.get(componentId)?.epochs.changed[row] ?? 0);\n if (epoch <= this.lastObservedEpoch || epoch > upperBound) return false;\n }\n for (const componentId of this.compiled.addedIds) {\n const sparseSet = graph.sparseTags.get(componentId);\n const denseIndex = sparseSet === undefined ? -1 : sparseTagIndex(sparseSet, entity);\n const epoch =\n denseIndex >= 0\n ? (sparseSet?.added[denseIndex] ?? 0)\n : (table.storage.get(componentId)?.epochs.added[row] ?? 0);\n if (epoch <= this.lastObservedEpoch || epoch > upperBound) return false;\n }\n return true;\n }\n\n private denseChangeMatches(table: Table, row: number, upperBound: number): boolean {\n for (const componentId of this.compiled.changedIds) {\n const epoch = table.storage.get(componentId)?.epochs.changed[row] ?? 0;\n if (epoch <= this.lastObservedEpoch || epoch > upperBound) return false;\n }\n for (const componentId of this.compiled.addedIds) {\n const epoch = table.storage.get(componentId)?.epochs.added[row] ?? 0;\n if (epoch <= this.lastObservedEpoch || epoch > upperBound) return false;\n }\n return true;\n }\n\n private spanUnavailableReason(): QuerySpanUnavailableReason | undefined {\n if (this.compiled.sparseRoute) return 'sparse-component';\n if ((this.compiled.descriptor.optional?.length ?? 0) > 0) return 'optional-data';\n // A writable relationship source would bypass the source owner (and its\n // materialized target/backpointer), while a target is an ECS-owned\n // projection. Keep read-only relationship inputs usable by Scene's\n // derived writer; only the descriptor's writable role is ineligible.\n if ((this.compiled.descriptor.write ?? []).some((component) => relationshipRole(component))) {\n return 'relationship-component';\n }\n return undefined;\n }\n}\n\nexport function createQuery<\n const R extends readonly Component[] = readonly [],\n const W extends readonly Component[] = readonly [],\n const O extends readonly Component[] = readonly [],\n>(\n world: WorldQueryAccess,\n descriptor: QueryDescriptor<R, W, O>,\n): Result<Query<R, W, O>, QueryCreationError> {\n const compiled = compileDescriptor(descriptor);\n if (!compiled.ok) return compiled;\n return ok(new ExecutableQuery(world, compiled.value));\n}\n","// @forgeax/engine-ecs — Resource store: typed key-value global singletons.\n//\n// Map<string, unknown> backend. insertResource is idempotent (overwrites).\n// getResource throws ResourceNotFoundError if key absent.\n\nimport { ResourceNotFoundError } from './errors';\n\n// ────────────────────────────────────────────────────────────────────────────\n// ResourceStore\n// ────────────────────────────────────────────────────────────────────────────\n\n/** Internal resource storage. */\nexport interface ResourceEntry {\n value: unknown;\n added: number;\n changed: number;\n}\n\nexport interface ResourceStore {\n readonly entries: Map<string, ResourceEntry>;\n}\n\n/** Create a fresh resource store. */\nexport function createResourceStore(): ResourceStore {\n return { entries: new Map() };\n}\n\n/**\n * Insert or overwrite a resource (idempotent, E-13).\n *\n * @example\n * ```ts\n * import { createResourceStore, insertResource, type ResourceStore } from './resource';\n *\n * const store: ResourceStore = createResourceStore();\n * insertResource(store, 'health', 100);\n * // overwriting is idempotent (no error / no duplicate slot):\n * insertResource(store, 'health', 95);\n * ```\n */\nexport function insertResource<T>(store: ResourceStore, key: string, value: T, epoch = 0): void {\n const current = store.entries.get(key);\n if (current === undefined) {\n store.entries.set(key, { value, added: epoch, changed: epoch });\n } else {\n current.value = value;\n current.changed = epoch;\n }\n}\n\n/**\n * Get a resource by key.\n * @throws ResourceNotFoundError if key does not exist (E-14).\n *\n * @example\n * ```ts\n * import { getResource, insertResource, type ResourceStore } from './resource';\n *\n * declare const store: ResourceStore;\n * insertResource(store, 'health', 100);\n * const hp = getResource<number>(store, 'health');\n * // hp === 100; throws ResourceNotFoundError on missing key (charter proposition 4)\n * ```\n */\nexport function getResource<T>(store: ResourceStore, key: string): T {\n const entry = store.entries.get(key);\n if (entry === undefined) {\n throw new ResourceNotFoundError(key);\n }\n return entry.value as T;\n}\n\n/**\n * Check if a resource exists.\n *\n * @example\n * ```ts\n * import { hasResource, insertResource, type ResourceStore } from './resource';\n *\n * declare const store: ResourceStore;\n * insertResource(store, 'health', 100);\n * if (hasResource(store, 'health')) {\n * // guarded access avoids ResourceNotFoundError from getResource\n * }\n * ```\n */\nexport function hasResource(store: ResourceStore, key: string): boolean {\n return store.entries.has(key);\n}\n\n/**\n * Remove a resource by key.\n *\n * @example\n * ```ts\n * import { hasResource, insertResource, removeResource, type ResourceStore } from './resource';\n *\n * declare const store: ResourceStore;\n * insertResource(store, 'health', 100);\n * removeResource(store, 'health');\n * // hasResource(store, 'health') === false; idempotent on missing keys\n * ```\n */\nexport function removeResource(store: ResourceStore, key: string): boolean {\n return store.entries.delete(key);\n}\n","// @forgeax/engine-ecs — CommandBuffer: deferred structural changes.\n//\n// System execution queues spawn/despawn/addComponent/removeComponent commands.\n// world.update() flushes the queue at frame end with while(queue.length > 0)\n// cascade support (D-06). Deferred spawn returns pending Entity handle (D-07).\n\nimport type { Result } from '@forgeax/engine-types';\nimport type { Component, ComponentSchema } from './component';\nimport { componentId } from './component';\nimport { fillComponentDefaults, validateComponentDataKeys } from './component-default-fallback';\nimport { Entity } from './entity';\nimport { ENTITY_NULL_RAW, type EntityHandle, entityGeneration, entityIndex } from './entity-handle';\nimport {\n type CommandCommitEvidence,\n CommandFailedError,\n type CommandKind,\n ComponentAlreadyPresentError,\n ComponentNotPresentError,\n RelationshipSelfCycleError,\n RelationshipTargetReadonlyError,\n RemoveEssentialComponentError,\n StaleEntityError,\n SystemFailedError,\n} from './errors';\nimport type { WorldExecutionState } from './execution/shared-kernel';\nimport { isRelationshipTarget, relationshipRole } from './relationship-index';\nimport type { ComponentData, EcsError } from './world';\nimport { type WorldInternal, worldInternal } from './world-internal';\n\n// ────────────────────────────────────────────────────────────────────────────\n// Command types\n// ────────────────────────────────────────────────────────────────────────────\n\nexport type Command =\n | { type: 'spawn'; componentDatas: ComponentData[]; entity: EntityHandle }\n | { type: 'despawn'; entity: EntityHandle }\n | { type: 'addComponent'; entity: EntityHandle; componentData: ComponentData }\n | { type: 'removeComponent'; entity: EntityHandle; component: Component };\n\n// ────────────────────────────────────────────────────────────────────────────\n// CommandBuffer interface\n// ────────────────────────────────────────────────────────────────────────────\n\n/**\n * CommandBuffer queues structural changes (spawn/despawn/addComponent/removeComponent)\n * during system execution. Flushed at end of world.update().\n */\nexport interface CommandBuffer {\n readonly status: 'open' | 'committed' | 'aborted';\n /** Deferred spawn: returns pending Entity handle. */\n spawn(...componentDatas: ComponentData[]): EntityHandle;\n /** Deferred despawn. */\n despawn(entity: EntityHandle): unknown;\n /** Deferred addComponent. */\n addComponent<S extends ComponentSchema>(\n entity: EntityHandle,\n componentData: ComponentData<S>,\n ): unknown;\n /** Deferred removeComponent. */\n removeComponent<S extends ComponentSchema>(\n entity: EntityHandle,\n component: Component<string, S>,\n ): unknown;\n /** Check if an entity is pending (deferred spawn, not yet flushed). */\n isDeferred(entity: EntityHandle): boolean;\n commit(): void;\n abort(error?: unknown): void;\n}\n\n// ────────────────────────────────────────────────────────────────────────────\n// World access interface (avoids circular import)\n// ────────────────────────────────────────────────────────────────────────────\n\n/** Minimal world interface needed by CommandBuffer for entity allocation. */\nexport interface WorldForCommands {\n readonly [worldInternal]: WorldInternal;\n readonly execution: WorldExecutionState;\n /**\n * Allocate a pending entity index, returning [entity handle, index slot].\n * @internal\n */\n /**\n * Mark a pending entity as materialized (flush phase).\n * @internal\n */\n /** Execute despawn directly (flush phase). */\n despawn(entity: EntityHandle): Result<void, EcsError>;\n /** Execute addComponent directly (flush phase). */\n addComponent<S extends ComponentSchema>(\n entity: EntityHandle,\n componentData: ComponentData<S>,\n ): Result<void, EcsError>;\n /** Execute removeComponent directly (flush phase). */\n removeComponent<S extends ComponentSchema>(\n entity: EntityHandle,\n component: Component<string, S>,\n ): Result<void, EcsError>;\n /** Fast membership probe used by command preflight. */\n hasComponent(entity: EntityHandle, component: Component): boolean;\n}\n\n// ────────────────────────────────────────────────────────────────────────────\n// Implementation\n// ────────────────────────────────────────────────────────────────────────────\n\nexport interface CommandBufferImpl extends CommandBuffer {\n /** @internal */\n _queue: Command[];\n /** @internal */\n _pendingEntities: Set<number>;\n /** @internal First validation failure captured while the system was staging commands. */\n _queueError: {\n readonly index: number;\n readonly kind: CommandKind;\n readonly cause: unknown;\n } | null;\n /** @internal */\n readonly _systemName: string;\n /** @internal */\n readonly _scheduleName: string;\n /** @internal */\n _setStatus(status: 'committed' | 'aborted'): void;\n}\n\n/**\n * Create a CommandBuffer bound to a World.\n * @param world - the World (for pending entity allocation)\n */\nexport function createCommandBuffer(\n world: WorldForCommands,\n context: { readonly systemName?: string; readonly scheduleName?: string } = {},\n): CommandBufferImpl {\n const queue: Command[] = [];\n const pendingEntities = new Set<number>();\n let status: CommandBuffer['status'] = 'open';\n let queueError: CommandBufferImpl['_queueError'] = null;\n const ensureOpen = (): void => {\n if (status !== 'open') throw new Error(`CommandBuffer is ${status}`);\n };\n const recordQueueError = (index: number, kind: CommandKind, cause: unknown): void => {\n if (queueError === null) queueError = { index, kind, cause };\n };\n\n const buffer: CommandBufferImpl = {\n _queue: queue,\n _pendingEntities: pendingEntities,\n _systemName: context.systemName ?? '<unknown-system>',\n _scheduleName: context.scheduleName ?? '<unknown-schedule>',\n get status() {\n return status;\n },\n get _queueError() {\n return queueError;\n },\n _setStatus(next) {\n if (status === 'open') status = next;\n },\n commit() {\n ensureOpen();\n status = 'committed';\n queue.length = 0;\n pendingEntities.clear();\n queueError = null;\n },\n abort() {\n if (status !== 'open') return;\n for (const raw of pendingEntities) {\n world[worldInternal].cancelPendingEntity(raw as EntityHandle);\n }\n status = 'aborted';\n queue.length = 0;\n pendingEntities.clear();\n queueError = null;\n },\n\n spawn(...componentDatas: ComponentData[]): EntityHandle {\n ensureOpen();\n // bug-20260615: validate raw spawn keys at queue time (synchronous,\n // points at the calling system's stack) rather than only at flush\n // time. Commands.spawn returns EntityHandle (no Result channel), so\n // unknown-key is captured as a batch preflight failure. The handle is\n // still reserved so callers may compose later commands; abort releases\n // every reservation without leaking a free slot.\n for (const cd of componentDatas) {\n const keyErr = validateComponentDataKeys(cd.component, cd.data as Record<string, unknown>);\n if (keyErr !== null) recordQueueError(queue.length, 'spawn', keyErr);\n }\n const entity = world[worldInternal].allocatePendingEntity();\n pendingEntities.add(entity as unknown as number);\n queue.push({ type: 'spawn', componentDatas, entity });\n return entity;\n },\n\n despawn(entity: EntityHandle): void {\n ensureOpen();\n queue.push({ type: 'despawn', entity });\n },\n\n addComponent<S extends ComponentSchema>(\n entity: EntityHandle,\n componentData: ComponentData<S>,\n ): void {\n ensureOpen();\n const keyErr = validateComponentDataKeys(\n componentData.component,\n componentData.data as Record<string, unknown>,\n );\n if (keyErr !== null) recordQueueError(queue.length, 'addComponent', keyErr);\n queue.push({ type: 'addComponent', entity, componentData: componentData as ComponentData });\n },\n\n removeComponent<S extends ComponentSchema>(\n entity: EntityHandle,\n component: Component<string, S>,\n ): void {\n ensureOpen();\n queue.push({ type: 'removeComponent', entity, component: component as Component });\n },\n\n isDeferred(entity: EntityHandle): boolean {\n return pendingEntities.has(entity as unknown as number);\n },\n };\n\n return buffer;\n}\n\nfunction commandFailure(\n buffer: CommandBufferImpl,\n index: number,\n kind: CommandKind,\n cause: unknown,\n): CommandFailedError {\n return new CommandFailedError(buffer._systemName, buffer._scheduleName, index, kind, cause);\n}\n\ntype RelationshipOverlay = Map<number, Map<number, EntityHandle | null>>;\n\nfunction relationshipTarget(\n component: Component,\n data: Readonly<Record<string, unknown>>,\n): EntityHandle | null {\n const role = relationshipRole(component);\n if (role?.kind !== 'source') return null;\n const raw = data[role.sourceField];\n if (raw === null || raw === undefined || raw === ENTITY_NULL_RAW) return null;\n return raw as EntityHandle;\n}\n\nfunction overlayTarget(\n overlay: RelationshipOverlay,\n entity: EntityHandle,\n component: Component,\n): EntityHandle | null | undefined {\n return overlay.get(entity as number)?.get(componentId(component));\n}\n\nfunction setOverlayTarget(\n overlay: RelationshipOverlay,\n entity: EntityHandle,\n component: Component,\n target: EntityHandle | null,\n): void {\n let entries = overlay.get(entity as number);\n if (entries === undefined) {\n entries = new Map();\n overlay.set(entity as number, entries);\n }\n entries.set(componentId(component), target);\n}\n\n/**\n * Check a relationship edge against committed rows plus the batch overlay.\n * The overlay is the only extra state needed: it records at most one target\n * per affected source/component, so a batch remains O(C + A) rather than\n * rescanning every World entity.\n */\nfunction relationshipCycle(\n world: WorldForCommands,\n holder: EntityHandle,\n component: Component,\n target: EntityHandle | null,\n overlay: RelationshipOverlay,\n): RelationshipSelfCycleError | undefined {\n if (target === null) return undefined;\n const role = relationshipRole(component);\n const allowSelf = role?.kind === 'source' && role.allowSelf;\n if (holder === target && !allowSelf) {\n return new RelationshipSelfCycleError(component.name, holder as number, target as number);\n }\n const visited = new Set<number>();\n let current: EntityHandle | null = target;\n while (current !== null) {\n const raw = current as number;\n if (raw === (holder as number) && !(holder === target && allowSelf)) {\n return new RelationshipSelfCycleError(component.name, holder as number, raw);\n }\n if (visited.has(raw)) return undefined;\n visited.add(raw);\n const staged = overlayTarget(overlay, current, component);\n if (staged !== undefined || overlay.get(raw)?.has(componentId(component)) === true) {\n current = staged ?? null;\n continue;\n }\n const row = world[worldInternal].getQueryRow(current, component);\n if (!row.ok) return undefined;\n current = relationshipTarget(component, row.value);\n }\n return undefined;\n}\n\n/**\n * Validate the failures that can be proven from the current World and the\n * command batch without mutating storage. The commit loop remains the only\n * writer; any failure not provable here is treated as an unexpected post-write\n * failure and poisons the World.\n */\nfunction preflightCommands(buffer: CommandBufferImpl, world: WorldForCommands): void {\n if (buffer._queueError !== null) {\n const { index, kind, cause } = buffer._queueError;\n throw commandFailure(buffer, index, kind, cause);\n }\n\n type Shadow = {\n readonly components: Set<number>;\n readonly added: Set<number>;\n readonly removed: Set<number>;\n dead: boolean;\n pending: boolean;\n };\n const shadows = new Map<number, Shadow>();\n const relationshipOverlay: RelationshipOverlay = new Map();\n const unavailableEntities = new Set<number>();\n const availablePendingEntities = new Set<number>();\n const shadowFor = (entity: EntityHandle): Shadow => {\n const raw = entity as unknown as number;\n const current = shadows.get(raw);\n if (current !== undefined) return current;\n const shadow: Shadow = {\n components: new Set<number>(),\n added: new Set<number>(),\n removed: new Set<number>(),\n dead: false,\n pending: false,\n };\n shadows.set(raw, shadow);\n return shadow;\n };\n const validateData = (\n holder: EntityHandle | null,\n componentData: ComponentData,\n ): unknown | undefined => {\n const result = world[worldInternal].preflightComponentData(\n holder,\n componentData,\n availablePendingEntities,\n unavailableEntities,\n );\n return result.ok ? undefined : result.error;\n };\n const liveError = (entity: EntityHandle, operation: string, component?: Component): unknown => {\n const result = world[worldInternal].lookupAlive(entity, operation, component?.name);\n return result.ok ? undefined : result.error;\n };\n for (const [index, command] of buffer._queue.entries()) {\n switch (command.type) {\n case 'spawn': {\n const raw = command.entity as unknown as number;\n const shadow = shadowFor(command.entity);\n shadow.pending = true;\n availablePendingEntities.add(raw);\n for (const componentData of command.componentDatas) {\n const dataError = validateData(command.entity, componentData);\n if (dataError !== undefined) throw commandFailure(buffer, index, command.type, dataError);\n if (shadow.components.has(componentId(componentData.component))) {\n throw commandFailure(\n buffer,\n index,\n command.type,\n new ComponentAlreadyPresentError(raw, componentData.component.name),\n );\n }\n shadow.components.add(componentId(componentData.component));\n const role = relationshipRole(componentData.component);\n if (role?.kind === 'source') {\n const filled = fillComponentDefaults(\n componentData.component,\n componentData.data as Record<string, unknown>,\n );\n const target = relationshipTarget(componentData.component, filled);\n setOverlayTarget(relationshipOverlay, command.entity, componentData.component, target);\n const cycle = relationshipCycle(\n world,\n command.entity,\n componentData.component,\n target,\n relationshipOverlay,\n );\n if (cycle !== undefined) throw commandFailure(buffer, index, command.type, cycle);\n }\n }\n break;\n }\n case 'despawn': {\n const shadow = shadowFor(command.entity);\n if (!shadow.pending && !world.hasComponent(command.entity, Entity)) {\n // A stale handle is a no-op for the direct facade today; preserve\n // that contract instead of inventing a new command error.\n shadow.dead = true;\n unavailableEntities.add(command.entity as unknown as number);\n availablePendingEntities.delete(command.entity as unknown as number);\n break;\n }\n shadow.dead = true;\n unavailableEntities.add(command.entity as unknown as number);\n availablePendingEntities.delete(command.entity as unknown as number);\n break;\n }\n case 'addComponent': {\n const raw = command.entity as unknown as number;\n const shadow = shadowFor(command.entity);\n const dataError = validateData(command.entity, command.componentData);\n if (dataError !== undefined) throw commandFailure(buffer, index, command.type, dataError);\n if (!shadow.pending) {\n const stale = liveError(\n command.entity,\n 'command.addComponent',\n command.componentData.component,\n );\n if (stale !== undefined) throw commandFailure(buffer, index, command.type, stale);\n }\n const role = relationshipRole(command.componentData.component);\n const present = shadow.pending\n ? shadow.components.has(componentId(command.componentData.component))\n : shadow.removed.has(componentId(command.componentData.component))\n ? false\n : shadow.added.has(componentId(command.componentData.component)) ||\n world.hasComponent(command.entity, command.componentData.component);\n if (shadow.dead) {\n throw commandFailure(\n buffer,\n index,\n command.type,\n liveError(command.entity, 'command.addComponent', command.componentData.component) ??\n new StaleEntityError(\n raw,\n entityIndex(command.entity),\n entityGeneration(command.entity),\n {\n operation: 'command.addComponent',\n expectedGeneration: entityGeneration(command.entity),\n actualGeneration: -1,\n },\n ),\n );\n }\n const reparent =\n present && role?.kind === 'source' && role.exclusive === true && !shadow.pending;\n if (present && !reparent) {\n throw commandFailure(\n buffer,\n index,\n command.type,\n new ComponentAlreadyPresentError(raw, command.componentData.component.name),\n );\n }\n shadow.components.add(componentId(command.componentData.component));\n if (!reparent) shadow.added.add(componentId(command.componentData.component));\n shadow.removed.delete(componentId(command.componentData.component));\n if (role?.kind === 'source') {\n const filled = fillComponentDefaults(\n command.componentData.component,\n command.componentData.data as Record<string, unknown>,\n );\n const target = relationshipTarget(command.componentData.component, filled);\n setOverlayTarget(\n relationshipOverlay,\n command.entity,\n command.componentData.component,\n target,\n );\n const cycle = relationshipCycle(\n world,\n command.entity,\n command.componentData.component,\n target,\n relationshipOverlay,\n );\n if (cycle !== undefined) throw commandFailure(buffer, index, command.type, cycle);\n }\n break;\n }\n case 'removeComponent': {\n const raw = command.entity as unknown as number;\n if (isRelationshipTarget(command.component)) {\n throw commandFailure(\n buffer,\n index,\n command.type,\n new RelationshipTargetReadonlyError(command.component.name, 'removeComponent'),\n );\n }\n if (componentId(command.component) === 0) {\n throw commandFailure(\n buffer,\n index,\n command.type,\n new RemoveEssentialComponentError(command.component.name),\n );\n }\n const shadow = shadowFor(command.entity);\n if (shadow.dead) {\n throw commandFailure(\n buffer,\n index,\n command.type,\n liveError(command.entity, 'command.removeComponent', command.component) ??\n new StaleEntityError(\n raw,\n entityIndex(command.entity),\n entityGeneration(command.entity),\n {\n operation: 'command.removeComponent',\n expectedGeneration: entityGeneration(command.entity),\n actualGeneration: -1,\n },\n ),\n );\n }\n if (!shadow.pending) {\n const stale = liveError(command.entity, 'command.removeComponent', command.component);\n if (stale !== undefined) throw commandFailure(buffer, index, command.type, stale);\n }\n const present = shadow.pending\n ? shadow.components.has(componentId(command.component))\n : shadow.removed.has(componentId(command.component))\n ? false\n : shadow.added.has(componentId(command.component)) ||\n world.hasComponent(command.entity, command.component);\n if (!present) {\n throw commandFailure(\n buffer,\n index,\n command.type,\n new ComponentNotPresentError(raw, command.component.name),\n );\n }\n shadow.components.delete(componentId(command.component));\n shadow.removed.add(componentId(command.component));\n shadow.added.delete(componentId(command.component));\n if (relationshipRole(command.component)?.kind === 'source') {\n setOverlayTarget(relationshipOverlay, command.entity, command.component, null);\n }\n break;\n }\n }\n }\n}\n\n/**\n * Flush all queued commands against the World.\n * Uses while(queue.length > 0) to support cascade (commands spawned during flush).\n */\nexport function flushCommands(buffer: CommandBufferImpl, world: WorldForCommands): void {\n if (buffer.status !== 'open') return;\n const queue = buffer._queue;\n try {\n preflightCommands(buffer, world);\n } catch (error) {\n buffer.abort(error);\n throw error;\n }\n let applied = 0;\n // Once the preflight boundary has passed, a command may have touched\n // storage even when its Result is an error (for example relationship\n // maintenance after a row was appended). `applied` is intentionally not\n // used as the poison decision: it only counts commands that returned ok.\n let mutationStarted = false;\n let commandIndex = -1;\n let currentCommand: Command | undefined;\n let lastCommittedCommand: CommandCommitEvidence | null = null;\n try {\n const requireSuccess = (result: unknown): void => {\n if (\n result !== null &&\n typeof result === 'object' &&\n 'ok' in result &&\n (result as { readonly ok: boolean }).ok === false\n ) {\n throw (result as { readonly error?: unknown }).error ?? new Error('Command failed');\n }\n };\n while (queue.length > 0) {\n // biome-ignore lint/style/noNonNullAssertion: queue length is checked\n const cmd = queue.shift()!;\n commandIndex += 1;\n currentCommand = cmd;\n switch (cmd.type) {\n case 'spawn':\n mutationStarted = true;\n requireSuccess(\n world[worldInternal].materializePendingEntity(cmd.entity, cmd.componentDatas),\n );\n buffer._pendingEntities.delete(cmd.entity as unknown as number);\n applied += 1;\n lastCommittedCommand = { index: commandIndex, kind: cmd.type };\n break;\n case 'despawn':\n mutationStarted = true;\n requireSuccess(world.despawn(cmd.entity));\n applied += 1;\n lastCommittedCommand = { index: commandIndex, kind: cmd.type };\n break;\n case 'addComponent':\n mutationStarted = true;\n requireSuccess(world.addComponent(cmd.entity, cmd.componentData));\n applied += 1;\n lastCommittedCommand = { index: commandIndex, kind: cmd.type };\n break;\n case 'removeComponent':\n mutationStarted = true;\n requireSuccess(world.removeComponent(cmd.entity, cmd.component));\n applied += 1;\n lastCommittedCommand = { index: commandIndex, kind: cmd.type };\n break;\n }\n }\n buffer.commit();\n } catch (error) {\n buffer.abort(error);\n if (error instanceof CommandFailedError) throw error;\n if (!mutationStarted && applied === 0) {\n throw commandFailure(\n buffer,\n Math.max(commandIndex, 0),\n currentCommand?.type ?? 'spawn',\n error,\n );\n }\n if (world.execution.health === 'healthy') {\n const poison = world[worldInternal].poisonExecution;\n poison({\n code: 'shared-kernel-failed',\n kernelName: 'CommandBuffer.flush',\n cause: error,\n partialWrite: true,\n retryable: false,\n });\n }\n throw new SystemFailedError(\n buffer._systemName,\n buffer._scheduleName,\n error,\n lastCommittedCommand,\n );\n }\n}\n","// @forgeax/engine-ecs — DAG Schedule: Kahn topological sort + cycle detection.\n//\n// addSystem registers a system + marks dirty. First update() triggers buildSchedule().\n// Same in-degree systems ordered by addSystem call order (stable tie-breaker, D-05).\n\nimport { err, ok, type Result } from '@forgeax/engine-types';\nimport { type CommandBuffer, createCommandBuffer, flushCommands } from './commands';\nimport type { Component } from './component';\nimport {\n CyclicDependencyError,\n ScheduleMutationError,\n SystemFailedError,\n type SystemSetNotRegisteredError,\n systemSetNotRegistered,\n} from './errors';\nimport type { Query, QueryDescriptor } from './query/query';\n// type-only import: erases at build time, carries no runtime edge (same\n// criterion as scripts/check-ecs-no-runtime-import.mjs). `world.ts` already\n// value-imports `schedule.ts`; this back-reference is type-space only so no\n// runtime cycle forms (plan-strategy D-1).\nimport type { ScheduleToken } from './schedule-token';\nimport type { World } from './world';\nimport { worldInternal } from './world-internal';\n\n// ────────────────────────────────────────────────────────────────────────────\n// Types\n// ────────────────────────────────────────────────────────────────────────────\n\ntype SystemQueryResults<\n Qs extends ReadonlyArray<QueryDescriptor> = ReadonlyArray<QueryDescriptor>,\n> = {\n [K in keyof Qs]: Qs[K] extends QueryDescriptor<\n infer R extends ReadonlyArray<Component>,\n infer W extends ReadonlyArray<Component>,\n infer O extends ReadonlyArray<Component>\n >\n ? Query<NoInfer<R>, NoInfer<W>, NoInfer<O>>\n : Query;\n};\n\n/**\n * System descriptor passed to `world.addSystem` — `fn` receives one persistent\n * executable Query per descriptor, mapped over `Qs` without casts.\n *\n * `Qs` is the tuple of query descriptors; defaults to\n * `readonly QueryDescriptor[]` so non-generic call sites stay zero-modification\n * (KD-5). The `fn` first parameter is mapped over `Qs` so each\n * `queryResults[i]` recovers its own row access roles (S-5, KD-2).\n *\n * @example\n * ```ts\n * // Single-query system — row access recovers each component schema.\n * import { defineComponent, World } from '@forgeax/engine-ecs';\n *\n * const Position = defineComponent('Position', { x: 'f32', y: 'f32' });\n * const Velocity = defineComponent('Velocity', { dx: 'f32', dy: 'f32' });\n *\n * const world = new World();\n * world.addSystem(Update, {\n * name: 'movement',\n * queries: [{ write: [Position], read: [Velocity] }],\n * fn: (_world, queryResults, _commands) => {\n * for (const row of queryResults[0]) {\n * row.mut(Position).x += row.get(Velocity).dx;\n * }\n * },\n * });\n * ```\n *\n * @example\n * ```ts\n * // Multi-query system — each queryResults[i] keeps its own row shape.\n * const Health = defineComponent('Health', { hp: 'f32' });\n * world.addSystem(Update, {\n * name: 'multi',\n * queries: [{ read: [Position] }, { read: [Health] }],\n * fn: (_world, queryResults) => {\n * for (const row of queryResults[0]) void row.get(Position).x;\n * for (const row of queryResults[1]) void row.get(Health).hp;\n * },\n * });\n * ```\n *\n * @example\n * ```ts\n * // Commands-only system — `queries: []` is a legal form; fn receives `[]`.\n * world.addSystem(Update, {\n * name: 'spawner',\n * queries: [],\n * fn: (_world, _queryResults, commands) => {\n * commands.spawn({ component: Position, data: { x: 0, y: 0 } });\n * },\n * });\n * ```\n */\nexport interface SystemDescriptor<\n Qs extends ReadonlyArray<QueryDescriptor> = ReadonlyArray<QueryDescriptor>,\n> {\n /** Unique system name (used for before/after references). */\n readonly name: string;\n /** Query descriptors this system reads. */\n readonly queries: Qs;\n /**\n * System function — receives the World, resolved query results, and commands.\n *\n * @param world The owning World — read resources (`world.getResource(KEY)`),\n * resolve components by name, etc. without closure capture.\n * @param queryResults Mapped over `Qs`: each entry is a persistent Query.\n * @param commands Deferred-mutation buffer (flushed after the system).\n */\n readonly fn: (\n world: World,\n queryResults: SystemQueryResults<Qs>,\n commands: CommandBuffer,\n ) => void | unknown;\n /** Run this system after named systems or the FixedUpdate anchor. */\n readonly after?: ReadonlyArray<string | ScheduleToken>;\n /** Run this system before named systems or the FixedUpdate anchor. */\n readonly before?: ReadonlyArray<string | ScheduleToken>;\n /**\n * Run condition. Evaluated each frame after ParamValidation passes (tag\n * 'ok') and before query iteration. Returning `false` skips the system silently —\n * no query runs, no fn call, no state added (plan-strategy D-8). Omitting it\n * (undefined) always runs the system.\n */\n readonly runIf?: (world: World) => boolean;\n}\n\n/**\n * A registered system token returned by {@link defineSystem}. Structurally the\n * frozen {@link SystemDescriptor} itself (plan-strategy D-6 — \"define ==\n * register\"). `world.addSystem(handle)` consumes it directly; the generic `Qs`\n * flows through so the `fn` per-query row access shapes survive (S-5).\n */\nexport type SystemHandle<\n Qs extends ReadonlyArray<QueryDescriptor> = ReadonlyArray<QueryDescriptor>,\n> = SystemDescriptor<Qs>;\n\n/** Internal system record with registration index. */\ninterface SystemRecord {\n descriptor: SystemDescriptor;\n /** Registration order index (for tie-breaking). */\n registrationIndex: number;\n /** Cached executable Queries, one per descriptor. */\n queries: Query[] | null;\n}\n\n// ────────────────────────────────────────────────────────────────────────────\n// Schedule\n// ────────────────────────────────────────────────────────────────────────────\n\n/**\n * Per-set record in the Schedule. Created lazily on first addSystems /\n * addSystems call for a given set name.\n */\nexport interface SetRecord {\n /** Member system names (insertion-ordered, Set preserves add order). */\n readonly members: Set<string>;\n /** Snapshot of runIf from the defining token. */\n readonly runIf: ((world: import('./world').World) => boolean) | undefined;\n /** Snapshot of chained from the defining token. */\n readonly chained: boolean;\n}\n\n/** The Schedule manages system registration, DAG sorting, and execution. */\nexport interface Schedule {\n /** Owning token for scope-aware diagnostics. */\n readonly token: ScheduleToken;\n /** All registered systems by name. */\n systems: Map<string, SystemRecord>;\n /** Set records keyed by set name. Created lazily. */\n sets: Map<string, SetRecord>;\n /** Next registration index. */\n nextIndex: number;\n /** Whether the sorted order is stale. */\n dirty: boolean;\n /** Sorted system names after buildSchedule(). */\n sortedOrder: string[];\n /** Direct predecessor names derived while the DAG is built. */\n predecessors: Map<string, Set<string>>;\n}\n\n/** Create a fresh Schedule. */\nexport function createSchedule(token: ScheduleToken): Schedule {\n return {\n token,\n systems: new Map(),\n sets: new Map(),\n nextIndex: 0,\n dirty: true,\n sortedOrder: [],\n predecessors: new Map(),\n };\n}\n\n/**\n * Register a system. Marks schedule as dirty.\n * Queries are lazily initialized on first runSchedule.\n *\n * `const Qs` locks the `queries` tuple at the call site so `fn`'s first\n * parameter recovers per-query row shapes without `as const` annotations\n * (S-5, KD-2). `SystemRecord` itself is intentionally non-generic — the\n * heterogeneous `Qs` cannot be expressed inside the systems Map (KD-3).\n */\nexport function addSystem<const Qs extends ReadonlyArray<QueryDescriptor>>(\n schedule: Schedule,\n descriptor: SystemDescriptor<Qs>,\n): void {\n const record: SystemRecord = {\n descriptor: descriptor as unknown as SystemDescriptor,\n registrationIndex: schedule.nextIndex++,\n queries: null,\n };\n schedule.systems.set(descriptor.name, record);\n schedule.dirty = true;\n}\n\n// ────────────────────────────────────────────────────────────────────────────\n// System token construction (token-first World ownership)\n// ────────────────────────────────────────────────────────────────────────────\n\n/**\n * Define a system at module level. Returns a frozen {@link SystemHandle} token\n * (the descriptor itself); executable registration is World-local.\n *\n * `world.addSystem(handle)` consumes the token directly — no by-name overload\n * (OOS-8). Duplicate names are resolved by the owning World schedule.\n *\n * `const Qs` locks the `queries` tuple so `fn`'s query-results parameter\n * recovers per-query row access shapes without `as const` (S-5).\n *\n * @example\n * ```ts\n * const Move = defineSystem({\n * name: 'movement',\n * queries: [{ with: [Position, Velocity] }],\n * fn: (_world, queryResults) => { ... },\n * });\n * world.addSystem(Move);\n * ```\n */\nexport function defineSystem<const Qs extends ReadonlyArray<QueryDescriptor>>(\n descriptor: SystemDescriptor<Qs>,\n): SystemHandle<Qs> {\n const handle = Object.freeze(descriptor) as unknown as SystemHandle<Qs>;\n return handle;\n}\n\n/**\n */\n// ────────────────────────────────────────────────────────────────────────────\n// SystemSet — nominal token (D-2c step 1, w2)\n// ────────────────────────────────────────────────────────────────────────────\n\n/** Brand symbol for {@link SystemSet}. Declared (not runtime-initialised) so\n * the token interface carries nominal identity without a runtime allocation.\n * Mirrors the `FORGEAX_STATE_BRAND` pattern in `@forgeax/engine-state`. */\ndeclare const FORGEAX_SYSTEM_SET_BRAND: unique symbol;\n\n/**\n * Opaque branded type for system-set tokens.\n *\n * Use {@link defineSystemSet} to create a token; never construct manually.\n * The {@link __forgeaxSystemSet} brand prevents plain-object assignment and\n * enables TypeScript narrowing at the two mutation entry points.\n */\nexport interface SystemSet {\n /** Brand — prevents structural compatibility with plain objects. */\n readonly __forgeaxSystemSet: typeof FORGEAX_SYSTEM_SET_BRAND;\n /** The user-supplied set name. */\n readonly name: string;\n /** Optional per-frame run condition. Consumed by M3 condition gate. */\n readonly runIf?: (world: import('./world').World) => boolean;\n /** Whether this set forms a sequential chain (M2). */\n readonly chained?: boolean;\n}\n\n/**\n * Define a system set at module level. Returns a frozen branded token and\n * keeps membership in the World-local Schedule.\n *\n * Duplicate names are independent tokens; the owning World decides membership.\n *\n * @example\n * ```ts\n * const GameplaySet = defineSystemSet({ name: 'gameplay', runIf: (w) => !w.getResource<boolean>('paused') });\n * const OrderedSet = defineSystemSet({ name: 'ordered', chained: true });\n * ```\n */\nexport function defineSystemSet(opts: {\n readonly name: string;\n readonly runIf?: (world: import('./world').World) => boolean;\n readonly chained?: boolean;\n}): SystemSet {\n const token: Record<string, unknown> = {\n __forgeaxSystemSet: undefined as unknown as typeof FORGEAX_SYSTEM_SET_BRAND,\n name: opts.name,\n };\n if (opts.runIf !== undefined) {\n token.runIf = opts.runIf;\n }\n if (opts.chained !== undefined) {\n token.chained = opts.chained;\n }\n const frozen = Object.freeze(token) as unknown as SystemSet;\n return frozen;\n}\n\n/**\n/**\n * Validate every token in `tokens` for local structural validity.\n * Returns `ok(undefined)` for a structurally valid token and reports an empty\n * token name as a structured registration error.\n *\n * Does not write any Schedule state — callers consume the `Result` and proceed\n * only on `ok`.\n */\nexport function validateSystemSetTokens(\n tokens: readonly SystemSet[],\n): Result<void, SystemSetNotRegisteredError> {\n for (const token of tokens) {\n if (token.name.length === 0) {\n return err(systemSetNotRegistered(token.name, []));\n }\n }\n return ok(undefined);\n}\n\n/**\n * Remove a registered system by name (M2 — plan-strategy D-3).\n *\n * Drops the entry from `schedule.systems` and marks the schedule dirty so the\n * next `runSchedule` rebuilds the sorted order via Kahn topo. Cycle detection\n * already happens inside `buildSchedule`, so a removal that breaks an unrelated\n * `before/after` reference simply skips the unknown name (existing behaviour).\n *\n * Failure: name not registered → `Result.err(ScheduleMutationError)` with\n * `.code = 'system-before-unknown'` and `.detail.candidates` carrying the\n * registered names for AI-friendly typo recovery.\n */\nexport function removeSystem(\n schedule: Schedule,\n name: string,\n): Result<void, ScheduleMutationError> {\n if (!schedule.systems.has(name)) {\n return err(\n new ScheduleMutationError(\n 'system-before-unknown',\n `Cannot removeSystem: no system registered as \"${name}\".`,\n 'Call world.inspect().systems to discover registered names.',\n { candidates: [...schedule.systems.keys()] },\n ),\n );\n }\n schedule.systems.delete(name);\n // Prune set membership: remove this system name from every set's members (D-1).\n for (const [, setRecord] of schedule.sets) {\n setRecord.members.delete(name);\n }\n schedule.dirty = true;\n return ok(undefined);\n}\n\n/**\n * Replace a registered system in-place (M2 — plan-strategy D-3 atomic semantics).\n *\n * Overwrites the `descriptor` field of the existing `SystemRecord` while\n * keeping `registrationIndex` and the `Map` slot identical, so all `before /\n * after` edges that reference this name remain bound to the same slot. Marks\n * the schedule dirty: the next `runSchedule` re-sorts.\n *\n * Failure: name not registered → `Result.err(ScheduleMutationError)` with\n * `.code = 'system-before-unknown'`.\n */\nexport function replaceSystem<const Qs extends ReadonlyArray<QueryDescriptor>>(\n schedule: Schedule,\n name: string,\n descriptor: SystemDescriptor<Qs>,\n): Result<void, ScheduleMutationError> {\n const record = schedule.systems.get(name);\n if (!record) {\n return err(\n new ScheduleMutationError(\n 'system-before-unknown',\n `Cannot replaceSystem: no system registered as \"${name}\".`,\n 'Call world.inspect().systems to discover registered names; or addSystem(descriptor) to register a new system.',\n { candidates: [...schedule.systems.keys()] },\n ),\n );\n }\n record.descriptor = descriptor as unknown as SystemDescriptor;\n // Reset cached query states — descriptor.queries may have changed shape.\n record.queries = null;\n schedule.dirty = true;\n return ok(undefined);\n}\n\n/**\n * Batch-register systems to a set. Validates the set token before writing.\n *\n * - First call for a system name: registers via the existing `addSystem` path.\n * - Subsequent calls: only adds the system name to the set's members (dedup).\n * - `runIf` / `chained` are snapshotted from the token into the SetRecord on\n * first encounter.\n *\n * Returns `Result.err` with `SystemSetNotRegisteredError` if the set token\n * fails identity validation.\n */\nexport function addSystems<const Qs extends ReadonlyArray<QueryDescriptor>>(\n schedule: Schedule,\n set: SystemSet,\n systems: ReadonlyArray<SystemDescriptor<Qs>>,\n): Result<void, SystemSetNotRegisteredError> {\n const validated = validateSystemSetTokens([set]);\n if (!validated.ok) {\n return err(validated.error);\n }\n\n const setName = set.name;\n let record = schedule.sets.get(setName);\n if (!record) {\n record = {\n members: new Set(),\n runIf: set.runIf,\n chained: set.chained ?? false,\n };\n schedule.sets.set(setName, record);\n }\n\n for (const system of systems) {\n const name = system.name;\n // Dedup: only register the system once in schedule.systems.\n if (!schedule.systems.has(name)) {\n addSystem(schedule, system);\n }\n // Always add membership — multi-belong is supported.\n record.members.add(name);\n }\n\n schedule.dirty = true;\n return ok(undefined);\n}\n\n/**\n * Build the sorted execution order via Kahn's topological sort.\n * Throws CyclicDependencyError if a cycle is detected.\n *\n * @returns sorted system names\n */\nexport function buildSchedule(schedule: Schedule): string[] {\n const systems = schedule.systems;\n const names = [...systems.keys()];\n if (schedule.token.name === 'Update') names.push('FixedUpdate');\n const nameSet = new Set(names);\n\n // Build adjacency list + in-degree map.\n const adj = new Map<string, string[]>(); // adj[a] = [b] means a → b (a must run before b)\n const inDegree = new Map<string, number>();\n const predecessors = new Map<string, Set<string>>();\n\n for (const name of names) {\n adj.set(name, []);\n inDegree.set(name, 0);\n predecessors.set(name, new Set());\n }\n\n const addEdge = (source: string, target: string): void => {\n adj.get(source)?.push(target);\n predecessors.get(target)?.add(source);\n inDegree.set(target, (inDegree.get(target) ?? 0) + 1);\n };\n const orderReferenceName = (reference: string | ScheduleToken): string =>\n typeof reference === 'string' ? reference : reference.name;\n\n for (const [name, record] of systems) {\n const desc = record.descriptor;\n\n // \"after\" constraints: for each dep in after, dep → name (dep runs before name)\n if (desc.after) {\n for (const reference of desc.after) {\n const dep = orderReferenceName(reference);\n if (!nameSet.has(dep)) continue; // scope validation handles cross-schedule references\n addEdge(dep, name);\n }\n }\n\n // \"before\" constraints: for each target in before, name → target (name runs before target)\n if (desc.before) {\n for (const reference of desc.before) {\n const target = orderReferenceName(reference);\n if (!nameSet.has(target)) continue; // scope validation handles cross-schedule references\n addEdge(name, target);\n }\n }\n }\n\n // Set membership contributes only run conditions and optional chaining.\n for (const [, setRecord] of schedule.sets) {\n if (setRecord.chained) {\n const members = [...setRecord.members];\n for (let i = 0; i < members.length - 1; i++) {\n const m1 = members[i];\n const m2 = members[i + 1];\n if (!m1 || !m2 || !nameSet.has(m1) || !nameSet.has(m2)) continue;\n // m1 → m2 (m1 runs before m2)\n addEdge(m1, m2);\n }\n }\n }\n\n // Kahn's algorithm with registration-order tie-breaker.\n // Use a queue sorted by registrationIndex for deterministic ordering.\n const queue: string[] = [];\n for (const name of names) {\n if (inDegree.get(name) === 0) {\n queue.push(name);\n }\n }\n // Sort initial queue by registration index. The fixed anchor is intrinsic and\n // receives a deterministic slot after user systems with the same indegree.\n queue.sort(\n (a, b) =>\n (systems.get(a)?.registrationIndex ?? Number.MAX_SAFE_INTEGER) -\n (systems.get(b)?.registrationIndex ?? Number.MAX_SAFE_INTEGER),\n );\n\n const sorted: string[] = [];\n while (queue.length > 0) {\n // biome-ignore lint/style/noNonNullAssertion: while(queue.length > 0) guarantees shift() returns a value\n const current = queue.shift()!;\n sorted.push(current);\n\n const neighbors = adj.get(current) ?? [];\n // Collect newly freed neighbors, then sort by registration index\n const freed: string[] = [];\n for (const neighbor of neighbors) {\n const newDeg = (inDegree.get(neighbor) ?? 0) - 1;\n inDegree.set(neighbor, newDeg);\n if (newDeg === 0) {\n freed.push(neighbor);\n }\n }\n freed.sort(\n (a, b) =>\n (systems.get(a)?.registrationIndex ?? Number.MAX_SAFE_INTEGER) -\n (systems.get(b)?.registrationIndex ?? Number.MAX_SAFE_INTEGER),\n );\n queue.push(...freed);\n }\n\n // Cycle detection: if we didn't process all nodes, there's a cycle.\n if (sorted.length < names.length) {\n // Find nodes still with in-degree > 0 (part of cycle).\n const remaining = names.filter((n) => !sorted.includes(n));\n const cyclePath = findCyclePath(remaining, adj);\n throw new CyclicDependencyError(cyclePath);\n }\n\n schedule.sortedOrder = sorted;\n schedule.predecessors = predecessors;\n schedule.dirty = false;\n return sorted;\n}\n\n/**\n * Find a cycle path among the remaining (unprocessed) nodes.\n * Returns the cycle as a readonly array of node names.\n */\nfunction findCyclePath(remaining: string[], adj: Map<string, string[]>): readonly string[] {\n const remainSet = new Set(remaining);\n const visited = new Set<string>();\n const path: string[] = [];\n\n function dfs(node: string): readonly string[] | null {\n if (visited.has(node)) {\n // Found cycle: extract cycle from path\n const cycleStart = path.indexOf(node);\n const cycle = path.slice(cycleStart);\n cycle.push(node);\n return cycle;\n }\n visited.add(node);\n path.push(node);\n\n for (const neighbor of adj.get(node) ?? []) {\n if (!remainSet.has(neighbor)) continue;\n const result = dfs(neighbor);\n if (result) return result;\n }\n\n path.pop();\n return null;\n }\n\n for (const start of remaining) {\n visited.clear();\n path.length = 0;\n const result = dfs(start);\n if (result) return result;\n }\n\n /* istanbul ignore next -- fallback: DFS always finds cycle in remaining nodes */\n return remaining;\n}\n\nfunction poisonSystemFailure(world: World, systemName: string, cause: unknown): void {\n const poison = world[worldInternal].poisonExecution;\n poison({\n code: 'shared-kernel-failed',\n kernelName: `system:${systemName}`,\n cause,\n partialWrite: true,\n retryable: false,\n });\n}\n\nfunction abortOutstandingCommands(\n commandsBySystem: Map<string, ReturnType<typeof createCommandBuffer>>,\n): void {\n for (const commands of commandsBySystem.values()) {\n if (commands.status === 'open') commands.abort();\n }\n}\n\n/**\n * Execute all systems in sorted order. Rebuilds schedule if dirty.\n * Each system receives its query results and a command buffer.\n * The world parameter provides the archetype graph, component ID resolution,\n * and resource checks.\n *\n * Layer 2 (ParamValidation): query empty → skip, resource missing → invalid.\n * A returned Result error poisons the active frame and stops execution.\n */\nfunction runScheduleBody(\n schedule: Schedule,\n world: World,\n selectedNames: readonly string[] | undefined,\n commandsBySystem: Map<string, ReturnType<typeof createCommandBuffer>>,\n finalDrain = true,\n): void {\n if (schedule.dirty) {\n buildSchedule(schedule);\n }\n if (\n selectedNames === undefined &&\n schedule.sets.size === 0 &&\n commandsBySystem.size === 0 &&\n schedule.sortedOrder.every((name) => {\n const record = schedule.systems.get(name);\n return (\n record !== undefined &&\n record.descriptor.queries.length === 0 &&\n record.descriptor.runIf === undefined &&\n (schedule.predecessors.get(name)?.size ?? 0) === 0\n );\n })\n ) {\n for (const name of schedule.sortedOrder) {\n const record = schedule.systems.get(name);\n /* istanbul ignore next -- sortedOrder comes from systems Map keys */\n if (!record) continue;\n\n const commands = createCommandBuffer(world, {\n systemName: name,\n scheduleName: schedule.token.name,\n });\n commandsBySystem.set(name, commands);\n let returnValue: unknown;\n try {\n returnValue = record.descriptor.fn(world, [], commands);\n } catch (error) {\n abortOutstandingCommands(commandsBySystem);\n poisonSystemFailure(world, name, error);\n throw new SystemFailedError(name, schedule.token.name, error);\n }\n if (returnValue && typeof returnValue === 'object' && 'ok' in returnValue) {\n const result = returnValue as { ok: boolean; error?: unknown };\n if (result.ok === false && result.error !== undefined) {\n abortOutstandingCommands(commandsBySystem);\n poisonSystemFailure(world, name, result.error);\n throw new SystemFailedError(name, schedule.token.name, result.error);\n }\n }\n }\n if (finalDrain) {\n try {\n for (const commands of commandsBySystem.values()) {\n flushCommands(commands, world);\n }\n } catch (error) {\n abortOutstandingCommands(commandsBySystem);\n throw error;\n }\n }\n return;\n }\n const selected = selectedNames ? new Set(selectedNames) : undefined;\n\n // Build reverse map: system name → set names it belongs to (D-5).\n // Rebuilt each frame so removeSystem / replaceSystem membership changes\n // take effect on the next frame.\n const systemToSets = new Map<string, string[]>();\n for (const [setName, setRecord] of schedule.sets) {\n for (const memberName of setRecord.members) {\n if (schedule.systems.has(memberName)) {\n let list = systemToSets.get(memberName);\n if (!list) {\n list = [];\n systemToSets.set(memberName, list);\n }\n list.push(setName);\n }\n }\n }\n\n // Per-frame set runIf cache (D-5). Discarded at frame end — no cross-frame state.\n const setRunIfCache = new Map<string, boolean>();\n\n for (const name of schedule.sortedOrder) {\n if (selected && !selected.has(name)) continue;\n const record = schedule.systems.get(name);\n /* istanbul ignore next -- defensive: sortedOrder comes from systems Map keys */\n if (!record) continue;\n\n // Apply only buffers that have an explicit graph edge into this system.\n for (const predecessor of schedule.predecessors.get(name) ?? []) {\n const producerCommands = commandsBySystem.get(predecessor);\n if (producerCommands) {\n try {\n flushCommands(producerCommands, world);\n } catch (error) {\n abortOutstandingCommands(commandsBySystem);\n throw error;\n }\n }\n }\n\n // Lazily initialize the persistent executable queries on first run.\n if (record.queries === null) {\n record.queries = record.descriptor.queries.map((descriptor) => {\n const result = world.query(descriptor);\n if (!result.ok) throw result.error;\n return result.value;\n });\n }\n // ── Set-level runIf AND gate (D-5) ──\n // before system-level runIf. Each set's runIf is lazily cached per frame. ──\n const setNames = systemToSets.get(name);\n let allSetConditionsPass = true;\n if (setNames) {\n for (const setName of setNames) {\n const setRecord = schedule.sets.get(setName);\n if (setRecord?.runIf) {\n let cached = setRunIfCache.get(setName);\n if (cached === undefined) {\n cached = setRecord.runIf(world);\n setRunIfCache.set(setName, cached);\n }\n if (!cached) {\n allSetConditionsPass = false;\n break;\n }\n }\n }\n }\n if (!allSetConditionsPass) {\n continue; // skip system: no system runIf, query iteration, or fn\n }\n\n // ── Run condition (runIf) — evaluated after ParamValidation 'ok', before\n // query iteration. false -> skip silently (no query, no fn, no cursor advance). ──\n if (record.descriptor.runIf && !record.descriptor.runIf(world)) {\n continue;\n }\n\n // ── Layer 3: system execution + Result collection ──\n // trusted-cast: the descriptor tuple constructed the matching Query tuple above.\n const commands = createCommandBuffer(world, {\n systemName: name,\n scheduleName: schedule.token.name,\n });\n commandsBySystem.set(name, commands);\n let returnValue: unknown;\n try {\n returnValue = record.descriptor.fn(\n world,\n record.queries as Parameters<typeof record.descriptor.fn>[1],\n commands,\n );\n } catch (error) {\n abortOutstandingCommands(commandsBySystem);\n poisonSystemFailure(world, name, error);\n throw new SystemFailedError(name, schedule.token.name, error);\n }\n\n // A returned Result error is a poisoned frame failure.\n if (returnValue && typeof returnValue === 'object' && 'ok' in (returnValue as object)) {\n const result = returnValue as { ok: boolean; error?: unknown };\n if (result.ok === false && result.error !== undefined) {\n abortOutstandingCommands(commandsBySystem);\n poisonSystemFailure(world, name, result.error);\n throw new SystemFailedError(name, schedule.token.name, result.error);\n }\n }\n // void return is treated as successful execution.\n }\n\n if (finalDrain) {\n // A schedule boundary drains every remaining buffer, including commands\n // enqueued by lifecycle hooks while another command is being applied.\n try {\n for (const commands of commandsBySystem.values()) {\n flushCommands(commands, world);\n }\n } catch (error) {\n abortOutstandingCommands(commandsBySystem);\n throw error;\n }\n }\n}\n\n/**\n * Execute one schedule with a terminalization guard. Query construction,\n * run-if evaluation, DAG compilation, and command draining may all throw an\n * unexpected error; every still-open buffer is nevertheless aborted before the\n * error reaches World.update.\n */\nexport function runSchedule(\n schedule: Schedule,\n world: World,\n selectedNames?: readonly string[],\n commandsBySystem = new Map<string, ReturnType<typeof createCommandBuffer>>(),\n finalDrain = true,\n): void {\n let completed = false;\n try {\n runScheduleBody(schedule, world, selectedNames, commandsBySystem, finalDrain);\n completed = true;\n } finally {\n // When Update is split around the FixedUpdate anchor, the first segment\n // deliberately leaves its command buffers open so FixedUpdate observes a\n // stable pre-frame World and the second segment can drain them. Only the\n // final segment (or an exceptional exit) may abort outstanding buffers.\n if (!completed || finalDrain) abortOutstandingCommands(commandsBySystem);\n }\n}\n","// @forgeax/engine-ecs - SharedRefStore.\n//\n// Reference-counted store for AssetRegistry-style shared handles. Schema vocab\n// `shared<T>` fields derive `Handle<T, 'shared'>` whose lifecycle is tracked\n// by retain/release on the holder side - allocators (typically the asset\n// registry) call `alloc` once and let consumers retain/release as the asset\n// flows through ECS components and external systems. When rc transitions\n// 1 -> 0 the store publishes release evidence. External owners dispose their\n// payloads from their own lifecycle effects; ECS does not invoke callbacks.\n//\n// Companion to UniqueRefStore (1-holder-direct-release semantics). The two\n// stores share storage shape and code patterns; only the lifecycle differs:\n//\n// UniqueRefStore: alloc -> store; release -> drop. No retain.\n// SharedRefStore: alloc -> rc=1; retain -> rc++; release -> rc--; rc=0 -> drop.\n//\n// §contract - shared handles are refcounted AND carry a generation\n// The handle u32 packs `(generation << 24) | slot` via the shared codec in\n// `@forgeax/engine-types` (same SSOT codec as UniqueRefStore and ECS\n// EntityHandle). `alloc` welds the slot's current generation; resolve /\n// retain / release compare the handle generation against\n// `_generations[slot]` BEFORE any refcount/payload work, so a handle whose\n// slot was released and re-allocated returns `SharedRefStaleError`\n// ('shared-ref-stale') instead of silently resolving the next payload.\n// Generation advances on the rc=0 drop and retires the slot when gen would\n// exceed MAX_GEN (gen 255 is still usable; retire at would-be 256, no wrap).\n// AI users keep the rule \"don't cache a handle\n// past release\" - the AssetRegistry mediates most shared handle lifecycles,\n// but a stale handle now fails structurally rather than silently.\n//\n// §tier boundary (feat-20260614 M6 D-15)\n// This store manages ONLY user-tier slots (`slot >= BUILTIN_BASE`). Builtin\n// asset payloads in the builtin range are process-static and live in their\n// authoring package; they\n// are never reference-counted. `nextSlot` starts at `BUILTIN_BASE` so minted\n// handles never collide with builtin slots, and alloc/retain/release/resolve\n// fail-fast with `BuiltinSlotNotOwnedError` when handed a builtin slot.\n//\n// Storage shape:\n// - `payloads: Map<number, unknown>` - key = handle u32 = slot index.\n// - `refcounts: Map<number, number>` - key = handle u32; rc >= 1 while live;\n// removed (not set to 0) on final release\n// so resolve / retain can detect the\n// released state via `payloads.has(raw)`.\n// - `freeSlots: number[]` - LIFO stack of recyclable slot indices.\n// - `nextSlot` - bump counter for the never-recycled tail\n// (starts at BUILTIN_BASE; user tier only).\n//\n// 24 bits = 16_777_215 simultaneous live shared handles - same ceiling as\n// UniqueRefStore + Entity, so the three managed-handle resources fail-fast\n// at the same bound.\n//\n// Release path (D-1 codes):\n// - resolve(h): err(SharedRefReleasedError) if payload absent.\n// - markChanged(h): publish an in-place payload mutation to subscribers.\n// - retain(h): err(SharedRefReleasedError) if payload absent.\n// - release(h): err(SharedRefDoubleReleaseError, rc=0) on rc=0 input.\n// - any(builtin slot): err(BuiltinSlotNotOwnedError) (D-15).\n//\n// Identity invariant (mirrors UniqueRefStore): resolve(h) returns the SAME\n// payload object on every call until the final release. Archetype migration\n// preserves this trivially - the column carries the u32 handle, never the\n// payload reference.\n\nimport type { Handle } from '@forgeax/engine-types';\nimport {\n BUILTIN_BASE,\n err,\n handleGeneration,\n handleSlot,\n isRetiredSlot,\n MAX_SLOT,\n ok,\n pack,\n type Result,\n toShared,\n unwrapHandle,\n} from '@forgeax/engine-types';\nimport {\n BuiltinSlotNotOwnedError,\n SharedRefDoubleReleaseError,\n SharedRefPayloadInvalidError,\n SharedRefReleasedError,\n SharedRefStaleError,\n} from './errors';\n\nconst SHARED_REF_RELEASE_EVIDENCE_CAPACITY = 4096;\n\nexport interface SharedRefMutation {\n readonly epoch: number;\n readonly handle: number;\n}\n\nexport interface SharedRefReleaseEvidence {\n readonly payload: unknown;\n readonly refcount: 0;\n readonly generation: number;\n readonly evidence: 'released';\n}\n\nexport interface SharedRefMutationRead {\n readonly cursor: number;\n readonly records: readonly SharedRefMutation[];\n}\n\n// MAX_SLOT is now imported from @forgeax/engine-types (codec SSOT, D-1).\n// The local constant is removed to avoid drift (AC-15).\n\n/**\n * Reference-counted store for ECS-aware `Handle<T, 'shared'>` lifecycles.\n *\n * The producer (typically AssetRegistry) calls `alloc` once and owns the\n * \"alloc-grant\" rc=1; consumers (ECS schema fields, external systems) call\n * `retain` on each new holder and `release` when the holder drops. When rc\n * transitions 1 -> 0 the store publishes one structured release-evidence\n * record; it does not invoke a user callback or own payload disposal.\n *\n * D-15: manages ONLY user-tier slots (`slot >= BUILTIN_BASE`). Builtin slots\n * (`< BUILTIN_BASE`) fail-fast with `BuiltinSlotNotOwnedError`.\n *\n * Public API:\n * - alloc(target, payload) -> Handle<T, 'shared'> (rc=1)\n * - intern(target, payload) -> stable producer handle per target + object identity\n * - resolve(handle) -> Result<T, SharedRefReleasedError | SharedRefStaleError | BuiltinSlotNotOwnedError>\n * - markChanged(handle) -> Result<void, SharedRefReleasedError | SharedRefStaleError | BuiltinSlotNotOwnedError>\n * - getMutationEpoch() -> monotonic payload-mutation cursor\n * - retain(handle) -> Result<void, SharedRefReleasedError | SharedRefStaleError | BuiltinSlotNotOwnedError>\n * - release(handle) -> Result<release evidence | undefined, ...>\n * - refcount(handle) -> number (0 == released; debug + tests)\n * - _liveCount() -> live slot count (debug + inspector)\n */\nexport class SharedRefStore {\n private readonly payloads = new Map<number, unknown>();\n private readonly refcounts = new Map<number, number>();\n private readonly freeSlots: number[] = [];\n private readonly internedByTarget = new Map<string, WeakMap<object, number>>();\n private readonly internedKeys = new Map<\n number,\n { readonly target: string; readonly payload: object }\n >();\n private nextSlot = BUILTIN_BASE;\n private mutationEpoch = 0;\n /** Latest published mutation epoch per live handle; not an event journal. */\n private readonly mutationEpochs = new Map<number, number>();\n private readonly releaseJournal: SharedRefReleaseEvidence[] = [];\n\n /**\n * Generation table indexed by slot (D-6). Each entry tracks the current\n * generation for the slot — written to during alloc (welded into the\n * returned handle via pack) and incremented on release (M4).\n *\n * @internal\n */\n // biome-ignore lint/style/useNamingConvention: internal field — @internal JSDoc suppresses lint:internal gate\n private readonly _generations: number[] = [];\n\n /**\n * Allocate a fresh shared handle for `payload`, branded against `target`.\n * Refcount starts at 1 (the alloc-grant). Nullish payloads are rejected\n * before a slot or free-list is touched.\n *\n * The returned handle carries a generation tag welded via codec.pack\n * (D-8, OOS-2): first allocation gen=0 (AC-06), reused slot gen = the\n * current generation from _generations[slot]. The toShared brand cast\n * happens internally — external callers no longer construct Handle<...>\n * directly.\n *\n * Minted slots are user-tier (`>= BUILTIN_BASE`); builtin slots are never\n * produced here (D-15).\n */\n alloc<Target extends string, T = unknown>(target: Target, payload: T): Handle<Target, 'shared'> {\n void target; // target is a phantom - tag flows only at the type level via Handle<Target,_>.\n if (payload === null || payload === undefined) {\n throw new SharedRefPayloadInvalidError(target, payload === null ? 'null' : 'undefined');\n }\n const slot = this.freeSlots.pop() ?? this.nextSlot++;\n if (slot > MAX_SLOT) {\n throw new RangeError(\n `SharedRefStore: slot index ${slot} exceeds 24-bit max (${MAX_SLOT}). ` +\n 'Reduce simultaneous shared handles or investigate handle leaks.',\n );\n }\n const gen = this._generations[slot] ?? 0;\n const raw = pack(slot, gen);\n this.payloads.set(raw, payload);\n this.refcounts.set(raw, 1);\n return toShared(raw);\n }\n\n /**\n * Return the idempotent producer handle for one object payload in this\n * store. Identity includes `target`, so the same object branded for two\n * asset kinds does not alias.\n *\n * A cache hit deliberately does not retain: this is one producer grant,\n * discovered repeatedly by an asset catalogue. Actual holders retain and\n * release through the ECS write barrier. Callers needing independent\n * grants or a per-handle deleter must use {@link alloc}.\n */\n intern<Target extends string, T extends object>(\n target: Target,\n payload: T,\n ): Handle<Target, 'shared'> {\n let byPayload = this.internedByTarget.get(target);\n if (byPayload === undefined) {\n byPayload = new WeakMap<object, number>();\n this.internedByTarget.set(target, byPayload);\n }\n\n const existingRaw = byPayload.get(payload);\n if (existingRaw !== undefined && this.payloads.has(existingRaw)) {\n return toShared(existingRaw);\n }\n\n const handle = this.alloc(target, payload);\n const raw = unwrapHandle(handle);\n byPayload.set(payload, raw);\n this.internedKeys.set(raw, { target, payload });\n return handle;\n }\n\n /**\n * Look up `payload` by handle. Returns `err(shared-ref-released)` when\n * the handle's slot has no live payload (rc reached 0, no re-alloc has\n * filled the slot); `err(builtin-slot-not-owned)` for a builtin slot.\n *\n * §contract - mirrors UniqueRefStore: a stale handle whose slot has been\n * released and re-allocated returns `err(shared-ref-stale)` - the handle's\n * welded generation no longer matches `_generations[slot]`. The gen check\n * runs before payload lookup, so stale-by-reuse is caught deterministically.\n */\n resolve<Target extends string, T = unknown>(\n handle: Handle<Target, 'shared'>,\n ): Result<T, SharedRefReleasedError | SharedRefStaleError | BuiltinSlotNotOwnedError> {\n const raw = unwrapHandle(handle);\n if (raw < BUILTIN_BASE) return err(new BuiltinSlotNotOwnedError(raw));\n // Gen comparison (M4): extract slot + handle gen, compare against\n // store's current gen. Mismatch means slot was released and re-allocated —\n // the caller's handle is stale. This check runs BEFORE payload lookup so\n // stale-by-reuse is always caught (AC-01).\n const slot = handleSlot(handle);\n const handleGen = handleGeneration(handle);\n const storeGen = this._generations[slot] ?? 0;\n if (handleGen !== storeGen) {\n return err(new SharedRefStaleError(slot, handleGen, storeGen));\n }\n const payload = this.payloads.get(raw);\n if (payload === undefined) {\n return err(new SharedRefReleasedError(raw, '<unknown>'));\n }\n return ok(payload as T);\n }\n\n /**\n * Publish that a live payload was mutated in place. Consumers that retain\n * projections of shared payload data compare the monotonic epoch and\n * explicitly refresh instead of rescanning every payload each frame.\n */\n markChanged<Target extends string>(\n handle: Handle<Target, 'shared'>,\n ): Result<void, SharedRefReleasedError | SharedRefStaleError | BuiltinSlotNotOwnedError> {\n const resolved = this.resolve(handle);\n if (!resolved.ok) return resolved;\n if (this.mutationEpoch >= Number.MAX_SAFE_INTEGER) {\n throw new RangeError('SharedRefStore mutation epoch exhausted');\n }\n this.mutationEpoch += 1;\n this.mutationEpochs.set(unwrapHandle(handle), this.mutationEpoch);\n return ok(undefined);\n }\n\n /** Current upper bound for explicitly published payload mutations. */\n getMutationEpoch(): number {\n return this.mutationEpoch;\n }\n\n /** Read each live handle whose latest published mutation is after `cursor`. */\n readChangesSince(cursor: number): SharedRefMutationRead {\n const records: SharedRefMutation[] = [];\n for (const [handle, epoch] of this.mutationEpochs) {\n if (epoch > cursor) records.push({ epoch, handle });\n }\n records.sort((left, right) => left.epoch - right.epoch || left.handle - right.handle);\n return {\n cursor: this.mutationEpoch,\n records,\n };\n }\n\n /**\n * Increment the refcount of a live shared handle. Returns\n * `err(shared-ref-released)` when the handle is not live - retain MUST\n * NOT resurrect a released slot (charter P3 explicit failure; would\n * defeat the rc=0 -> drop invariant); `err(builtin-slot-not-owned)` for a\n * builtin slot.\n */\n retain<Target extends string>(\n handle: Handle<Target, 'shared'>,\n ): Result<void, SharedRefReleasedError | SharedRefStaleError | BuiltinSlotNotOwnedError> {\n const raw = unwrapHandle(handle);\n if (raw < BUILTIN_BASE) return err(new BuiltinSlotNotOwnedError(raw));\n // Gen comparison runs before rc read (q12: all three operations compare gen first).\n const slot = handleSlot(handle);\n const handleGen = handleGeneration(handle);\n const storeGen = this._generations[slot] ?? 0;\n if (handleGen !== storeGen) {\n return err(new SharedRefStaleError(slot, handleGen, storeGen));\n }\n const rc = this.refcounts.get(raw);\n if (rc === undefined) {\n return err(new SharedRefReleasedError(raw, '<unknown>'));\n }\n this.refcounts.set(raw, rc + 1);\n return ok(undefined);\n }\n\n /**\n * Decrement the refcount. When rc transitions 1 -> 0, the slot is dropped\n * and one structured release-evidence record is published. The evidence\n * captures the payload, zero refcount, next generation and `released` marker\n * after the store has removed the live slot.\n *\n * Returns `err(shared-ref-double-release, rc=0)` when the handle has\n * already reached rc=0 (or was never live); `err(builtin-slot-not-owned)`\n * for a builtin slot. AI users branch on `.code` and route the\n * second-release log to Layer 3 ErrorHandler without aborting the despawn\n * chain.\n */\n release<Target extends string>(\n handle: Handle<Target, 'shared'>,\n ): Result<\n SharedRefReleaseEvidence | undefined,\n SharedRefDoubleReleaseError | SharedRefStaleError | BuiltinSlotNotOwnedError\n > {\n const raw = unwrapHandle(handle);\n if (raw < BUILTIN_BASE) return err(new BuiltinSlotNotOwnedError(raw));\n // Gen comparison runs FIRST — before rc read, before any mutation (q12).\n const slot = handleSlot(handle);\n const handleGen = handleGeneration(handle);\n const storeGen = this._generations[slot] ?? 0;\n if (handleGen !== storeGen) {\n // AC-03: stale release MUST NOT touch rc / payload / freeSlots.\n return err(new SharedRefStaleError(slot, handleGen, storeGen));\n }\n const rc = this.refcounts.get(raw);\n if (rc === undefined) {\n return err(new SharedRefDoubleReleaseError(raw, '<unknown>', 0));\n }\n if (rc > 1) {\n this.refcounts.set(raw, rc - 1);\n return ok(undefined);\n }\n // rc === 1 -> drop. Capture the payload for release evidence before\n // clearing the live slot; nullish payloads never enter the store.\n const payload = this.payloads.get(raw);\n const internedKey = this.internedKeys.get(raw);\n if (internedKey !== undefined) {\n const byPayload = this.internedByTarget.get(internedKey.target);\n if (byPayload?.get(internedKey.payload) === raw) {\n byPayload.delete(internedKey.payload);\n }\n this.internedKeys.delete(raw);\n }\n this.refcounts.delete(raw);\n this.payloads.delete(raw);\n this.mutationEpochs.delete(raw);\n // Gen increment + retire (AC-07): bump gen; once it would exceed MAX_GEN\n // (gen 255 is still usable; the bump to 256 triggers retire) the slot is\n // permanently retired — NOT pushed to freeSlots. This prevents handle\n // aliasing. Shares the isRetiredSlot SSOT predicate with EntityHandle.\n const generation = storeGen + 1;\n this._generations[slot] = generation;\n if (!isRetiredSlot(generation)) {\n this.freeSlots.push(slot);\n }\n // else: slot retired (gen exceeded MAX_GEN) - never returns to freeSlots.\n const evidence = Object.freeze({\n payload,\n refcount: 0 as const,\n generation,\n evidence: 'released' as const,\n });\n this.releaseJournal.push(evidence);\n if (this.releaseJournal.length > SHARED_REF_RELEASE_EVIDENCE_CAPACITY) {\n this.releaseJournal.shift();\n }\n return ok(evidence);\n }\n\n /** Read the bounded release evidence owned by this store. */\n readReleaseEvidence(): readonly SharedRefReleaseEvidence[] {\n return this.releaseJournal;\n }\n\n /**\n * Return the current refcount for `handle`. Returns 0 for a released\n * (or never-allocated) slot. Primarily a debug + tests entry point;\n * production code rarely reads rc directly (the rc=0 -> drop invariant\n * is the surface AI users consume via release / the per-handle deleter).\n */\n refcount<Target extends string>(handle: Handle<Target, 'shared'>): number {\n const raw = unwrapHandle(handle);\n return this.refcounts.get(raw) ?? 0;\n }\n\n /** @internal Diagnostic count of live slots. Exposed for tests + inspector. */\n _liveCount(): number {\n return this.payloads.size;\n }\n}\n","import type { EntityHandle } from '../entity-handle';\n\nexport type StructuralEvidenceKind = 'spawn' | 'despawn' | 'component-added' | 'component-removed';\n\nexport interface StructuralEvidenceInput {\n readonly kind: StructuralEvidenceKind;\n readonly entity: EntityHandle;\n readonly componentId?: number;\n}\n\nexport interface StructuralEvidence extends StructuralEvidenceInput {\n readonly sequence: number;\n}\n\nexport type StructuralEvidenceRead =\n | {\n readonly status: 'ok';\n readonly cursor: number;\n readonly events: readonly StructuralEvidence[];\n }\n | { readonly status: 'overflow'; readonly cursor: number; readonly oldestAvailable: number };\n\n/** Bounded producer-owned structural evidence; consumers never infer facts by scanning. */\nexport class StructuralEvidenceRing {\n private readonly events: Array<StructuralEvidence | undefined>;\n private nextSequence = 1;\n\n constructor(readonly capacity = 1024) {\n if (!Number.isSafeInteger(capacity) || capacity <= 0) {\n throw new RangeError('StructuralEvidenceRing capacity must be a positive safe integer');\n }\n this.events = new Array<StructuralEvidence | undefined>(capacity);\n }\n\n get cursor(): number {\n return this.nextSequence - 1;\n }\n\n append(input: StructuralEvidenceInput): number {\n const sequence = this.nextSequence;\n this.nextSequence += 1;\n this.events[(sequence - 1) % this.capacity] = { ...input, sequence };\n return sequence;\n }\n\n readAfter(cursor: number): StructuralEvidenceRead {\n const latest = this.cursor;\n if (!Number.isSafeInteger(cursor) || cursor < 0 || cursor > latest) {\n throw new RangeError(`StructuralEvidenceRing cursor ${cursor} is outside 0..${latest}`);\n }\n const oldestAvailable = Math.max(1, latest - this.capacity + 1);\n if (cursor < oldestAvailable - 1)\n return { status: 'overflow', cursor: latest, oldestAvailable };\n const events: StructuralEvidence[] = [];\n for (let sequence = cursor + 1; sequence <= latest; sequence += 1) {\n const event = this.events[(sequence - 1) % this.capacity];\n if (event === undefined || event.sequence !== sequence) {\n return { status: 'overflow', cursor: latest, oldestAvailable };\n }\n events.push(event);\n }\n return { status: 'ok', cursor: latest, events };\n }\n}\n","// @forgeax/engine-ecs - UniqueRefStore.\n//\n// Per-slot singleton store for ECS-managed asset handles. Schema vocab\n// `ref<T>` fields derive `Handle<T, 'unique'>` whose lifecycle is owned by\n// the ECS - World hooks `despawn` / `removeComponent` / `set` into\n// `UniqueRefStore.release` so dropping a holder entity reliably releases the\n// referenced asset slot. AssetRegistry handles (`handle<T>` schema vocab) take\n// the orthogonal `'shared'` mode and never enter this store.\n//\n// §contract — handles carry a generation; stale-by-reuse is detected\n// The handle u32 packs `(generation << 24) | slot` via the shared codec in\n// `@forgeax/engine-types` (the same SSOT codec ECS `EntityHandle` uses). The\n// slot occupies the low 24 bits (capped at MAX_SLOT == ENTITY_MAX_INDEX);\n// the generation occupies the high 8 bits. `alloc` welds the slot's current\n// generation into the returned handle; `resolve` / `release` compare the\n// handle's generation against the store's `_generations[slot]` BEFORE any\n// payload work, so a handle whose slot was released and re-allocated is\n// caught deterministically and returns `UniqueRefStaleError` ('unique-ref-\n// stale') — it no longer silently resolves to the next payload.\n//\n// Generation advances on release and retires the slot when gen would exceed\n// MAX_GEN (255) — gen 255 is still usable; the bump to 256 triggers retire —\n// rather than wrapping, so a re-used slot can never collide with an old\n// handle's generation (mirrors EntityHandle via the isRetiredSlot SSOT).\n//\n// AC-06 (unique-ref-double-release) remains payload-presence detected\n// (`payloads.has(raw)`) for a handle whose generation still matches; the\n// generation check catches the orthogonal stale-by-reuse case first.\n//\n// Storage shape:\n// - `payloads: Map<number, unknown>` - key = handle u32 = slot index.\n// Strong reference; deleted on release.\n// Type-erased (the store never inspects\n// payload fields); `Handle<T, 'unique'>`\n// carries `T` at the type level and the\n// single read site (World.get's ref path)\n// narrows `unknown -> T` at the boundary.\n// - `freeSlots: number[]` - LIFO stack of recyclable slot indices.\n// - `releaseCallbacks: Map<...>` - per-slot onRelease cb cleared before fire.\n// - `nextSlot` - bump counter for the never-recycled tail.\n//\n// 24 bits = 16_777_215 simultaneous live managed handles - the same ceiling\n// as Entity, so an ECS that hit the entity ceiling cannot grow past the\n// managed-ref ceiling either. Ceiling-exhaust handling is a future concern;\n// the store deliberately panics on overflow to fail fast rather than\n// silently wrap.\n//\n// Release path (D-1 codes):\n// - resolve(h): err(UniqueRefReleasedError) if payload absent.\n// - release(h): err(UniqueRefDoubleReleaseError) on second release.\n//\n// Object.is identity invariant (AC-04 prelude):\n// resolve(h) returns the SAME payload object on every call until release\n// - the store does not clone, wrap, or proxy the payload. M4 carry-over\n// reuses this invariant: archetype migrate moves the row index, not the\n// payload reference, so wrapper identity survives migration.\n\nimport type { Handle } from '@forgeax/engine-types';\nimport {\n err,\n handleGeneration,\n handleSlot,\n isRetiredSlot,\n MAX_SLOT,\n ok,\n pack,\n type Result,\n toUnique,\n unwrapHandle,\n} from '@forgeax/engine-types';\nimport { UniqueRefDoubleReleaseError, UniqueRefReleasedError, UniqueRefStaleError } from './errors';\n\n// MAX_SLOT is now imported from @forgeax/engine-types (codec SSOT, D-1).\n// The local constant is removed to avoid drift (AC-15).\n\n/**\n * Per-slot singleton store for ECS-managed `Handle<T, 'unique'>` lifecycles.\n * World hooks the three release paths (despawn, removeComponent, set) into\n * `release(handle)`; `resolve(handle)` is the read path AI users reach\n * indirectly through `world.get(e, C)` for `ref<T>` schema fields.\n *\n * §contract — handles carry a generation; stale-by-reuse is detected: the\n * handle u32 packs `(gen << 24) | slot` via the shared codec; `resolve` /\n * `release` compare the handle generation against `_generations[slot]` and\n * return `UniqueRefStaleError` ('unique-ref-stale') when a released slot has\n * been re-allocated, instead of silently resolving to the next payload.\n * README §\"Managed handles carry a generation\" is the canonical AI-user-\n * facing statement.\n *\n * Identity invariant (AC-04 prelude): the payload returned by `resolve` is\n * the same object reference on every call until `release`. Carry-over (M4)\n * relies on this - archetype migrate moves the row index, not the payload.\n *\n * Storage is type-erased (`unknown`): the store routes lifecycle without ever\n * inspecting payload fields. Per-call payload typing flows through method\n * generics: `alloc<T>` accepts a `T` payload + matching `onRelease(T)`, and\n * `resolve<T>` returns `Result<T, ...>`. Both narrow at the call boundary\n * (the single read site is World.get's ref path); making the class generic\n * on `T` was decoration with no internal use, so the parameter was dropped\n * (architecture-principles.md §1 SSOT).\n */\nexport class UniqueRefStore {\n private readonly payloads = new Map<number, unknown>();\n private readonly freeSlots: number[] = [];\n private readonly releaseCallbacks = new Map<number, ((payload: unknown) => void) | undefined>();\n private nextSlot = 1;\n\n /**\n * Generation table indexed by slot (D-6). Each entry tracks the current\n * generation for the slot — written to during alloc (welded into the\n * returned handle via pack) and incremented on release (M4).\n *\n * Slot 0 is the sentinel and always has gen=0 — it is never allocated\n * and never incremented (R6).\n *\n * @internal\n */\n // biome-ignore lint/style/useNamingConvention: internal field — @internal JSDoc suppresses lint:internal gate\n private readonly _generations: number[] = [];\n\n /**\n * Allocate a fresh managed handle for `payload`, branded against `target`.\n *\n * Slot 0 is reserved as the \"null/unset\" sentinel - schema-vocab `ref<T>`\n * fields default to this sentinel before the first write, and World's\n * release loop uses it to short-circuit (`shouldRelease(0) === false`).\n *\n * The returned handle carries a generation tag welded via codec.pack\n * (D-8, OOS-2): first allocation gen=0 (AC-06), reused slot gen = the\n * current generation from _generations[slot]. The toUnique brand cast\n * happens internally — external callers no longer construct Handle<...>\n * directly.\n *\n * @returns a `Handle<T, 'unique'>` u32. The branded number is safe to\n * widen to `number` for GPU upload (charter consistent abstraction).\n */\n alloc<Target extends string, T = unknown>(\n target: Target,\n payload: T,\n onRelease?: (payload: T) => void,\n ): Handle<Target, 'unique'> {\n void target; // target is a phantom - tag flows only at the type level via Handle<Target,_>.\n const slot = this.freeSlots.pop() ?? this.nextSlot++;\n if (slot > MAX_SLOT) {\n throw new RangeError(\n `UniqueRefStore: slot index ${slot} exceeds 24-bit max (${MAX_SLOT}). ` +\n 'Reduce simultaneous managed handles or investigate handle leaks.',\n );\n }\n const gen = this._generations[slot] ?? 0;\n const raw = pack(slot, gen);\n this.payloads.set(raw, payload);\n if (onRelease !== undefined) {\n this.releaseCallbacks.set(raw, onRelease as (payload: unknown) => void);\n }\n return toUnique(raw);\n }\n\n /**\n * Look up `payload` by handle. Returns `err(unique-ref-released)` when\n * the handle's slot has no live payload (release happened in between, and\n * no re-alloc has filled the slot). Resolves the same payload object on\n * every call - identity-stable until release.\n *\n * §contract: a stale handle whose slot has been released and re-allocated\n * returns `err(unique-ref-stale)` — the generation welded into the handle\n * no longer matches `_generations[slot]`. The gen check runs before the\n * payload lookup, so stale-by-reuse is caught deterministically — see\n * README §\"Managed handles carry a generation\".\n *\n * `T` flows from the caller's `Handle<T, 'unique'>` type; the store erases\n * payload types at the storage layer and the call boundary re-narrows.\n */\n resolve<Target extends string, T = unknown>(\n handle: Handle<Target, 'unique'>,\n ): Result<T, UniqueRefReleasedError | UniqueRefStaleError> {\n const raw = unwrapHandle(handle);\n // Gen comparison (M4): extract slot + handle gen, compare against\n // store's current gen. Runs BEFORE payload lookup.\n const slot = handleSlot(handle);\n const handleGen = handleGeneration(handle);\n const storeGen = this._generations[slot] ?? 0;\n if (handleGen !== storeGen) {\n return err(new UniqueRefStaleError(slot, handleGen, storeGen));\n }\n const payload = this.payloads.get(raw);\n if (payload === undefined) {\n // Slot 0 (sentinel) and any handle whose payload was already removed\n // both surface as released. The phantom Target is unavailable at\n // runtime - the error carries '<unknown>' to keep the structured\n // shape consistent.\n return err(new UniqueRefReleasedError(raw, '<unknown>'));\n }\n return ok(payload as T);\n }\n\n /**\n * Release `handle` - drop the payload and push the slot onto the free list.\n * Releasing the same handle twice surfaces `unique-ref-double-release`\n * (D-1) so World's release loop can route the second release to Layer 3\n * ErrorHandler without aborting the despawn chain. Detection is by\n * payload-presence, not generation (§contract — managed handles are\n * operational, not persistent).\n *\n * Releasing the slot-0 sentinel is a no-op - World's release loop calls\n * `shouldRelease` first to filter sentinels.\n */\n release<Target extends string>(\n handle: Handle<Target, 'unique'>,\n ): Result<void, UniqueRefDoubleReleaseError | UniqueRefStaleError> {\n const raw = unwrapHandle(handle);\n // Gen comparison runs FIRST (q12: all operations compare gen first).\n const slot = handleSlot(handle);\n const handleGen = handleGeneration(handle);\n const storeGen = this._generations[slot] ?? 0;\n if (handleGen !== storeGen) {\n // AC-03: stale release MUST NOT drop payload / fire callback / touch freeSlots.\n return err(new UniqueRefStaleError(slot, handleGen, storeGen));\n }\n const payload = this.payloads.get(raw);\n if (payload === undefined) {\n return err(new UniqueRefDoubleReleaseError(raw, '<unknown>'));\n }\n // Order (feat-20260614 M1 D-1): clean up ALL store state BEFORE invoking\n // onRelease. The payload is captured on the stack above so cb still\n // observes the value (D-5 RAII-equivalent semantics preserved); both\n // releaseCallbacks and payloads entries are dropped first, then the\n // freelist push happens, and only then is cb invoked. A throwing cb\n // leaves the store fully consistent: a second release sees\n // `payloads.has(raw) === false` and returns UniqueRefDoubleReleaseError\n // without re-firing the callback (AC-01, AC-02, AC-06). try/finally is\n // explicitly NOT used (D-1 alternative (a) rejected — would swallow the\n // first-release throw and violate spec section 3.1).\n const cb = this.releaseCallbacks.get(raw);\n this.releaseCallbacks.delete(raw);\n this.payloads.delete(raw);\n // Gen increment + retire (AC-07): bump gen; once it would exceed MAX_GEN\n // (gen 255 is still usable; the bump to 256 triggers retire) the slot is\n // permanently retired — NOT pushed to freeSlots.\n this._generations[slot] = storeGen + 1;\n if (!isRetiredSlot(this._generations[slot])) {\n this.freeSlots.push(slot);\n }\n // else: slot retired (gen exceeded MAX_GEN) — never returns to freeSlots.\n if (cb !== undefined) {\n cb(payload);\n }\n return ok(undefined);\n }\n\n /** @internal Replace the payload of a live slot without changing its handle. */\n _setPayload<Target extends string, T>(handle: Handle<Target, 'unique'>, payload: T): void {\n const raw = unwrapHandle(handle);\n if (!this.payloads.has(raw)) {\n throw new Error(`UniqueRefStore: cannot replace released payload ${raw}.`);\n }\n this.payloads.set(raw, payload);\n }\n\n /**\n * `true` if `handle` references a live slot - used by World's release loop\n * to decide whether to call `release` (skips sentinel + already-released).\n *\n * The release loop differentiates \"expected sentinel\" (no error) from\n * \"leaked already-released handle\" (`unique-ref-double-release`) at the\n * caller layer; this helper handles only the no-op short-circuit.\n */\n isLive<Target extends string>(handle: Handle<Target, 'unique'>): boolean {\n const raw = unwrapHandle(handle);\n if (raw === 0) return false;\n return this.payloads.has(raw);\n }\n\n /** @internal Diagnostic count of live slots. Exposed for tests + inspector. */\n _liveCount(): number {\n return this.payloads.size;\n }\n}\n","// @forgeax/engine-ecs — world-entity-lifecycle: entity lifecycle and hierarchy.\n//\n// Owns spawn preflight and hierarchy orchestration. World is the sole state\n// owner; this module composes its typed internal capabilities into those\n// public lifecycle behaviors.\n\nimport { err, ok, pack, type Result } from '@forgeax/engine-types';\nimport type { Component, ComponentSchema, InputShapeOf } from './component';\nimport { componentId, componentSchema } from './component';\nimport { expandComponentRequirements } from './component-schema';\nimport { ENTITY_NULL_RAW, type EntityHandle, entityGeneration, entityIndex } from './entity-handle';\nimport {\n ComponentNotPresentError,\n RelationshipDetachMismatchError,\n RelationshipSelfCycleError,\n StaleEntityError,\n} from './errors';\nimport { relationshipRole } from './relationship-index';\nimport type { Archetype } from './storage/archetype';\nimport type { ArchetypeGraph } from './storage/archetype-graph';\nimport type { ComponentData, EcsError, World } from './world';\nimport { worldInternal } from './world-internal';\n\nfunction tableRow(world: World, record: { archetypeId: number; archetypeRow: number }): number {\n const archetype = world[worldInternal].getGraph().archetypes[record.archetypeId];\n return archetype?.rows[record.archetypeRow] ?? -1;\n}\n\n/**\n * Core implementation of `spawn`.\n */\nexport function spawnCore(\n world: World,\n componentDatas: ComponentData[],\n): Result<EntityHandle, EcsError> {\n componentDatas = expandComponentRequirements(componentDatas);\n for (const cd of componentDatas) {\n const preflight = world[worldInternal].preflightComponentData(null, cd);\n if (!preflight.ok) return preflight;\n }\n const spawnedEntity = world[worldInternal].allocatePendingEntity();\n const materialized = world[worldInternal].materializeEntity(spawnedEntity, componentDatas);\n if (!materialized.ok) return materialized;\n return ok(spawnedEntity);\n}\n\n/** Attach a child and maintain the relationship mirror through component storage. */\nexport function worldAddChild<S extends ComponentSchema>(\n world: World,\n parent: EntityHandle,\n child: EntityHandle,\n component: Component<string, S>,\n data: Partial<InputShapeOf<S>>,\n): Result<void, EcsError> {\n const holderComp = component as Component;\n if (relationshipRole(holderComp)?.kind !== 'source') {\n return err(new ComponentNotPresentError(child as number, component.name));\n }\n\n const parentResult = world[worldInternal].lookupAlive(parent, 'addChild', component.name);\n if (!parentResult.ok) return parentResult;\n const parentSlot = entityIndex(parent);\n const parentGeneration = entityGeneration(parent);\n const childResult = world[worldInternal].lookupAlive(child, 'addChild', component.name);\n if (!childResult.ok) return childResult;\n const childSlot = entityIndex(child);\n\n const role = relationshipRole(holderComp);\n if (child === parent && !(role?.kind === 'source' && role.allowSelf)) {\n return err(new RelationshipSelfCycleError(component.name, child as number, child as number));\n }\n const cycleHit =\n child === parent && role?.kind === 'source' && role.allowSelf\n ? null\n : relationshipChainCycleHit(world, holderComp, parentSlot, parentGeneration, childSlot);\n if (cycleHit !== null) {\n return err(new RelationshipSelfCycleError(component.name, child as number, cycleHit as number));\n }\n\n return world.addComponent(child, { component, data });\n}\n\n/** Detach a child only when its current relationship target matches `parent`. */\nexport function worldRemoveChild<S extends ComponentSchema>(\n world: World,\n parent: EntityHandle,\n child: EntityHandle,\n component: Component<string, S>,\n): Result<void, EcsError> {\n const holderComp = component as Component;\n const childResult = world[worldInternal].lookupAlive(child, 'removeChild', component.name);\n if (!childResult.ok) return childResult;\n\n const childRecord = childResult.value;\n const childArch = (world[worldInternal].getGraph() as ArchetypeGraph).archetypes[\n childRecord.archetypeId\n ];\n if (!childArch) {\n return err(\n new StaleEntityError(child as number, entityIndex(child), entityGeneration(child), {\n operation: 'removeChild',\n component: component.name,\n expectedGeneration: entityGeneration(child),\n actualGeneration: childRecord.generation,\n }),\n );\n }\n if (\n !childArch.components.some((component) => componentId(component) === componentId(holderComp))\n ) {\n return err(\n new RelationshipDetachMismatchError(component.name, child as number, parent as number, 0),\n );\n }\n\n const oldValue = world[worldInternal].readRow(\n childArch,\n holderComp,\n tableRow(world, childRecord),\n ) as Record<string, unknown>;\n const currentTarget = relationshipTargetEntity(holderComp, oldValue);\n if (currentTarget !== parent) {\n return err(\n new RelationshipDetachMismatchError(\n component.name,\n child as number,\n parent as number,\n currentTarget ?? 0,\n ),\n );\n }\n\n return world.removeComponent(child, component);\n}\n\n/** Move a child to a new parent after cycle validation and old-mirror detachment. */\nexport function worldReparent<S extends ComponentSchema>(\n world: World,\n child: EntityHandle,\n newParent: EntityHandle,\n component: Component<string, S>,\n data: Partial<InputShapeOf<S>>,\n): Result<void, EcsError> {\n const holderComp = component as Component;\n const role = relationshipRole(holderComp);\n if (role?.kind !== 'source') {\n return err(new ComponentNotPresentError(child as number, component.name));\n }\n if (child === newParent && !role.allowSelf) {\n return err(\n new RelationshipSelfCycleError(component.name, child as number, newParent as number),\n );\n }\n const cycleHit =\n child === newParent && role.allowSelf\n ? null\n : relationshipChainCycleHit(\n world,\n holderComp,\n entityIndex(newParent),\n entityGeneration(newParent),\n entityIndex(child),\n );\n if (cycleHit !== null) {\n return err(new RelationshipSelfCycleError(component.name, child as number, cycleHit as number));\n }\n\n const childResult = world[worldInternal].lookupAlive(child, 'reparent', component.name);\n if (!childResult.ok) return childResult;\n\n const childRecord = childResult.value;\n const childArch = (world[worldInternal].getGraph() as ArchetypeGraph).archetypes[\n childRecord.archetypeId\n ];\n if (!childArch) {\n return err(\n new StaleEntityError(child as number, entityIndex(child), entityGeneration(child), {\n operation: 'reparent',\n component: component.name,\n expectedGeneration: entityGeneration(child),\n actualGeneration: childRecord.generation,\n }),\n );\n }\n const payload = {\n ...(data as Record<string, unknown>),\n [role.sourceField]: newParent,\n } as Partial<InputShapeOf<S>>;\n if (\n childArch.components.some((component) => componentId(component) === componentId(holderComp))\n ) {\n // Existing exclusive sources are updated through the same owner-level\n // write barrier as `world.set`; remove+add would expose a partial mirror\n // state and would invalidate unrelated query spans.\n return world.set(child, component as never, payload as never);\n }\n return world.addComponent(child, { component, data: payload });\n}\n\n/** Iterate ancestors in child-to-root order while safely terminating corrupt cycles. */\nexport function worldIterAncestors(world: World, entity: EntityHandle): Iterable<EntityHandle> {\n return {\n *[Symbol.iterator]() {\n const records = world[worldInternal].getRecords();\n const slot = entityIndex(entity);\n const generation = entityGeneration(entity);\n if (!world[worldInternal].recordIsLive(records[slot], generation)) return;\n\n const visited = new Set<number>();\n let currentSlot = slot;\n let currentGeneration = generation;\n while (true) {\n const key = pack(currentSlot, currentGeneration);\n if (visited.has(key)) return;\n visited.add(key);\n\n const currentRecord = records[currentSlot];\n if (!world[worldInternal].recordIsLive(currentRecord, currentGeneration)) return;\n const currentArch = (world[worldInternal].getGraph() as ArchetypeGraph).archetypes[\n currentRecord.archetypeId\n ];\n if (!currentArch) return;\n\n let foundParent = false;\n for (const component of currentArch.components) {\n if (\n relationshipRole(component)?.kind !== 'source' ||\n !currentArch.components.some(\n (candidate) => componentId(candidate) === componentId(component),\n )\n )\n continue;\n const value = world[worldInternal].readRow(\n currentArch,\n component,\n tableRow(world, currentRecord),\n ) as Record<string, unknown>;\n const target = relationshipTargetEntity(component, value);\n if (target === null) continue;\n yield target;\n currentSlot = entityIndex(target);\n currentGeneration = entityGeneration(target);\n if (!world[worldInternal].recordIsLive(records[currentSlot], currentGeneration)) return;\n foundParent = true;\n break;\n }\n if (!foundParent) return;\n }\n },\n };\n}\n\n/** Iterate descendants depth-first through relationship mirror lists. */\nexport function worldIterDescendants(world: World, entity: EntityHandle): Iterable<EntityHandle> {\n return {\n *[Symbol.iterator]() {\n const records = world[worldInternal].getRecords();\n const slot = entityIndex(entity);\n const generation = entityGeneration(entity);\n if (!world[worldInternal].recordIsLive(records[slot], generation)) return;\n\n const visited = new Set<number>();\n const stack: number[] = [slot];\n while (stack.length > 0) {\n const currentSlot = stack.pop();\n if (currentSlot === undefined) break;\n const currentRecord = records[currentSlot];\n if (!currentRecord || currentRecord.archetypeId === -1) continue;\n const currentArch = world[worldInternal].getGraph().archetypes[currentRecord.archetypeId];\n if (!currentArch) continue;\n\n for (const child of descendantChildren(\n world,\n currentArch,\n tableRow(world, currentRecord),\n )) {\n const childSlot = entityIndex(child);\n const childGeneration = entityGeneration(child);\n const key = pack(childSlot, childGeneration);\n if (\n visited.has(key) ||\n !world[worldInternal].recordIsLive(records[childSlot], childGeneration)\n ) {\n continue;\n }\n visited.add(key);\n yield child;\n stack.push(childSlot);\n }\n }\n },\n };\n}\n\nfunction descendantChildren(world: World, arch: Archetype, row: number): EntityHandle[] {\n const children: EntityHandle[] = [];\n for (const component of arch.components) {\n const value = world[worldInternal].readRow(arch, component, row) as Record<string, unknown>;\n for (const [fieldName, fieldType] of Object.entries(componentSchema(component))) {\n if (fieldType !== 'array<entity>') continue;\n const list = value[fieldName];\n if (!(list instanceof Uint32Array)) continue;\n for (const raw of list) children.push(raw as EntityHandle);\n }\n }\n return children;\n}\n\nfunction relationshipTargetEntity(\n component: Component,\n value: Record<string, unknown>,\n): EntityHandle | null {\n for (const [fieldName, fieldType] of Object.entries(componentSchema(component))) {\n if (fieldType !== 'entity') continue;\n const raw = value[fieldName];\n if (raw === null || raw === undefined || raw === ENTITY_NULL_RAW) return null;\n return raw as EntityHandle;\n }\n return null;\n}\n\nfunction relationshipChainCycleHit(\n world: World,\n holderComponent: Component,\n startSlot: number,\n startGeneration: number,\n targetSlot: number,\n): EntityHandle | null {\n const visited = new Set<number>();\n let currentSlot = startSlot;\n let currentGeneration = startGeneration;\n while (true) {\n const key = pack(currentSlot, currentGeneration);\n if (visited.has(key)) return null;\n visited.add(key);\n const currentRecord = world[worldInternal].getRecords()[currentSlot];\n if (!world[worldInternal].recordIsLive(currentRecord, currentGeneration)) return null;\n const currentArchetype = (world[worldInternal].getGraph() as ArchetypeGraph).archetypes[\n currentRecord.archetypeId\n ];\n if (\n !currentArchetype?.components.some(\n (candidate) => componentId(candidate) === componentId(holderComponent),\n )\n )\n return null;\n const value = world[worldInternal].readRow(\n currentArchetype,\n holderComponent,\n tableRow(world, currentRecord),\n ) as Record<string, unknown>;\n const target = relationshipTargetEntity(holderComponent, value);\n if (target === null) return null;\n const targetEntitySlot = entityIndex(target);\n if (targetEntitySlot === targetSlot) return target;\n currentSlot = targetEntitySlot;\n currentGeneration = entityGeneration(target);\n }\n}\n","// @forgeax/engine-ecs — safe read-only World seam.\n//\n// This is the only cross-package World capability needed by relationship and\n// scene projections. It exposes semantic scalar/array reads, never the table,\n// archetype, buffer-pool, or mutation stores behind those reads.\n\nimport type { Component } from './component';\nimport type { EntityHandle } from './entity-handle';\n\n/** Stable identity for the World-owned semantic read capability. */\nexport const worldRead: unique symbol = Symbol.for(\n 'forgeax.ecs.worldRead',\n) as unknown as typeof worldRead;\n\n/**\n * Read-only semantic probes used by owner packages such as scene.\n *\n * Missing entities, components, fields, and out-of-range elements return\n * `undefined`; callers never receive a storage object or mutable view.\n */\nexport interface WorldRead {\n readonly getFieldValue: (\n entity: EntityHandle,\n component: Component,\n fieldName: string,\n ) => number | undefined;\n readonly getArrayLength: (\n entity: EntityHandle,\n component: Component,\n fieldName: string,\n ) => number | undefined;\n readonly getArrayElement: (\n entity: EntityHandle,\n component: Component,\n fieldName: string,\n index: number,\n ) => number | undefined;\n}\n","// @forgeax/engine-ecs -- World schedule and resource orchestration.\n\nimport { err, ok, type Result } from '@forgeax/engine-types';\nimport type { CommandBufferImpl } from './commands';\nimport {\n CommandFailedError,\n CyclicDependencyError,\n ProtectedResourceError,\n ScheduleScopeMismatchError,\n SystemFailedError,\n type SystemSetNotRegisteredError,\n TimeConfigInvalidError,\n TimeDeltaInvalidError,\n} from './errors';\nimport {\n SHARED_KERNEL_EXECUTOR_RESOURCE_KEY,\n type SharedKernelDispatch,\n type SharedKernelExecutor,\n SharedKernelFailureError,\n WorldPoisonedError,\n} from './execution/shared-kernel';\nimport type { QueryDescriptor } from './query/query';\nimport {\n getResource as resGet,\n hasResource as resHas,\n insertResource as resInsert,\n removeResource as resRemove,\n} from './resource';\nimport {\n buildSchedule,\n runSchedule,\n type Schedule,\n type SystemDescriptor,\n type SystemSet,\n addSystem as scheduleAddSystem,\n addSystems as scheduleAddSystems,\n removeSystem as scheduleRemoveSystem,\n replaceSystem as scheduleReplaceSystem,\n} from './schedule';\nimport { FixedUpdate, isScheduleToken, type ScheduleToken, Update } from './schedule-token';\nimport type { ArchetypeGraph } from './storage/archetype-graph';\nimport { FIXED_TIME_RESOURCE_KEY, type MutableFixedTimeResource, TIME_RESOURCE_KEY } from './time';\nimport type {\n World,\n WorldInspection,\n WorldScheduleData,\n WorldScheduleQueryData,\n WorldScheduleSystemData,\n} from './world';\nimport { worldInternal } from './world-internal';\n\nconst FIXED_ANCHOR_NAME = FixedUpdate.name;\ntype ResourceKey = string | { readonly name: string };\n\nfunction resourceName(key: ResourceKey): string {\n return typeof key === 'string' ? key : key.name;\n}\n\nfunction warmSharedKernel(world: World, descriptor: unknown): void {\n if (\n (descriptor as { readonly kind?: string }).kind !== 'shared-kernel' ||\n !world.hasResource(SHARED_KERNEL_EXECUTOR_RESOURCE_KEY)\n )\n return;\n world\n .getResource<SharedKernelExecutor>(SHARED_KERNEL_EXECUTOR_RESOURCE_KEY)\n .warmup?.(descriptor as SharedKernelDispatch);\n}\n\nfunction scheduleFor(\n world: World,\n token: ScheduleToken,\n): Result<Schedule, ScheduleScopeMismatchError> {\n const schedule = isScheduleToken(token) ? world[worldInternal].getSchedule(token) : undefined;\n if (schedule) return ok(schedule);\n return err(new ScheduleScopeMismatchError(token?.name ?? 'Unknown', Update.name));\n}\n\nfunction setOwner(world: World, set: SystemSet): ScheduleToken | undefined {\n for (const [token, schedule] of world[worldInternal].getSchedules()) {\n if (schedule.sets.has(set.name)) return token;\n }\n return undefined;\n}\n\nfunction scopeError(\n source: ScheduleToken,\n target: ScheduleToken,\n reference?: string,\n): Result<never, ScheduleScopeMismatchError> {\n return err(new ScheduleScopeMismatchError(source.name, target.name, reference));\n}\n\nexport function worldAddSystem<const Qs extends ReadonlyArray<QueryDescriptor>>(\n world: World,\n token: ScheduleToken,\n descriptor: SystemDescriptor<Qs>,\n): Result<void, ScheduleScopeMismatchError> {\n const target = scheduleFor(world, token);\n if (!target.ok) return target;\n scheduleAddSystem(target.value, descriptor);\n warmSharedKernel(world, descriptor);\n return ok(undefined);\n}\n\nexport function worldRemoveSystem(\n world: World,\n token: ScheduleToken,\n name: string,\n): ReturnType<typeof scheduleRemoveSystem> | Result<never, ScheduleScopeMismatchError> {\n const target = scheduleFor(world, token);\n if (!target.ok) return target;\n return scheduleRemoveSystem(target.value, name);\n}\n\nexport function worldReplaceSystem<const Qs extends ReadonlyArray<QueryDescriptor>>(\n world: World,\n token: ScheduleToken,\n name: string,\n descriptor: SystemDescriptor<Qs>,\n): ReturnType<typeof scheduleReplaceSystem> | Result<never, ScheduleScopeMismatchError> {\n const target = scheduleFor(world, token);\n if (!target.ok) return target;\n const replaced = scheduleReplaceSystem(target.value, name, descriptor);\n if (replaced.ok) warmSharedKernel(world, descriptor);\n return replaced;\n}\n\nexport function worldAddSystems<const Qs extends ReadonlyArray<QueryDescriptor>>(\n world: World,\n token: ScheduleToken,\n set: SystemSet,\n systems: ReadonlyArray<SystemDescriptor<Qs>>,\n): Result<void, SystemSetNotRegisteredError | ScheduleScopeMismatchError> {\n const target = scheduleFor(world, token);\n if (!target.ok) return target;\n const owner = setOwner(world, set);\n if (owner && owner !== token) return scopeError(token, owner, set.name);\n const added = scheduleAddSystems(target.value, set, systems);\n if (added.ok) {\n for (const system of systems) warmSharedKernel(world, system);\n }\n return added;\n}\n\nfunction validateScheduleReferences(\n world: World,\n token: ScheduleToken,\n schedule: Schedule,\n): ScheduleScopeMismatchError | undefined {\n for (const record of schedule.systems.values()) {\n for (const reference of [\n ...(record.descriptor.before ?? []),\n ...(record.descriptor.after ?? []),\n ]) {\n if (isScheduleToken(reference)) {\n const isFixedAnchor = token === Update && reference === FixedUpdate;\n if (reference !== token && !isFixedAnchor) {\n return new ScheduleScopeMismatchError(token.name, reference.name, reference.name);\n }\n continue;\n }\n if (typeof reference === 'string') {\n for (const [otherToken, other] of world[worldInternal].getSchedules()) {\n if (otherToken !== token && other.systems.has(reference)) {\n return new ScheduleScopeMismatchError(token.name, otherToken.name, reference);\n }\n }\n }\n }\n }\n return undefined;\n}\n\nfunction runFixed(\n world: World,\n fixed: MutableFixedTimeResource,\n accumulator: { value: number },\n): void {\n const fixedSchedule = world[worldInternal].getSchedule(FixedUpdate) as Schedule | undefined;\n if (!fixedSchedule) return;\n if (fixedSchedule.systems.size === 0) {\n discardFixedOverflow(fixed, accumulator);\n return;\n }\n let steps = 0;\n while (accumulator.value >= fixed.delta && steps < fixed.maxStepsPerUpdate) {\n accumulator.value = Math.round((accumulator.value - fixed.delta) * 1e12) / 1e12;\n fixed.overstep = accumulator.value;\n fixed.tick += 1;\n runSchedule(fixedSchedule, world);\n steps += 1;\n }\n if (steps === fixed.maxStepsPerUpdate && accumulator.value >= fixed.delta) {\n const remainder = accumulator.value % fixed.delta;\n const dropped = accumulator.value - remainder;\n accumulator.value = remainder;\n fixed.droppedSeconds += dropped;\n fixed.droppedUpdates += 1;\n }\n}\n\nfunction discardFixedOverflow(\n fixed: MutableFixedTimeResource,\n accumulator: { value: number },\n): void {\n if (accumulator.value < fixed.delta) return;\n const remainder = accumulator.value % fixed.delta;\n const dropped = accumulator.value - remainder;\n accumulator.value = remainder;\n fixed.droppedSeconds += dropped;\n fixed.droppedUpdates += 1;\n}\n\nexport function worldUpdate(\n world: World,\n deltaSeconds = 0,\n): Result<\n void,\n | TimeDeltaInvalidError\n | TimeConfigInvalidError\n | ScheduleScopeMismatchError\n | WorldPoisonedError\n | CommandFailedError\n | SystemFailedError\n | CyclicDependencyError\n | SharedKernelFailureError\n> {\n if (world.execution.health === 'poisoned') {\n return err(new WorldPoisonedError(world.identity, world.execution.fault));\n }\n if (!Number.isFinite(deltaSeconds) || deltaSeconds < 0)\n return err(new TimeDeltaInvalidError(deltaSeconds));\n\n const writer = world[worldInternal].getClockWriter();\n const time = writer.time;\n const fixed = writer.fixed;\n if (time.maxDeltaSeconds < (fixed.maxStepsPerUpdate + 1) * fixed.delta) {\n return err(\n new TimeConfigInvalidError({\n fixedDeltaSeconds: fixed.delta,\n maxStepsPerUpdate: fixed.maxStepsPerUpdate,\n maxDeltaSeconds: time.maxDeltaSeconds,\n }),\n );\n }\n\n for (const [token, schedule] of world[worldInternal].getSchedules()) {\n const mismatch = validateScheduleReferences(world, token, schedule);\n if (mismatch) return err(mismatch);\n }\n\n const measured = Math.min(deltaSeconds, time.maxDeltaSeconds);\n time.delta = measured;\n time.elapsed += measured;\n // Accumulate the measured frame delta. maxDeltaSeconds bounds Time's public\n // delta, while the fixed cap makes oversized host gaps observable via metrics.\n const accumulator = { value: world[worldInternal].getFixedAccumulator() + measured };\n const update = world[worldInternal].getSchedule(Update) as Schedule | undefined;\n if (!update) return err(new ScheduleScopeMismatchError('World', Update.name));\n\n try {\n if (update.dirty) buildSchedule(update);\n const order = update.sortedOrder;\n const anchor = order.indexOf(FIXED_ANCHOR_NAME);\n const fixedSchedule = world[worldInternal].getSchedule(FixedUpdate) as Schedule | undefined;\n const hasFixedSystems = (fixedSchedule?.systems.size ?? 0) > 0;\n if (anchor < 0 || !hasFixedSystems) {\n runSchedule(\n update,\n world,\n order.filter((name) => name !== FIXED_ANCHOR_NAME),\n );\n if (measured > 0) discardFixedOverflow(fixed, accumulator);\n } else {\n const updateCommands = new Map<string, CommandBufferImpl>();\n runSchedule(update, world, order.slice(0, anchor), updateCommands, false);\n if (measured > 0) runFixed(world, fixed, accumulator);\n runSchedule(update, world, order.slice(anchor + 1), updateCommands);\n }\n } catch (error) {\n if (error instanceof CommandFailedError || error instanceof SystemFailedError) {\n return err(error);\n }\n if (error instanceof CyclicDependencyError || error instanceof SharedKernelFailureError) {\n return err(error);\n }\n if (world.execution.health === 'healthy') {\n world[worldInternal].poisonExecution({\n code: 'shared-kernel-failed',\n kernelName: `schedule:${Update.name}`,\n cause: error,\n partialWrite: true,\n retryable: false,\n });\n }\n return err(new SystemFailedError('<schedule>', Update.name, error));\n }\n world[worldInternal].setFixedAccumulator(accumulator.value);\n fixed.overstep = accumulator.value;\n return ok(undefined);\n}\n\nexport function worldInsertResource<T>(world: World, key: ResourceKey, value: T): void {\n const name = resourceName(key);\n if (name === TIME_RESOURCE_KEY || name === FIXED_TIME_RESOURCE_KEY) {\n throw new ProtectedResourceError(name, 'insert');\n }\n resInsert(\n world[worldInternal].getResources(),\n name,\n value,\n world[worldInternal].nextMutationEpoch(),\n );\n}\n\nexport function worldGetResource<T>(world: World, key: ResourceKey): T {\n return resGet<T>(world[worldInternal].getResources(), resourceName(key));\n}\n\nexport function worldHasResource(world: World, key: ResourceKey): boolean {\n return resHas(world[worldInternal].getResources(), resourceName(key));\n}\n\nexport function worldRemoveResource(world: World, key: ResourceKey): void {\n const name = resourceName(key);\n if (name === TIME_RESOURCE_KEY || name === FIXED_TIME_RESOURCE_KEY) {\n throw new ProtectedResourceError(name, 'remove');\n }\n if (resHas(world[worldInternal].getResources(), name)) {\n resRemove(world[worldInternal].getResources(), name);\n world[worldInternal].nextMutationEpoch();\n }\n}\n\nexport function worldInspect(world: World): WorldInspection {\n const graph = world[worldInternal].getGraph() as ArchetypeGraph;\n const resources = world[worldInternal].getResources();\n let entityCount = 0;\n const archetypes: WorldInspection['archetypes'] = [];\n const activeComponentSet = new Set<string>();\n for (const arch of graph.archetypes) {\n if (!arch) continue;\n entityCount += arch.size;\n const componentNames = arch.components.map((component) => component.name);\n archetypes.push({\n key: arch.key,\n componentNames,\n entityCount: arch.size,\n tableId: arch.tableId,\n });\n if (arch.size > 0) for (const name of componentNames) activeComponentSet.add(name);\n }\n\n const schedules = [\n ...(world[worldInternal].getSchedules() as ReadonlyMap<ScheduleToken, Schedule>),\n ].map(([token, schedule]) => {\n const systems = [...schedule.systems.entries()]\n .filter(([name]) => name !== FIXED_ANCHOR_NAME)\n .map(([name]) => ({\n name,\n sets: [...schedule.sets].flatMap(([setName, record]) =>\n record.members.has(name) ? [setName] : [],\n ),\n }));\n return { schedule: token, systems };\n });\n const systems = schedules.flatMap((entry) => entry.systems);\n const tables = graph.tables.map((table) => ({\n id: table.id,\n key: table.key,\n componentNames: table.components.map((component) => component.name),\n entityCount: table.size,\n capacity: table.capacity,\n }));\n return {\n entityCount,\n archetypeCount: archetypes.length,\n archetypes,\n tableCount: tables.length,\n tables,\n activeComponents: [...activeComponentSet],\n systemCount: systems.length,\n systems,\n resourceKeys: [...resources.entries.keys()],\n schedules,\n scheduleSystemCount(token: ScheduleToken): number {\n return schedules.find((entry) => entry.schedule === token)?.systems.length ?? 0;\n },\n };\n}\n\nfunction referenceName(reference: string | ScheduleToken): string {\n return typeof reference === 'string' ? reference : reference.name;\n}\n\nfunction componentNames(components: readonly { readonly name: string }[] | undefined): string[] {\n return (components ?? []).map((component) => component.name);\n}\n\nfunction queryData(query: QueryDescriptor): WorldScheduleQueryData {\n return {\n with: componentNames(query.with),\n without: componentNames(query.without),\n optional: componentNames(query.optional),\n changed: componentNames(query.changed),\n added: componentNames(query.added),\n };\n}\n\n/** Project schedule registration into a JSON-safe graph for tooling and AI inspection. */\nexport function worldScheduleData(world: World): ReadonlyArray<WorldScheduleData> {\n return [...(world[worldInternal].getSchedules() as ReadonlyMap<ScheduleToken, Schedule>)].map(\n ([token, schedule]) => {\n if (schedule.dirty) buildSchedule(schedule);\n\n const systems: WorldScheduleSystemData[] = [...schedule.systems.entries()]\n .filter(([name]) => name !== FIXED_ANCHOR_NAME)\n .map(([name, record]) => {\n const descriptor = record.descriptor;\n const queries = descriptor.queries.map(queryData);\n return {\n name,\n sets: [...schedule.sets].flatMap(([setName, set]) =>\n set.members.has(name) ? [setName] : [],\n ),\n before: (descriptor.before ?? []).map((reference) => referenceName(reference)),\n after: (descriptor.after ?? []).map((reference) => referenceName(reference)),\n queries,\n resources: [],\n };\n });\n\n const systemSets = [...schedule.sets].map(([name, set]) => ({\n name,\n members: [...set.members].filter((member) => schedule.systems.has(member)),\n before: [],\n after: [],\n chained: set.chained,\n }));\n const dependencies = [...schedule.predecessors].flatMap(([target, predecessors]) =>\n [...predecessors].map((source) => [source, target] as const),\n );\n\n return { name: token.name, systems, systemSets, dependencies };\n },\n );\n}\n\nfunction queryUsesComponent(query: QueryDescriptor, component: object): boolean {\n return [\n query.read,\n query.write,\n query.optional,\n query.with,\n query.without,\n query.changed,\n query.added,\n ].some((items) => items?.includes(component as never) === true);\n}\n\n/** Control-plane guard used before releasing a World-local component registration. */\nexport function worldScheduleUsesComponent(world: World, component: object): boolean {\n for (const schedule of (\n world[worldInternal].getSchedules() as ReadonlyMap<ScheduleToken, Schedule>\n ).values()) {\n for (const record of schedule.systems.values()) {\n if (record.descriptor.queries.some((query) => queryUsesComponent(query, component)))\n return true;\n }\n }\n return false;\n}\n","import { fieldTypeToMetaKey, type ManagedArrayElementType, TYPE_METADATA } from './component';\n\n/** Freeze the detached POD produced by World.inspect(). */\nexport function detachWorldInspection<T extends object>(snapshot: T): Readonly<T> {\n return freezeInspection(snapshot);\n}\n\nfunction freezeInspection<T>(value: T): Readonly<T> {\n if (value === null || (typeof value !== 'object' && typeof value !== 'function')) {\n return value as Readonly<T>;\n }\n for (const key of Reflect.ownKeys(value as object)) {\n const child = (value as Record<PropertyKey, unknown>)[key];\n if (child !== null && (typeof child === 'object' || typeof child === 'function')) {\n freezeInspection(child);\n }\n }\n return Object.freeze(value) as Readonly<T>;\n}\n\n/**\n * Element-byte-width for a managed-array element type, read off the global\n * TYPE_METADATA table (single SSOT). `entity` stores as `u32` (4 bytes); every\n * scalar maps to its own key. `fieldTypeToMetaKey` always resolves a key for a\n * ManagedArrayElementType, and every such row carries a concrete `byteSize`.\n */\nexport function elementByteSize(elementType: ManagedArrayElementType): number {\n const key = fieldTypeToMetaKey(elementType);\n // biome-ignore lint/style/noNonNullAssertion: every ManagedArrayElementType resolves to a row with a concrete byteSize\n return TYPE_METADATA[key!]!.byteSize!;\n}\n\nexport function reinterpretSlotBytes(\n bytes: Uint8Array,\n elementType: ManagedArrayElementType,\n elementCount: number,\n): ReturnType<typeof reinterpretBufferRegion> {\n return reinterpretBufferRegion(bytes.buffer, bytes.byteOffset, elementType, elementCount);\n}\n\nexport function reinterpretBufferRegion(\n buffer: ArrayBufferLike,\n byteOffset: number,\n elementType: ManagedArrayElementType,\n elementCount: number,\n):\n | Float32Array\n | Float64Array\n | Int32Array\n | Uint32Array\n | Int16Array\n | Uint16Array\n | Int8Array\n | Uint8Array {\n // shared<X> template literals: column-stored as u32 handles, reinterpret\n // as Uint32Array. The brand is applied at the FieldValueType level;\n // runtime storage is plain u32 (feat-20260614 M5; replaces the retired\n // 'handle<X>' arm).\n if (elementType.startsWith('shared<')) {\n return new Uint32Array(buffer, byteOffset, elementCount);\n }\n switch (elementType) {\n case 'f32':\n return new Float32Array(buffer, byteOffset, elementCount);\n case 'f64':\n return new Float64Array(buffer, byteOffset, elementCount);\n case 'i32':\n return new Int32Array(buffer, byteOffset, elementCount);\n case 'u32':\n case 'enum':\n case 'ref':\n case 'entity':\n return new Uint32Array(buffer, byteOffset, elementCount);\n case 'i16':\n return new Int16Array(buffer, byteOffset, elementCount);\n case 'u16':\n return new Uint16Array(buffer, byteOffset, elementCount);\n case 'i8':\n return new Int8Array(buffer, byteOffset, elementCount);\n case 'u8':\n case 'bool':\n return new Uint8Array(buffer, byteOffset, elementCount);\n }\n // Exhaustiveness fallthrough: TypeScript template-literal type\n // (`shared<${string}>`) is structurally not narrowed away by the\n // `startsWith` guard above, so this branch is unreachable yet TS still\n // requires a return path.\n return new Uint32Array(buffer, byteOffset, elementCount);\n}\n\n/**\n * Reinterpret `bytes` as the typed view for `elementType` and write `value`\n * at element index `idx`. Mirrors the `array<T>` storage law (4/8/2/1-byte\n * element widths per TYPE_METADATA.byteSize) and is used by `world.push`\n * to land a new tail element into BufferPool slot bytes after a `grow`.\n */\nexport function writeArrayElementAt(\n bytes: Uint8Array,\n idx: number,\n elementType: ManagedArrayElementType,\n value: number,\n): void {\n const buf = bytes.buffer;\n const offset = bytes.byteOffset;\n const byteLen = bytes.byteLength;\n switch (elementType) {\n case 'f32':\n new Float32Array(buf, offset, byteLen >>> 2)[idx] = value;\n return;\n case 'f64':\n new Float64Array(buf, offset, byteLen >>> 3)[idx] = value;\n return;\n case 'i32':\n new Int32Array(buf, offset, byteLen >>> 2)[idx] = value;\n return;\n case 'u32':\n case 'enum':\n case 'ref':\n case 'entity':\n new Uint32Array(buf, offset, byteLen >>> 2)[idx] = value;\n return;\n case 'i16':\n new Int16Array(buf, offset, byteLen >>> 1)[idx] = value;\n return;\n case 'u16':\n new Uint16Array(buf, offset, byteLen >>> 1)[idx] = value;\n return;\n case 'i8':\n new Int8Array(buf, offset, byteLen)[idx] = value;\n return;\n case 'u8':\n case 'bool':\n new Uint8Array(buf, offset, byteLen)[idx] = value;\n return;\n }\n}\n\n/**\n * Reinterpret `bytes` as the typed view for `elementType` and read element\n * `idx`. Mirrors `writeArrayElementAt` -- consumed by `world.pop` to materialise\n * the tail value before the count is decremented.\n */\nexport function readArrayElementAt(\n bytes: Uint8Array,\n idx: number,\n elementType: ManagedArrayElementType,\n): number {\n const buf = bytes.buffer;\n const offset = bytes.byteOffset;\n const byteLen = bytes.byteLength;\n // shared<X> template literals: column-stored as u32 handles, read as\n // Uint32Array. (feat-20260614 M5; replaces retired 'handle<X>' arm.)\n if (elementType.startsWith('shared<')) {\n return new Uint32Array(buf, offset, byteLen >>> 2)[idx] ?? 0;\n }\n switch (elementType) {\n case 'f32':\n return new Float32Array(buf, offset, byteLen >>> 2)[idx] ?? 0;\n case 'f64':\n return new Float64Array(buf, offset, byteLen >>> 3)[idx] ?? 0;\n case 'i32':\n return new Int32Array(buf, offset, byteLen >>> 2)[idx] ?? 0;\n case 'u32':\n case 'enum':\n case 'ref':\n case 'entity':\n return new Uint32Array(buf, offset, byteLen >>> 2)[idx] ?? 0;\n case 'i16':\n return new Int16Array(buf, offset, byteLen >>> 1)[idx] ?? 0;\n case 'u16':\n return new Uint16Array(buf, offset, byteLen >>> 1)[idx] ?? 0;\n case 'i8':\n return new Int8Array(buf, offset, byteLen)[idx] ?? 0;\n case 'u8':\n case 'bool':\n return new Uint8Array(buf, offset, byteLen)[idx] ?? 0;\n }\n return 0;\n}\n","// @forgeax/engine-ecs — World: top-level ECS container.\n//\n// World owns entities, archetypes (via ArchetypeGraph), and component registry.\n// Supports multi-component spawn, despawn (with generation retirement D-08),\n// get/set, addComponent/removeComponent (archetype migration via edges).\n// M3: addSystem / update (DAG schedule) + deferred commands + Resource CRUD.\n//\n// [w6] All 6 public methods return Result<T, EcsError> (AP-8 Layer 1).\n// Construction errors (EntityIndexOverflowError) still throw — they are\n// build-time / infrastructure failures.\n\nimport type { Handle, Result } from '@forgeax/engine-types';\nimport {\n BUILTIN_BASE,\n err,\n isRetiredSlot,\n ok,\n toShared,\n toUnique,\n unwrapHandle,\n} from '@forgeax/engine-types';\nimport { BufferPool } from './buffer-pool';\nimport {\n type ArrayMeta,\n bufferFieldByteLength,\n type Component,\n ComponentCatalog,\n type ComponentSchema,\n componentId,\n componentSchema,\n type InputShapeOf,\n isEntityField,\n isManagedArrayField,\n isManagedBufferField,\n isManagedField,\n type ShapeOf,\n TYPE_METADATA,\n} from './component';\nimport { fillComponentDefaults, validateComponentDataKeys } from './component-default-fallback';\nimport { componentDefinition, expandComponentRequirements } from './component-schema';\nimport { validateManagedArrayValues, validateSharedFieldValues } from './component-value-validate';\nimport { Entity as EntityComponent } from './entity';\nimport {\n ENTITY_MAX_INDEX,\n ENTITY_NULL_RAW,\n type EntityHandle,\n encodeEntity,\n entityGeneration,\n entityIndex,\n} from './entity-handle';\nimport type {\n CommandFailedError,\n ComponentFieldInvalidValueError,\n ComponentNotDefinedError,\n ComponentNumericValueInvalidError,\n DerivedRangeOutOfBoundsError,\n ManagedArrayErrorEnvelope,\n ManagedArrayInvalidValueError,\n ManagedBufferShrinkNotSupportedError,\n RelationshipDetachMismatchError,\n RelationshipMirrorComponentNotRegisteredError,\n RelationshipMirrorFieldTypeMismatchError,\n ScheduleMutationError,\n ScheduleScopeMismatchError,\n SharedKernelEligibilityError,\n SharedKernelFailureError,\n SystemFailedError,\n SystemSetNotRegisteredError,\n TimeConfigInvalidError,\n TimeDeltaInvalidError,\n UniqueRefDoubleReleaseError,\n UniqueRefReleasedError,\n} from './errors';\nimport {\n ChangeEpochExhaustedError,\n ComponentAlreadyPresentError,\n ComponentNotPresentError,\n EntityIndexOverflowError,\n FixedSizeMismatchError,\n ManagedBufferOutOfBoundsError,\n RelationshipSelfCycleError,\n RelationshipTargetReadonlyError,\n RemoveEssentialComponentError,\n StaleEntityError,\n validateEnumFieldValues,\n validateNumericFieldValues,\n WorldPoisonedError,\n} from './errors';\nimport {\n createWorldIdentity,\n healthyWorldExecutionState,\n poisonedWorldExecutionState,\n type WorldExecutionFault,\n type WorldExecutionState,\n} from './execution/shared-kernel';\nimport type { QueryDescriptor } from './query/query';\nimport { createQuery, type Query, type QueryCreationError } from './query/query';\nimport {\n isRelationshipTarget,\n RelationshipIndex,\n type RelationshipTargetComponent,\n relationshipMirror,\n relationshipRole,\n relationshipSource,\n} from './relationship-index';\nimport { createResourceStore, type ResourceStore } from './resource';\nimport { createSchedule, type SystemDescriptor, type SystemSet } from './schedule';\nimport { FixedUpdate, Update } from './schedule-token';\nimport type { SharedRefStore } from './shared-ref-store';\nimport { SharedRefStore as SharedRefStoreImpl } from './shared-ref-store';\nimport { type Archetype, appendArchetypeRow, removeArchetypeRow } from './storage/archetype';\nimport {\n type ArchetypeGraph,\n createArchetypeGraph,\n getAddEdge,\n getOrCreateArchetype,\n getRemoveEdge,\n getTable,\n} from './storage/archetype-graph';\nimport {\n type ChangeTicks,\n copyComponentEpoch,\n markComponentChanged,\n markComponentsAdded,\n readComponentChange,\n removeSparseTag,\n} from './storage/change-detection';\nimport {\n arrayCountColumnName,\n type Column,\n type FieldView,\n normalizeBufferWrite,\n} from './storage/column';\nimport type { StructuralEvidenceInput } from './storage/structural-evidence';\nimport { StructuralEvidenceRing as StructuralEvidenceRingImpl } from './storage/structural-evidence';\nimport { appendTableRow, removeTableRow, type Table } from './storage/table';\nimport {\n createWorldClock,\n DEFAULT_TIME_POLICY,\n FIXED_TIME_RESOURCE_KEY,\n TIME_RESOURCE_KEY,\n type WorldOptions,\n} from './time';\nimport { type UniqueRefStore, UniqueRefStore as UniqueRefStoreImpl } from './unique-ref-store';\nimport {\n spawnCore,\n worldAddChild,\n worldIterAncestors,\n worldIterDescendants,\n worldRemoveChild,\n worldReparent,\n} from './world-entity-lifecycle';\nimport { worldInternal } from './world-internal';\nimport { type WorldRead, worldRead } from './world-read';\nimport {\n worldAddSystem,\n worldAddSystems,\n worldGetResource,\n worldHasResource,\n worldInsertResource,\n worldInspect,\n worldRemoveResource,\n worldRemoveSystem,\n worldReplaceSystem,\n worldScheduleData,\n worldScheduleUsesComponent,\n worldUpdate,\n} from './world-scheduling';\nimport {\n detachWorldInspection,\n elementByteSize,\n readArrayElementAt,\n reinterpretBufferRegion,\n reinterpretSlotBytes,\n writeArrayElementAt,\n} from './world-storage-primitives';\n\n/**\n * Union of all EcsError types that World methods can return via Result.\n * AI users: switch on `.code` for programmatic branching.\n */\nexport type EcsError =\n | CommandFailedError\n | StaleEntityError\n | ComponentNotPresentError\n | ComponentAlreadyPresentError\n | ComponentFieldInvalidValueError\n | ComponentNumericValueInvalidError\n | ManagedArrayInvalidValueError\n | UniqueRefReleasedError\n | UniqueRefDoubleReleaseError\n | ManagedBufferOutOfBoundsError\n | ManagedBufferShrinkNotSupportedError\n | FixedSizeMismatchError\n | RelationshipSelfCycleError\n | RelationshipMirrorComponentNotRegisteredError\n | RelationshipMirrorFieldTypeMismatchError\n | RelationshipDetachMismatchError\n | RelationshipTargetReadonlyError\n | ComponentNotDefinedError\n | RemoveEssentialComponentError\n | SystemSetNotRegisteredError\n | SystemFailedError\n | TimeDeltaInvalidError\n | TimeConfigInvalidError\n | ScheduleScopeMismatchError\n | SharedKernelEligibilityError\n | SharedKernelFailureError\n | DerivedRangeOutOfBoundsError\n | ChangeEpochExhaustedError\n | WorldPoisonedError;\n\n/** Component data for spawn/addComponent: component token + initial values.\n *\n * `data` is `Partial<InputShapeOf<S>>` (feat-20260517 / M2; tweak-20260616\n * input/output split): spawn / addComponent / SceneAsset.instantiate share the\n * SAME shape contract via the layer-2 + layer-3 silent fallback applied inside\n * `writeRow` (`fillComponentDefaults`). The input shape widens\n * `array<scalar, N>` / `array<scalar>` to also accept `readonly number[]`\n * because writeArrayField copies bytes from either shape — AI users can write\n * `times: [0.5]` instead of `new Float32Array([0.5])` boilerplate. Wrong-VALUE\n * fields (e.g. `{ fov: 'bad' }`) still fire field-level TS2322 — mapped-tuple\n * primary inference does not degrade to the \"No overload matches\" wall\n * (AC-03 / C-4). */\nexport interface ComponentData<S extends ComponentSchema = ComponentSchema> {\n component: Component<string, S>;\n data: Partial<InputShapeOf<S>>;\n}\n\ntype WritableComponent<C extends Component> = C extends RelationshipTargetComponent ? never : C;\n\ntype ErrorContext = { readonly systemName: string };\n\n/**\n * Per-archetype summary returned by `world.inspect()`. Sorted ComponentId key\n * (always prefixed by the essential id=0 Entity column, e.g. \"0+2+5+7\"),\n * human-readable component names, live entity count, allocated row capacity.\n */\nexport interface ArchetypeInfo {\n /** Sorted ComponentId key, always prefixed by the id=0 Entity column (e.g. \"0+2+5+7\"). */\n readonly key: string;\n /** Human-readable component names in this archetype. */\n readonly componentNames: string[];\n /** Number of live entities in this archetype. */\n readonly entityCount: number;\n readonly tableId: number;\n}\n\nexport interface TableInfo {\n readonly id: number;\n readonly key: string;\n readonly componentNames: string[];\n readonly entityCount: number;\n readonly capacity: number;\n}\n\n/**\n * Typed diagnostic snapshot of the World state.\n * Returned by `world.inspect()` for programmatic introspection by AI users.\n */\nexport interface WorldInspection {\n /** Total number of live entities. */\n readonly entityCount: number;\n /** Number of archetypes currently allocated. */\n readonly archetypeCount: number;\n /** Per-archetype details. */\n readonly archetypes: ArchetypeInfo[];\n readonly tableCount: number;\n readonly tables: TableInfo[];\n /**\n * Names of components that are currently active in this World — i.e.\n * every distinct component name appearing on at least one non-empty\n * archetype. Collected by walking the archetype graph, so a component\n * that was defined but never spawned into this World does not appear.\n */\n readonly activeComponents: string[];\n /** Number of registered systems. Always equals `systems.length` (M2 derived invariant). */\n readonly systemCount: number;\n /**\n * Per-system summary (M3 — plan-strategy D-8). One entry per\n * registered system, in registration order. The `systemCount` field is\n * preserved as a derived alias of `systems.length` so existing inspector\n * P0 e2e cases that read `systemCount` keep working.\n *\n * `sets` is the list of set names this system belongs to (empty array for\n * systems registered via plain `addSystem` without `addSystems`).\n */\n readonly systems: ReadonlyArray<{ readonly name: string; readonly sets: readonly string[] }>;\n /** Keys of all inserted resources. */\n readonly resourceKeys: string[];\n /** Systems grouped by their schedule token. */\n readonly schedules: ReadonlyArray<{\n readonly schedule: import('./schedule-token').ScheduleToken;\n readonly systems: ReadonlyArray<{ readonly name: string; readonly sets: readonly string[] }>;\n }>;\n /** Count systems in one explicit schedule. */\n scheduleSystemCount(schedule: import('./schedule-token').ScheduleToken): number;\n}\n\n/** JSON-safe schedule graph and access metadata returned by `world.scheduleData()`. */\nexport interface WorldScheduleQueryData {\n readonly with: readonly string[];\n readonly without: readonly string[];\n readonly optional: readonly string[];\n readonly changed: readonly string[];\n readonly added: readonly string[];\n}\n\n/** JSON-safe system registration and access metadata. */\nexport interface WorldScheduleSystemData {\n readonly name: string;\n readonly sets: readonly string[];\n readonly before: readonly string[];\n readonly after: readonly string[];\n readonly queries: readonly WorldScheduleQueryData[];\n readonly resources: readonly string[];\n}\n\n/** JSON-safe system-set membership and ordering metadata. */\nexport interface WorldScheduleSetData {\n readonly name: string;\n readonly members: readonly string[];\n readonly before: readonly string[];\n readonly after: readonly string[];\n readonly chained: boolean;\n}\n\n/** JSON-safe projection of one explicit World schedule. */\nexport interface WorldScheduleData {\n readonly name: string;\n readonly systems: readonly WorldScheduleSystemData[];\n readonly systemSets: readonly WorldScheduleSetData[];\n readonly dependencies: readonly (readonly [string, string])[];\n}\n\n/**\n * Internal record describing where an entity lives.\n *\n * Liveness (feat-20260602 / plan-strategy D-4): the former `alive` boolean was\n * absorbed into `generation`. A despawn unconditionally bumps `generation` (so a\n * stale handle's `gen` no longer matches), and `gen > 255` retires the slot\n * permanently (it is never pushed back to `freeIndices`). The single liveness\n * predicate is therefore \"handle gen matches AND archetypeId !== -1\" -- see\n * `World.recordIsLive`. A deferred-spawn allocation is \"pending\" when\n * archetypeId === -1 (not yet materialized into an archetype row). During a\n * failed append, `archetypeId` is reserved before the first storage write and\n * `archetypeRow` remains `-1`; that marker prevents command abort from\n * reclaiming a reservation that may already have touched table storage.\n */\nexport interface EntityRecord {\n generation: number;\n archetypeId: number; // -1 if no archetype (pending / despawned)\n archetypeRow: number;\n}\n\n/**\n * The World owns the component registry, archetype graph, entity index table,\n * and recyclable free-list.\n */\nexport class World {\n readonly [worldRead]: WorldRead;\n // ── Internal state ──\n\n /** World-local state is kept together so one owner closes each mutation. */\n private executionState: WorldExecutionState = healthyWorldExecutionState(createWorldIdentity());\n private readonly graph: ArchetypeGraph;\n private readonly records: EntityRecord[] = [];\n private readonly freeIndices: number[] = [];\n /** BufferPool for schema-declared variable buffers and arrays. */\n private readonly bufferPool = new BufferPool();\n /** Per-World managed unique-ref store used by lifecycle mutations. */\n private readonly uniqueRefs: UniqueRefStore = new UniqueRefStoreImpl();\n /** Per-World shared-ref store; public read-only for direct handle operations. */\n readonly sharedRefs: SharedRefStore = new SharedRefStoreImpl();\n private readonly componentMutationEpochs: number[] = [];\n private readonly structuralEvidence = new StructuralEvidenceRingImpl();\n /** One packed reverse index per relationship source component. */\n private readonly relationshipIndexes = new Map<number, RelationshipIndex>();\n private mutationEpoch = 0;\n private structureEpoch = 0;\n /** Keep identity as a prototype getter; it is a diagnostic capability, not enumerable state. */\n get identity() {\n return this.executionState.identity;\n }\n /** Plugin-owned component discovery scoped to this World and removed through leases. */\n readonly components = new ComponentCatalog((component) => this.componentIsInUse(component));\n /** DAG schedules for the two built-in execution scopes. */\n private readonly schedules = new Map([\n [Update, createSchedule(Update)],\n [FixedUpdate, createSchedule(FixedUpdate)],\n ]);\n /** Resource store: typed key-value global singletons. */\n private readonly resources: ResourceStore = createResourceStore();\n private readonly clock: ReturnType<typeof createWorldClock>;\n /** Remainder carried between fixed-step runs. */\n private fixedAccumulator = 0;\n constructor(options: WorldOptions = {}) {\n this.graph = createArchetypeGraph(options.storage === 'shared');\n this.clock = createWorldClock({ ...DEFAULT_TIME_POLICY, ...options.time });\n this.resources.entries.set(TIME_RESOURCE_KEY, {\n value: this.clock.time,\n added: 0,\n changed: 0,\n });\n this.resources.entries.set(FIXED_TIME_RESOURCE_KEY, {\n value: this.clock.fixed,\n added: 0,\n changed: 0,\n });\n this[worldInternal] = {\n allocatePendingEntity: this.allocatePendingEntity.bind(this),\n cancelPendingEntity: this.cancelPendingEntity.bind(this),\n getArrayView: this.getArrayView.bind(this),\n getBufferPool: () => this.bufferPool,\n getClockWriter: () => this.clock.writer,\n getComponentChange: this.internalgetComponentChange.bind(this),\n getComponentMutationEpochs: () => this.componentMutationEpochs,\n getEntityArchetype: this.internalgetEntityArchetype.bind(this),\n getFixedAccumulator: () => this.fixedAccumulator,\n getGraph: () => this.graph,\n getMutationEpoch: () => this.mutationEpoch,\n getQueryRow: (entity, component) =>\n this.get(entity, component) as Result<Record<string, unknown>, EcsError>,\n getRecords: () => this.records,\n getRelationshipEpoch: (component) =>\n this.relationshipIndexes.get(componentId(component))?.epoch ?? 0,\n getRelationshipTargetEntities: this.relationshipTargetEntries.bind(this),\n getResources: () => this.resources,\n getSchedule: (token) => this.schedules.get(token),\n getSchedules: () => this.schedules,\n getSharedRefs: () => this.sharedRefs,\n getStructureEpoch: this.getStructureEpoch.bind(this),\n getStructuralEvidence: () => this.structuralEvidence,\n lookupAlive: this.lookupAlive.bind(this),\n markComponentChanged: this.internalmarkComponentChanged.bind(this),\n markComponentRangeChanged: this.internalmarkComponentRangeChanged.bind(this),\n materializeEntity: this.materializeEntity.bind(this),\n materializePendingEntity: this.materializePendingEntity.bind(this),\n nextMutationEpoch: this.internalnextMutationEpoch.bind(this),\n poisonExecution: this.internalpoisonExecution.bind(this),\n publishDerivedRange: this.internalpublishDerivedRange.bind(this),\n preflightComponentData: this.preflightComponentData.bind(this),\n readRow: this.readRow.bind(this),\n recordIsLive: this.recordIsLive.bind(this),\n routeError: this.routeError.bind(this),\n restoreMutationEpoch: this.internalrestoreMutationEpoch.bind(this),\n setFixedAccumulator: (value) => {\n this.fixedAccumulator = value;\n },\n setQueryRow: this.internalsetQueryRow.bind(this),\n };\n this[worldRead] = {\n getFieldValue: this.internalgetFieldValue.bind(this),\n getArrayLength: this.internalgetArrayLength.bind(this),\n getArrayElement: this.internalgetArrayElement.bind(this),\n };\n }\n\n /** Immutable integrity state for execution coordinators and headless callers. */\n get execution(): WorldExecutionState {\n return this.executionState;\n }\n\n /** Resolve a schedule token owned by this World realm without package singleton identity. */\n scheduleToken(\n name: import('./schedule-token').ScheduleName,\n ): import('./schedule-token').ScheduleToken {\n if (name === 'Update') return Update;\n if (name === 'FixedUpdate') return FixedUpdate;\n return FixedUpdate;\n }\n\n /** Seal the first execution fault; application code recovers with a new World. */\n private internalpoisonExecution(fault: WorldExecutionFault): void {\n if (this.executionState.health === 'healthy') {\n this.executionState = poisonedWorldExecutionState(this.identity, fault);\n }\n }\n\n /**\n * A poisoned identity is diagnostic evidence, not a mutable recovery path.\n * Public entity mutation therefore returns the same structured fence as\n * `update()` instead of allocating a new reservation or touching a partial\n * row. Recovery remains construction of a fresh World.\n */\n private poisonedResult<T>(): Result<T, EcsError> | undefined {\n if (this.executionState.health !== 'poisoned') return undefined;\n return err(new WorldPoisonedError(this.identity, this.executionState.fault));\n }\n\n query<\n const R extends readonly Component[] = readonly [],\n const W extends readonly Component[] = readonly [],\n const O extends readonly Component[] = readonly [],\n >(descriptor: QueryDescriptor<R, W, O>): Result<Query<R, W, O>, QueryCreationError> {\n return createQuery(this, descriptor);\n }\n\n // ──────────────────────────────────────────────────────────────────────────\n // Internal access — query engine\n // ──────────────────────────────────────────────────────────────────────────\n\n private componentIsInUse(component: Component): boolean {\n if (\n this.graph.archetypes.some(\n (archetype) =>\n archetype.size > 0 && archetype.components.some((candidate) => candidate === component),\n )\n ) {\n return true;\n }\n return worldScheduleUsesComponent(this, component);\n }\n\n private recordStructuralEvidence(evidence: StructuralEvidenceInput): void {\n this.structuralEvidence.append(evidence);\n }\n\n /** Resolve current logical identity for a packed entity handle. */\n private internalgetEntityArchetype(entity: EntityHandle): Archetype | undefined {\n const record = this.records[entityIndex(entity)];\n if (!this.recordIsLive(record, entityGeneration(entity))) return undefined;\n return this.graph.archetypes[record.archetypeId];\n }\n\n /** Component change state for query filters. */\n private internalgetComponentChange(\n entity: EntityHandle,\n componentId: number,\n ): ChangeTicks | undefined {\n const record = this.records[entityIndex(entity)];\n if (!this.recordIsLive(record, entityGeneration(entity))) return undefined;\n return readComponentChange(this.graph, record, entity, componentId);\n }\n\n /** Allocate one epoch after a mutation has succeeded. */\n private internalnextMutationEpoch(): number {\n if (this.mutationEpoch >= Number.MAX_SAFE_INTEGER) {\n throw new ChangeEpochExhaustedError(this.mutationEpoch);\n }\n this.mutationEpoch += 1;\n return this.mutationEpoch;\n }\n\n private internalrestoreMutationEpoch(epoch: number): void {\n this.mutationEpoch = epoch;\n }\n\n private internalpublishDerivedRange(\n table: ArchetypeGraph['tables'][number],\n componentId: number,\n rowStart: number,\n rowCount: number,\n epoch: number,\n ): void {\n const epochs = table.storage.get(componentId)?.epochs;\n if (epochs === undefined) {\n throw new Error(`Derived component ${componentId} is not in the table.`);\n }\n epochs.changed.fill(epoch, rowStart, rowStart + rowCount);\n this.componentMutationEpochs[componentId] = epoch;\n }\n\n /** Record one successful structural mutation. */\n private advanceStructureEpoch(): void {\n this.structureEpoch += 1;\n }\n\n /** Current structural revision for mounted World projections. */\n getStructureEpoch(): number {\n return this.structureEpoch;\n }\n\n /** Mark one mutation's component instances with a shared epoch. */\n private internalmarkComponentsAdded(entity: EntityHandle, componentIds: readonly number[]): void {\n const record = this.records[entityIndex(entity)];\n if (!this.recordIsLive(record, entityGeneration(entity))) return;\n const epoch = this.internalnextMutationEpoch();\n markComponentsAdded(this.graph, record, entity, componentIds, epoch);\n for (const componentId of componentIds) {\n this.componentMutationEpochs[componentId] = epoch;\n }\n }\n\n /** Mark an existing component as changed at the current tick. */\n private internalmarkComponentChanged(entity: EntityHandle, componentId: number): void {\n const record = this.records[entityIndex(entity)];\n if (!this.recordIsLive(record, entityGeneration(entity))) return;\n let epoch: number | undefined;\n markComponentChanged(this.graph, record, entity, componentId, () => {\n epoch = this.internalnextMutationEpoch();\n return epoch;\n });\n if (epoch !== undefined) {\n this.componentMutationEpochs[componentId] = epoch;\n }\n }\n\n /** Mark one contiguous component range with a single epoch. */\n private internalmarkComponentRangeChanged(\n table: ArchetypeGraph['tables'][number],\n componentId: number,\n rowStart: number,\n rowCount: number,\n ): void {\n const epochs = table.storage.get(componentId)?.epochs;\n if (epochs === undefined || rowCount === 0) return;\n const epoch = this.internalnextMutationEpoch();\n epochs.changed.fill(epoch, rowStart, rowStart + rowCount);\n this.componentMutationEpochs[componentId] = epoch;\n }\n\n /** Query facade write after the facade has already marked evidence. */\n private internalsetQueryRow(\n entity: EntityHandle,\n component: Component,\n value: Record<string, unknown>,\n ): Result<void, EcsError> {\n const result = this.set(entity, component, value as never, false);\n if (result.ok && relationshipRole(component)?.kind === 'source') {\n this.markComponentChanged(entity, component);\n }\n return result;\n }\n\n /** Return resource change ticks for diagnostics and resource-driven systems. */\n getResourceChange(name: string): ChangeTicks | undefined {\n const entry = this.resources.entries.get(name);\n return entry === undefined ? undefined : { added: entry.added, changed: entry.changed };\n }\n\n /** Route an expected internal failure through the host-owned error channel. */\n private routeError(err: unknown, ctx?: ErrorContext): void {\n // Internal expected failures are reported without becoming a second\n // schedule or terminal hook. The host owns fatal frame policy.\n console.error(`[${ctx?.systemName ?? 'World'}]`, err);\n }\n\n // ──────────────────────────────────────────────────────────────────────────\n // System registration + update (M3)\n // ──────────────────────────────────────────────────────────────────────────\n\n /**\n * Register a system with query descriptor and optional ordering constraints.\n *\n * `const Qs` mirrors the free `addSystem` signature so the call-site\n * `queries` tuple is locked literal-form, letting `descriptor.fn`'s first\n * parameter recover per-query row access shapes (S-5, KD-3 — class method\n * generic, not free function double track).\n *\n * @example\n * ```ts\n * const Position = defineComponent('Position', { x: 'f32', y: 'f32' });\n * const world = new World();\n * world.addSystem(Update, {\n * name: 'read-pos',\n * queries: [{ with: [Position] }],\n * fn: (world, queries) => { void world; for (const row of queries[0]) { void row.entity; } },\n * });\n * ```\n */\n addSystem<const Qs extends ReadonlyArray<QueryDescriptor>>(\n schedule: import('./schedule-token').ScheduleToken,\n descriptor: SystemDescriptor<Qs>,\n ): Result<void, ScheduleScopeMismatchError> {\n return worldAddSystem(this, schedule, descriptor);\n }\n\n /**\n * Remove a registered system by name (M2 — plan-strategy D-3).\n *\n * Returns `Result<void, ScheduleMutationError>`:\n * - ok branch: the slot is dropped and the schedule will rebuild on the\n * next `update()`.\n * - err branch with `.code === 'system-before-unknown'`: no system carries\n * this name; `.detail.candidates` lists the registered names.\n *\n * Designed to support `@forgeax/engine-remote`'s typed `injectSystem` /\n * `removeSystem` channel and the WS-disconnect reverse-remove path.\n *\n * @example\n * ```ts\n * const r = world.removeSystem(Update, 'movement');\n * if (!r.ok) console.error(r.error.code, r.error.detail.candidates);\n * ```\n */\n removeSystem(\n schedule: import('./schedule-token').ScheduleToken,\n name: string,\n ): Result<void, ScheduleMutationError | ScheduleScopeMismatchError> {\n return worldRemoveSystem(this, schedule, name);\n }\n\n /**\n * Replace a registered system in-place (M2 — plan-strategy D-3 atomic semantics).\n *\n * Overwrites the descriptor stored under `name` while preserving the\n * registration slot — `before / after` references that target this name\n * remain bound.\n *\n * Returns `Result<void, ScheduleMutationError>`:\n * - ok branch: descriptor swapped, schedule marked dirty.\n * - err branch with `.code === 'system-before-unknown'`: no system carries\n * this name; use `addSystem(descriptor)` to register a new one instead.\n *\n * @example\n * ```ts\n * const r = world.replaceSystem(Update, 'movement', {\n * name: 'movement',\n * queries: [{ with: [Position] }],\n * fn: (world, queryResults) => { ... },\n * });\n * ```\n */\n replaceSystem<const Qs extends ReadonlyArray<QueryDescriptor>>(\n schedule: import('./schedule-token').ScheduleToken,\n name: string,\n descriptor: SystemDescriptor<Qs>,\n ): Result<void, ScheduleMutationError | ScheduleScopeMismatchError> {\n return worldReplaceSystem(this, schedule, name, descriptor);\n }\n\n /**\n * Batch-register systems to a set. Validates the set token before writing.\n *\n * - First call for a system name: registers it via the existing `addSystem` path.\n * - Subsequent calls: only adds the system name to the set's members (dedup).\n *\n * Returns `Result.err` with `SystemSetNotRegisteredError` if the set token\n * fails identity validation.\n *\n * @example\n * ```ts\n * const GameplaySet = defineSystemSet({ name: 'gameplay' });\n * const world = new World();\n * const r = world.addSystems(Update, GameplaySet, [movement, collision]);\n * if (!r.ok) console.error(r.error.code, r.error.hint);\n * ```\n */\n addSystems<const Qs extends ReadonlyArray<QueryDescriptor>>(\n schedule: import('./schedule-token').ScheduleToken,\n set: SystemSet,\n systems: ReadonlyArray<SystemDescriptor<Qs>>,\n ): Result<void, SystemSetNotRegisteredError | ScheduleScopeMismatchError> {\n return worldAddSystems(this, schedule, set, systems);\n }\n\n /**\n * Execute one frame: run all systems in DAG order, then flush deferred commands.\n * Empty world (no systems) completes silently (E-09).\n *\n * @example\n * ```ts\n * const Position = defineComponent('Position', { x: 'f32', y: 'f32' });\n * const world = new World();\n * world.spawn({ component: Position, data: { x: 0, y: 0 } }).unwrap();\n * world.update(); // run all systems + flush commands\n * ```\n */\n update(\n deltaSeconds = 0,\n ): Result<\n void,\n | TimeDeltaInvalidError\n | TimeConfigInvalidError\n | ScheduleScopeMismatchError\n | WorldPoisonedError\n | CommandFailedError\n | SystemFailedError\n | import('./errors').CyclicDependencyError\n | SharedKernelFailureError\n > {\n return worldUpdate(this, deltaSeconds);\n }\n\n // ──────────────────────────────────────────────────────────────────────────\n // Resource CRUD (M3)\n // ──────────────────────────────────────────────────────────────────────────\n\n /** Insert or overwrite a resource (idempotent, E-13). */\n insertResource<T>(key: string | { readonly name: string }, value: T): void {\n worldInsertResource(this, key, value);\n }\n\n /**\n * Get a resource by key.\n * @throws ResourceNotFoundError if key not found (E-14).\n */\n getResource(key: typeof import('./time').Time): import('./time').TimeResource;\n getResource(key: typeof import('./time').FixedTime): import('./time').FixedTimeResource;\n getResource<T>(key: string | { readonly name: string }): T;\n getResource<T>(key: string | { readonly name: string }): T {\n return worldGetResource<T>(this, key);\n }\n\n /** Check if a resource exists. */\n hasResource(key: string | { readonly name: string }): boolean {\n return worldHasResource(this, key);\n }\n\n /** Remove a resource by key. */\n removeResource(key: string | { readonly name: string }): void {\n worldRemoveResource(this, key);\n }\n\n // ──────────────────────────────────────────────────────────────────────────\n // Inspection / diagnostics (M4)\n // ──────────────────────────────────────────────────────────────────────────\n\n /**\n * Return a typed diagnostic snapshot of the World state.\n * All fields are non-undefined. Useful for AI users to programmatically\n * introspect entity count, archetypes, registered components, systems,\n * and resources without console.log or a debugger.\n *\n * @example\n * ```ts\n * const Position = defineComponent('Position', { x: 'f32', y: 'f32' });\n * const world = new World();\n * world.spawn({ component: Position, data: { x: 0, y: 0 } }).unwrap();\n * const snap = world.inspect();\n * console.log(snap.entityCount, snap.activeComponents);\n * ```\n */\n inspect(): WorldInspection {\n return detachWorldInspection(worldInspect(this));\n }\n\n /** Return the registered schedule graphs and their declared access metadata. */\n scheduleData(): ReadonlyArray<WorldScheduleData> {\n return worldScheduleData(this);\n }\n\n // ──────────────────────────────────────────────────────────────────────────\n // Managed-ref public API (feat-20260528-rapier-physics M1 / t4)\n // ──────────────────────────────────────────────────────────────────────────\n\n /**\n * Allocate a standalone managed reference handle with an optional release\n * callback. Returns a branded {@link Handle}<Target, 'unique'> that can be\n * stored in schema-vocab `ref<T>` fields or resolved through\n * {@link UniqueRefStore.resolve} (via `world.get` on a component with\n * `ref<T>` fields).\n *\n * When the handle is released (despawn / removeComponent / set-overwrite),\n * the `onRelease` callback fires with the payload (captured on the stack);\n * by then the slot's bookkeeping (callback table, payload map, freelist) is\n * already cleared, so a *throwing* `onRelease` re-propagates from the first\n * `release` call without leaving the store inconsistent — a second `release`\n * of the same handle returns `UniqueRefDoubleReleaseError` as expected. RAII\n * cleanup semantics preserved (plan-strategy D-5; throw-safety AC-01/02).\n *\n * Handles are *operational, not persistent*: caching them across release\n * boundaries (despawn / removeComponent / set-overwrite) is undefined\n * behavior — the same `u32` may silently resolve to a freshly allocated\n * payload after slot reuse. See `packages/ecs/README.md` § \"Managed handles\n * are operational, not persistent\" and `docs/specs/2026-06-14-ecs-managed-\n * lifecycle-ssot-design.md` § 3.3.\n *\n * @typeParam Target - phantom string branding the handle (type-level only).\n * @typeParam T - the payload type stored alongside the handle.\n * @param target - phantom target string (type-level discriminant).\n * @param payload - the value to store. Identity-stable until release.\n * @param onRelease - optional cleanup hook called with the payload on release.\n * @returns a branded `Handle<Target, 'unique'>` u32.\n *\n * @example\n * ```ts\n * const world = new World();\n * const handle = world.allocUniqueRef<'PhysicsBody', RigidBodyHandle>(\n * 'PhysicsBody',\n * rapierHandle,\n * (h) => rapierWorld.removeRigidBody(h),\n * );\n * const Holder = defineComponent('Holder', { body: 'unique<PhysicsBody>' });\n * world.spawn(Holder, { body: handle });\n * // Despawn triggers onRelease -> Rapier body is cleaned up.\n * ```\n */\n allocUniqueRef<Target extends string, T>(\n target: Target,\n payload: T,\n onRelease?: (payload: T) => void,\n ): Handle<Target, 'unique'> {\n return this.uniqueRefs.alloc(target, payload, onRelease);\n }\n\n /**\n * Allocate a shared (refcount-tracked) handle through the per-World\n * {@link SharedRefStore}. Returns a `Handle<Target, 'shared'>` u32 with\n * rc=1 (the alloc-grant). Consumers retain/release via `world.sharedRefs`.\n *\n * Final release publishes structured evidence through the owning\n * {@link SharedRefStore}; payload disposal remains with the\n * renderer/assets/plugin owner and is not a user callback.\n *\n * Intended for asset-registry-style producers — anything whose lifecycle\n * is shared across multiple holders (ECS components + external systems).\n * The single-holder one-shot release pattern stays on\n * {@link World.allocUniqueRef} (`Handle<T, 'unique'>`).\n *\n * @typeParam Target - phantom string branding the handle (type-level only).\n * @typeParam T - the payload type stored alongside the handle.\n * @param target - phantom target string (type-level discriminant).\n * @param payload - the value to store. Identity-stable until final release.\n * @returns a branded `Handle<Target, 'shared'>` u32 with rc=1.\n *\n * @example\n * ```ts\n * const world = new World();\n * const handle = world.allocSharedRef<'MaterialAsset', MaterialPayload>(\n * 'MaterialAsset',\n * payload,\n * );\n * const M = defineComponent('M', { asset: 'shared<MaterialAsset>' });\n * world.spawn({ component: M, data: { asset: handle } });\n * // The write-barrier dispatch retains/releases automatically on spawn / despawn.\n * ```\n */\n allocSharedRef<Target extends string, T>(target: Target, payload: T): Handle<Target, 'shared'> {\n return this.sharedRefs.alloc(target, payload);\n }\n\n /**\n * Return one producer-owned shared handle per `(target, payload object)` in\n * this World. Repeated discovery does not retain; ECS holders still retain\n * and release through the normal write barrier. Asset catalogues use this\n * when repeated scene instantiation resolves the same catalogued payload.\n * Use {@link World.allocSharedRef} for independent resources or deleters.\n */\n internSharedRef<Target extends string, T extends object>(\n target: Target,\n payload: T,\n ): Handle<Target, 'shared'> {\n return this.sharedRefs.intern(target, payload);\n }\n\n // ──────────────────────────────────────────────────────────────────────────\n // ──────────────────────────────────────────────────────────────────────────\n // Component access and storage — World owns mutation state and coordination.\n // Independent table/column algorithms remain private methods so all mutation\n // paths share one state owner and publication boundary.\n // ──────────────────────────────────────────────────────────────────────────\n\n private relationshipTargetWriteError(\n component: Component,\n operation: string,\n ): Result<never, EcsError> {\n return err(new RelationshipTargetReadonlyError(component.name, operation));\n }\n\n private relationshipTargetPayloadWrites(data: Readonly<Record<string, unknown>>): boolean {\n return Object.values(data).some((value) => {\n if (Array.isArray(value)) return value.length > 0;\n if (ArrayBuffer.isView(value)) return value.byteLength > 0;\n return true;\n });\n }\n\n /** Test live component presence without constructing a Result error. */\n hasComponent(entity: EntityHandle, component: Component): boolean {\n const archetype = this.internalgetEntityArchetype(entity);\n return (\n archetype?.components.some(\n (candidate) => componentId(candidate) === componentId(component),\n ) === true\n );\n }\n\n private table(archetype: Archetype): Table {\n return getTable(this.graph, archetype.tableId);\n }\n\n private tableRow(record: EntityRecord): number {\n return this.graph.archetypes[record.archetypeId]?.rows[record.archetypeRow] ?? -1;\n }\n\n private markComponentChanged(entity: EntityHandle, component: Component): void {\n this.internalmarkComponentChanged(entity, componentId(component));\n }\n\n private relationshipIndex(component: Component): RelationshipIndex | undefined {\n if (relationshipRole(component)?.kind !== 'source') return undefined;\n let index = this.relationshipIndexes.get(componentId(component));\n if (index === undefined) {\n index = new RelationshipIndex();\n this.relationshipIndexes.set(componentId(component), index);\n }\n return index;\n }\n\n /** Read the World-owned materialized target array; never consults a shadow list. */\n private relationshipTargetEntries(\n source: Component,\n target: EntityHandle,\n ): readonly EntityHandle[] {\n const role = relationshipRole(source);\n if (role?.kind !== 'source') return [];\n const mirror = relationshipMirror(source);\n if (mirror === undefined) return [];\n // Internal relationship maintenance may read the live mirror view\n // directly; the public `get` path clones target arrays to keep them\n // read-only. Avoid allocating a component snapshot on every append or\n // removal while retaining the same World-owned storage authority.\n return (\n (this.getArrayView(target, mirror, role.targetField) as EntityHandle[] | undefined) ?? []\n );\n }\n\n /** Read a relationship target length without materialising its array view. */\n private relationshipTargetLength(source: Component, target: EntityHandle): number {\n const role = relationshipRole(source);\n if (role?.kind !== 'source') return 0;\n const mirror = relationshipMirror(source);\n if (mirror === undefined) return 0;\n return this.internalgetArrayLength(target, mirror, role.targetField) ?? 0;\n }\n\n private relationshipTargetEntity(\n component: Component,\n value: Record<string, unknown>,\n ): EntityHandle | null {\n for (const [fieldName, fieldType] of Object.entries(componentSchema(component))) {\n if (isEntityField(fieldType)) {\n const raw = value[fieldName];\n if (raw === null || raw === undefined) return null;\n const asNum = raw as number;\n if (asNum === ENTITY_NULL_RAW) return null;\n return asNum as EntityHandle;\n }\n }\n return null;\n }\n\n private preflightComponentFieldValues(\n holder: EntityHandle | null,\n componentData: ComponentData,\n ): Result<void, EcsError> {\n const data = componentData.data as Record<string, unknown>;\n const arrayError = validateManagedArrayValues(componentData.component, data);\n if (arrayError !== null) return err(arrayError as unknown as EcsError);\n const sharedError = validateSharedFieldValues(componentData.component, data);\n if (sharedError !== null) return err(sharedError as unknown as EcsError);\n const numericError = validateNumericFieldValues(\n componentData.component,\n data,\n holder === null ? undefined : (holder as number),\n );\n if (numericError !== null) return err(numericError as unknown as EcsError);\n return ok(undefined);\n }\n\n /**\n * Validate one structural component payload without touching archetypes,\n * columns, relationship mirrors, epochs, or managed-reference stores.\n * CommandBuffer uses this same owner-level gate as the direct World facade;\n * the optional pending set lets a batch refer to an entity reserved earlier\n * in that batch without mistaking it for a stale live handle.\n */\n private preflightComponentData(\n holder: EntityHandle | null,\n componentData: ComponentData,\n pendingEntities?: ReadonlySet<number>,\n unavailableEntities?: ReadonlySet<number>,\n ): Result<void, EcsError> {\n const data = componentData.data as Record<string, unknown>;\n const keyError = validateComponentDataKeys(componentData.component, data);\n if (keyError !== null) return err(keyError as unknown as EcsError);\n const valuePreflight = this.preflightComponentFieldValues(holder, componentData);\n if (!valuePreflight.ok) return valuePreflight;\n if (\n isRelationshipTarget(componentData.component) &&\n this.relationshipTargetPayloadWrites(data)\n ) {\n return err(new RelationshipTargetReadonlyError(componentData.component.name, 'command'));\n }\n\n const filled = fillComponentDefaults(componentData.component, data);\n const enumError = validateEnumFieldValues(\n componentData.component,\n filled,\n holder === null ? undefined : (holder as number),\n );\n if (enumError !== null) return err(enumError as unknown as EcsError);\n\n const role = relationshipRole(componentData.component as Component);\n if (role?.kind !== 'source') return ok(undefined);\n const target = this.relationshipTargetEntity(componentData.component as Component, filled);\n if (target === null) return ok(undefined);\n\n const targetRaw = target as unknown as number;\n if (unavailableEntities?.has(targetRaw) === true) {\n const targetRecord = this.records[entityIndex(target)];\n return err(\n new StaleEntityError(target as number, entityIndex(target), entityGeneration(target), {\n operation: 'relationship-insert',\n component: componentData.component.name,\n expectedGeneration: entityGeneration(target),\n actualGeneration: targetRecord?.generation ?? -1,\n }),\n );\n }\n const targetIsPending = pendingEntities?.has(targetRaw) === true;\n const targetRecord = this.records[entityIndex(target)];\n const actualGeneration = targetRecord?.generation ?? -1;\n const targetLive = this.recordIsLive(targetRecord, entityGeneration(target));\n const holderIsPending =\n holder === null || pendingEntities?.has(holder as unknown as number) === true;\n if (!targetIsPending && !targetLive && !holderIsPending) {\n return err(\n new StaleEntityError(target as number, entityIndex(target), entityGeneration(target), {\n operation: 'relationship-insert',\n component: componentData.component.name,\n expectedGeneration: entityGeneration(target),\n actualGeneration,\n }),\n );\n }\n\n // A pending holder has no row to walk yet. Once materialized, its target\n // is still checked by the same source-side relationship callback.\n if (holder === null || pendingEntities?.has(holder as unknown as number) === true) {\n return ok(undefined);\n }\n const roleAllowsSelf = role?.kind === 'source' && role.allowSelf;\n if (holder === target && !roleAllowsSelf) {\n return err(\n new RelationshipSelfCycleError(\n componentData.component.name,\n holder as number,\n target as number,\n ),\n );\n }\n\n const cycleHit =\n holder === target && roleAllowsSelf\n ? null\n : this.relationshipCycleHit(componentData.component as Component, target, holder);\n if (cycleHit !== null) {\n return err(\n new RelationshipSelfCycleError(\n componentData.component.name,\n holder as number,\n cycleHit as number,\n ),\n );\n }\n return ok(undefined);\n }\n\n private relationshipCycleHit(\n holderComponent: Component,\n start: EntityHandle,\n holder: EntityHandle,\n ): EntityHandle | null {\n const visited = new Set<number>();\n let current = start;\n while (true) {\n if (current === holder) return current;\n const raw = current as unknown as number;\n if (visited.has(raw)) return null;\n visited.add(raw);\n const record = this.records[entityIndex(current)];\n if (!this.recordIsLive(record, entityGeneration(current))) return null;\n const archetype = this.graph.archetypes[record.archetypeId];\n if (\n !archetype?.components.some(\n (candidate) => componentId(candidate) === componentId(holderComponent),\n )\n ) {\n return null;\n }\n const value = this.readRow(archetype, holderComponent, this.tableRow(record)) as Record<\n string,\n unknown\n >;\n const next = this.relationshipTargetEntity(holderComponent, value);\n if (next === null) return null;\n current = next;\n }\n }\n\n /**\n * Commit a relationship source through its owner-specific write path.\n * Relationship sources have one entity field, so dispatching before the\n * generic field loop avoids paying the ordinary component-field traversal on\n * every hierarchy reparent while keeping mirror/index publication here.\n */\n private setRelationshipSource(\n entity: EntityHandle,\n component: Component,\n value: Record<string, unknown>,\n record: EntityRecord,\n arch: Archetype,\n markChanged: boolean,\n ): Result<void, EcsError> {\n const role = relationshipRole(component);\n if (role?.kind !== 'source') return ok(undefined);\n\n const row = this.tableRow(record);\n const currentValue = this.readRow(arch, component, row) as Record<string, unknown>;\n const valuePreflight = this.preflightComponentFieldValues(entity, {\n component,\n data: value as Partial<InputShapeOf<ComponentSchema>>,\n });\n if (!valuePreflight.ok) return valuePreflight;\n\n const mergedValue = {\n ...currentValue,\n ...value,\n };\n const enumError = validateEnumFieldValues(component, mergedValue, entity as number);\n if (enumError !== null) return err(enumError as unknown as EcsError);\n\n const oldRelationshipTarget = this.relationshipTargetEntity(component, currentValue);\n const nextRelationshipTarget = this.relationshipTargetEntity(component, mergedValue);\n const relationshipChanged = oldRelationshipTarget !== nextRelationshipTarget;\n let preparedMirrorAdded: boolean | undefined;\n\n if (relationshipChanged && nextRelationshipTarget !== null) {\n // Keep the hot source-write path equivalent to the public relationship\n // preflight, without re-running the generic component-data validator\n // over the already-read/merged source row.\n const targetRecord = this.records[entityIndex(nextRelationshipTarget)];\n const actualGeneration = targetRecord?.generation ?? -1;\n if (!this.recordIsLive(targetRecord, entityGeneration(nextRelationshipTarget))) {\n return err(\n new StaleEntityError(\n nextRelationshipTarget as number,\n entityIndex(nextRelationshipTarget),\n entityGeneration(nextRelationshipTarget),\n {\n operation: 'relationship-insert',\n component: component.name,\n expectedGeneration: entityGeneration(nextRelationshipTarget),\n actualGeneration,\n },\n ),\n );\n }\n if (entity === nextRelationshipTarget && !role.allowSelf) {\n return err(\n new RelationshipSelfCycleError(\n component.name,\n entity as number,\n nextRelationshipTarget as number,\n ),\n );\n }\n const cycleHit =\n entity === nextRelationshipTarget\n ? null\n : this.relationshipCycleHit(component, nextRelationshipTarget, entity);\n if (cycleHit !== null) {\n return err(\n new RelationshipSelfCycleError(component.name, entity as number, cycleHit as number),\n );\n }\n const prepared = this.prepareRelationshipInsert(component, mergedValue);\n if (!prepared.ok) return prepared;\n preparedMirrorAdded = prepared.value;\n }\n\n // Prepare first, then detach/attach the mirror, and only then publish the\n // source scalar. A later relationship error can therefore poison the same\n // World without exposing a source value that disagrees with its mirror.\n if (relationshipChanged && oldRelationshipTarget !== null) {\n const removed = this.relationshipOnRemove(entity, component, currentValue);\n if (!removed.ok) {\n this.poisonAfterEntityMutation('World.set', removed.error);\n return removed;\n }\n }\n if (relationshipChanged && nextRelationshipTarget !== null) {\n const inserted = this.relationshipOnInsert(\n entity,\n component,\n mergedValue,\n preparedMirrorAdded,\n );\n if (!inserted.ok) {\n this.poisonAfterEntityMutation('World.set', inserted.error);\n return inserted;\n }\n }\n\n const fieldCols = this.table(arch).storage.get(componentId(component))?.fields;\n const sourceColumn = fieldCols?.get(role.sourceField);\n if (sourceColumn === undefined) {\n return err(new ComponentNotPresentError(entity as number, component.name));\n }\n sourceColumn.view[row] =\n nextRelationshipTarget === null ? ENTITY_NULL_RAW : (nextRelationshipTarget as number);\n if (markChanged) this.markComponentChanged(entity, component);\n return ok(undefined);\n }\n\n /** Prepare the target side before a source archetype mutation commits. */\n private prepareRelationshipInsert(\n component: Component,\n value: Record<string, unknown>,\n ): Result<boolean, EcsError> {\n const role = relationshipRole(component);\n if (role?.kind !== 'source') return ok(false);\n const target = this.relationshipTargetEntity(component, value);\n if (target === null) return ok(false);\n const mirror = relationshipMirror(component);\n if (mirror === undefined) return ok(false);\n const targetRec = this.records[entityIndex(target)];\n const actualGeneration = targetRec?.generation ?? -1;\n if (!this.recordIsLive(targetRec, entityGeneration(target))) {\n return err(\n new StaleEntityError(target as number, entityIndex(target), entityGeneration(target), {\n operation: 'relationship-insert',\n component: component.name,\n expectedGeneration: entityGeneration(target),\n actualGeneration,\n }),\n );\n }\n const targetArch = this.graph.archetypes[targetRec.archetypeId];\n const hasMirror =\n targetArch?.components.some((candidate) => componentId(candidate) === componentId(mirror)) ??\n false;\n let mirrorAdded = false;\n if (!hasMirror) {\n const added = this.addComponentCore(\n target,\n { component: mirror, data: {} as Partial<ShapeOf<ComponentSchema>> },\n true,\n false,\n );\n if (!added.ok) return added;\n mirrorAdded = true;\n }\n const length = this.relationshipTargetLength(component, target);\n const capacity = this.ensureArrayCapacity(target, mirror, role.targetField, length + 1);\n if (capacity.ok) return ok(mirrorAdded);\n if (mirrorAdded) {\n // Mirror creation is part of preparation, not publication. If capacity\n // reservation fails, remove the newly-created target component through\n // the silent internal path so the caller sees no target, epoch, or\n // structural evidence side effect.\n const rolledBack = this.removeComponentCore(target, mirror, true);\n if (!rolledBack.ok) {\n this.poisonAfterEntityMutation('World.prepareRelationshipInsert', rolledBack.error);\n return rolledBack;\n }\n }\n return capacity;\n }\n\n /** Append `holder` to the materialized target list. */\n private relationshipOnInsert(\n holder: EntityHandle,\n component: Component,\n value: Record<string, unknown>,\n // addComponentCore may have prepared the target before migrating the\n // source. Carry that one-shot fact so the final commit can publish a\n // newly-created mirror exactly once instead of preparing a second time.\n preparedMirrorAdded?: boolean,\n ): Result<void, EcsError> {\n const role = relationshipRole(component);\n if (role?.kind !== 'source') return ok(undefined);\n const target = this.relationshipTargetEntity(component, value);\n if (target === null) return ok(undefined);\n const mirror = relationshipMirror(component);\n /* istanbul ignore next -- defineComponent relationship validation guarantees mirror exists */\n if (mirror === undefined) return ok(undefined);\n\n let mirrorAdded = preparedMirrorAdded ?? false;\n if (preparedMirrorAdded === undefined) {\n const prepared = this.prepareRelationshipInsert(component, value);\n if (!prepared.ok) {\n // A dangling source edge is still useful state: hierarchy/animation\n // projections report the missing target. The target mirror cannot be\n // updated, but insertion itself remains atomic and successful.\n if (prepared.error.code === 'stale-entity') return ok(undefined);\n return prepared;\n }\n mirrorAdded = prepared.value;\n }\n\n // Lazy-create the mirror component on the target when absent (D-3c).\n const targetSlot = entityIndex(target);\n const targetRec = this.records[targetSlot];\n if (!this.recordIsLive(targetRec, entityGeneration(target))) return ok(undefined);\n const targetArch = this.graph.archetypes[targetRec.archetypeId];\n const mirrorLocalId = componentId(mirror);\n const hasMirror =\n targetArch?.components.some((component) => componentId(component) === mirrorLocalId) ?? false;\n if (!hasMirror) {\n const added = this.addComponentCore(\n target,\n {\n component: mirror,\n data: {} as Partial<ShapeOf<ComponentSchema>>,\n },\n true,\n false,\n );\n if (!added.ok) return added;\n mirrorAdded = true;\n }\n const slot = this.relationshipTargetLength(component, target);\n const mirrored = this.appendArrayElement(target, mirror, role.targetField, holder);\n if (!mirrored.ok) return mirrored;\n this.relationshipIndex(component)?.attach(holder, target, slot);\n if (mirrorAdded) {\n this.internalmarkComponentsAdded(target, [mirrorLocalId]);\n this.advanceStructureEpoch();\n this.recordStructuralEvidence({\n kind: 'component-added',\n entity: target,\n componentId: mirrorLocalId,\n });\n }\n return ok(undefined);\n }\n\n /** Remove `holder` from the materialized target list. */\n private relationshipOnRemove(\n holder: EntityHandle,\n component: Component,\n oldValue: Record<string, unknown>,\n ): Result<void, EcsError> {\n const role = relationshipRole(component);\n if (role?.kind !== 'source') return ok(undefined);\n const target = this.relationshipTargetEntity(component, oldValue);\n if (target === null) return ok(undefined);\n const mirror = relationshipMirror(component);\n /* istanbul ignore next -- defineComponent relationship validation guarantees mirror exists */\n if (mirror === undefined) return ok(undefined);\n const targetSlot = entityIndex(target);\n const targetRec = this.records[targetSlot];\n if (!this.recordIsLive(targetRec, entityGeneration(target))) return ok(undefined);\n\n const index = this.relationshipIndex(component);\n if (index === undefined) return ok(undefined);\n const slot = index.slotOf(holder);\n if (slot === undefined || index.targetOf(holder) !== target) return ok(undefined);\n const mirrored = this.removeArrayElementAt(target, mirror, role.targetField, slot);\n if (!mirrored.ok) return mirrored;\n index.detach(holder);\n if (mirrored.value !== undefined) index.updateSlot(mirrored.value, target, slot);\n return ok(undefined);\n }\n\n private linkedSpawnMirrorField(mirror: Component): string | undefined {\n const source = relationshipSource(mirror);\n const role = source === undefined ? undefined : relationshipRole(source);\n return role?.kind === 'source' && role.linkedSpawn ? role.targetField : undefined;\n }\n\n private relationshipLinkedSpawnChildren(\n entity: EntityHandle,\n archetype: Archetype,\n ): EntityHandle[] {\n const record = this.records[entityIndex(entity)];\n const row = record === undefined ? -1 : this.tableRow(record);\n const collected: EntityHandle[] = [];\n for (const component of archetype.components) {\n const mirrorField = this.linkedSpawnMirrorField(component);\n if (mirrorField === undefined) continue;\n const snapshot = this.readRow(archetype, component, row) as Record<string, unknown>;\n const list = snapshot[mirrorField];\n if (!(list instanceof Uint32Array)) continue;\n for (const raw of list) {\n if (raw !== ENTITY_NULL_RAW) collected.push(raw as EntityHandle);\n }\n }\n return collected;\n }\n\n /**\n * Read component data from an entity.\n *\n * **Transient view contract (feat-20260602):** for fixed-capacity\n * `array<T,N>` and `buffer<N>` fields, the returned `TypedArray` (and any\n * subarray of it) aliases the archetype column buffer directly. The view is\n * valid only until the next structural change (`spawn` / `despawn` /\n * `addComponent` / `removeComponent`). Holding a view across a structural\n * change is undefined behaviour -- the backing `ArrayBuffer` is detached on\n * column growth, and swap-remove at the same row index points to the wrong\n * entity. **Re-fetch `world.get(e, C)` on every access.** See\n * `packages/ecs/README.md` Transient view contract section.\n *\n * @returns `Result<ShapeOf<S>, EcsError>` —\n * `ok(ShapeOf<S>)` on success;\n * `err(StaleEntityError)` (`.code = 'stale-entity'`) if entity is dead;\n * `err(ComponentNotPresentError)` (`.code = 'component-not-present'`) if\n * the entity does not have the component (a never-present component on\n * this entity degrades to the same `component-not-present` path — there is\n * no separate \"not registered\" failure; components are global at\n * `defineComponent` time).\n *\n * @example\n * ```ts\n * const Position = defineComponent('Position', { x: 'f32', y: 'f32' });\n * const world = new World();\n * const e = world.spawn({ component: Position, data: { x: 1, y: 2 } }).unwrap();\n * const r = world.get(e, Position);\n * if (!r.ok) { return; } // r.error.code === 'stale-entity' on dead handle\n * const pos = r.value;\n * ```\n */\n get<S extends ComponentSchema>(\n entity: EntityHandle,\n component: Component<string, S>,\n ): Result<ShapeOf<S>, EcsError> {\n const record = this.lookupAlive(entity, 'get', component.name);\n if (!record.ok) return record;\n\n const rec = record.value;\n const arch = this.graph.archetypes[rec.archetypeId];\n /* istanbul ignore next -- defensive: alive record always has valid archetypeId */\n if (!arch) {\n return err(\n new StaleEntityError(entity as number, entityIndex(entity), entityGeneration(entity), {\n operation: 'get',\n component: component.name,\n expectedGeneration: entityGeneration(entity),\n actualGeneration: rec.generation,\n }),\n );\n }\n\n // Check if this archetype has the component (using World-local ID).\n const localId = componentId(component);\n if (!arch.components.some((candidate) => componentId(candidate) === localId)) {\n return err(new ComponentNotPresentError(entity as number, component.name));\n }\n\n return ok(this.readRow(arch, component, this.tableRow(rec)));\n }\n\n /**\n * Column-level zero-copy view of an `array<T, N>` / `array<T>` field.\n *\n * Resolves the live byte region for `(entity, component, fieldName)`\n * directly at the column level and returns the element-typed TypedArray\n * aliasing it (`view.buffer` is the SSOT byte region; mutations route\n * through `world.set`). Unlike `get`, this does NOT build the\n * `{}` whole-component object nor walk every schema field. Per-frame\n * consumers that need one column (the resolved world mat4) take this path to\n * avoid the `get` overhead (1 `{}` alloc + N-field readRow walk).\n *\n * Fixed `array<T,N>` columns (feat-20260602) store their elements inline, so\n * the view aliases the archetype column buffer directly (no BufferPool\n * indirection); variable `array<T>` columns still alias the BufferPool slot.\n * The returned view's element type follows the schema element type\n * (`array<entity,N>` -> `Uint32Array`, `array<f32,N>` -> `Float32Array`,\n * etc.) -- the prior f32-only early-return gate is removed.\n *\n * **Transient view contract:** the returned `TypedArray` aliases the column\n * buffer and is valid only until the next structural change (`spawn` /\n * `despawn` / `addComponent` / `removeComponent`). Column growth\n * (`growColumn`) detaches the old `ArrayBuffer` via `transfer()`; a\n * swap-remove at the same row index leaves the view pointing to the wrong\n * entity. **Callers must re-fetch `getArrayView` on every access** and must\n * not hold the view across any operation that may cause archetype migration.\n * All existing per-frame consumers (`propagateTransforms` / `render-extract`\n * / `pick`) already conform -- they fetch the view inside a single pass with\n * no intervening structural changes.\n *\n * Returns `undefined` when the entity is dead, the component is absent, the\n * field does not exist, or the field is not an `array<...>` column.\n *\n * Engine-internal fast path; AI users read the typed view through\n * `world.get(e, GlobalTransform).world`. The accessor is the zero-materialization\n * route the propagate kernel and render walk use.\n */\n private getArrayView(\n entity: EntityHandle,\n component: Component,\n fieldName: string,\n ): FieldView | undefined {\n const record = this.lookupAlive(entity, 'getArrayView', component.name);\n if (!record.ok) return undefined;\n\n const rec = record.value;\n const arch = this.graph.archetypes[rec.archetypeId];\n if (!arch) return undefined;\n return this.readArrayView(arch, component, this.tableRow(rec), fieldName);\n }\n\n /**\n * Write (partial) component data to an entity.\n *\n * @returns `Result<void, EcsError>` —\n * `ok(void)` on success;\n * `err(StaleEntityError)` (`.code = 'stale-entity'`) if entity is dead;\n * `err(ComponentNotPresentError)` (`.code = 'component-not-present'`) if\n * entity does not have the component (F-02: no longer silently ignores).\n *\n * @example\n * ```ts\n * const Position = defineComponent('Position', { x: 'f32', y: 'f32' });\n * const world = new World();\n * const e = world.spawn({ component: Position, data: { x: 0, y: 0 } }).unwrap();\n * const r = world.set(e, Position, { x: 10 });\n * if (!r.ok) { return; } // r.error.code === 'stale-entity' on dead handle\n * r.unwrap();\n * ```\n */\n set<S extends ComponentSchema, C extends Component<string, S>>(\n entity: EntityHandle,\n component: C & WritableComponent<C>,\n value: Partial<InputShapeOf<S>>,\n markChanged = true,\n ): Result<void, EcsError> {\n const poisoned = this.poisonedResult<void>();\n if (poisoned !== undefined) return poisoned;\n if (isRelationshipTarget(component)) return this.relationshipTargetWriteError(component, 'set');\n const record = this.lookupAlive(entity, 'set', component.name);\n if (!record.ok) return record;\n\n const rec = record.value;\n const arch = this.graph.archetypes[rec.archetypeId];\n /* istanbul ignore next -- defensive: alive record always has valid archetypeId */\n if (!arch) {\n return err(\n new StaleEntityError(entity as number, entityIndex(entity), entityGeneration(entity), {\n operation: 'set',\n component: component.name,\n expectedGeneration: entityGeneration(entity),\n actualGeneration: rec.generation,\n }),\n );\n }\n const row = this.tableRow(rec);\n const localId = componentId(component);\n if (!arch.components.some((candidate) => componentId(candidate) === localId)) {\n // F-02: set on missing component returns err instead of silent ignore\n return err(new ComponentNotPresentError(entity as number, component.name));\n }\n const relationship = relationshipRole(component);\n if (relationship?.kind === 'source') {\n return this.setRelationshipSource(\n entity,\n component,\n value as Record<string, unknown>,\n rec,\n arch,\n markChanged,\n );\n }\n const valuePreflight = this.preflightComponentFieldValues(entity, {\n component,\n data: value,\n });\n if (!valuePreflight.ok) return valuePreflight;\n const currentValue = this.readRow(arch, component, row) as Record<string, unknown>;\n const mergedValue = {\n ...currentValue,\n ...(value as Record<string, unknown>),\n };\n const enumError = validateEnumFieldValues(component, mergedValue, entity as number);\n if (enumError !== null) return err(enumError as unknown as EcsError);\n\n if (component.storage === 'sparse') {\n if (markChanged) this.markComponentChanged(entity, component);\n return ok(undefined);\n }\n const fieldCols = this.table(arch).storage.get(localId)?.fields;\n if (fieldCols === undefined) {\n throw new Error(`Table storage for ${component.name} does not exist.`);\n }\n for (const fieldName of Object.keys(value)) {\n const col = fieldCols.get(fieldName);\n if (!col) {\n continue;\n }\n const fieldType = (componentSchema(component) as Record<string, string>)[fieldName] ?? '';\n // M1/M2 release loop (set path): release the prior managed value\n // BEFORE writing the new one. Single SSOT helper `releaseManagedFieldOnRow`\n // (feat-20260614 D-2) covers every managed-field family (`ref<T>` /\n // `string` / `buffer` / variable `array<T>`); it self-skips fields that\n // do not match `isManagedField` here, but for set-ref/string we already\n // gated on it so the call is hot. Zeroes the column when applicable.\n if (isManagedField(fieldType)) {\n this.releaseManagedFieldOnRow(arch, component, row, fieldName);\n }\n const raw = (value as Record<string, unknown>)[fieldName];\n if (fieldType === 'bool') {\n col.view[row] = raw ? 1 : 0;\n } else if (isEntityField(fieldType)) {\n // M3 entity field overwrite: encode null as ENTITY_NULL_RAW;\n // otherwise store the Entity bit pattern (slot+gen).\n col.view[row] = raw === null || raw === undefined ? ENTITY_NULL_RAW : (raw as number);\n } else if (isManagedBufferField(fieldType)) {\n // M2 set path: collapsed-vocab keyword family `'buffer'` (variable) +\n // `'buffer<N>'` (fixed). The two shapes diverge here:\n // - `buffer<N>` — schema-declared byteLength is fixed; raw must be a\n // `Uint8Array` whose `byteLength === N`. Mismatched payloads route\n // `FixedSizeMismatchError` via Result.err so AI users observe an\n // explicit failure instead of silent truncation (verify round 1\n // B1 fix; charter P3 — explicit failure > silent acceptance).\n // - `'buffer'` — variable capacity; release the prior slot then\n // alloc a fresh one sized to the new payload's byteLength (mirrors\n // the `array<T>` set path's release-then-alloc D-5 ordering).\n // raw is normalized from any AllowSharedBufferSource view to a\n // Uint8Array over its bytes (feat-20260621 V2 / AC-A4). Non-buffer\n // raw (a forced cast feeding e.g. a number) normalizes to null and\n // is treated as a no-op (column slot stays unchanged).\n const isFixedBuffer = fieldType !== 'buffer';\n const bytes = normalizeBufferWrite(raw);\n if (bytes !== null) {\n if (isFixedBuffer) {\n // feat-20260602: fixed `buffer<N>` lives inline as a stride-N u8\n // column (arity = N bytes). Write the payload straight into the\n // row window -- no BufferPool slot.\n const expected = bufferFieldByteLength(fieldType);\n if (bytes.byteLength !== expected) {\n return err(new FixedSizeMismatchError(fieldName, expected, bytes.byteLength));\n }\n const arity = col.arity;\n (col.view as Uint8Array).set(bytes.subarray(0, arity), row * arity);\n } else {\n // Variable `'buffer'` set: release prior slot via SSOT helper\n // (feat-20260614 D-2) then alloc fresh sized to the new payload\n // (verify round 1 B2 fix path). The helper zeroes the column on\n // release; sentinel slot id 0 is a no-op.\n this.releaseManagedFieldOnRow(arch, component, row, fieldName);\n const allocR = this.bufferPool.alloc(bytes.byteLength);\n if (!allocR.ok) {\n const ctx: ErrorContext = {\n systemName: `World.set (${component.name}.${fieldName})`,\n };\n this.routeError(allocR.error as EcsError, ctx);\n col.view[row] = 0;\n continue;\n }\n const slot = allocR.value;\n slot.view.set(bytes);\n col.view[row] = slot.id;\n }\n }\n } else if (fieldType === 'string') {\n // M1 string-field set path (AC-05 path 3): the prior handle was\n // already released by the unified `isManagedField` pre-write block\n // above (D-R3) -- here we just alloc the new handle and store the\n // u32. Mirrors the array<T> release-then-alloc pattern (D-5) so AI\n // users observe the UniqueRefStore _liveCount net-zero invariant\n // on field overwrite. Missing / non-string raw -> '' fallback\n // (AC-06).\n const text = typeof raw === 'string' ? raw : '';\n const handle = this.uniqueRefs.alloc<'String'>('String', text);\n col.view[row] = unwrapHandle(handle);\n } else {\n const arrayMeta = componentDefinition(component).fields[fieldName]?.arrayMeta;\n if (arrayMeta !== undefined) {\n // M1 set path for array<T> / array<T,N> fields (feat-20260614 D-3\n // calling convention). The set semantics mirror spawn: release the\n // prior slot via the SSOT helper, then alloc a fresh one sized to\n // the new value, copy bytes verbatim, store slot id (+ count for\n // variable). Fixed `array<T,N>` is inline — the helper short-\n // circuits and writeArrayField writes directly into the row's\n // stride window with no pool traffic.\n this.releaseManagedFieldOnRow(arch, component, row, fieldName);\n this.writeArrayField(arch, component, row, fieldName, fieldType, arrayMeta, raw);\n } else {\n // The pre-write `releaseManagedFieldOnRow` block above already\n // released the prior `'shared<T>'` rc via SharedRefStore.release;\n // here we retain the new value so net rc delta is +1 / 0 / -1 per\n // M4 invariant (set: -1+1=0; spawn: 0+1=+1; despawn: -1).\n col.view[row] = raw as number;\n if (fieldType.startsWith('shared<') && (raw as number) !== 0) {\n this.retainSharedScalarHandle(raw as number, component.name, fieldName);\n }\n }\n }\n }\n if (markChanged) this.markComponentChanged(entity, component);\n return ok(undefined);\n }\n\n // ──────────────────────────────────────────────────────────────────────────\n // Internal relationship array maintenance. Public array mutation is always\n // expressed as one `world.set` payload; these helpers only implement the\n // engine-owned target projection and backpointer swap-remove path.\n //\n // Append/remove are engine-owned relationship maintenance only.\n //\n // ──────────────────────────────────────────────────────────────────────────\n\n /**\n * Append `value` to the variable `array<T>` field `fieldName` on `entity`.\n *\n * BufferPool grow is amortized O(1) via the size-class freelist (research\n * Finding 5). Relationship target arrays grow byte-wise.\n *\n * @returns `Result<void, EcsError>` with the normal stale/component errors.\n *\n * The helper is called only by relationship synchronization.\n */\n private appendArrayElement(\n entity: EntityHandle,\n component: Component,\n fieldName: string,\n value: EntityHandle,\n ): Result<void, EcsError> {\n const record = this.lookupAlive(entity, 'relationship-append', component.name);\n if (!record.ok) return record;\n const rec = record.value;\n const arch = this.graph.archetypes[rec.archetypeId];\n /* istanbul ignore next -- alive record always has a valid archetype */\n if (!arch) {\n return err(\n new StaleEntityError(entity as number, entityIndex(entity), entityGeneration(entity), {\n operation: 'relationship-append',\n component: component.name,\n expectedGeneration: entityGeneration(entity),\n actualGeneration: rec.generation,\n }),\n );\n }\n const row = this.tableRow(rec);\n const localId = componentId(component);\n const fieldCols = this.table(arch).storage.get(localId)?.fields;\n if (!fieldCols) {\n return err(new ComponentNotPresentError(entity as number, component.name));\n }\n const col = fieldCols.get(fieldName);\n if (!col) return err(new ComponentNotPresentError(entity as number, component.name));\n const arrayMeta = componentDefinition(component).fields[fieldName]?.arrayMeta;\n if (arrayMeta === undefined) {\n return err(new ComponentNotPresentError(entity as number, component.name));\n }\n const meta = TYPE_METADATA[arrayMeta.elementType];\n /* istanbul ignore next -- arrayMeta.elementType is guaranteed in TYPE_METADATA */\n if (!meta) return err(new ComponentNotPresentError(entity as number, component.name));\n // biome-ignore lint/style/noNonNullAssertion: every array element type has a byte size\n const elementBytes = meta.byteSize!;\n const slotId = col.view[row] as number;\n\n const countCol = fieldCols.get(arrayCountColumnName(fieldName));\n /* istanbul ignore next -- variable arrays always allocate the count column */\n if (countCol === undefined) {\n return err(new ComponentNotPresentError(entity as number, component.name));\n }\n const count = countCol.view[row] as number;\n const newCount = count + 1;\n const newByteLength = newCount * elementBytes;\n\n let liveSlotId = slotId;\n if (liveSlotId === 0) {\n // Empty/unallocated slot — alloc fresh.\n const allocR = this.bufferPool.alloc(newByteLength);\n if (!allocR.ok) return err(allocR.error);\n liveSlotId = allocR.value.id;\n col.view[row] = liveSlotId;\n } else {\n // A previously-allocated slot may have drained below its high-water\n // mark: swap-remove (`_removeArrayElementByValue`) and `pop` only lower\n // the count column, never shrink the managed buffer. When the refilled\n // length still fits inside the slot's current logical length, reuse the\n // buffer in place -- routing through `grow` would hit the (correct, but\n // here irrelevant) shrink-not-supported guard and strand the field\n // (e.g. `Children.entities` never repopulating after a full drain).\n if (newByteLength > this.bufferPool.view(liveSlotId).byteLength) {\n const growR = this.bufferPool.grow(liveSlotId, newByteLength);\n if (!growR.ok) return err(growR.error);\n }\n }\n const liveBytes = this.bufferPool.view(liveSlotId);\n // Reinterpret the slot bytes as the element-typed view and write at the\n // tail index. Entity values are stored as their u32 bit pattern.\n writeArrayElementAt(liveBytes, count, arrayMeta.elementType, value as number);\n countCol.view[row] = newCount;\n this.markComponentChanged(entity, component);\n return ok(undefined);\n }\n\n private ensureArrayCapacity(\n entity: EntityHandle,\n component: Component,\n fieldName: string,\n minimum: number,\n ): Result<void, EcsError> {\n const record = this.lookupAlive(entity, 'relationship-capacity', component.name);\n if (!record.ok) return record;\n const rec = record.value;\n const arch = this.graph.archetypes[rec.archetypeId];\n if (!arch) {\n return err(\n new StaleEntityError(entity as number, entityIndex(entity), entityGeneration(entity), {\n operation: 'relationship-capacity',\n component: component.name,\n expectedGeneration: entityGeneration(entity),\n actualGeneration: rec.generation,\n }),\n );\n }\n const row = this.tableRow(rec);\n const fieldCols = this.table(arch).storage.get(componentId(component))?.fields;\n if (!fieldCols) return err(new ComponentNotPresentError(entity as number, component.name));\n const col = fieldCols.get(fieldName);\n if (!col) return err(new ComponentNotPresentError(entity as number, component.name));\n const arrayMeta = componentDefinition(component).fields[fieldName]?.arrayMeta;\n if (arrayMeta === undefined) {\n return err(new ComponentNotPresentError(entity as number, component.name));\n }\n const meta = TYPE_METADATA[arrayMeta.elementType];\n if (!meta?.byteSize) {\n return err(new ComponentNotPresentError(entity as number, component.name));\n }\n const maximum = Math.floor(262_144 / meta.byteSize);\n if (!Number.isSafeInteger(minimum) || minimum < 0 || minimum > maximum) {\n return err(new ManagedBufferOutOfBoundsError(minimum, maximum));\n }\n\n const byteLength = minimum * meta.byteSize;\n const slotId = col.view[row] as number;\n if (slotId === 0) {\n if (minimum === 0) return ok(undefined);\n const allocated = this.bufferPool.alloc(byteLength);\n if (!allocated.ok) return allocated;\n col.view[row] = allocated.value.id;\n return ok(undefined);\n }\n if (this.bufferPool.view(slotId).byteLength >= byteLength) return ok(undefined);\n const grown = this.bufferPool.grow(slotId, byteLength);\n return grown.ok ? ok(undefined) : grown;\n }\n\n /**\n * Remove one variable-array element at a known slot. Relationship holders\n * supply the slot from their backpointer, so this is O(1) and never scans\n * the materialized target array.\n */\n private removeArrayElementAt(\n entity: EntityHandle,\n component: Component<string, ComponentSchema>,\n fieldName: string,\n slot: number,\n ): Result<EntityHandle | undefined, EcsError> {\n const record = this.lookupAlive(entity, 'removeArrayElementAt', component.name);\n if (!record.ok) return record;\n const rec = record.value;\n const arch = this.graph.archetypes[rec.archetypeId];\n if (!arch) return err(new ComponentNotPresentError(entity as number, component.name));\n const fieldCols = this.table(arch).storage.get(componentId(component))?.fields;\n if (!fieldCols) return err(new ComponentNotPresentError(entity as number, component.name));\n const col = fieldCols.get(fieldName);\n const arrayMeta = componentDefinition(component).fields[fieldName]?.arrayMeta;\n const countCol = fieldCols.get(arrayCountColumnName(fieldName));\n if (!col || !arrayMeta || arrayMeta.length !== undefined || !countCol) {\n return err(new ComponentNotPresentError(entity as number, component.name));\n }\n const row = this.tableRow(rec);\n const count = countCol.view[row] as number;\n if (slot < 0 || slot >= count) return ok(undefined);\n const slotId = col.view[row] as number;\n if (slotId === 0) return ok(undefined);\n const liveBytes = this.bufferPool.view(slotId);\n const last = count - 1;\n const moved =\n slot === last\n ? undefined\n : (readArrayElementAt(liveBytes, last, arrayMeta.elementType) as EntityHandle);\n if (slot !== last) {\n writeArrayElementAt(liveBytes, slot, arrayMeta.elementType, moved as number);\n }\n countCol.view[row] = last;\n this.markComponentChanged(entity, component);\n return ok(moved);\n }\n\n // ──────────────────────────────────────────────────────────────────────────\n // addComponent / removeComponent (archetype migration via edges, AC-07)\n // ──────────────────────────────────────────────────────────────────────────\n\n /**\n * Add a component to an existing entity, triggering archetype migration.\n *\n * @returns `Result<void, EcsError>` —\n * `ok(void)` on success;\n * `err(StaleEntityError)` (`.code = 'stale-entity'`) if entity is dead;\n * `err(ComponentAlreadyPresentError)` (`.code = 'component-already-present'`)\n * if entity already has the component (E-03).\n *\n * @example\n * ```ts\n * const Position = defineComponent('Position', { x: 'f32', y: 'f32' });\n * const Velocity = defineComponent('Velocity', { dx: 'f32', dy: 'f32' });\n * const world = new World();\n * const e = world.spawn({ component: Position, data: { x: 0, y: 0 } }).unwrap();\n * const r = world.addComponent(e, { component: Velocity, data: { dx: 1, dy: 0 } });\n * if (!r.ok) { return; } // r.error.code === 'stale-entity' on dead handle\n * r.unwrap();\n * ```\n */\n addComponent<S extends ComponentSchema, C extends Component<string, S>>(\n entity: EntityHandle,\n componentData: ComponentData<S> & { component: C & WritableComponent<C> },\n ): Result<void, EcsError> {\n const poisoned = this.poisonedResult<void>();\n if (poisoned !== undefined) return poisoned;\n if (\n isRelationshipTarget(componentData.component) &&\n this.relationshipTargetPayloadWrites(componentData.data as Record<string, unknown>)\n )\n return this.relationshipTargetWriteError(componentData.component, 'addComponent');\n return this.addComponentCore(entity, componentData, false);\n }\n\n /**\n * Core implementation of `addComponent` with reentry guard.\n *\n * @param internal — `true` when called from relationship maintenance\n * (lazy mirror create or exclusive reparent).\n */\n private addComponentCore<S extends ComponentSchema>(\n entity: EntityHandle,\n componentData: ComponentData<S>,\n internal: boolean,\n resolveRequirements = true,\n // A relationship preflight can create a target mirror before the source\n // migration. Preserve whether that preflight created it through the\n // exclusive-reparent recursion.\n preparedMirrorAdded?: boolean,\n ): Result<void, EcsError> {\n const record = this.lookupAlive(entity, 'addComponent', componentData.component.name);\n if (!record.ok) return record;\n\n const rec = record.value;\n let srcArch = this.graph.archetypes[rec.archetypeId];\n /* istanbul ignore next -- defensive: alive record always has valid archetypeId */\n if (!srcArch) {\n return err(\n new StaleEntityError(entity as number, entityIndex(entity), entityGeneration(entity), {\n operation: 'addComponent',\n component: componentData.component.name,\n expectedGeneration: entityGeneration(entity),\n actualGeneration: rec.generation,\n }),\n );\n }\n\n const preflight = this.preflightComponentData(entity, componentData);\n if (!preflight.ok) return preflight;\n\n const filled = fillComponentDefaults(\n componentData.component,\n componentData.data as Record<string, unknown>,\n );\n\n // Reserve a source relationship's target before adding any required\n // components. A capacity failure must not leave a required component on\n // the holder, nor a lazily-created mirror on the target. Existing\n // exclusive sources keep their dedicated reparent path below.\n let relationshipMirrorAdded = preparedMirrorAdded;\n const componentAlreadyPresent = srcArch.components.some(\n (candidate) => componentId(candidate) === componentId(componentData.component),\n );\n if (\n !componentAlreadyPresent &&\n !internal &&\n relationshipRole(componentData.component as Component)?.kind === 'source' &&\n relationshipMirrorAdded === undefined\n ) {\n const prepared = this.prepareRelationshipInsert(\n componentData.component as Component,\n filled as Record<string, unknown>,\n );\n if (!prepared.ok) return prepared;\n relationshipMirrorAdded = prepared.value;\n // Preparing a relationship may materialize the mirror on the same\n // entity (self-targeting relationships are valid when `allowSelf` is\n // enabled). That nested add migrates `rec`, so the source archetype\n // captured above is no longer authoritative. Refresh it before the\n // requested component migration instead of removing a row from the\n // stale, already-empty table.\n srcArch = this.graph.archetypes[rec.archetypeId];\n if (srcArch === undefined) {\n return err(\n new StaleEntityError(entity as number, entityIndex(entity), entityGeneration(entity), {\n operation: 'addComponent',\n component: componentData.component.name,\n expectedGeneration: rec.generation,\n actualGeneration: rec.generation,\n }),\n );\n }\n }\n\n // Generic component requirements are resolved once at the structural\n // boundary. Explicit data remains authoritative; only missing required\n // identities are added before the requested component is migrated.\n if (resolveRequirements) {\n const required = expandComponentRequirements([componentData]).slice(1);\n for (const requirement of required) {\n if (\n srcArch.components.some(\n (candidate) => componentId(candidate) === componentId(requirement.component),\n )\n ) {\n continue;\n }\n // The closure is expanded once above. Bypass requirement expansion for\n // each member so malformed dependency cycles remain finite and the\n // structural work still happens in one deterministic sequence.\n const added = this.addComponentCore(entity, requirement as ComponentData, internal, false);\n if (!added.ok) return added;\n srcArch = this.graph.archetypes[rec.archetypeId];\n if (!srcArch) {\n return err(\n new StaleEntityError(entity as number, entityIndex(entity), entityGeneration(entity), {\n operation: 'addComponent',\n component: componentData.component.name,\n expectedGeneration: rec.generation,\n actualGeneration: rec.generation,\n }),\n );\n }\n }\n }\n\n // Check if entity already has this component (using World-local ID).\n const localId = componentId(componentData.component);\n if (srcArch.components.some((candidate) => componentId(candidate) === localId)) {\n // M2 exclusive relationship: re-adding the holder with a (possibly new)\n // target auto-reparents instead of failing (AC-12). Prune the old side\n // first (removeComponent prunes the old target), then fall through to\n // the normal add (which appends the new target). The two steps keep the\n // materialized target list consistent (AC-13);\n // removeComponent + addComponent each touch the mirror exactly once and\n // the mirror component carries no relationship of its own, so there is\n // no recursion. Reparent only fires for top-level user calls\n // (!internal); engine-internal lazy create / append\n // never re-add an existing relationship component.\n const role = relationshipRole(componentData.component as Component);\n if (role?.kind === 'source' && role.exclusive && !internal) {\n const prepared = this.prepareRelationshipInsert(\n componentData.component as Component,\n filled as Record<string, unknown>,\n );\n if (!prepared.ok) return prepared;\n const removeR = this.removeComponentCore(\n entity,\n componentData.component as Component,\n false,\n );\n if (!removeR.ok) return removeR;\n return this.addComponentCore(entity, componentData, false, true, prepared.value);\n }\n return err(new ComponentAlreadyPresentError(entity as number, componentData.component.name));\n }\n\n // Get target archetype via edge cache.\n const targetArch = getAddEdge(\n this.graph,\n srcArch,\n localId,\n componentData.component as Component,\n );\n\n if (componentData.component.storage === 'sparse') {\n this.moveEntityArchetype(rec, srcArch, targetArch);\n } else {\n this.migrateEntity(rec, srcArch, targetArch);\n }\n\n // Write the new component's data. Apply layer-2 + layer-3 silent\n // fallback so addComponent shares the SAME default-resolution path\n // as spawn / SceneAsset.instantiate (feat-20260517 / M2 / AC-04\n // research §F4 auto-symmetry; ComponentData<S>['data'] is the\n // physical bridge).\n if (componentData.component.storage === 'table') {\n this.writeRow(targetArch, componentData.component, this.tableRow(rec), filled as ShapeOf<S>);\n }\n // Relationship sync: append to the materialized target list.\n if (!internal && relationshipRole(componentData.component as Component)?.kind === 'source') {\n const relationshipResult = this.relationshipOnInsert(\n entity,\n componentData.component as Component,\n filled as Record<string, unknown>,\n relationshipMirrorAdded,\n );\n if (!relationshipResult.ok) {\n this.poisonAfterEntityMutation('World.addComponent', relationshipResult.error);\n return relationshipResult;\n }\n }\n\n if (!internal) {\n // Relationship insertion is part of the same publication boundary. A\n // target-side storage failure poisons the World; it must not leave a\n // components-added epoch/evidence record that claims the edge exists.\n this.internalmarkComponentsAdded(entity, [componentId(componentData.component)]);\n this.advanceStructureEpoch();\n this.recordStructuralEvidence({\n kind: 'component-added',\n entity,\n componentId: localId,\n });\n }\n return ok(undefined);\n }\n\n /**\n * Remove a component from an existing entity, triggering archetype migration.\n *\n * @returns `Result<void, EcsError>` —\n * `ok(void)` on success;\n * `err(StaleEntityError)` (`.code = 'stale-entity'`) if entity is dead;\n * `err(ComponentNotPresentError)` (`.code = 'component-not-present'`)\n * if entity doesn't have the component (E-04).\n *\n * @example\n * ```ts\n * const Position = defineComponent('Position', { x: 'f32', y: 'f32' });\n * const world = new World();\n * const e = world.spawn({ component: Position, data: { x: 0, y: 0 } }).unwrap();\n * const r = world.removeComponent(e, Position);\n * if (!r.ok) { return; } // r.error.code === 'stale-entity' on dead handle\n * r.unwrap();\n * ```\n */\n removeComponent<S extends ComponentSchema, C extends Component<string, S>>(\n entity: EntityHandle,\n component: C & WritableComponent<C>,\n ): Result<void, EcsError> {\n const poisoned = this.poisonedResult<void>();\n if (poisoned !== undefined) return poisoned;\n if (isRelationshipTarget(component))\n return this.relationshipTargetWriteError(component, 'removeComponent');\n return this.removeComponentCore(entity, component, false);\n }\n\n /**\n * Core implementation of `removeComponent` with reentry guard.\n *\n * @param internal — `true` when called from relationship maintenance\n * (exclusive reparent).\n */\n private removeComponentCore<S extends ComponentSchema>(\n entity: EntityHandle,\n component: Component<string, S>,\n internal: boolean,\n ): Result<void, EcsError> {\n // Essential-component hard reject (feat-20260602 / plan-strategy D-3): the\n // id=0 `Entity` component is carried by every archetype unconditionally (it\n // is the row's own packed handle) and cannot be removed. Reject before any\n // liveness lookup so the rejection is structural, not entity-state-dependent.\n if (componentId(component) === componentId(EntityComponent)) {\n return err(new RemoveEssentialComponentError(component.name));\n }\n\n const record = this.lookupAlive(entity, 'removeComponent', component.name);\n if (!record.ok) return record;\n\n const rec = record.value;\n const srcArch = this.graph.archetypes[rec.archetypeId];\n /* istanbul ignore next -- defensive: alive record always has valid archetypeId */\n if (!srcArch) {\n return err(\n new StaleEntityError(entity as number, entityIndex(entity), entityGeneration(entity), {\n operation: 'removeComponent',\n component: component.name,\n expectedGeneration: entityGeneration(entity),\n actualGeneration: rec.generation,\n }),\n );\n }\n\n // Check if entity has this component (using World-local ID).\n const localId = componentId(component);\n if (!srcArch.components.some((candidate) => componentId(candidate) === localId)) {\n return err(new ComponentNotPresentError(entity as number, component.name));\n }\n\n // Capture the old relationship value before column removal so the\n // materialized target list can be pruned.\n const role = relationshipRole(component as Component);\n const needsOldValue = role?.kind === 'source' && !internal;\n if (needsOldValue) {\n const oldValue = this.readRow(srcArch, component as Component, this.tableRow(rec)) as Record<\n string,\n unknown\n >;\n // Relationship sync: prune the holder from the target's materialized list.\n if (role?.kind === 'source' && !internal) {\n const relation = this.relationshipOnRemove(entity, component as Component, oldValue);\n if (!relation.ok) {\n this.poisonAfterEntityMutation('World.removeComponent', relation.error);\n return relation;\n }\n }\n }\n\n // M1 release loop (removeComponent path): release every `ref<T>` field\n // on the component being removed before migration drops the row.\n if (component.storage === 'table') {\n this.releaseManagedRefsOnRow(srcArch, component as Component, this.tableRow(rec));\n }\n\n // Get target archetype via edge cache.\n const targetArch = getRemoveEdge(this.graph, srcArch, localId);\n\n if (component.storage === 'sparse') {\n this.moveEntityArchetype(rec, srcArch, targetArch);\n const set = this.graph.sparseTags.get(componentId(component));\n if (set !== undefined) removeSparseTag(set, entity);\n } else {\n this.migrateEntity(rec, srcArch, targetArch);\n }\n if (!internal) {\n this.advanceStructureEpoch();\n this.recordStructuralEvidence({\n kind: 'component-removed',\n entity,\n componentId: localId,\n });\n }\n return ok(undefined);\n }\n\n // ──────────────────────────────────────────────────────────────────────────\n // Internal — deferred command support (CommandBuffer interface)\n // ──────────────────────────────────────────────────────────────────────────\n\n /**\n * Allocate a pending entity for deferred spawn.\n * Returns an Entity handle. The entity is \"pending\" because\n * archetypeId === -1 (set by allocateIndex); no separate flag needed.\n */\n private allocatePendingEntity(): EntityHandle {\n const indexSlot = this.allocateIndex();\n // biome-ignore lint/style/noNonNullAssertion: allocateIndex guarantees a valid slot with an initialized record\n return encodeEntity(indexSlot, this.records[indexSlot]!.generation);\n }\n\n /**\n * Return a deferred-spawn reservation to the free-list without publishing a\n * row or advancing an epoch. CommandBuffer.abort is the sole caller; a\n * materialized entity is intentionally left untouched so an unexpected\n * post-write failure poisons the World instead of attempting an unsafe undo.\n */\n private cancelPendingEntity(entity: EntityHandle): void {\n const slot = entityIndex(entity);\n const record = this.records[slot];\n if (record === undefined || record.generation !== entityGeneration(entity)) return;\n if (record.archetypeId !== -1 || record.archetypeRow !== -1) return;\n record.generation += 1;\n if (!isRetiredSlot(record.generation)) this.freeIndices.push(slot);\n }\n\n /**\n * Materialize one already-reserved entity. Synchronous spawn and deferred\n * command flush share this exact insertion/publication path; only the\n * caller's validation and reservation boundary differs.\n *\n */\n private materializeEntity(\n entity: EntityHandle,\n componentDatas: ComponentData[],\n ): Result<void, EcsError> {\n const poisoned = this.poisonedResult<void>();\n if (poisoned !== undefined) return poisoned;\n const slot = entityIndex(entity);\n const record = this.records[slot];\n if (!record || record.archetypeId !== -1) return ok(undefined);\n\n let storageTouched = false;\n try {\n // Find or create target archetype (using World-local IDs).\n const componentIds = componentDatas.map((cd) => componentId(cd.component));\n const components = componentDatas.map((cd) => cd.component);\n const arch = getOrCreateArchetype(this.graph, componentIds, components);\n\n // Mark the reservation as mutation-owned before either append can write.\n // If appendTableRow succeeds and appendArchetypeRow fails, command abort\n // must not reclaim an entity whose table storage may already be touched.\n // A poisoned World is the recovery boundary for that partial state.\n record.archetypeId = arch.id;\n storageTouched = true;\n const table = this.table(arch);\n const tableRow = appendTableRow(table, entity);\n const archetypeRow = appendArchetypeRow(arch, tableRow);\n record.archetypeRow = archetypeRow;\n\n // Write initial data. Apply the same default-resolution path as the\n // synchronous World.spawn / addComponent operations.\n for (const cd of componentDatas) {\n const filled = fillComponentDefaults(cd.component, cd.data as Record<string, unknown>);\n this.writeRow(arch, cd.component, tableRow, filled as ShapeOf<ComponentSchema>);\n }\n\n // The reserved handle is the source of truth for the essential Entity\n // self column. Relationship maintenance is part of the write boundary;\n // component/epoch publication waits until it has completed.\n this.writeEntitySelf(arch, tableRow, entity);\n\n // Publish relationship targets after all rows and managed writes are\n // ready. A non-stale error here is a possible partial write. No\n // components-added epoch or structural evidence has been published yet.\n for (const cd of componentDatas) {\n if (relationshipRole(cd.component as Component)?.kind !== 'source') continue;\n const filled = fillComponentDefaults(cd.component, cd.data as Record<string, unknown>);\n const relationshipResult = this.relationshipOnInsert(\n entity,\n cd.component as Component,\n filled as Record<string, unknown>,\n );\n if (!relationshipResult.ok) {\n this.poisonAfterEntityMutation('World.materializeEntity', relationshipResult.error);\n return relationshipResult;\n }\n }\n this.internalmarkComponentsAdded(entity, [\n componentId(EntityComponent),\n ...componentDatas.map((cd) => componentId(cd.component)),\n ]);\n this.advanceStructureEpoch();\n this.recordStructuralEvidence({ kind: 'spawn', entity });\n return ok(undefined);\n } catch (error) {\n if (storageTouched) this.poisonAfterEntityMutation('World.materializeEntity', error);\n throw error;\n }\n }\n\n private poisonAfterEntityMutation(kernelName: string, cause: unknown): void {\n this.internalpoisonExecution({\n code: 'shared-kernel-failed',\n kernelName,\n cause,\n partialWrite: true,\n retryable: false,\n });\n }\n\n /** Deferred commands use the common materialization owner. */\n private materializePendingEntity(\n entity: EntityHandle,\n componentDatas: ComponentData[],\n ): Result<void, EcsError> {\n return this.materializeEntity(entity, expandComponentRequirements(componentDatas));\n }\n\n // ──────────────────────────────────────────────────────────────────────────\n // Internal — entity index allocation\n // ──────────────────────────────────────────────────────────────────────────\n\n private allocateIndex(): number {\n if (this.executionState.health === 'poisoned') {\n throw new WorldPoisonedError(this.identity, this.executionState.fault);\n }\n const recycled = this.freeIndices.pop();\n if (recycled !== undefined) {\n return recycled;\n }\n const slot = this.records.length;\n if (slot > ENTITY_MAX_INDEX) {\n throw new EntityIndexOverflowError(slot);\n }\n this.records.push({ generation: 0, archetypeId: -1, archetypeRow: -1 });\n return slot;\n }\n\n /**\n * Single liveness predicate (feat-20260602 / plan-strategy D-4): a slot is\n * live for a given handle generation iff the record exists, its generation\n * still matches the handle (despawn bumps generation, so a stale or recycled\n * handle fails here), and the slot is materialized into an archetype\n * (archetypeId !== -1). Replaces the former `record.alive && record.generation\n * === gen` conjunction and the intermediate `!record.pending` clause. An\n * append in progress keeps `archetypeRow === -1` until both storage indexes\n * exist.\n */\n private recordIsLive(record: EntityRecord | undefined, gen: number): record is EntityRecord {\n return (\n record !== undefined &&\n record.generation === gen &&\n record.archetypeId !== -1 &&\n record.archetypeRow !== -1\n );\n }\n\n private lookupAlive(\n entity: EntityHandle,\n operation: string,\n component?: string,\n ): Result<EntityRecord, EcsError> {\n const slot = entityIndex(entity);\n const gen = entityGeneration(entity);\n const record = this.records[slot];\n if (!this.recordIsLive(record, gen)) {\n return err(\n new StaleEntityError(entity as number, slot, gen, {\n operation,\n ...(component !== undefined ? { component } : {}),\n expectedGeneration: gen,\n actualGeneration: this.records[slot]?.generation ?? -1,\n }),\n );\n }\n return ok(record);\n }\n\n private readArrayView(\n arch: Archetype,\n component: Component,\n row: number,\n fieldName: string,\n ): FieldView | undefined {\n const fieldCols = this.table(arch).storage.get(componentId(component))?.fields;\n if (!fieldCols) return undefined;\n\n const fieldType = componentSchema(component)[fieldName];\n if (fieldType === undefined) return undefined;\n // Component reflection already parses and freezes array metadata at\n // registration time. Reusing it here keeps the per-entity zero-copy path\n // parse-free; this accessor is called once for every renderable every\n // frame. The field lookup also preserves the existing undefined result\n // for non-array fields without reparsing arbitrary schema strings.\n const arrayMeta = componentDefinition(component).fields[fieldName]?.arrayMeta;\n if (arrayMeta === undefined) return undefined;\n\n const col = fieldCols.get(fieldName);\n if (!col) return undefined;\n\n const elementCount =\n arrayMeta.length ??\n (fieldCols.get(arrayCountColumnName(fieldName))?.view[row] as number | undefined) ??\n 0;\n return this.materializeArrayView(col, row, arrayMeta, elementCount);\n }\n\n /** Read one scalar column without constructing a component snapshot. */\n private internalgetFieldValue(\n entity: EntityHandle,\n component: Component,\n fieldName: string,\n ): number | undefined {\n const record = this.lookupAlive(entity, 'world-read', component.name);\n if (!record.ok) return undefined;\n const arch = this.graph.archetypes[record.value.archetypeId];\n if (arch === undefined) return undefined;\n const fieldCols = this.table(arch).storage.get(componentId(component))?.fields;\n return fieldCols?.get(fieldName)?.view[this.tableRow(record.value)] as number | undefined;\n }\n\n /** Read an array's live logical length without allocating a TypedArray. */\n private internalgetArrayLength(\n entity: EntityHandle,\n component: Component,\n fieldName: string,\n ): number | undefined {\n const record = this.lookupAlive(entity, 'world-read', component.name);\n if (!record.ok) return undefined;\n const arch = this.graph.archetypes[record.value.archetypeId];\n if (arch === undefined) return undefined;\n const row = this.tableRow(record.value);\n const fieldCols = this.table(arch).storage.get(componentId(component))?.fields;\n if (fieldCols === undefined) return undefined;\n const arrayMeta = componentDefinition(component).fields[fieldName]?.arrayMeta;\n if (arrayMeta === undefined) return undefined;\n if (arrayMeta.length !== undefined) return arrayMeta.length;\n const count = fieldCols.get(arrayCountColumnName(fieldName))?.view[row];\n return typeof count === 'number' ? count : 0;\n }\n\n /** Read one array element directly from its column or BufferPool slot. */\n private internalgetArrayElement(\n entity: EntityHandle,\n component: Component,\n fieldName: string,\n index: number,\n ): number | undefined {\n if (!Number.isSafeInteger(index) || index < 0) return undefined;\n const record = this.lookupAlive(entity, 'world-read', component.name);\n if (!record.ok) return undefined;\n const arch = this.graph.archetypes[record.value.archetypeId];\n if (arch === undefined) return undefined;\n const row = this.tableRow(record.value);\n const fieldCols = this.table(arch).storage.get(componentId(component))?.fields;\n if (fieldCols === undefined) return undefined;\n const arrayMeta = componentDefinition(component).fields[fieldName]?.arrayMeta;\n if (arrayMeta === undefined) return undefined;\n const length =\n arrayMeta.length ??\n (fieldCols.get(arrayCountColumnName(fieldName))?.view[row] as number | undefined);\n if (length === undefined || index >= length) return undefined;\n const col = fieldCols.get(fieldName);\n if (col === undefined) return undefined;\n if (arrayMeta.length !== undefined) return col.view[row * col.arity + index] as number;\n\n const slotId = col.view[row] as number;\n const bytes = this.bufferPool.view(slotId);\n if (arrayMeta.elementType === 'entity') {\n const byteOffset = index * 4;\n if (byteOffset + 4 > bytes.byteLength) return undefined;\n return (\n ((bytes[byteOffset] ?? 0) |\n ((bytes[byteOffset + 1] ?? 0) << 8) |\n ((bytes[byteOffset + 2] ?? 0) << 16) |\n ((bytes[byteOffset + 3] ?? 0) << 24)) >>>\n 0\n );\n }\n return readArrayElementAt(bytes, index, arrayMeta.elementType);\n }\n\n // ──────────────────────────────────────────────────────────────────────────\n // Internal — archetype data read/write\n // ──────────────────────────────────────────────────────────────────────────\n\n private readRow<S extends ComponentSchema>(\n arch: Archetype,\n component: Component<string, S>,\n row: number,\n ): ShapeOf<S> {\n const localId = componentId(component);\n const fieldCols = this.table(arch).storage.get(localId)?.fields;\n const out = {} as ShapeOf<S>;\n /* istanbul ignore next -- defensive: component is registered and arch has it */\n if (!fieldCols) {\n return out;\n }\n for (const [fieldName, fieldType] of Object.entries(componentSchema(component))) {\n const col = fieldCols.get(fieldName);\n if (!col) {\n continue;\n }\n const raw = col.view[row];\n if (fieldType === 'bool') {\n (out as Record<string, unknown>)[fieldName] = raw === 1;\n } else if (isEntityField(fieldType)) {\n // Entity field: decode the stored raw u32 verbatim back to Entity\n // (or null when the slot carries the ENTITY_NULL_RAW sentinel). No\n // liveness validation happens here -- a slot referencing a despawned\n // target returns its original raw encoding unchanged; the consumer is\n // responsible for checking liveness (e.g. `world.get(ref, Entity)`).\n (out as Record<string, unknown>)[fieldName] = raw === ENTITY_NULL_RAW ? null : raw;\n } else if (isManagedBufferField(fieldType)) {\n if (fieldType !== 'buffer') {\n // feat-20260602: fixed `buffer<N>` lives inline (stride-N u8 column,\n // arity = N). Return the row's byte window directly -- no pool slot.\n const arity = col.arity;\n (out as Record<string, unknown>)[fieldName] = (col.view as Uint8Array).subarray(\n row * arity,\n row * arity + arity,\n );\n } else {\n // Variable `'buffer'`: column stores slot id; the live view is\n // resolved on demand so post-grow callers always see the refreshed\n // Uint8Array.\n (out as Record<string, unknown>)[fieldName] = this.bufferPool.view(raw as number);\n }\n } else if (fieldType === 'string') {\n // M1 string-field read path (AC-03 / AC-09): resolve the column\n // u32 handle through UniqueRefStore -- same dispatch arm as the\n // 'unique<T>' read (D-R3). Returns the native JS string payload by\n // strong reference; identity is stable across reads until the\n // next set or release (AC-03 read-side identity contract).\n // Released / sentinel handles surface as unique-ref-released via\n // resolve; we fall back to '' rather than propagate the error so\n // the read shape (`out.value: string`) stays total -- AI users\n // never see undefined or wrapper objects.\n const resolveR = this.uniqueRefs.resolve<'String'>(toUnique<'String'>(raw as number));\n (out as Record<string, unknown>)[fieldName] = resolveR.ok ? resolveR.value : '';\n } else {\n const arrayMeta = componentDefinition(component).fields[fieldName]?.arrayMeta;\n if (arrayMeta !== undefined) {\n // M1 read path: materialise a fresh TypedArray snapshot each call\n // (D-4 no cache; plan-strategy §2.2 read-only contract). The\n // snapshot aliases the BufferPool slot bytes; mutations route\n // through the World mutation API.\n const elementCount =\n arrayMeta.length ??\n (fieldCols.get(arrayCountColumnName(fieldName))?.view[row] as number | undefined) ??\n 0;\n const materialized = this.materializeArrayView(col, row, arrayMeta, elementCount);\n // Relationship target arrays are a read-only projection. Keep the\n // public component snapshot detached so mutating the returned view\n // cannot bypass the World-owned mirror/index path.\n (out as Record<string, unknown>)[fieldName] = isRelationshipTarget(component)\n ? materialized.slice()\n : materialized;\n } else {\n (out as Record<string, unknown>)[fieldName] = raw;\n }\n }\n }\n return out;\n }\n\n /**\n * Write the full packed entity handle into the row's essential id=0 `Entity`\n * column (`self` field). Called by `spawn` / `materializePendingEntity`\n * after the row is appended (feat-20260602 / plan-strategy D-3). The column\n * always exists -- `createArchetype` folds the Entity column into every\n * archetype -- so this is a direct u32 store, no readRow/writeRow walk.\n */\n private writeEntitySelf(arch: Archetype, row: number, handle: EntityHandle): void {\n const col = this.table(arch).storage.get(componentId(EntityComponent))?.fields.get('self');\n /* istanbul ignore next -- defensive: Entity column is folded into every archetype */\n if (!col) return;\n col.view[row] = handle as unknown as number;\n }\n\n private writeRow<S extends ComponentSchema>(\n arch: Archetype,\n component: Component<string, S>,\n row: number,\n value: ShapeOf<S>,\n ): void {\n const localId = componentId(component);\n const fieldCols = this.table(arch).storage.get(localId)?.fields;\n /* istanbul ignore next -- defensive: component is registered and arch has it */\n if (!fieldCols) {\n return;\n }\n for (const [fieldName, fieldType] of Object.entries(componentSchema(component))) {\n const col = fieldCols.get(fieldName);\n /* istanbul ignore next -- defensive: schema fields always have columns */\n if (!col) {\n continue;\n }\n const raw = (value as Record<string, unknown>)[fieldName];\n if (fieldType === 'bool') {\n col.view[row] = raw ? 1 : 0;\n } else if (isEntityField(fieldType)) {\n // M3 entity field: encode (slot, gen) into u32 column. `null`\n // / undefined map to ENTITY_NULL_RAW sentinel.\n col.view[row] = raw === null || raw === undefined ? ENTITY_NULL_RAW : (raw as number);\n } else if (isManagedBufferField(fieldType)) {\n // M2 spawn path: collapsed-vocab keyword family `'buffer'` (variable)\n // + `'buffer<N>'` (fixed):\n // - `buffer<N>` (feat-20260602) — lives inline as a stride-N u8\n // column (arity = N). Copy any provided payload straight into the\n // row window (truncate to N); no BufferPool slot.\n // - `'buffer'` — variable capacity; alloc one BufferPool slot sized\n // to the provided payload's byteLength. Missing / non-buffer raw\n // -> alloc(0) zero-length live view (verify round 1 B2 fix path;\n // pre-fix the bare keyword routed `bufferFieldByteLength('buffer')`\n // -> NaN -> alloc(NaN) -> managed-buffer-out-of-bounds, dropping\n // the payload bytes silently). Failures route to Layer 3\n // error channel; column slot stays at 0 (sentinel) so subsequent\n // release short-circuits.\n // raw is normalized from any AllowSharedBufferSource view to a\n // Uint8Array over its bytes (feat-20260621 V2 / AC-A4).\n const bytes = normalizeBufferWrite(raw);\n if (fieldType !== 'buffer') {\n const arity = col.arity;\n if (bytes !== null) {\n const copyLen = Math.min(bytes.byteLength, arity);\n (col.view as Uint8Array).set(bytes.subarray(0, copyLen), row * arity);\n }\n } else {\n const allocBytes = bytes !== null ? bytes.byteLength : 0;\n const allocR = this.bufferPool.alloc(allocBytes);\n if (!allocR.ok) {\n const ctx: ErrorContext = {\n systemName: `World.spawn (${component.name}.${fieldName})`,\n };\n this.routeError(allocR.error, ctx);\n col.view[row] = 0;\n continue;\n }\n const slot = allocR.value;\n if (bytes !== null) {\n // allocBytes is the payload's exact byteLength so no truncation.\n const copyLen = Math.min(bytes.byteLength, slot.view.byteLength);\n slot.view.set(bytes.subarray(0, copyLen));\n }\n col.view[row] = slot.id;\n }\n } else if (fieldType === 'string') {\n // M1 string-field spawn path (AC-04 / AC-06): route the JS string\n // payload through `uniqueRefs.alloc('String', text)` -- the same\n // UniqueRefStore the `ref<T>` arm uses (D-R3 single-arm dispatch).\n // The store holds the immutable string by strong reference so\n // identity is stable across reads (AC-03). Missing / non-string raw\n // falls back to '' so AI users always see a readable string on\n // get (no nullable handling).\n const text = typeof raw === 'string' ? raw : '';\n const handle = this.uniqueRefs.alloc<'String'>('String', text);\n col.view[row] = unwrapHandle(handle);\n } else {\n const arrayMeta = componentDefinition(component).fields[fieldName]?.arrayMeta;\n if (arrayMeta !== undefined) {\n // M1 spawn path for array<T> / array<T,N> fields (D-3 double-\n // column for variable; single column for fixed).\n // Spawn path: no prior-slot release (fresh rows carry stale debris\n // owned by the migrated entity in the new archetype) — feat-20260614\n // D-3 calling convention.\n this.writeArrayField(arch, component, row, fieldName, fieldType, arrayMeta, raw);\n } else {\n col.view[row] = raw as number;\n // feat-20260614 M5 / D-5: scalar 'shared<T>' spawn retain. The\n // alloc-grant rc=1 stays held by the producer (e.g. AssetRegistry);\n // each ECS holder bumps rc via this retain so despawn / overwrite\n // releases bring rc back symmetrically. Sentinel slot 0 is a no-op.\n if (fieldType.startsWith('shared<') && (raw as number) !== 0) {\n this.retainSharedScalarHandle(raw as number, component.name, fieldName);\n }\n }\n }\n }\n }\n\n // ──────────────────────────────────────────────────────────────────────────\n // Internal — managed-ref + managed-buffer release loop (M1 / M2)\n // ──────────────────────────────────────────────────────────────────────────\n\n /** Release all ECS-owned field handles before a row is removed or overwritten. */\n private releaseManagedRefsOnRow(arch: Archetype, component: Component, row: number): void {\n const fieldCols = this.table(arch).storage.get(componentId(component))?.fields;\n if (!fieldCols) return;\n for (const fieldName of Object.keys(componentSchema(component))) {\n this.releaseManagedFieldOnRow(arch, component, row, fieldName);\n }\n }\n\n /**\n * Release one ECS-owned field according to its schema. Inline buffers have\n * no pool slot; shared-array elements still release their handles. Store\n * failures use the host error channel so row cleanup remains total.\n */\n private releaseManagedFieldOnRow(\n arch: Archetype,\n component: Component,\n row: number,\n fieldName: string,\n ): void {\n const fieldCols = this.table(arch).storage.get(componentId(component))?.fields;\n if (!fieldCols) return;\n const col = fieldCols.get(fieldName);\n if (!col) return;\n const fieldType = (componentSchema(component) as Record<string, string>)[fieldName] ?? '';\n if (isManagedField(fieldType)) {\n // Sub-dispatch by the schema-vocab keyword (feat-20260614 M4 / AC-08):\n // - 'shared<T>' scalar -> SharedRefStore.release (rc--; drop on rc=0)\n // - 'unique<T>' / 'string' -> UniqueRefStore.release (direct slot drop)\n // Both column shapes are u32 handles; the lookup store differs.\n // Keeping both arms inside the unified `isManagedField` block is\n // intentional: meta key (TYPE_METADATA `'shared'` vs `'ref'`) decides\n // the store, not a separate top-level branch (architecture-principles\n // §1 SSOT — meta key = release semantics).\n const handleU32 = col.view[row] as number;\n if (fieldType.startsWith('shared<')) {\n this.releaseSharedRefHandle(handleU32, component.name, fieldName);\n return;\n }\n this.releaseManagedRefHandle(handleU32, component.name, fieldName);\n return;\n }\n if (isManagedBufferField(fieldType)) {\n if (fieldType === 'buffer') {\n const slotId = col.view[row] as number;\n this.releaseManagedBufferSlot(slotId);\n col.view[row] = 0;\n }\n return;\n }\n if (isManagedArrayField(fieldType)) {\n // Use the pre-parsed arrayMeta cached on the component descriptor at\n // registration (AC-03c parse-free hot path); reaching for\n // `parseManagedArraySchema` here would violate the parse-free\n // invariant exercised by hierarchy.unit.test.ts §w5 AC-03(a).\n const arrayMeta = componentDefinition(component).fields[fieldName]?.arrayMeta;\n if (arrayMeta === undefined) return;\n const isSharedElement = arrayMeta.elementType.startsWith('shared<');\n if (arrayMeta.length === undefined) {\n // Variable `array<T>`: BufferPool slot id in primary column + live\n // count in `<fieldName>:count` sidecar. For `array<shared<T>>`,\n // walk live elements and release each shared handle BEFORE\n // releasing the slot bytes (feat-20260614 M4 / D-3 — slot bytes\n // are only valid until the slot is recycled).\n const slotId = col.view[row] as number;\n const countCol = fieldCols.get(arrayCountColumnName(fieldName));\n if (isSharedElement && slotId !== 0) {\n const liveCount = countCol !== undefined ? (countCol.view[row] as number) : 0;\n const slotView = liveCount > 0 ? this.bufferPool.view(slotId) : null;\n if (slotView !== null && slotView.byteLength > 0) {\n this.releaseSharedArrayElements(slotView, liveCount);\n }\n }\n this.releaseManagedBufferSlot(slotId);\n col.view[row] = 0;\n if (countCol !== undefined) countCol.view[row] = 0;\n return;\n }\n // Fixed `array<T,N>` (feat-20260602): inline stride-N column, no\n // BufferPool slot to release. For `array<shared<T>,N>`, walk the N\n // inline elements and release each shared handle. Zero the row\n // window so subsequent writes do not double-release.\n if (isSharedElement) {\n const arity = col.arity;\n const elementBytes = (TYPE_METADATA.shared?.byteSize ?? 4) as number;\n const rowByteOffset = col.view.byteOffset + row * arity * elementBytes;\n const rowBytes = new Uint8Array(col.view.buffer, rowByteOffset, arity * elementBytes);\n this.releaseSharedArrayElements(rowBytes, arity);\n rowBytes.fill(0);\n }\n }\n }\n\n /** Release one unique-ref handle; sentinel 0 is ignored. */\n private releaseManagedRefHandle(\n handleU32: number,\n componentName: string,\n fieldName: string,\n ): void {\n if (handleU32 === 0) return; // sentinel: skip silently.\n const r = this.uniqueRefs.release(handleU32 as Handle<string, 'unique'>);\n if (r.ok) return;\n // Layer 3 routing: surface double-release as a structured error so AI\n // users see {code, hint, expected, detail} on their handler. Severity\n // defaults to Error so the chain continues; matchSeverity prints to\n // console.error rather than throw.\n const ctx: ErrorContext = {\n systemName: `World.release (${componentName}.${fieldName})`,\n };\n this.routeError(r.error, ctx);\n }\n\n /** Release one shared-ref handle, preserving builtin slots and refcounts. */\n private releaseSharedRefHandle(\n handleU32: number,\n componentName: string,\n fieldName: string,\n ): void {\n // feat-20260614 M6 D-15 / R-14: builtin slots (< BUILTIN_BASE, including the\n // sentinel 0) are process-static and never reference-counted -> short-circuit\n // before touching SharedRefStore. This single guard is the SSOT for both the\n // scalar arm (here) and the array-element arm (releaseSharedArrayElements).\n if (handleU32 < BUILTIN_BASE) return;\n const r = this.sharedRefs.release(toShared<string>(handleU32));\n if (r.ok) return;\n const ctx: ErrorContext = {\n systemName: `World.release (${componentName}.${fieldName})`,\n };\n this.routeError(r.error, ctx);\n }\n\n /** Retain one shared-ref scalar handle for a World-owned field. */\n private retainSharedScalarHandle(\n handleU32: number,\n componentName: string,\n fieldName: string,\n ): void {\n // feat-20260614 M6 D-15 / R-14: builtin slots (< BUILTIN_BASE, including the\n // sentinel 0) short-circuit — process-static, never reference-counted. SSOT\n // guard shared with the array-element arm (retainSharedArrayElements).\n if (handleU32 < BUILTIN_BASE) return;\n const r = this.sharedRefs.retain(toShared<string>(handleU32));\n if (r.ok) return;\n const ctx: ErrorContext = {\n systemName: `World.write (${componentName}.${fieldName} shared scalar retain)`,\n };\n this.routeError(r.error, ctx);\n }\n\n /** Release one variable-buffer slot; id 0 is the unallocated sentinel. */\n private releaseManagedBufferSlot(slotId: number): void {\n if (slotId === 0) return; // sentinel: skip silently.\n this.bufferPool.release(slotId);\n }\n\n // ──────────────────────────────────────────────────────────────────────────\n // Internal — array<T> / array<T,N> spawn / set helpers (M1 / w7)\n // ──────────────────────────────────────────────────────────────────────────\n\n /**\n * Attach field context to a `ManagedArrayErrorEnvelope`.\n * The envelope shape (`code / hint / expected / detail`) already mirrors\n * the EcsError contract; this helper only attaches the systemName context\n * so AI users can correlate the error with the holder component / field.\n */\n private routeArrayError(\n err: ManagedArrayErrorEnvelope,\n componentName: string,\n fieldName: string,\n ): void {\n const ctx: ErrorContext = {\n systemName: `World.write (${componentName}.${fieldName})`,\n };\n this.routeError(err, ctx);\n }\n\n /**\n * Write an array field for spawn or set. Fixed arrays stay inline; variable\n * arrays use one BufferPool slot plus a live-count sidecar.\n */\n private writeArrayField(\n arch: Archetype,\n component: Component,\n row: number,\n fieldName: string,\n _fieldType: string,\n arrayMeta: ArrayMeta,\n raw: unknown,\n ): void {\n const fieldCols = this.table(arch).storage.get(componentId(component))?.fields;\n /* istanbul ignore next -- writeArrayField caller validated the column map */\n if (!fieldCols) return;\n const col = fieldCols.get(fieldName);\n /* istanbul ignore next -- writeArrayField caller validated the column */\n if (!col) return;\n\n const elementType = arrayMeta.elementType;\n // Normalize parametrised element-type template literals to the family\n // key for TYPE_METADATA lookup; the column stores plain u32 handles\n // either way:\n // - `shared<X>` -> 'shared' (feat-20260614 M4 / D-3 -- element-level\n // retain/release semantics route via the dedicated `'shared'` arm\n // below)\n const metaKey = elementType.startsWith('shared<') ? 'shared' : (elementType as string);\n const meta = TYPE_METADATA[metaKey];\n /* istanbul ignore next -- arrayMeta.elementType is guaranteed in TYPE_METADATA */\n if (!meta) return;\n // biome-ignore lint/style/noNonNullAssertion: every array element type has a byte size\n const elementBytes = meta.byteSize!;\n\n const isVariable = arrayMeta.length === undefined;\n const fixedLength = arrayMeta.length ?? 0;\n\n // Determine the payload's logical element count. Accept any TypedArray\n // (Float32Array / Uint32Array / etc.) plus plain numeric arrays; an\n // undefined / missing payload is treated as a length-0 init. Bytes are\n // copied from the source's underlying ArrayBuffer when present.\n let payloadCount = 0;\n let payloadBytes: Uint8Array | null = null;\n if (raw !== null && raw !== undefined) {\n if (\n raw instanceof Float32Array ||\n raw instanceof Float64Array ||\n raw instanceof Int32Array ||\n raw instanceof Uint32Array ||\n raw instanceof Int16Array ||\n raw instanceof Uint16Array ||\n raw instanceof Int8Array ||\n raw instanceof Uint8Array\n ) {\n payloadCount = raw.length;\n payloadBytes = new Uint8Array(raw.buffer, raw.byteOffset, raw.byteLength);\n } else if (Array.isArray(raw)) {\n payloadCount = raw.length;\n // Plain JS array: pack each element through the declared element\n // type's TypedArray constructor (`meta.viewCtor`) so the numeric\n // VALUE is encoded, not its integer bit pattern. Dispatching on\n // `viewCtor` (the type SSOT) rather than byte size is what keeps\n // `array<f32,N>` distinct from `array<u32,N>` -- both are 4 bytes,\n // so a size-keyed setter would store an f32 `1.0` as the u32 bits\n // `0x00000001` (reads back ~1.4e-45). The TypedArray then exposes\n // its little-endian bytes for the shared copy path below.\n if (payloadCount > 0 && meta.viewCtor !== undefined) {\n const typed = new meta.viewCtor(payloadCount);\n for (let i = 0; i < payloadCount; i++) {\n const val = raw[i];\n typed[i] = typeof val === 'number' ? val : 0;\n }\n payloadBytes = new Uint8Array(typed.buffer, typed.byteOffset, typed.byteLength);\n }\n }\n }\n\n // Effective count for variable arrays = payload count; for fixed\n // arrays = schema-declared N (the payload's length is advisory — we\n // copy up to N elements and pad the rest with zero).\n const effectiveCount = isVariable ? payloadCount : fixedLength;\n\n // Fixed `array<T,N>` (feat-20260602): the column is an inline stride-N\n // view (`col.arity === N`), so write the payload bytes directly into the\n // row's stride window — no BufferPool slot, no slot-id store, no\n // prior-slot release. The byte window starts at `row * arity * elementBytes`\n // and spans N elements; payloads shorter than N copy a prefix and leave\n // the tail at its current value (spawn rows are zero-initialised by the\n // fresh column buffer; the swap-pop migration copies the whole block).\n if (!isVariable) {\n const arity = col.arity;\n const rowByteOffset = col.view.byteOffset + row * arity * elementBytes;\n const rowBytes = new Uint8Array(col.view.buffer, rowByteOffset, arity * elementBytes);\n const copyLen =\n payloadBytes === null ? 0 : Math.min(payloadBytes.byteLength, rowBytes.byteLength);\n if (copyLen > 0 && payloadBytes !== null) {\n rowBytes.set(payloadBytes.subarray(0, copyLen));\n }\n // Zero the tail past the copied prefix so a short / missing payload\n // matches the prior fresh-slot semantics (the old pool path always\n // alloc'd a zeroed slot, so unwritten elements read back as 0).\n if (copyLen < rowBytes.byteLength) {\n rowBytes.fill(0, copyLen);\n }\n // feat-20260614 M4 / D-3: `array<shared<T>,N>` element-level retain.\n // Walk the copied prefix as u32 handles and retain each non-sentinel\n // element. Caller releases priors via `releaseManagedFieldOnRow` on\n // the set path (D-3 calling convention); the spawn path's fresh row\n // is zero-initialised so no priors exist.\n if (metaKey === 'shared' && copyLen > 0) {\n this.retainSharedArrayElements(rowBytes, copyLen >>> 2);\n }\n return;\n }\n\n // Variable `array<T>`: prior-slot release lives at the caller (set path)\n // — D-3 calling convention. Spawn path's fresh rows carry stale swap-pop\n // debris which MUST NOT be released here.\n const byteLength = effectiveCount * elementBytes;\n const allocR = this.bufferPool.alloc(byteLength);\n if (!allocR.ok) {\n this.routeArrayError(\n {\n code: allocR.error.code,\n hint: allocR.error.hint,\n expected: allocR.error.expected,\n detail: allocR.error.detail,\n } as ManagedArrayErrorEnvelope,\n component.name,\n fieldName,\n );\n col.view[row] = 0;\n if (isVariable) {\n const countCol = fieldCols.get(arrayCountColumnName(fieldName));\n if (countCol !== undefined) countCol.view[row] = 0;\n }\n return;\n }\n const slot = allocR.value;\n if (payloadBytes !== null) {\n const copyLen = Math.min(payloadBytes.byteLength, slot.view.byteLength);\n slot.view.set(payloadBytes.subarray(0, copyLen));\n }\n col.view[row] = slot.id;\n if (isVariable) {\n const countCol = fieldCols.get(arrayCountColumnName(fieldName));\n /* istanbul ignore else -- count column allocated by createArchetype */\n if (countCol !== undefined) countCol.view[row] = effectiveCount;\n }\n // feat-20260614 M4 / D-3: variable `array<shared<T>>` element-level\n // retain. Walk the live element prefix (effectiveCount u32 handles) and\n // retain each non-sentinel handle. Prior elements were released by the\n // caller via `releaseManagedFieldOnRow` on the set path (D-3 calling\n // convention); the spawn path has no priors.\n if (metaKey === 'shared' && effectiveCount > 0) {\n this.retainSharedArrayElements(slot.view, effectiveCount);\n }\n }\n\n /**\n * Walk the first `count` u32 handles in `bytes` and call\n * `SharedRefStore.retain` on each non-sentinel slot id (feat-20260614 M4 /\n * D-3). Failures route via the error channel so the write chain stays\n * total; charter explicit-failure boundary lets AI users see structured\n * `shared-ref-released` payloads when retaining a stale handle.\n *\n * Helper-internal -- only called from `writeArrayField`'s `'shared'` arm.\n */\n private retainSharedArrayElements(bytes: Uint8Array, count: number): void {\n const view = new Uint32Array(bytes.buffer, bytes.byteOffset, count);\n for (let i = 0; i < count; i++) {\n const raw = view[i];\n if (raw === undefined) continue;\n // R-14: route through the scalar SSOT helper so the `< BUILTIN_BASE`\n // short-circuit (builtin slots + sentinel 0) lives in exactly one place.\n this.retainSharedScalarHandle(raw, 'array<shared<T>>', 'element');\n }\n }\n\n /**\n * Walk the first `count` u32 handles in `bytes` and call\n * `SharedRefStore.release` on each non-sentinel slot id (feat-20260614 M4 /\n * D-3). Mirrors `retainSharedArrayElements`; called from\n * `releaseManagedFieldOnRow`'s array arm BEFORE the BufferPool slot is\n * released so the underlying bytes are still valid.\n */\n private releaseSharedArrayElements(bytes: Uint8Array, count: number): void {\n const view = new Uint32Array(bytes.buffer, bytes.byteOffset, count);\n for (let i = 0; i < count; i++) {\n const raw = view[i];\n if (raw === undefined) continue;\n // R-14: route through the scalar SSOT helper so the `< BUILTIN_BASE`\n // short-circuit (builtin slots + sentinel 0) lives in exactly one place.\n this.releaseSharedRefHandle(raw, 'array<shared<T>>', 'element');\n }\n }\n\n /**\n * Materialize an array snapshot. Fixed arrays alias their inline column;\n * variable arrays alias the live BufferPool slot and use the count sidecar.\n * Both views are transient and must not be held across structural changes.\n */\n private materializeArrayView(\n col: Column,\n row: number,\n arrayMeta: ArrayMeta,\n elementCount: number,\n ): FieldView {\n if (arrayMeta.length !== undefined) {\n // Fixed `array<T,N>` (feat-20260602): the elements live INLINE in the\n // stride-N column. Reinterpret the row's byte window directly — no\n // BufferPool indirection.\n const elementBytes = elementByteSize(arrayMeta.elementType);\n const arity = col.arity;\n const rowByteOffset = col.view.byteOffset + row * arity * elementBytes;\n return reinterpretBufferRegion(\n col.view.buffer,\n rowByteOffset,\n arrayMeta.elementType,\n arrayMeta.length,\n );\n }\n return reinterpretSlotBytes(\n this.bufferPool.view(col.view[row] as number),\n arrayMeta.elementType,\n elementCount,\n );\n }\n\n // ──────────────────────────────────────────────────────────────────────────\n // Internal — archetype migration\n // ──────────────────────────────────────────────────────────────────────────\n\n /**\n * Copy surviving component columns into the target row, then swap-remove\n * the source row. Managed handles and variable-array sidecars are copied\n * verbatim; release remains the responsibility of remove/despawn paths.\n */\n private migrateEntity(record: EntityRecord, srcArch: Archetype, targetArch: Archetype): void {\n const oldArchetypeRow = record.archetypeRow;\n const oldTableRow = srcArch.rows[oldArchetypeRow] ?? 0;\n const srcTable = this.table(srcArch);\n const targetTable = this.table(targetArch);\n const entity = (srcTable.storage.get(componentId(EntityComponent))?.fields.get('self')?.view[\n oldTableRow\n ] ?? 0) as EntityHandle;\n const newTableRow = appendTableRow(targetTable, entity);\n const newArchetypeRow = appendArchetypeRow(targetArch, newTableRow);\n\n // Copy shared component data.\n for (const [compId, srcComponentStorage] of srcTable.storage) {\n const srcFieldCols = srcComponentStorage.fields;\n const targetComponentStorage = targetTable.storage.get(compId);\n const targetFieldCols = targetComponentStorage?.fields;\n if (!targetFieldCols) {\n continue; // Component was removed — skip.\n }\n for (const [fieldName, srcCol] of srcFieldCols) {\n const targetCol = targetFieldCols.get(fieldName);\n if (!targetCol) {\n continue;\n }\n // Copy the whole stride-N block per row. Scalar / variable / `:count`\n // columns have arity 1 (single-element copy, byte-identical to the\n // prior `view[newRow] = view[oldRow]` form); fixed inline\n // `array<T,N>` / `buffer<N>` columns carry their N elements inline and\n // must migrate the entire block (feat-20260602).\n const arity = srcCol.arity;\n targetCol.view.set(\n srcCol.view.subarray(oldTableRow * arity, oldTableRow * arity + arity),\n newTableRow * arity,\n );\n }\n if (targetComponentStorage !== undefined) {\n copyComponentEpoch(\n srcComponentStorage.epochs,\n oldTableRow,\n targetComponentStorage.epochs,\n newTableRow,\n );\n }\n }\n\n const archetypeSwap = removeArchetypeRow(srcArch, oldArchetypeRow);\n if (archetypeSwap !== null) {\n const movedEntity = (srcTable.storage.get(componentId(EntityComponent))?.fields.get('self')\n ?.view[archetypeSwap.movedTableRow] ?? 0) as EntityHandle;\n const movedRecord = this.records[entityIndex(movedEntity)];\n if (movedRecord?.generation === entityGeneration(movedEntity)) {\n movedRecord.archetypeRow = archetypeSwap.newRow;\n }\n }\n const tableSwap = removeTableRow(srcTable, oldTableRow);\n if (tableSwap !== null) {\n const movedRecord = this.records[entityIndex(tableSwap.movedEntity)];\n if (movedRecord?.generation === entityGeneration(tableSwap.movedEntity)) {\n const movedArchetype = this.graph.archetypes[movedRecord.archetypeId];\n if (movedArchetype !== undefined) {\n movedArchetype.rows[movedRecord.archetypeRow] = tableSwap.newRow;\n }\n }\n }\n\n record.archetypeId = targetArch.id;\n record.archetypeRow = newArchetypeRow;\n }\n\n private moveEntityArchetype(\n record: EntityRecord,\n srcArch: Archetype,\n targetArch: Archetype,\n ): void {\n const table = this.table(srcArch);\n if (srcArch.tableId !== targetArch.tableId) {\n throw new Error('Logical archetype move requires a shared Table.');\n }\n const oldArchetypeRow = record.archetypeRow;\n const tableRow = srcArch.rows[oldArchetypeRow] ?? 0;\n const archetypeSwap = removeArchetypeRow(srcArch, oldArchetypeRow);\n if (archetypeSwap !== null) {\n const movedEntity = (table.storage.get(componentId(EntityComponent))?.fields.get('self')\n ?.view[archetypeSwap.movedTableRow] ?? 0) as EntityHandle;\n const movedRecord = this.records[entityIndex(movedEntity)];\n if (movedRecord?.generation === entityGeneration(movedEntity)) {\n movedRecord.archetypeRow = archetypeSwap.newRow;\n }\n }\n record.archetypeId = targetArch.id;\n record.archetypeRow = appendArchetypeRow(targetArch, tableRow);\n }\n\n /**\n * Retire one live entity and any linked-spawn descendants. The complete\n * row/relationship/managed-data mutation stays on World so a failure after\n * the first write can poison this identity instead of crossing an extraction\n * owner boundary.\n */\n private despawnEntity(entity: EntityHandle, internal: boolean): Result<void, EcsError> {\n const slot = entityIndex(entity);\n const generation = entityGeneration(entity);\n const record = this.records[slot];\n if (!this.recordIsLive(record, generation)) return ok(undefined);\n\n const archetype = this.graph.archetypes[record.archetypeId];\n const linkedChildren =\n archetype === undefined ? [] : this.relationshipLinkedSpawnChildren(entity, archetype);\n let mutationStarted = false;\n try {\n if (archetype !== undefined) {\n const table = this.table(archetype);\n const archetypeRow = record.archetypeRow;\n const tableRow = archetype.rows[archetypeRow] ?? 0;\n mutationStarted = true;\n for (const component of archetype.components) {\n const role = relationshipRole(component);\n if (role?.kind === 'source' && !internal) {\n const oldValue = this.readRow(archetype, component, tableRow) as Record<\n string,\n unknown\n >;\n const relation = this.relationshipOnRemove(entity, component, oldValue);\n if (!relation.ok) {\n this.poisonAfterEntityMutation('World.despawn', relation.error);\n return relation;\n }\n }\n this.releaseManagedRefsOnRow(archetype, component, tableRow);\n }\n for (const component of archetype.components) {\n if (component.storage !== 'sparse') continue;\n const sparse = this.graph.sparseTags.get(componentId(component));\n if (sparse !== undefined) removeSparseTag(sparse, entity);\n }\n const archetypeSwap = removeArchetypeRow(archetype, archetypeRow);\n if (archetypeSwap !== null) {\n const movedEntity = (table.storage.get(componentId(EntityComponent))?.fields.get('self')\n ?.view[archetypeSwap.movedTableRow] ?? 0) as EntityHandle;\n const movedRecord = this.records[entityIndex(movedEntity)];\n if (movedRecord?.generation === entityGeneration(movedEntity)) {\n movedRecord.archetypeRow = archetypeSwap.newRow;\n }\n }\n const tableSwap = removeTableRow(table, tableRow);\n if (tableSwap !== null) {\n const movedRecord = this.records[entityIndex(tableSwap.movedEntity)];\n if (movedRecord?.generation === entityGeneration(tableSwap.movedEntity)) {\n const movedArchetype = this.graph.archetypes[movedRecord.archetypeId];\n if (movedArchetype !== undefined) {\n movedArchetype.rows[movedRecord.archetypeRow] = tableSwap.newRow;\n }\n }\n }\n }\n this.recordStructuralEvidence({ kind: 'despawn', entity });\n record.archetypeId = -1;\n record.archetypeRow = -1;\n record.generation += 1;\n if (!isRetiredSlot(record.generation)) this.freeIndices.push(slot);\n for (const child of linkedChildren) {\n const childResult = this.despawnEntity(child, true);\n if (!childResult.ok) return childResult;\n }\n this.advanceStructureEpoch();\n return ok(undefined);\n } catch (error) {\n if (mutationStarted) this.poisonAfterEntityMutation('World.despawn', error);\n throw error;\n }\n }\n\n // ──────────────────────────────────────────────────────────────────────────\n // Spawn\n // ──────────────────────────────────────────────────────────────────────────\n\n /**\n * Spawn an entity with one or more components.\n * Multi-component spawn directly targets the correct archetype (AC-06).\n *\n * @returns `Result<Entity, EcsError>` — `ok(Entity)` on success.\n * EntityIndexOverflowError still throws (build-time / infrastructure failure).\n *\n * @example\n * ```ts\n * const Position = defineComponent('Position', { x: 'f32', y: 'f32' });\n * const world = new World();\n * const r = world.spawn({ component: Position, data: { x: 0, y: 0 } });\n * if (!r.ok) { console.error(r.error.code); return; }\n * const entity = r.value;\n * ```\n */\n spawn<const SArr extends readonly ComponentSchema[]>(\n ...componentDatas: {\n [K in keyof SArr]: {\n component: Component<string, SArr[K]>;\n data: Partial<InputShapeOf<SArr[K]>>;\n };\n }\n ): Result<EntityHandle, EcsError>;\n spawn(...componentDatas: ComponentData[]): Result<EntityHandle, EcsError> {\n const poisoned = this.poisonedResult<EntityHandle>();\n if (poisoned !== undefined) return poisoned;\n const target = componentDatas.find(\n (data) =>\n isRelationshipTarget(data.component) &&\n this.relationshipTargetPayloadWrites(data.data as Record<string, unknown>),\n );\n if (target !== undefined) return this.relationshipTargetWriteError(target.component, 'spawn');\n return spawnCore(this, componentDatas);\n }\n\n // ──────────────────────────────────────────────────────────────────────────\n // Despawn (D-08: generation retirement)\n // ──────────────────────────────────────────────────────────────────────────\n\n /**\n * Despawn an entity. Stale handles are silently ignored (E-01, AC-17).\n * Generation retirement: gen=255 → index permanently retired (D-08/E-08).\n *\n * @returns `Result<void, EcsError>` — `ok(void)` always (idempotent on stale handles).\n *\n * @example\n * ```ts\n * const Position = defineComponent('Position', { x: 'f32', y: 'f32' });\n * const world = new World();\n * const e = world.spawn({ component: Position, data: { x: 0, y: 0 } }).unwrap();\n * const r = world.despawn(e);\n * r.unwrap(); // idempotent: ok(void) even on stale handle\n * ```\n */\n despawn(entity: EntityHandle): Result<void, EcsError> {\n const poisoned = this.poisonedResult<void>();\n if (poisoned !== undefined) return poisoned;\n return this.despawnEntity(entity, false);\n }\n\n /** Despawn every live entity through the normal lifecycle and ref cleanup path. */\n despawnAll(): Result<void, EcsError> {\n const poisoned = this.poisonedResult<void>();\n if (poisoned !== undefined) return poisoned;\n const entities: EntityHandle[] = [];\n for (let index = 0; index < this.records.length; index += 1) {\n const record = this.records[index];\n if (record !== undefined && record.archetypeId >= 0) {\n entities.push(encodeEntity(index, record.generation));\n }\n }\n for (const entity of entities) {\n const result = this.despawn(entity);\n if (!result.ok) return result;\n }\n return ok(undefined);\n }\n\n // ──────────────────────────────────────────────────────────────────────────\n // Hierarchy facade — lifecycle orchestration lives in world-entity-lifecycle.\n // World owns the component storage and relationship mutation primitives.\n // ──────────────────────────────────────────────────────────────────────────\n\n addChild<S extends ComponentSchema>(\n parent: EntityHandle,\n child: EntityHandle,\n component: Component<string, S>,\n data: Partial<InputShapeOf<S>>,\n ): Result<void, EcsError> {\n const poisoned = this.poisonedResult<void>();\n if (poisoned !== undefined) return poisoned;\n return worldAddChild(this, parent, child, component, data);\n }\n\n removeChild<S extends ComponentSchema>(\n parent: EntityHandle,\n child: EntityHandle,\n component: Component<string, S>,\n ): Result<void, EcsError> {\n const poisoned = this.poisonedResult<void>();\n if (poisoned !== undefined) return poisoned;\n return worldRemoveChild(this, parent, child, component);\n }\n\n reparent<S extends ComponentSchema>(\n child: EntityHandle,\n newParent: EntityHandle,\n component: Component<string, S>,\n data: Partial<InputShapeOf<S>>,\n ): Result<void, EcsError> {\n const poisoned = this.poisonedResult<void>();\n if (poisoned !== undefined) return poisoned;\n return worldReparent(this, child, newParent, component, data);\n }\n\n iterAncestors(entity: EntityHandle): Iterable<EntityHandle> {\n return worldIterAncestors(this, entity);\n }\n\n iterDescendants(entity: EntityHandle): Iterable<EntityHandle> {\n return worldIterDescendants(this, entity);\n }\n}\n","/**\n * @module @forgeax/engine-ecs\n *\n * Archetype ECS with Result-based mutation errors and poisoned-frame recovery:\n *\n * 1. **Layer 1 (World methods)** — every mutation (`get`/`set`/`spawn`/`despawn`/\n * `addComponent`/`removeComponent`) returns `Result<T, EcsError>`.\n * Use `.unwrap()` for quick-and-dirty or `if (!r.ok) ... r.error ...` for programmatic branching.\n *\n *\n * AI users: import types from this module — `.d.ts` signatures expose\n * `Result<T, EcsError>` on all World methods, making error paths discoverable\n * without reading source. Switch on `.code` for programmatic error branching.\n *\n * **Warning — Result propagation in system bodies**: TypeScript lacks Rust's `?`\n * operator. Handle every Result branch explicitly or return the failure from\n * the system so the frame poison boundary can stop the host.\n */\n\n// Layered exports: core API first (World / defineComponent / Entity / Query),\n// then Result + error types, then advanced API (Schedule / CommandBuffer),\n// then errors, then constants. AI users reading .d.ts see high-frequency\n// APIs at the top of the file (charter V1 proposition 1).\n\n// ────────────────────────────────────────────────────────────────────────────\n// Result type — the return type of all World mutation methods\n// ────────────────────────────────────────────────────────────────────────────\n\n/**\n * Discriminated union result type: `ResultOk<T>` or `ResultErr<E>`.\n * All World mutation methods return `Result<T, EcsError>`. The discriminant\n * is `.ok: boolean`; the success branch carries `.value: T`, the failure\n * branch carries `.error: E`. Method chain: `.unwrap()` / `.unwrapOr(d)`.\n *\n * @example\n * ```ts\n * // Plain field-access idiom (charter proposition 5 consistent abstraction):\n * const r = world.get(entity, Position);\n * if (!r.ok) { console.error(r.error.code, r.error.hint); return; }\n * const data = r.value; // ShapeOf<S>\n *\n * // Method-chain idiom (`.unwrap()` throws the original EcsError on err):\n * const data2 = world.get(entity, Position).unwrap();\n *\n * // Defaulted-fallback idiom (charter proposition 4 explicit-failure\n * // boundary — `unwrapOr` silently drops the error):\n * const data3 = world.get(entity, Position).unwrapOr({ x: 0, y: 0 });\n * ```\n */\n\nimport { isComponentDefinitionOrderValid } from './component';\n// ────────────────────────────────────────────────────────────────────────────\n// Essential-id forced registration (feat-20260602 M1 / w1; plan-strategy\n// D-1 / D-6b; feat-20260611 D-9 SSOT switch to ESSENTIAL_COMPONENT_IDS).\n//\n// The `Entity` component MUST be the first `defineComponent` evaluated in the\n// process so the owner identity assigns it id=0. ESM\n// evaluates import bindings in source order before any other statement, so this\n// import -- placed textually first among the barrel's module imports -- forces\n// `entity.ts` (and thus `defineComponent('Entity', ...)`) to run ahead of\n// every downstream component module. The fail-fast assertion below converts\n// an import-order regression from a silent runtime mis-id into a structured\n// startup throw (charter P3).\n//\n// The assertion reads `ESSENTIAL_COMPONENT_IDS` (the SSOT for which ids must\n// be present and where) rather than hard-coding a token property so adding a\n// future essential component requires updating exactly one place.\n//\n// `Entity` is re-exported from the barrel as a value (the id=0 component\n// token). The matching type-space handle type is `EntityHandle`, re-exported\n// from `./entity-handle` -- the two no longer share a name (feat-20260611 I-1;\n// renamed from `./entity` to `./entity-handle` in tweak-20260611-M3 to make\n// the file's role explicit; tweak-20260612 then lifted the Entity component\n// from the historical `components/entity.ts` back into `./entity` since that\n// slot was free).\nimport { Disabled, Entity, ESSENTIAL_COMPONENT_IDS, foldEssentials } from './entity';\n\nif (\n !isComponentDefinitionOrderValid() ||\n ESSENTIAL_COMPONENT_IDS.length !== 1 ||\n ESSENTIAL_COMPONENT_IDS[0] !== 0\n) {\n throw new Error(\n 'forgeax-engine-ecs: ESSENTIAL_COMPONENT_IDS invariant violated ' +\n `(expected [0], got [${ESSENTIAL_COMPONENT_IDS.join(', ')}]). ` +\n 'A defineComponent() call evaluated before the @forgeax/engine-ecs barrel forced the id counter ' +\n 'past 0. Ensure no module defines a component at import time before importing from the barrel.',\n );\n}\n\n/**\n * Branded-number handle type identifying a row (24-bit index + 8-bit\n * generation). The `Entity` component token (value-space, id=0) and the\n * `EntityHandle` type (type-space) are deliberately separate names since\n * feat-20260611 -- a single shared name caused repeated AI-user confusion in\n * `: Entity` annotations.\n */\nexport type { EntityHandle } from './entity-handle';\nexport type { EcsErrorCode } from './errors';\nexport { SharedRefStaleError, UniqueRefStaleError } from './errors';\nexport {\n createWorldContext,\n worldPlugin,\n} from './plugin-service';\nexport {\n defineRelationship,\n type RelationshipTargetComponent,\n} from './relationship-index';\nexport {\n FixedUpdate,\n type ScheduleName,\n type ScheduleToken,\n Update,\n} from './schedule-token';\nexport {\n FixedTime,\n type FixedTimeResource,\n Time,\n type TimePolicy,\n type TimeResource,\n type WorldOptions,\n} from './time';\n/**\n * Union of all EcsError types returned by World methods via Result.\n * Switch on `.code` for programmatic branching (e.g. `error.code === 'stale-entity'`).\n */\nexport type { EcsError } from './world';\n/**\n * The id=0 essential `Entity` component token. The matching type-space handle\n * type (the branded number returned by `world.spawn` and accepted by every\n * World method that takes an entity argument) is `EntityHandle`, exported\n * separately from this barrel.\n *\n * @example Handle type + spawn:\n * ```ts\n * const e: EntityHandle = world.spawn({ component: Position, data: { x: 0, y: 0 } }).unwrap();\n * ```\n * @example Read the handle off its own column / probe liveness:\n * ```ts\n * world.get(e, Entity).unwrap().self === e;\n * ```\n */\nexport { Disabled, Entity, ESSENTIAL_COMPONENT_IDS, foldEssentials };\n\n// ────────────────────────────────────────────────────────────────────────────\n// Core API — the 80% surface most users need\n// ────────────────────────────────────────────────────────────────────────────\n\n/**\n * Two-axis phantom-branded handle: `Handle<TargetTag, Mode>`.\n *\n * - `Mode = 'unique'` — released by ECS on despawn / removeComponent / set\n * (e.g. derived from schema vocab `ref<T>`).\n * - `Mode = 'shared'` — external owner manages release; ECS treats as\n * plain id (e.g. derived from schema vocab `handle<T>`,\n * `MeshFilter.assetHandle: Handle<'MeshAsset','shared'>`).\n *\n * Cross-mode and cross-target assignment is a TS error (AC-02).\n *\n * The handle type is owned by `@forgeax/engine-types`; ECS schema fields\n * consume it but the ECS barrel does not forward the type.\n *\n * @example\n * ```ts\n * import type { Handle } from '@forgeax/engine-types';\n *\n * declare const mesh: Handle<'MeshAsset', 'shared'>;\n * // const mat: Handle<'MaterialAsset', 'shared'> = mesh; // TS error\n * ```\n */\n/**\n * Opaque component token carrying name + schema type information.\n *\n * Prefer letting `defineComponent` infer the type — both the literal name `N`\n * and schema `S` flow through, enabling typed `QueryRow.get` / `QueryRow.mut`\n * access without `as` assertions.\n *\n * @example\n * ```ts\n * // Recommended — infer both N and S:\n * const Pos = defineComponent('Pos', { x: 'f32', y: 'f32' });\n * // ^? Component<'Pos', { x: 'f32'; y: 'f32' }>\n *\n * // Only annotate when you must — and use both type parameters:\n * const Vel: Component<'Vel', { dx: 'f32'; dy: 'f32' }> =\n * defineComponent('Vel', { dx: 'f32', dy: 'f32' });\n * ```\n */\nexport type {\n Component,\n ComponentSchema,\n FieldReflection,\n InputShapeOf,\n SchemaOf,\n ShapeOf,\n} from './component';\n/**\n * Declare a component schema. Returns a frozen opaque token with `.name`, `.fields`, `.storage`.\n *\n * @example\n * ```ts\n * const Position = defineComponent('Position', { x: 'f32', y: 'f32' });\n * ```\n */\nexport { defineComponent } from './component';\n/**\n * Query descriptor for With/Without archetype filtering.\n *\n * @example\n * ```ts\n * const desc: QueryDescriptor = { with: [Position, Velocity], without: [Static] };\n * ```\n */\nexport type {\n Query,\n QueryCreationError,\n QueryDescriptor,\n QueryRow,\n QuerySpan,\n} from './query/query';\n/**\n * ECS-aware refcount-tracked handle store (M3). Owns the lifecycle of every\n * `Handle<T, 'shared'>` derived from `shared<T>` schema fields. The producer\n * (typically AssetRegistry) calls `alloc` once (alloc-grant rc=1); each\n * additional holder retains; release decrements; rc 1 -> 0 drops the slot\n * and publishes structured release evidence. Payload disposal belongs to the\n * renderer/assets/plugin owner; ECS invokes no user callback.\n *\n * D-15: the store manages ONLY user-tier slots (`>= BUILTIN_BASE`); builtin\n * asset payloads are process-static in their authoring package\n * (@forgeax/engine-runtime) and never reference-counted. Passing a builtin\n * slot fails fast with `BuiltinSlotNotOwnedError`.\n *\n * `World` owns one `SharedRefStore` per instance, exposed as\n * `world.sharedRefs`. The schema-field write barrier (retain on spawn / set,\n * release on despawn / removeComponent) short-circuits on builtin slots.\n *\n * @example\n * ```ts\n * const world = new World();\n * const handle = world.allocSharedRef('MaterialAsset', payload);\n * const M = defineComponent('M', { asset: 'shared<MaterialAsset>' });\n * world.spawn({ component: M, data: { asset: handle } });\n * // the SharedRefStore publishes release evidence at rc=0.\n * ```\n */\nexport type { SharedRefReleaseEvidence } from './shared-ref-store';\n\n/**\n * ECS-managed handle store (M1). Owns the lifecycle of every\n * `Handle<T, 'unique'>` derived from `ref<T>` schema fields - World hooks\n * `despawn` / `removeComponent` / `set` into `release(handle)`.\n *\n * `World` owns one `UniqueRefStore` per instance, constructed eagerly in the\n * `World` constructor (always-on since feat-20260515-string-managed-collapse).\n * Production code rarely touches the store directly - schema-vocab `ref<T>`\n * fields make `world.get(e, C).<refField>` the canonical access path.\n *\n * @example\n * ```ts\n * const Material = defineComponent('Material', { handle: 'unique<MaterialPayload>' });\n * const world = new World();\n * // World owns the UniqueRefStore internally; AI users do not wire it.\n * ```\n */\n\n/**\n * Component data bundle for spawn/addComponent: pairs a component token with initial values.\n *\n * @example\n * ```ts\n * const data: ComponentData = { component: Position, data: { x: 1, y: 2 } };\n * ```\n */\nexport type { ComponentData } from './world';\n/**\n * Top-level ECS container. Owns entities, archetypes, systems, and resources.\n *\n * @example\n * ```ts\n * const world = new World();\n * const e = world.spawn({ component: Position, data: { x: 0, y: 0 } });\n * world.update();\n * ```\n */\nexport { World } from './world';\n\n// ────────────────────────────────────────────────────────────────────────────\n// Advanced API — system scheduling, commands, resources, inspection\n// ────────────────────────────────────────────────────────────────────────────\n\n/**\n * Deferred command buffer passed to system functions. Queues structural changes\n * (spawn/despawn/addComponent/removeComponent) for end-of-frame flush.\n *\n * @example\n * ```ts\n * fn: (world, results, commands) => {\n * const e = commands.spawn({ component: Bullet, data: { dmg: 10 } });\n * commands.despawn(oldEntity);\n * }\n * ```\n */\nexport type { CommandBuffer } from './commands';\n/**\n * System descriptor for `world.addSystem()`. Declares queries, execution function,\n * and optional before/after ordering constraints.\n *\n * @example\n * ```ts\n * world.addSystem(Update, {\n * name: 'movement',\n * queries: [{ with: [Position, Velocity] }],\n * fn: (world, results, commands) => { ... },\n * });\n * ```\n */\n/**\n * SystemSet nominal branded token type. Use {@link defineSystemSet} to create\n * a token; never construct manually. The {@link SystemSet.__forgeaxSystemSet}\n * brand prevents plain-object assignment.\n *\n * @example\n * ```ts\n * import type { SystemSet } from '@forgeax/engine-ecs';\n * const set: SystemSet = defineSystemSet({ name: 'gameplay' });\n * ```\n */\nexport type {\n SystemDescriptor,\n SystemHandle,\n SystemSet,\n} from './schedule';\n/**\n * Define a frozen system token. Executable registration is World-local through\n * `world.addSystem`.\n *\n * @example\n * ```ts\n * const Move = defineSystem({\n * name: 'movement',\n * queries: [{ with: [Position, Velocity] }],\n * fn: (world, results) => { ... },\n * });\n * world.addSystem(Move);\n * ```\n */\n/**\n * Define a frozen system-set token. Membership is World-local.\n *\n * @example\n * ```ts\n * const GameplaySet = defineSystemSet({ name: 'gameplay', runIf: (w) => !w.getResource<boolean>('paused') });\n * const OrderedSet = defineSystemSet({ name: 'ordered', chained: true });\n * ```\n */\nexport {\n defineSystem,\n defineSystemSet,\n} from './schedule';\n\n/**\n * Inspection snapshot returned by `world.inspect()`. Contains entity count,\n * archetype info, active components, system count, and resource keys.\n *\n * @example\n * ```ts\n * const info = world.inspect();\n * console.log(info.entityCount, info.archetypeCount);\n * ```\n */\n\n// ────────────────────────────────────────────────────────────────────────────\n// Entity encoding utilities\n// ────────────────────────────────────────────────────────────────────────────\n\n/**\n * Encode/decode entity handles for serialization or debugging.\n *\n * @example\n * ```ts\n * const { index, generation } = decodeEntity(entity);\n * const rebuilt = encodeEntity(index, generation);\n * ```\n */\n\n// ────────────────────────────────────────────────────────────────────────────\n// Query engine utilities\n// ────────────────────────────────────────────────────────────────────────────\n\n// ────────────────────────────────────────────────────────────────────────────\n// Component internals (for advanced use: custom storage, tooling)\n// ────────────────────────────────────────────────────────────────────────────\n\n// ────────────────────────────────────────────────────────────────────────────\n// Layer-3 default-value SSOT helper (feat-20260517-spawn-default-fallback / M1)\n// ────────────────────────────────────────────────────────────────────────────\n\n// ────────────────────────────────────────────────────────────────────────────\n\n// ────────────────────────────────────────────────────────────────────────────\n// Constants\n// ────────────────────────────────────────────────────────────────────────────\n\n// Component policy and metadata are an explicit schema projection, not fields\n// on the token or a process-global registry. Owners that need these facts must\n// receive the token's projection through this seam.\nexport { componentDefinition } from './component-schema';\nexport { ENTITY_MAX_GENERATION, ENTITY_MAX_INDEX, ENTITY_NULL_RAW } from './entity-handle';\n\n// w8: Inspector contributor (registerEcsInspector + RegisterEcsInspectorResult)\n// deleted — routing layer (Registry / sandbox) is removed; eval is the sole\n// command channel.\n// w9: ECS_MUTATING_METHODS export deleted — sandbox dismantled; mutating-methods.ts removed.\n"]}