aiecsjs 0.5.6 → 0.5.8

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 (65) hide show
  1. package/README.md +50 -926
  2. package/README_ZHTW.md +51 -936
  3. package/api.json +23 -0
  4. package/dist/chunk-3FV6UMUS.cjs +2 -0
  5. package/dist/chunk-3FV6UMUS.cjs.map +1 -0
  6. package/dist/chunk-3ZLNR4JX.cjs +2 -0
  7. package/dist/chunk-3ZLNR4JX.cjs.map +1 -0
  8. package/dist/chunk-N5OETPTK.js +2 -0
  9. package/dist/chunk-N5OETPTK.js.map +1 -0
  10. package/dist/chunk-TNZMD7E5.js +2 -0
  11. package/dist/chunk-TNZMD7E5.js.map +1 -0
  12. package/dist/chunk-YFTCD2UG.js +2 -0
  13. package/dist/chunk-YFTCD2UG.js.map +1 -0
  14. package/dist/chunk-ZIZSWIHW.cjs +2 -0
  15. package/dist/chunk-ZIZSWIHW.cjs.map +1 -0
  16. package/dist/commands.cjs +1 -1
  17. package/dist/commands.cjs.map +1 -1
  18. package/dist/commands.d.cts +1 -1
  19. package/dist/commands.d.ts +1 -1
  20. package/dist/commands.js +1 -1
  21. package/dist/commands.js.map +1 -1
  22. package/dist/index.cjs +1 -1
  23. package/dist/index.cjs.map +1 -1
  24. package/dist/index.d.cts +49 -4
  25. package/dist/index.d.ts +49 -4
  26. package/dist/index.js +1 -1
  27. package/dist/index.js.map +1 -1
  28. package/dist/observers.cjs +1 -1
  29. package/dist/observers.d.cts +1 -1
  30. package/dist/observers.d.ts +1 -1
  31. package/dist/observers.js +1 -1
  32. package/dist/observers.js.map +1 -1
  33. package/dist/relations.cjs +1 -1
  34. package/dist/relations.cjs.map +1 -1
  35. package/dist/relations.d.cts +1 -1
  36. package/dist/relations.d.ts +1 -1
  37. package/dist/relations.js +1 -1
  38. package/dist/relations.js.map +1 -1
  39. package/dist/serialize.cjs +1 -1
  40. package/dist/serialize.d.cts +1 -1
  41. package/dist/serialize.d.ts +1 -1
  42. package/dist/serialize.js +1 -1
  43. package/dist/{types-BGEeHad-.d.cts → types-BeVLA7xG.d.cts} +11 -1
  44. package/dist/{types-BGEeHad-.d.ts → types-BeVLA7xG.d.ts} +11 -1
  45. package/dist/worker.cjs +1 -1
  46. package/dist/worker.cjs.map +1 -1
  47. package/dist/worker.d.cts +2 -2
  48. package/dist/worker.d.ts +2 -2
  49. package/dist/worker.js +1 -1
  50. package/dist/worker.js.map +1 -1
  51. package/llms-full.txt +109 -1500
  52. package/llms.txt +8 -29
  53. package/package.json +7 -2
  54. package/dist/chunk-FZ5DSL4K.cjs +0 -2
  55. package/dist/chunk-FZ5DSL4K.cjs.map +0 -1
  56. package/dist/chunk-H3E365XN.cjs +0 -2
  57. package/dist/chunk-H3E365XN.cjs.map +0 -1
  58. package/dist/chunk-IFA7MVBB.js +0 -2
  59. package/dist/chunk-IFA7MVBB.js.map +0 -1
  60. package/dist/chunk-L3H4HVUJ.cjs +0 -2
  61. package/dist/chunk-L3H4HVUJ.cjs.map +0 -1
  62. package/dist/chunk-R67UJPKI.js +0 -2
  63. package/dist/chunk-R67UJPKI.js.map +0 -1
  64. package/dist/chunk-TKDLUVJR.js +0 -2
  65. package/dist/chunk-TKDLUVJR.js.map +0 -1
package/llms-full.txt CHANGED
@@ -12,959 +12,83 @@ The short index lives at `llms.txt` (see https://llmstxt.org/).
12
12
 
13
13
  # aiecsjs
14
14
 
15
- [![npm version](https://img.shields.io/npm/v/aiecsjs.svg)](https://www.npmjs.com/package/aiecsjs)
16
- [![CI](https://github.com/islumina/aiecsjs/actions/workflows/ci.yml/badge.svg)](https://github.com/islumina/aiecsjs/actions/workflows/ci.yml)
17
- [![License](https://img.shields.io/badge/license-MIT-brightgreen.svg)](LICENSE)
18
- [![AI Generated](https://img.shields.io/badge/AI_Generated-Claude_Code_Opus_4.7_Max-blueviolet.svg)](https://www.anthropic.com/claude-code)
19
- [![繁體中文](https://img.shields.io/badge/lang-繁體中文-red.svg)](README_ZHTW.md)
15
+ TypeScript-first archetype ECS with TypedArray SoA components, command buffers, relations, serialization, and SAB-ready snapshot transport.
20
16
 
21
- > A TypeScript-first archetype ECS for browser and Node, with SAB-ready snapshot transport and AI-readable documentation.
22
-
23
- Part of the [ai\*js micro-runtime ecosystem](https://github.com/islumina) — see also [aifsmjs](https://github.com/islumina/aifsmjs) (FSM) and [aibridgejs](https://github.com/islumina/aibridgejs) (cross-context RPC).
24
-
25
- aiecsjs uses **archetype tables with TypedArray columns** and **bitmask queries** — the same architecture that powers piecs and wolf-ecs at the top of public benchmarks. Its API is **functional and tree-shakable**, composed with `pipe()`. Components support both Structure-of-Arrays (SoA) and Array-of-Structures (AoS) layouts. Since 0.3, `EntityId` packs index + generation into a single 32-bit number; the ABA-safe `EntityRef` API shipped in 0.3.0.
26
-
27
- ```ts
28
- import { createWorld, createEntity, addComponent, defineComponent, defineQuery, pipe, forEachEntityIndexed, Types } from 'aiecsjs'
29
-
30
- const Position = defineComponent({ x: Types.f32, y: Types.f32 })
31
- const Velocity = defineComponent({ x: Types.f32, y: Types.f32 })
32
-
33
- const world = createWorld()
34
- const eid = createEntity(world)
35
- addComponent(world, eid, Position, { x: 0, y: 0 })
36
- addComponent(world, eid, Velocity, { x: 1, y: 2 })
37
-
38
- const movers = defineQuery([Position, Velocity])
39
- const movement = (w, dt) => { forEachEntityIndexed(w, movers, (e, i, pos, vel) => { pos.x[i] += vel.x[i] * dt; pos.y[i] += vel.y[i] * dt }); return w }
40
-
41
- pipe(movement)(world, 1/60)
42
- ```
43
-
44
- > **Use `forEachEntityIndexed` for column iteration.** Its callback is `(e, i, ...cols)`: `e` is the packed `EntityId` (use it directly for `destroyEntity`, `hasComponent`, `getComponent`, command buffers), and `i` is the **safe column subscript** — index every SoA column with it (`pos.x[i]`). The packed `e` is **not** a column index: it only equals the index until a slot is recycled (generation 0); after any `destroyEntity` recycles a slot, `e !== i` and indexing a column with `e` reads the wrong slot (out of bounds → `undefined`/`NaN`). `forEachEntityIndexed` hands you the correct `i` so this footgun is closed in code. Use `forEachEntity` when you only need the `EntityId` (and index columns via `getEntityIndex(e)` if you must).
45
-
46
- > **Status: experimental (v0.5.x).** The API surface in `STABILITY.md` is committed for the 0.x line, but expect adjustments. A stable 1.0 freeze is targeted after community feedback.
47
-
48
- ## Table of contents
49
-
50
- - [Why aiecsjs?](#why-aiecsjs)
51
- - [Install](#install)
52
- - [Quick Start](#quick-start)
53
- - [Core Concepts](#core-concepts)
54
- - [Guide](#guide)
55
- - [API Reference](#api-reference)
56
- - [Performance](#performance)
57
- - [Multi-threading Guide](#multi-threading-guide)
58
- - [WebGPU Interop](#webgpu-interop)
59
- - [Serialization Guide](#serialization-guide)
60
- - [Migration Guides](#migration-guides)
61
- - [For AI Agents](#for-ai-agents)
62
- - [FAQ](#faq)
63
- - [Caveats and Known Limitations](#caveats-and-known-limitations)
64
- - [Contributing](#contributing)
65
- - [Changelog](#changelog)
66
- - [License](#license)
67
-
68
- ## Why aiecsjs?
69
-
70
- - **Archetype-first storage** — entities sharing the same component set live in one contiguous table; queries walk straight `for` loops over parallel TypedArrays. Iteration is cache-friendly by construction.
71
- - **Zero-config TypeScript inference** — `defineQuery([Position, Velocity])` returns an iterator that yields `(eid, posCols, velCols)` with the correct TypedArray types. No manual generics.
72
- - **AI-first documentation contract** — every public export has a stability tag and a `since` version. Ships `llms.txt`, `llms-full.txt`, and `api.json` so LLM tools can read the API surface directly.
73
-
74
- ### Comparison
75
-
76
- | | aiecsjs 0.1 | bitECS 0.4 | miniplex 2.0 | becsy 0.15 |
77
- |---|---|---|---|---|
78
- | Storage | Archetype + SoA columns | SparseSet + bitmask + SoA/AoS | Archetype + JS objects | Configurable (packed/sparse/compact) + ArrayBuffer |
79
- | API style | Functional + `pipe` | Functional + `pipe` | Chainable OO | Decorator classes |
80
- | TS inference on query | Tuple-aware columns | Manual | Predicate inference | Class-based |
81
- | Multi-thread | SAB snapshot transport (0.x); true shared cols planned 0.3+ | SAB-ready, scheduling DIY | Single-thread | Roadmap (not shipped) |
82
- | AI docs | `llms.txt` + `llms-full.txt` + `api.json` | No | No | No |
83
- | Maintenance | Active (new) | Active | Slowed (~3y since npm release) | Active |
84
-
85
- ### When NOT to use aiecsjs
86
-
87
- - **You need the tiniest possible bundle (≤ 3 kB).** Use [bitECS 0.4](https://github.com/NateTheGreatt/bitECS) — its SparseSet model is leaner and tree-shakes aggressively.
88
- - **You want plain JS objects as entities with full DX freedom.** Use [miniplex](https://github.com/hmans/miniplex). It's the DX champion at the cost of a 2–4× iteration penalty.
89
- - **You need automatic system scheduling with declared read/write entitlements.** Use [@lastolivegames/becsy](https://github.com/LastOliveGames/becsy). aiecsjs systems are just functions in `pipe()` order.
90
- - **Your workload is entity-churn dominated (>50% of entities change shape per frame).** A sparse-set ECS will beat an archetype ECS here. Use bitECS or goodluck.
91
-
92
- ### What aiecsjs does NOT do
93
-
94
- The core stays narrow on purpose. The following are explicit non-goals; reach for a dedicated tool or write app-layer code:
95
-
96
- - **System scheduler with declared read/write entitlements.** `pipe()` runs systems in declared order. Use `@lastolivegames/becsy` if you need parallel scheduling.
97
- - **Render component / scene-graph sync.** ECS holds data only. Pair with PixiJS, Three.js, or your renderer of choice.
98
- - **Physics / spatial partition.** No broad-phase, no collision. Use Rapier, Matter, or a dedicated quadtree.
99
- - **Network replication.** `aiecsjs/serialize` produces snapshot bytes; how they cross the wire is your app's choice.
100
- - **Reactive value-predicate queries.** `enterQuery` / `exitQuery` fire on component-set membership change only. Component value mutations are not tracked.
101
- - **Prefab / entity inheritance / hierarchy.** `aiecsjs/relations` provides plain entity-to-entity references, not inheritance.
102
-
103
- ## Integration with aibridgejs
104
-
105
- If you stream world state across an [aibridgejs](https://www.npmjs.com/package/aibridgejs) bridge (iframe / Flutter InAppWebView), the bridge enforces a strict JSON envelope and silently drops `Date`, `Map`, `Set`, and class instances. AoS components from `defineObjectComponent(...)` can legally hold any of these; sending them as-is corrupts the payload on the host side.
106
-
107
- Correct shape — serialise first, emit a plain object or byte array:
108
-
109
- ```ts
110
- import { toJSON } from 'aiecsjs/serialize'
111
-
112
- const snap = toJSON(world)
113
- await bridge.emit('world.snapshot', snap)
114
- ```
115
-
116
- Do NOT do — `getComponent` returns the live column view or the AoS instance with its prototype intact, which the bridge cannot transport:
117
-
118
- ```ts
119
- await bridge.emit('inv', getComponent(world, eid, Inventory))
120
- ```
121
-
122
- `serializeWorld(world)` (binary, `Uint8Array`) is also bridge-safe; wrap the bytes in a JSON envelope like `{ kind: 'binary', bytes: Array.from(snap) }`, or use a transferable channel when the host supports it.
17
+ > **Status: 0.5.8 - stable 1.0-track core.** Root ECS APIs are stable; worker transport remains adapter-shaped and environment-dependent.
123
18
 
124
19
  ## Install
125
20
 
126
21
  ```bash
127
- npm install aiecsjs
128
22
  pnpm add aiecsjs
129
- yarn add aiecsjs
130
- bun add aiecsjs
131
- ```
132
-
133
- CDN (ESM):
134
-
135
- ```html
136
- <script type="module">
137
- import { createWorld } from 'https://unpkg.com/aiecsjs?module'
138
- </script>
139
23
  ```
140
24
 
141
- Peer requirements: **Node 18+** (for ESM and structured-clone WebStreams), **TypeScript 5.0+** (optional but recommended for the inference goodies).
142
-
143
- ## Quick Start
144
-
145
25
  ```ts
146
26
  import {
147
- createWorld, createEntity, destroyEntity,
148
- defineComponent, addComponent, removeComponent,
149
- defineQuery, forEachEntityIndexed, pipe, Types,
150
- } from 'aiecsjs'
151
- import { createLoop } from 'aiecsjs/loop'
152
-
153
- const Position = defineComponent({ x: Types.f32, y: Types.f32 })
154
- const Velocity = defineComponent({ x: Types.f32, y: Types.f32 })
155
- const Lifetime = defineComponent({ remaining: Types.f32 })
156
-
157
- const world = createWorld({ initialCapacity: 1024 })
158
-
159
- for (let i = 0; i < 100; i++) {
160
- const e = createEntity(world)
161
- addComponent(world, e, Position, { x: Math.random() * 100, y: Math.random() * 100 })
162
- addComponent(world, e, Velocity, { x: Math.random() * 2 - 1, y: Math.random() * 2 - 1 })
163
- addComponent(world, e, Lifetime, { remaining: 5 })
164
- }
165
-
166
- const movers = defineQuery([Position, Velocity])
167
- const decaying = defineQuery([Lifetime])
168
-
169
- const movementSystem = (w, dt) => {
170
- forEachEntityIndexed(w, movers, (e, i, pos, vel) => {
171
- pos.x[i] += vel.x[i] * dt // `i` is the safe column subscript
172
- pos.y[i] += vel.y[i] * dt
173
- })
174
- return w
175
- }
176
-
177
- const lifetimeSystem = (w, dt) => {
178
- forEachEntityIndexed(w, decaying, (e, i, life) => {
179
- life.remaining[i] -= dt
180
- if (life.remaining[i] <= 0) destroyEntity(w, e) // destroyEntity takes the packed `e`
181
- })
182
- return w
183
- }
184
-
185
- const tick = pipe(movementSystem, lifetimeSystem)
186
- const loop = createLoop({ fixed: 1 / 60, onUpdate: (dt) => tick(world, dt) })
187
- loop.start()
188
- ```
189
-
190
- That's a complete simulation: 100 particles drifting until each one's lifetime expires.
191
-
192
- ## Core Concepts
193
-
194
- **Entity.** A versioned 32-bit ID. The low bits are the entity index; the high bits are a generation counter that bumps when the ID is recycled. This prevents the "I cached a reference to entity 42 but now entity 42 is something else" class of bug. Default split is 24 index bits + 8 generation bits (≈ 16M entities × 256 recycles each). Because the packed ID is **not** the column index once a slot is recycled, prefer **`forEachEntityIndexed((e, i, ...cols) => …)`** for column iteration — it hands you the masked index `i` (the safe SoA subscript, `pos.x[i]`) alongside the packed `e`. For the raw `forEachEntity` form, derive the index with `getEntityIndex(e)`.
195
-
196
- **Component.** A data type attached to entities. Two flavours:
197
- - **SoA (Structure of Arrays)** — declared with `defineComponent({ x: Types.f32, y: Types.f32 })`. Each field becomes a TypedArray column indexed by entity ID. Best for hot, numeric data.
198
- - **AoS (Array of Structures)** — declared with `defineObjectComponent(() => ({ ref: null }))`. Each entity gets its own JS object. Best for heterogeneous data or external references (e.g. a `three.js` Mesh).
199
-
200
- **System.** Just a function: `(world, ctx) => world`. No base class, no decorators. Compose multiple systems with `pipe()`. The returned world is the same world reference — `pipe` is associative and the world is mutated in place.
201
-
202
- **Query.** A persistent descriptor over component sets: `defineQuery({ all: [Position], any: [Active, Visible], none: [Hidden] })`. Queries are pre-compiled to a bitmask pair and cached in the world; iteration is O(matching archetypes), not O(entities).
203
-
204
- **World.** Owns all entities, components, archetypes, and query indices. Multiple worlds are supported; they do not share entity IDs unless you opt-in by sharing a `SharedArrayBuffer`.
205
-
206
- **Archetype.** An internal table — one per unique component combination present in the world. When an entity gains or loses a component, it migrates from one archetype to another. Migration cost scales with the number of component columns the entity has; iteration cost does not.
207
-
208
- ## Guide
209
-
210
- ### Defining components
211
-
212
- ```ts
213
- // SoA: TypedArray-backed, max performance, SAB-safe
214
- const Position = defineComponent({ x: Types.f32, y: Types.f32 })
215
-
216
- // SoA with a fixed-size vector field
217
- const Transform = defineComponent({
218
- position: [Types.f32, 3], // Float32Array per entity, length 3
219
- scale: Types.f32,
220
- })
221
-
222
- // Tag: zero-byte marker, no data
223
- const Player = defineTag()
224
- const Dead = defineTag()
225
-
226
- // AoS: arbitrary JS objects, main-thread only
227
- const MeshRef = defineObjectComponent<{ mesh: THREE.Mesh | null }>(() => ({ mesh: null }))
228
- ```
229
-
230
- ### Spawning and destroying entities
231
-
232
- ```ts
233
- const eid = createEntity(world)
234
- addComponent(world, eid, Position, { x: 10, y: 20 })
235
- addComponent(world, eid, Player)
236
-
237
- if (entityExists(world, eid)) {
238
- destroyEntity(world, eid)
239
- }
240
- ```
241
-
242
- `destroyEntity` increments the entity's generation immediately, so any cached `EntityId` becomes invalid on the next `entityExists` check.
243
-
244
- ### Writing systems
245
-
246
- ```ts
247
- const moveSystem = (world: World, dt: number) => {
248
- forEachEntityIndexed(world, defineQuery([Position, Velocity]), (e, i, pos, vel) => {
249
- pos.x[i] += vel.x[i] * dt // `i` is the safe column subscript
250
- pos.y[i] += vel.y[i] * dt
251
- })
252
- return world
253
- }
254
- ```
255
-
256
- **Prefer `forEachEntityIndexed` for column iteration.** Its callback is `(e, i, ...cols)`: index every SoA column with `i` (the masked slot index), and pass the packed `e` to entity operations (`destroyEntity`, `hasComponent`, command buffers). The yielded `i` is always the correct subscript, even after a slot is recycled — so you never hand-mask or call `getEntityIndex` in the loop. Use **`forEachEntity`** when you only need the `EntityId` (its first argument is a packed `EntityId`, not a column index; derive the subscript with `getEntityIndex(e)` if you must index columns). See [Core Concepts → Entity](#core-concepts) for why `e !== i` once a slot is recycled.
257
-
258
- Hoist `defineQuery(...)` calls out of the hot loop — the same query object is returned for the same component set, but the lookup still costs a hash.
259
-
260
- ### Tags in mixed queries
261
-
262
- Every component named in `defineQuery([...])` — **including tags** — occupies one callback slot, in declaration order. A tag has no storage, so its slot is passed as the literal `true`:
263
-
264
- ```ts
265
- const Frozen = defineTag()
266
- const q = defineQuery([Frozen, Position]) // tag first
267
-
268
- // ❌ Wrong: `pos` binds to the tag slot (`true`); `pos.x` throws.
269
- forEachEntityIndexed(world, q, (e, i, pos) => { /* pos === true */ })
270
-
271
- // ✅ Correct: account for every slot. Tag arrives as `true`.
272
- forEachEntityIndexed(world, q, (e, i, _frozen, pos) => {
273
- pos.x[i] += 1
274
- })
275
- ```
276
-
277
- **Recommendation: put tags last** so data columns come first and the trailing `true` slots are easy to ignore:
278
-
279
- ```ts
280
- const q = defineQuery([Position, Velocity, Frozen]) // tags last
281
- forEachEntityIndexed(world, q, (e, i, pos, vel /* , _frozen */) => {
282
- pos.x[i] += vel.x[i]
283
- })
284
- ```
285
-
286
- (Tags still filter membership either way — ordering only affects the callback's argument layout. The column-argument list is `any`-typed, so a mismatched binding is a runtime error, not a compile error.)
287
-
288
- ### Composing with pipe and createLoop
289
-
290
- ```ts
291
- import { createLoop } from 'aiecsjs/loop'
292
-
293
- const tick = pipe(inputSystem, physicsSystem, movementSystem, renderSystem)
294
-
295
- const loop = createLoop({
296
- fixed: 1 / 60,
297
- maxSubSteps: 5,
298
- onUpdate: (dt) => tick(world, dt),
299
- onRender: (alpha) => renderInterpolated(world, alpha),
300
- })
301
-
302
- loop.start()
303
- // later: loop.stop()
27
+ Types,
28
+ addComponent,
29
+ createEntity,
30
+ createWorld,
31
+ defineComponent,
32
+ forEachEntity,
33
+ getComponent,
34
+ } from "aiecsjs";
304
35
  ```
305
36
 
306
- The accumulator pattern in `createLoop` is the canonical fixed-timestep model from `gafferongames.com` — physics is deterministic and decoupled from variable frame rate.
307
-
308
- ### Reactive queries (enter/exit)
309
-
310
- ```ts
311
- const newlyDead = enterQuery(defineQuery([Dead]))
312
- const noLongerDead = exitQuery(defineQuery([Dead]))
313
-
314
- const reapSystem = (world) => {
315
- forEachEntity(world, newlyDead, (e) => playDeathAnimation(e))
316
- forEachEntity(world, noLongerDead, (e) => stopDeathAnimation(e))
317
- return world
318
- }
319
- ```
320
-
321
- `enterQuery` yields only entities that newly match this frame; `exitQuery` yields only entities that left. Both are computed incrementally during structural changes — there's no per-frame scan.
322
-
323
- > **Define reactive queries at module scope** (as above), before any update runs. A reactive query's enter/exit buffer is **armed lazily** — the world starts tracking a query's transitions the first time that query (or its `enterQuery`/`exitQuery` view) participates in a structural change or is read. Create/destroy events that happen *before* the first registration are not retroactively captured. Module-scope definitions register the query at import time, so the very first `tick` already observes transitions; queries created lazily inside a system may miss the events from the frame they were introduced.
324
-
325
- ### Observers
326
-
327
- ```ts
328
- import { onAdd, onRemove, onSet } from 'aiecsjs/observers'
329
-
330
- const stopAdd = onAdd(world, Position, (e) => console.log('positioned', e))
331
- const stopRemove = onRemove(world, Player, (e) => console.log('un-playered', e))
332
- const stopSet = onSet(world, Health, (e, val) => console.log('health set', e, val))
333
-
334
- // Auto-unsubscribe via AbortSignal (since 0.2.0):
335
- const ac = new AbortController()
336
- onAdd(world, Position, (e) => trackEntity(e), { signal: ac.signal })
337
- // later, abort once and all observers attached to this signal are removed
338
- ac.abort()
339
-
340
- // Or the returned unsubscribe — both are idempotent and may be combined:
341
- stopAdd()
342
- stopRemove()
343
- stopSet()
344
- ```
345
-
346
- Observers fire synchronously inside the mutation call. Use them for side effects that must happen at the exact moment of the change (debugging, replication). For batched UI updates, prefer reactive queries.
347
-
348
- **`onSet` is a low-level mutation hook**, not a reactive value-predicate query. It fires after `setComponent(world, eid, comp, value)` when the component is already present on the entity — `addComponent` does NOT trigger `onSet` (use `onAdd` for that path; an `addComponent` followed by `setComponent` fires both, in that order). `enterQuery` / `exitQuery` respond to structural component-set changes only; if you need a reactive "value crossed threshold" view, layer that in app code on top of `onSet`.
349
-
350
- ### Command buffers — when and why
351
-
352
- The golden rule: **do not add or remove components on entities you're currently iterating over.** Doing so can skip or double-process entities because the archetype membership changes mid-walk. Use a command buffer to defer:
353
-
354
- ```ts
355
- import { withCommandBuffer } from 'aiecsjs/commands'
356
-
357
- const damageSystem = (world) => {
358
- const dying = defineQuery([Health])
359
- withCommandBuffer(world, (cb) => {
360
- forEachEntityIndexed(world, dying, (e, i, health) => {
361
- if (health.hp[i] <= 0) cb.destroy(e) // index the column with `i`, queue the packed `e`
362
- })
363
- }) // auto-flushes here
364
- return world
365
- }
366
- ```
367
-
368
- Or manually:
369
-
370
- ```ts
371
- import { createCommandBuffer, flush } from 'aiecsjs/commands'
372
-
373
- const cb = createCommandBuffer(world)
374
- forEachEntity(world, q, (e) => { cb.remove(e, SomeTag) })
375
- flush(cb)
376
- ```
377
-
378
- ### Relations and hierarchies
379
-
380
- > The Relations API is **stable since 0.4.0**. The graph API (`defineRelation` / `addRelation` / `removeRelation` / `getRelationTargets` / `getRelationData`) and the built-in `ChildOf` relation are frozen for the 1.x track.
381
-
382
- ```ts
383
- import { defineRelation, addRelation, ChildOf, getRelationTargets, getRelationData } from 'aiecsjs/relations'
384
-
385
- const Likes = defineRelation<{ since: number }>()
386
- addRelation(world, alice, Likes, bob, { since: 2020 })
387
- addRelation(world, alice, ChildOf, parent)
388
-
389
- const parentOfAlice = getRelationTargets(world, alice, ChildOf)
390
- const likedSince = getRelationData(world, alice, Likes, bob) // { since: 2020 }
391
- ```
392
-
393
- Exclusive relations (one target only) and the `getRelationData` reader are stable as of 0.4.0. Wildcard relation queries and serialisation of relation graphs remain future work and are not part of the frozen surface.
394
-
395
- ## API Reference
396
-
397
- Full machine-readable surface in [`api.json`](./api.json). Stability flags in [`STABILITY.md`](./STABILITY.md).
398
-
399
- ### World — `aiecsjs`
400
-
401
- | Function | Signature | Stability |
402
- |---|---|---|
403
- | `createWorld` | `(options?: WorldOptions) => World` | stable |
404
- | `disposeWorld` | `(world: World) => void` | stable (since 0.2.0) |
405
- | `destroyWorld` | `(world: World) => void` | **deprecated** since 0.2.0 — alias of `disposeWorld`; scheduled for removal in 1.0 |
406
- | `resetWorld` | `(world: World) => void` | stable |
407
- | `getWorldSize` | `(world: World) => number` (alive count) | stable |
408
- | `getWorldCapacity` | `(world: World) => number` | stable |
409
-
410
- `WorldOptions`:
411
- ```ts
412
- type WorldOptions = {
413
- initialCapacity?: number // default 1024
414
- maxEntities?: number // default 1_000_000
415
- indexBits?: 20 | 24 // default 24 → 16M entities
416
- generationBits?: 8 | 12 | 16 // default 8 → 256 recycles
417
- buffer?: SharedArrayBuffer // opt-in SAB backing
418
- bufferByteOffset?: number // when sharing one SAB across worlds
419
- }
420
- ```
421
-
422
- ### Entity — `aiecsjs`
423
-
424
- | Function | Signature | Stability |
425
- |---|---|---|
426
- | `createEntity` | `(world: World) => EntityId` | stable |
427
- | `destroyEntity` | `(world: World, eid: EntityId) => void` | stable |
428
- | `entityExists` | `(world: World, eid: EntityId) => boolean` | stable |
429
- | `getEntityIndex` | `(eid: EntityId) => number` | stable |
430
- | `getEntityGeneration` | `(eid: EntityId) => number` | stable (since 0.3.0) — returns the 8-bit generation field; uses default 24/8 layout |
431
- | `packEntity` | `(index: number, generation: number) => EntityId` | stable (since 0.3.0) — packs index + generation using default 24/8 layout |
432
- | `refOf` | `<T>(world: World, eid: EntityId) => EntityRef<T>` | stable (since 0.3.0) — creates ABA-safe ref; throws `EntityNotAliveError` if entity is dead |
433
- | `deref` | `<T>(world: World, ref: EntityRef<T>) => EntityId \| null` | stable (since 0.3.0) — returns live `EntityId` or `null` if stale/cross-world; never throws |
434
- | `aliveRef` | `<T>(world: World, ref: EntityRef<T>) => boolean` | stable (since 0.3.0) — boolean guard form of `deref`; never throws |
435
- | `EntityRef` | `interface EntityRef<T> { id: EntityId; worldId: number }` | stable (since 0.3.0) — opaque ABA-safe reference; in-memory only |
436
- | `EntityNotAliveError` | `class EntityNotAliveError extends Error { eid: number }` | stable (since 0.3.0) — thrown by `refOf` when entity is not alive |
437
-
438
- ### Component — `aiecsjs`
439
-
440
- | Function | Signature | Stability |
441
- |---|---|---|
442
- | `defineComponent` | `<S extends SoASchema>(schema: S) => SoAComponent<S>` | stable |
443
- | `defineTag` | `() => TagComponent` | stable |
444
- | `defineObjectComponent` | `<T>(factory?: () => T) => AoSComponent<T>` | stable |
445
- | `addComponent` | `<C>(world, eid, c: C, init?) => void` | stable |
446
- | `removeComponent` | `<C>(world, eid, c: C) => void` | stable |
447
- | `hasComponent` | `<C>(world, eid, c: C) => boolean` | stable |
448
- | `getComponent` | `<C>(world, eid, c: C) => ComponentView<C>` | stable |
449
- | `setComponent` | `<C, V>(world, eid, c: C, v: V) => void` | stable |
450
-
451
- `Types`:
452
- ```ts
453
- const Types = { i8, u8, i16, u16, i32, u32, f32, f64, eid, bool } as const
454
- ```
455
-
456
- ### Query — `aiecsjs`
457
-
458
- | Function | Signature | Stability |
459
- |---|---|---|
460
- | `defineQuery` | `(components: ComponentLike[] \| QueryDescriptor) => Query` | stable |
461
- | `runQuery` | `(world: World, q: Query) => readonly EntityId[]` | stable |
462
- | `forEachEntity` | `<Q>(world, q: Q, fn: (eid, ...cols) => void) => void` | stable |
463
- | `forEachEntityIndexed` | `<Q>(world, q: Q, fn: (eid, i, ...cols) => void) => void` | stable |
464
- | `iterQuery` | `(world, q) => IterableIterator<EntityId>` | stable |
465
- | `enterQuery` | `(q: Query) => Query` | stable |
466
- | `exitQuery` | `(q: Query) => Query` | stable |
467
- | `queryArchetypes` | `(world, q) => readonly Archetype[]` | experimental |
468
-
469
- ### System — `aiecsjs`
470
-
471
- | Function | Signature | Stability |
472
- |---|---|---|
473
- | `pipe` | `<W, Ctx>(...systems) => System<W, Ctx>` | stable |
474
- | `System` (type) | `(world, ctx) => world` | stable |
475
-
476
- ### Loop — `aiecsjs/loop`
477
-
478
- | Function | Signature | Stability |
479
- |---|---|---|
480
- | `createLoop` | `(opts) => { start(), stop() }` | stable |
481
-
482
- ### Command Buffer — `aiecsjs/commands`
483
-
484
- | Function | Signature | Stability |
485
- |---|---|---|
486
- | `createCommandBuffer` | `(world) => CommandBuffer` | stable |
487
- | `flush` | `(cb: CommandBuffer) => void` | stable |
488
- | `withCommandBuffer` | `<R>(world, fn: (cb) => R) => R` | stable |
489
-
490
- ### Observers — `aiecsjs/observers`
491
-
492
- | Function | Signature | Stability |
493
- |---|---|---|
494
- | `observe` | `(world, q, event, handler, opts?: { signal? }) => () => void` | stable |
495
- | `onAdd` | `(world, comp, handler, opts?: { signal? }) => () => void` | stable |
496
- | `onRemove` | `(world, comp, handler, opts?: { signal? }) => () => void` | stable |
497
- | `onSet` | `(world, comp, handler, opts?: { signal? }) => () => void` | stable; low-level mutation hook, not reactive |
498
-
499
- ### Serialization — `aiecsjs/serialize`
500
-
501
- | Function | Signature | Stability |
502
- |---|---|---|
503
- | `serializeWorld` | `(world, opts?) => Uint8Array` | stable |
504
- | `deserializeWorld` | `(bytes, opts?) => World` | stable |
505
- | `toJSON` | `(world) => WorldSnapshot` | stable |
506
- | `fromJSON` | `(snap) => World` | stable |
507
- | `createDeltaSerializer` | `(world, opts?) => DeltaSerializer` | experimental |
508
-
509
- ### Worker / SAB — `aiecsjs/worker`
510
-
511
- | Function | Signature | Stability |
512
- |---|---|---|
513
- | `transferableSnapshot` | `(world) => { buffer, meta }` | experimental |
514
- | `adoptSnapshot` | `(snap) => World` | experimental |
515
- | `attachWorld` | `(buffer, opts?) => World` | experimental |
516
- | `detachWorld` | `(world) => void` | experimental |
517
-
518
- ### Relations — `aiecsjs/relations`
519
-
520
- | Function | Signature | Stability |
521
- |---|---|---|
522
- | `defineRelation` | `<T>(opts?) => Relation<T>` | stable |
523
- | `addRelation` | `(world, src, rel, tgt, data?) => void` | stable |
524
- | `removeRelation` | `(world, src, rel, tgt) => void` | stable |
525
- | `getRelationTargets` | `(world, src, rel) => readonly EntityId[]` | stable |
526
- | `getRelationData` | `<T>(world, src, rel, tgt) => T \| undefined` | stable (since 0.4.0) |
527
- | `ChildOf` (constant) | `Relation` | stable |
528
-
529
- ### Utility — `aiecsjs`
530
-
531
- | Export | Type | Stability |
532
- |---|---|---|
533
- | `VERSION` | `string` | stable |
534
- | `IS_SAB_SUPPORTED` | `boolean` | stable |
535
- | `isWorld` | `(x: unknown) => x is World` | stable |
536
- | `isEntity` | `(world, x) => x is EntityId` | stable |
537
-
538
- ## Performance
539
-
540
- ### Storage model
541
-
542
- ```
543
- World
544
- ├── Archetype 0: [] (empty entities)
545
- ├── Archetype 1: [Position]
546
- │ ├── entities: Uint32Array [e1, e2, e3, ...]
547
- │ └── columns: Position.x: Float32Array, Position.y: Float32Array
548
- ├── Archetype 2: [Position, Velocity]
549
- │ ├── entities: Uint32Array [e4, e5, ...]
550
- │ ├── columns: Position.x, Position.y, Velocity.x, Velocity.y
551
- └── Archetype 3: [Position, Velocity, Health]
552
- └── ...
553
- ```
554
-
555
- A query for `(Position, Velocity)` matches archetypes 2 and 3 and walks each linearly. Each archetype's columns are contiguous `Float32Array`s — the JIT can vectorise the inner loop and the L1 cache hit rate is near 100%.
556
-
557
- ### Cost model
558
-
559
- - **Iteration**: `O(matching archetypes × entities per archetype)` with effectively zero per-entity overhead after the archetype list is resolved. Resolution is amortised by query caching.
560
- - **Add / remove component**: `O(component count on entity)`. The entity row is copied from its source archetype's columns into the destination's. If you flicker a tag every frame on N entities, this is N × (column count) memory moves per frame.
561
- - **Query setup**: `O(component count)` at `defineQuery` time. Re-using the same component set returns the cached query.
562
-
563
- ### Tips
564
-
565
- - Hoist `defineQuery` out of the hot loop. Same component set returns the same query object, but the lookup still costs a hash.
566
- - Prefer **bulk operations**: spawn 1000 entities by calling `createEntity` + `addComponent` in a tight loop; the archetype migration runs once per shape.
567
- - Group **frequently-toggled tags** into one stable component with a boolean field, instead of constantly adding/removing a tag — the latter triggers archetype migration.
568
- - For very hot inner loops, fetch each column once at the top of the system: `const px = Position.x; const vx = Velocity.x;` then index directly.
569
-
570
- ### Reproducible micro-benchmark
571
-
572
- ```ts
573
- import { createWorld, createEntity, addComponent, defineComponent, defineQuery, forEachEntityIndexed, Types } from 'aiecsjs'
574
-
575
- const Position = defineComponent({ x: Types.f32, y: Types.f32 })
576
- const Velocity = defineComponent({ x: Types.f32, y: Types.f32 })
577
-
578
- const world = createWorld({ initialCapacity: 100_000 })
579
- for (let i = 0; i < 100_000; i++) {
580
- const e = createEntity(world)
581
- addComponent(world, e, Position, { x: 0, y: 0 })
582
- addComponent(world, e, Velocity, { x: 1, y: 1 })
583
- }
584
-
585
- const movers = defineQuery([Position, Velocity])
586
- const start = performance.now()
587
- for (let frame = 0; frame < 1000; frame++) {
588
- forEachEntityIndexed(world, movers, (e, i, pos, vel) => {
589
- pos.x[i] += vel.x[i]; pos.y[i] += vel.y[i]
590
- })
591
- }
592
- console.log('ms per frame:', (performance.now() - start) / 1000)
593
- ```
594
-
595
- ### Disclaimer
596
-
597
- These tips are derived from public ECS benchmarks (noctjs/ecs-benchmark, ddmills/js-ecs-benchmarks) and the peer-reviewed C++ comparison by Cox, Williams, Vickers, Ward, and Headleand (CGVC 2025, [DOI 10.2312/cgvc.20251224](https://doi.org/10.2312/cgvc.20251224)). In renderer-heavy applications, ECS overhead is typically 1–2% of frame time (as observed by Felix Z on Meta's Project Flowerbed) — so the practical win from picking aiecsjs over a slower ECS is small unless your simulation is the bottleneck. Pick the library whose DX matches your workload.
598
-
599
- ## Multi-threading Guide
600
-
601
- aiecsjs is **SharedArrayBuffer-ready**: a world's archetype columns can live in shared memory and a Worker can iterate them in parallel.
602
-
603
- ### Capability detection
604
-
605
- ```ts
606
- import { IS_SAB_SUPPORTED } from 'aiecsjs'
607
- if (!IS_SAB_SUPPORTED) {
608
- console.warn('SAB unavailable; check COOP/COEP headers')
609
- }
610
- ```
611
-
612
- In browsers, `SharedArrayBuffer` requires the page to be **cross-origin isolated**: serve with `Cross-Origin-Opener-Policy: same-origin` and `Cross-Origin-Embedder-Policy: require-corp`.
613
-
614
- ### Main thread
615
-
616
- ```ts
617
- const buffer = new SharedArrayBuffer(64 * 1024 * 1024) // 64 MB
618
- const world = createWorld({ buffer })
619
-
620
- // populate world...
621
-
622
- const worker = new Worker(new URL('./sim-worker.ts', import.meta.url), { type: 'module' })
623
- worker.postMessage({ buffer, meta: transferableSnapshot(world).meta })
624
- ```
625
-
626
- ### Worker thread
627
-
628
- ```ts
629
- // sim-worker.ts
630
- import { adoptSnapshot, defineComponent, defineQuery, forEachEntityIndexed, Types } from 'aiecsjs'
631
-
632
- const Position = defineComponent({ x: Types.f32, y: Types.f32 })
633
- const Velocity = defineComponent({ x: Types.f32, y: Types.f32 })
634
-
635
- self.onmessage = (msg) => {
636
- const world = adoptSnapshot(msg.data)
637
- const movers = defineQuery([Position, Velocity])
638
- setInterval(() => {
639
- forEachEntityIndexed(world, movers, (e, i, pos, vel) => {
640
- pos.x[i] += vel.x[i]
641
- pos.y[i] += vel.y[i]
642
- })
643
- }, 16)
644
- }
645
- ```
646
-
647
- ### Atomics and synchronisation
648
-
649
- Reads and writes to TypedArray columns inside a SAB are **not atomic by default**. For most game-loop work, the convention is: one writer thread per column (e.g. physics worker owns positions), readers see eventually-consistent data. If you need strict ordering, use `Atomics.load` / `Atomics.store`; you give up vectorisation in exchange.
650
-
651
- ### Pitfalls
652
-
653
- - **AoS components are NOT SAB-shareable.** Workers see only SoA columns. Either keep AoS data on the main thread or replace with SoA equivalents.
654
- - **`createEntity` / `destroyEntity` from a Worker requires the worker to own the entity index.** Currently, attach worlds with `{ readOnly: true }` when the Worker should only mutate columns.
655
- - **No synchronisation primitives are baked into aiecsjs.** Use `Atomics.wait` / `Atomics.notify` yourself if you need barriers.
656
-
657
- ## WebGPU Interop
658
-
659
- A SoA component's columns are TypedArrays — exactly the format `GPUQueue.writeBuffer` accepts. There is no "ECS on GPU" mode; the integration is one-directional (CPU writes, GPU reads).
660
-
661
- ```ts
662
- const Position = defineComponent({ x: Types.f32, y: Types.f32 })
663
- // after populating the world ...
664
-
665
- const gpuBuffer = device.createBuffer({
666
- size: Position.x.byteLength,
667
- usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST,
668
- })
669
-
670
- // upload every frame, or only when archetypes change
671
- device.queue.writeBuffer(gpuBuffer, 0, Position.x)
672
- ```
673
-
674
- ### Caveats
675
-
676
- - **Archetype migration invalidates column references.** If an entity moves to a new archetype, `Position.x` now points to a different `Float32Array` for that entity. For stable GPU buffers, dedicate a single archetype to entities you upload (e.g. tag them with a `Renderable` component that never gets removed) or upload per-archetype.
677
- - **Write-back from GPU to ECS is not supported.** Read-only on the GPU side. If you need GPU-computed values back in CPU columns, map the buffer manually and write into the column.
678
- - **Non-goal: running ECS systems on the GPU.** aiecsjs does not generate compute shaders from systems. Use a dedicated GPU compute framework for that.
679
-
680
- ## Serialization Guide
681
-
682
- ### Binary save/load
683
-
684
- ```ts
685
- import { serializeWorld, deserializeWorld } from 'aiecsjs/serialize'
686
-
687
- const bytes = serializeWorld(world)
688
- localStorage.setItem('save', btoa(String.fromCharCode(...bytes)))
689
-
690
- const restored = deserializeWorld(Uint8Array.from(atob(localStorage.getItem('save')!), c => c.charCodeAt(0)))
691
- ```
692
-
693
- The binary format is **version-stamped**. Loading bytes from an older `aiecsjs` version returns a world if migration succeeds, throws otherwise. AoS components are stored as JSON inside the binary blob.
694
-
695
- ### JSON save/load
696
-
697
- ```ts
698
- import { toJSON, fromJSON } from 'aiecsjs/serialize'
699
-
700
- const snap = toJSON(world) // human-readable
701
- const restored = fromJSON(snap)
702
- ```
703
-
704
- Slower and larger than binary, but inspectable in DevTools.
705
-
706
- ### Network delta
707
-
708
- For multiplayer, you want to send only what changed since last tick:
709
-
710
- ```ts
711
- import { createDeltaSerializer } from 'aiecsjs/serialize'
712
-
713
- const delta = createDeltaSerializer(world, { components: [Position, Velocity, Health] })
714
- setInterval(() => {
715
- const bytes = delta.capture()
716
- ws.send(bytes)
717
- }, 50)
718
-
719
- // on the other side:
720
- const remoteDelta = createDeltaSerializer(remoteWorld)
721
- ws.onmessage = (e) => remoteDelta.apply(remoteWorld, new Uint8Array(e.data))
722
- ```
723
-
724
- > ⚠️ `createDeltaSerializer` is `experimental` in 0.1; the wire format may change before 1.0.
725
-
726
- ## Migration Guides
727
-
728
- Full tables in [`docs/MIGRATION.md`](https://github.com/islumina/aiecsjs/blob/main/docs/MIGRATION.md).
729
-
730
- ### From bitECS 0.4
731
-
732
- | bitECS | aiecsjs |
733
- |---|---|
734
- | `createWorld()` | `createWorld()` |
735
- | `defineComponent({ x: Types.f32 })` | `defineComponent({ x: Types.f32 })` |
736
- | `addComponent(world, Comp, eid)` | `addComponent(world, eid, Comp, init?)` (arg order!) |
737
- | `removeComponent(world, Comp, eid)` | `removeComponent(world, eid, Comp)` |
738
- | `defineQuery([Comp])(world)` | `forEachEntity(world, defineQuery([Comp]), fn)` |
739
- | `enterQuery(query)` | `enterQuery(defineQuery([...]))` (no `world` arg) |
740
- | `pipe(s1, s2)(world)` | `pipe(s1, s2)(world, ctx)` (ctx threaded through) |
741
-
742
- Key mental shift: aiecsjs is **archetype-first**. Tag flicker (adding/removing a tag every frame) is more expensive than in bitECS. Group toggleable state into boolean fields instead.
743
-
744
- ### From miniplex
745
-
746
- | miniplex | aiecsjs |
747
- |---|---|
748
- | `world.add({ position: {x, y}, velocity: {x, y} })` | `createEntity` + `addComponent` (per component) |
749
- | `world.with('position', 'velocity')` | `defineQuery([Position, Velocity])` |
750
- | `for (const e of query)` | `forEachEntity(world, query, fn)` |
751
- | `world.remove(entity)` | `destroyEntity(world, eid)` |
752
- | `world.queue.add(...)` | `withCommandBuffer(world, cb => cb.create() ...)` |
753
-
754
- Mental shift: components are **declared up front** in aiecsjs, not anonymous object shapes. The win is TypedArray performance + multi-thread compatibility.
755
-
756
- ### From ECSY
757
-
758
- ECSY is [archived](https://github.com/ecsyjs/ecsy) as of April 2025. Migration is straightforward because both are archetype-style.
759
-
760
- | ECSY | aiecsjs |
761
- |---|---|
762
- | `class C extends Component { static schema = { x: Types.Number } }` | `defineComponent({ x: Types.f32 })` |
763
- | `class S extends System { execute(dt) { this.queries.foo.results.forEach(...) } }` | `const S = (world, dt) => { forEachEntity(world, foo, fn); return world }` |
764
- | `world.registerComponent(C)` | (implicit on `defineComponent`) |
765
- | `world.registerSystem(S)` then `world.execute(dt)` | `const tick = pipe(S1, S2); tick(world, dt)` |
766
-
767
- ## For AI Agents
768
-
769
- This section is designed to be loaded as context by AI coding assistants. The same information is available in machine-readable form in [`llms.txt`](./llms.txt), [`llms-full.txt`](./llms-full.txt), and [`api.json`](./api.json).
770
-
771
- ### Decision matrix
772
-
773
- | If you need... | Use aiecsjs | Use this instead |
774
- |-------------------------------------------------|------------------|--------------------------|
775
- | Fastest iteration over 10k+ entities | ✅ | — |
776
- | Plain JS object entities, no typed schema | ❌ | miniplex |
777
- | Automatic system scheduling / parallelism | ❌ (v0.1) | becsy |
778
- | SAB-based main+worker setup | ✅ | — |
779
- | Hot reload, frequent entity churn (>50%/frame) | works but slower | bitECS 0.4 (SparseSet) |
780
- | Tiny bundle (< 3 kB) | ❌ | bitECS 0.4 |
781
- | TypeScript-first inference | ✅ | — |
782
-
783
- ### Common patterns (copy-paste)
784
-
785
- **1. Spawn-and-move**
786
-
787
- ```ts
788
- import { createWorld, createEntity, addComponent, defineComponent, defineQuery, forEachEntityIndexed, pipe, Types } from 'aiecsjs'
789
-
790
- const Position = defineComponent({ x: Types.f32, y: Types.f32 })
791
- const Velocity = defineComponent({ x: Types.f32, y: Types.f32 })
792
-
793
- const world = createWorld()
794
- for (let i = 0; i < 1000; i++) {
795
- const e = createEntity(world)
796
- addComponent(world, e, Position, { x: i, y: 0 })
797
- addComponent(world, e, Velocity, { x: 0, y: 1 })
798
- }
799
-
800
- const movers = defineQuery([Position, Velocity])
801
- const move = (w, dt) => {
802
- forEachEntityIndexed(w, movers, (e, i, p, v) => { p.x[i] += v.x[i] * dt; p.y[i] += v.y[i] * dt })
803
- return w
804
- }
805
- pipe(move)(world, 0.016)
806
- ```
807
-
808
- **2. Reactive UI via enter/exit query**
809
-
810
- ```ts
811
- const visible = defineQuery([Renderable])
812
- const becameVisible = enterQuery(visible)
813
- const becameHidden = exitQuery(visible)
814
-
815
- const renderSync = (world) => {
816
- forEachEntity(world, becameVisible, (e) => domLayer.mount(e))
817
- forEachEntity(world, becameHidden, (e) => domLayer.unmount(e))
818
- return world
819
- }
820
- ```
821
-
822
- **3. Command buffer for safe deferred ops**
823
-
824
- ```ts
825
- import { withCommandBuffer } from 'aiecsjs/commands'
826
-
827
- const reapDead = (world) => {
828
- withCommandBuffer(world, (cb) => {
829
- forEachEntity(world, deadQ, (e) => cb.destroy(e))
830
- })
831
- return world
832
- }
833
- ```
834
-
835
- **4. SAB worker handoff**
836
-
837
- ```ts
838
- // main.ts
839
- const buffer = new SharedArrayBuffer(16 * 1024 * 1024)
840
- const world = createWorld({ buffer })
841
- const worker = new Worker(new URL('./physics.ts', import.meta.url), { type: 'module' })
842
- worker.postMessage(transferableSnapshot(world))
843
-
844
- // physics.ts
845
- import { adoptSnapshot } from 'aiecsjs/worker'
846
- self.onmessage = (e) => {
847
- const world = adoptSnapshot(e.data)
848
- // ... iterate columns
849
- }
850
- ```
851
-
852
- **5. Networked delta replay**
37
+ ## Quick Start
853
38
 
854
39
  ```ts
855
- import { createDeltaSerializer } from 'aiecsjs/serialize'
40
+ const Position = defineComponent({ x: Types.f32, y: Types.f32 });
41
+ const Velocity = defineComponent({ x: Types.f32, y: Types.f32 });
856
42
 
857
- const tx = createDeltaSerializer(world, { components: [Position, Velocity] })
858
- setInterval(() => ws.send(tx.capture()), 50)
43
+ const world = createWorld({ initialCapacity: 1024 });
44
+ const e = createEntity(world);
45
+ addComponent(world, e, Position, { x: 0, y: 0 });
46
+ addComponent(world, e, Velocity, { x: 1, y: 0 });
859
47
 
860
- // remote
861
- const rx = createDeltaSerializer(remoteWorld)
862
- ws.onmessage = (e) => rx.apply(remoteWorld, new Uint8Array(e.data))
48
+ forEachEntity(world, [Position, Velocity], (entity) => {
49
+ const pos = getComponent(world, entity, Position);
50
+ const vel = getComponent(world, entity, Velocity);
51
+ pos.x += vel.x;
52
+ pos.y += vel.y;
53
+ });
863
54
  ```
864
55
 
865
- ### Anti-patterns
866
-
867
- 1. **Mutating a `getComponent()` return value after the entity changes archetype.** The returned view points into the old archetype's TypedArray; it no longer represents this entity. Always re-fetch.
868
- 2. **Adding or removing components during `forEachEntity` without a command buffer.** May skip or double-process entities. Use `withCommandBuffer`.
869
- 3. **Holding `EntityId` across `destroyEntity`.** The ID may be recycled with a new generation. Always `entityExists(world, eid)` first.
870
- 4. **Using AoS components inside a SAB-backed Worker world.** AoS storage is main-thread only. Replace with SoA.
871
- 5. **Storing column references in closures longer than one frame.** Archetype migration replaces the TypedArray reference for an entity. Re-fetch each frame.
872
- 6. **Calling `addComponent(world, Comp, eid)` (bitECS order).** aiecsjs is `(world, eid, Comp, init?)`. Different positional args.
56
+ Use `defineTag()` for marker components and `defineObjectComponent()` when you need object references instead of TypedArray storage.
873
57
 
874
- ### Stable invariants
58
+ ## Public Surface
875
59
 
876
- - `pipe(a, b, c)(world, ctx) === c(b(a(world, ctx), ctx), ctx)` — pipe is associative.
877
- - `pipe(...)` always returns the same `World` reference (mutations in place).
878
- - `defineQuery(X)` returns the same `Query` object for the same component set in the same module.
879
- - Entity ID `0` is reserved. `createEntity` never returns `0`.
880
- - `VERSION` exported from `'aiecsjs'` equals the published npm version.
881
- - SoA columns are TypedArrays indexed by the entity **index** (always in `[0, getWorldCapacity(world))`), never by the packed `eid` — the two differ once a slot is recycled. `forEachEntityIndexed` yields this index as its `i` argument (correct for any world layout). For the raw `forEachEntity` form on the default world layout (`indexBits: 24`) the index is `getEntityIndex(eid)`; for a world created with a non-default `indexBits`, `getEntityIndex` uses the default 24-bit mask and is **not** the column index — prefer `forEachEntityIndexed` (or `EntityRef` + `deref`) instead.
882
- - Component identity is **global** (created by `defineComponent`), but each component's storage is **per-world**.
60
+ | Import | Purpose |
61
+ | --- | --- |
62
+ | `aiecsjs` | World/entity/component/query/system helpers, `Types`, refs, errors, `VERSION`. |
63
+ | `aiecsjs/loop` | `createLoop()` for fixed-step style loops. |
64
+ | `aiecsjs/commands` | `createCommandBuffer()`, `flush()`, `withCommandBuffer()` for deferred structural changes. |
65
+ | `aiecsjs/observers` | `onAdd`, `onRemove`, `onSet`, `observe`. |
66
+ | `aiecsjs/serialize` | Binary/JSON world snapshots and delta serializer. |
67
+ | `aiecsjs/worker` | Transfer/adopt/attach helpers for worker snapshots. |
68
+ | `aiecsjs/relations` | `defineRelation`, `ChildOf`, relation add/remove/read helpers. |
883
69
 
884
- ### Glossary
885
-
886
- - **Archetype** — a unique combination of components; entities sharing components live in the same archetype table.
887
- - **SoA (Structure of Arrays)** — each component field is a separate TypedArray column. Default and preferred for hot data.
888
- - **AoS (Array of Structures)** — each component instance is a plain JS object. For heterogeneous or rarely-touched data.
889
- - **Bitmask** — a `Uint32Array` where each bit position represents one component; queries match by bitwise AND.
890
- - **Command buffer** — a queue of pending structural mutations applied at a defined sync point.
891
- - **Generation** — a counter incremented when an entity ID is recycled; prevents dangling references.
892
-
893
- ### Runtime version detection
894
-
895
- ```ts
896
- import { VERSION } from 'aiecsjs'
897
- if (VERSION.startsWith('0.')) {
898
- // running an experimental version; expect API drift in 0.x
899
- }
900
- ```
901
-
902
- ### Stability contract
903
-
904
- See [`STABILITY.md`](./STABILITY.md). In short: imports from `aiecsjs` (root) are **stable** within 0.x minors. `aiecsjs/relations` is **stable** since 0.4.0; `aiecsjs/worker` is **experimental**. Anything in `aiecsjs/internal` is **internal** — do not import.
905
-
906
- ### Telemetry / privacy
907
-
908
- aiecsjs ships **no telemetry**, **no network calls**, **no postinstall scripts**. Verify with `npm pack --dry-run` and inspect the tarball.
909
-
910
- ### Citation for AI-generated code
911
-
912
- When you generate code that uses aiecsjs, include this comment at the top of the file:
913
-
914
- ```ts
915
- // generated with aiecsjs@0.1.0 — https://github.com/islumina/aiecsjs
916
- ```
70
+ ## Sharp Edges
917
71
 
918
- ### Known LLM gotchas
72
+ - Structural mutation during a query loop is allowed by the library, but app systems should prefer `withCommandBuffer()` when adding/removing/destroying entities from inside iteration.
73
+ - Reactive query buffers are unbounded until drained. Poll and clear them every frame or event tick.
74
+ - Query registration currently uses a global module cache; many worlds/components can make structural changes scan more query metadata than expected.
75
+ - Exclusive relation cleanup scans relation capacity on destroy. Large sparse relation tables can make destroy cost visible.
76
+ - Serialization restores capacity with safety clamps, but snapshots from untrusted sources should still be treated as hostile input.
77
+ - Worker/SAB helpers depend on the runtime environment. Feature-detect `SharedArrayBuffer` and cross-origin isolation in browsers.
78
+ - `pnpm lint` currently reports many `noExplicitAny` warnings. They are not release-blocking, but they add AI-review noise.
919
79
 
920
- - **aiecsjs is NOT bitECS.** Argument order for `addComponent` differs: aiecsjs uses `(world, eid, Component, init?)`; bitECS uses `(world, Component, eid)`.
921
- - **Index SoA columns with the masked index, NOT the packed `EntityId`.** The footgun is closed in code: prefer **`forEachEntityIndexed(w, q, (e, i, ...cols) => …)`**, which yields the masked slot index `i` (the correct subscript: `pos.x[i]`) alongside the packed `e`. The packed `e` is **not** a column index — it only equals the index while no slot has been recycled (generation 0); after any `destroyEntity` it reads the wrong/out-of-bounds slot. With the raw `forEachEntity` form, derive the index yourself: hoist `const i = getEntityIndex(e)` once per callback. Either way, use `e` for entity operations (`destroyEntity(w, e)`, `hasComponent`, `getComponent`, command buffers).
922
- - **A tag occupies a callback slot too.** `defineQuery([Tag, Position])` calls the callback as `(e, i, true, posCols)` under `forEachEntityIndexed` (`(e, true, posCols)` under `forEachEntity`) — the tag is passed as the literal `true`. Put tags **last** in the array (`defineQuery([Position, Tag])`) so data columns come first; or accept and ignore the trailing `true`. Binding `pos` to a tag slot makes `pos === true`, and `pos.x` throws.
923
- - **`forEachEntity` / `forEachEntityIndexed` are the fast path.** `runQuery` allocates an array; `for...of iterQuery(...)` allocates an iterator. In hot loops, use `forEachEntityIndexed` (or `forEachEntity` when you only need the `EntityId`).
924
- - **`defineObjectComponent` factory runs ONCE at definition**, not per entity. Mutate the entity's instance via `setComponent` / `getComponent`.
925
- - **The component reference is the storage handle.** `Position` is not a constructor — it's a value object that aiecsjs uses to address the right archetype columns.
80
+ ## AI Context
926
81
 
927
- ## FAQ
928
-
929
- **Q: Is aiecsjs production-ready?**
930
- A: Not yet. 0.x is experimental. The API surface in `STABILITY.md` is the working contract; expect bug fixes. Target 1.0 is post-implementation hardening.
931
-
932
- **Q: Can I use class instances as components?**
933
- A: Yes, with `defineObjectComponent`. But AoS components are main-thread only and slower than SoA in iteration.
934
-
935
- **Q: How many components can I have?**
936
- A: aiecsjs uses multi-word bitmasks; the practical limit is set by `WorldOptions.maxComponents` (default 256). Raise it if needed.
937
-
938
- **Q: Does aiecsjs support hot reload?**
939
- A: Component identities are module-scoped. If you re-import a module under HMR, the component identity changes; the safe path is to call `resetWorld(world)` and re-spawn.
940
-
941
- **Q: Why not a class-based API?**
942
- A: Functional API tree-shakes better, has lower overhead, and is what LLMs reliably generate. The trade-off (no automatic scheduling) is acceptable for the target audience.
943
-
944
- **Q: Why isn't `aiecsjs` available on npm yet?**
945
- A: It will be on first stable publish. Until then, the docs are the contract.
946
-
947
- ## Caveats and Known Limitations
948
-
949
- - **Max entity count** is capped by `indexBits` × `generationBits`. Default 24 + 8 = 16M entities × 256 recycles.
950
- - **No automatic system scheduler / parallel execution** in 0.1. Systems run in `pipe()` order on one thread (you can launch additional workers manually).
951
- - **Relations API (`aiecsjs/relations`) is stable since 0.4.0.** Wildcard relation queries and relation-graph serialisation remain future work.
952
- - **AoS components** not SAB-shareable across workers.
953
- - **Network delta serializer** wire format is experimental in 0.1; may change.
954
- - **WebGPU integration is one-way** (CPU → GPU). No compute-shader system generation.
955
- - **Limited dev-mode validation.** Production builds skip invariant checks for speed; dev builds (`process.env.NODE_ENV !== 'production'`) include argument-order and entity-existence checks.
956
-
957
- ## Contributing
958
-
959
- aiecsjs is primarily AI-generated and maintained by a single author. Issue reports and small PRs welcome at [github.com/islumina/aiecsjs](https://github.com/islumina/aiecsjs). Large architectural changes — please open an issue first.
960
-
961
- ## Changelog
962
-
963
- See [`CHANGELOG.md`](./CHANGELOG.md).
82
+ - Short index: [`llms.txt`](llms.txt)
83
+ - Full generated context: [`llms-full.txt`](llms-full.txt)
84
+ - Stability contract: [`STABILITY.md`](STABILITY.md)
85
+ - Current review backlog: [`REVIEW.md`](REVIEW.md)
86
+ - Machine-readable API: [`api.json`](api.json)
87
+ - Release history: [`CHANGELOG.md`](CHANGELOG.md)
964
88
 
965
89
  ## License
966
90
 
967
- [MIT](./LICENSE) © yshengliao
91
+ MIT
968
92
 
969
93
  ---
970
94
 
@@ -972,359 +96,31 @@ See [`CHANGELOG.md`](./CHANGELOG.md).
972
96
 
973
97
  # Changelog
974
98
 
975
- All notable changes to `aiecsjs` are recorded in this file.
976
-
977
- The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
99
+ All notable changes to aiecsjs are summarized here. Detailed historical review notes live in Git history; this file keeps current release context compact.
978
100
 
979
101
  ## [Unreleased]
980
102
 
981
- ### Planned
982
-
983
- - Add `pipeAsync` for async system composition.
984
- - Doc-test harness so README code blocks are mechanically verified.
985
- - Promote `aiecsjs/worker` to `stable` once true SAB shared-memory column aliasing is implemented.
986
- - Document the 8-bit generation wrap caveat in [STABILITY.md](./STABILITY.md): with the
987
- default `generationBits=8`, a single slot recycled 256 times wraps back to its
988
- starting generation, briefly re-opening the ABA window. Safe for v0.5 shmup
989
- workloads (~5000 frame to wrap a single slot at 60 fps × ~1k destroys); high-churn
990
- pools should set `createWorld({ indexBits: 16, generationBits: 16 })` (16 + 16 = 32 bits;
991
- 65 536 entities × 65 536 generations). See test
992
- [tests/ref.test.ts](./tests/ref.test.ts) `generation wrap` describe block.
993
-
994
- ## [0.5.6] - 2026-06-09
995
-
996
- ### Changed
997
-
998
- - Docs: document `forEachEntity`'s packed-EntityId footgun and cross-link `forEachEntityIndexed` / `getEntityIndex` (closes downstream issue #3). No runtime change — the JSDoc reaches consumers through the generated `.d.ts` / `.d.cts`.
999
-
1000
- ## [0.5.5] - 2026-06-08
1001
-
1002
- ### Changed
1003
-
1004
- - Project home migrated to the [`islumina`](https://github.com/islumina) GitHub org; published from there via npm trusted publisher (OIDC + SLSA provenance). Family-wide version alignment at `0.5.5`.
1005
-
1006
- ### Internal
1007
-
1008
- - Test version assertions now derive from `package.json` instead of a hard-coded string, shrinking the release version-sync surface.
1009
-
1010
- ## [0.5.3] - 2026-06-05
1011
-
1012
- ### Added
1013
-
1014
- - Add `forEachEntityIndexed` yielding the masked index alongside the EntityId; closes the A1 packed-EntityId footgun in code (safe column iteration is now the default; `forEachEntity` unchanged).
1015
-
1016
- ### Docs
1017
-
1018
- - **Correctness clarification — `forEachEntity`'s `e` is a packed `EntityId`, not a column index.** The column-iteration docs/examples now lead with `forEachEntityIndexed((e, i, ...cols) => …)`, indexing SoA columns with the yielded safe index `i` (`pos.x[i]`) — no manual masking (`README.md`, `README_ZHTW.md`, `docs/MIGRATION.md`, `docs/MIGRATION_ZHTW.md`, regenerated `llms-full.txt`). `forEachEntity` is documented as the form to use when you only need the `EntityId`; for that raw form, derive the subscript with `getEntityIndex(e)`. The old `pos.x[e]` pattern only worked while generation 0 (`e === getEntityIndex(e)`); after any `destroyEntity` recycles a slot it read an out-of-bounds column slot. Added a recycle regression test proving both the bug and the fix; `e`'s packed semantics are intentionally unchanged (it is still what you pass to `destroyEntity`/`hasComponent`/command buffers). Corrected the 0.1.0 storage note that implied `Position.x[eid]` indexes by the packed id.
1019
- - **A2 (tag slot footgun).** Documented that each tag in `defineQuery([...])` occupies a callback slot passed as `true`, with a correct mixed-query example; recommend placing tags last so data columns come first. Docs-only — the callback arity is intentionally unchanged (changing it would shift data params for code that correctly writes `(e, _tag, pos)`; deferred to a future major). Column arguments remain `any`-typed.
1020
- - **A3 (reactive-query lazy arm).** Documented that enter/exit buffers are armed lazily on first registration/read, and recommend defining reactive queries at module scope so the first `tick` already observes transitions.
1021
-
1022
- ### Fixed
1023
-
1024
- - Synced the embedded `VERSION` constant (`src/version.ts`) to `0.5.2` to match `package.json` — the release gate asserts they are equal (`tests/utils.test.ts`). No API change; `dist` differs from 0.5.1 only by this version stamp.
1025
-
1026
- ## [0.5.1] - 2026-06-02
1027
-
1028
- ### Fixed
1029
-
1030
- - **`destroyEntity` now fires the reactive `enterQuery`/`exitQuery` surface.** Previously `destroyEntity` cleared the entity mask wholesale without notifying `recordEntityMaskChange`, so `exitQuery(...)` buffers stayed empty on destroy — asymmetric with both `removeComponent` (which notifies) and the query-targeted `observe(q, 'remove')` observer (which already fired on destroy). A destroyed entity now records an exit for every query it was matching. The pre-destroy mask is snapshotted at destroy entry so reentrant teardown handlers cannot suppress the exit. No public API change.
1031
- - **`disposeWorld` / `destroyWorld` now release the large per-entity arrays.** The dispose path cleared archetypes/storages/queries but left `entityMask`, `entityArchetype`, `generations`, `freeList`, `componentBitFor`, `bitToQueries`, `queryArchetypeStamp`, and `sab` allocated. Because the public world handle's `capacity` getter closes over the internal state object, those arrays survived for the lifetime of the (typically retained) handle, defeating the "clear large buffers to help GC" intent. They are now released (typed arrays swapped to length-0 instances, Maps/arrays cleared, `sab` nulled). Post-dispose operations still throw as before — this is internal state, not public API.
1032
- - **`unpackBinary` best-effort mode no longer leaks a raw `SyntaxError`.** Under `onUnknownVersion: 'best-effort'`, a malformed/garbled snapshot body reaching `JSON.parse` now surfaces a namespaced `aiecsjs:` error (with the original parse error attached as `cause`), consistent with the rest of the serializer. All existing length/bounds checks are unchanged.
1033
- - **`DeltaSerializer.apply()` is now sound on a non-pristine / churned replica.** It previously treated the wire `eid` (a raw slot index, generation 0) as a packed id — throwing `addComponent on dead entity` once a replica slot's generation had advanced — and padded with `while (targetState.size < e.eid) createEntity()`, conflating the live count with a slot index and spawning phantom entities for holes in the source id space. `apply()` now materialises each entity at the source's slot via a new internal `ensureEntityAtSlot` primitive (reuse a live slot, reclaim a freed one, or advance the frontier), using the slot's current generation. No public API or wire-format change. Caveat: deltas carry only added/changed entities — entity/component removals are not propagated, so `apply()` remains additive.
1034
-
1035
- ## [0.5.0] - 2026-05-30
1036
-
1037
- ai\*js family version-unify milestone — the seven packages align on a common `0.5.0`. **No runtime API change; `dist/` is byte-identical to 0.4.1 apart from the bumped `VERSION` string.**
1038
-
1039
- ### Changed
1040
-
1041
- - **Migration-guide links repointed to GitHub blob URLs.** `docs/` became repository-only in 0.4.1 (dropped from the npm `files[]`), so the relative `./docs/MIGRATION*.md` links in `README.md` / `README_ZHTW.md` no longer resolved from the npm package page or the installed tarball. They now point at `https://github.com/islumina/aiecsjs/blob/main/docs/…` so consumers can follow them.
1042
- - **Version aligned to the ai\*js family `0.5.0` unify milestone.** A coordinated family-wide minor bump; aiecsjs carries no source / public-API / relations change in this release.
1043
-
1044
- ## [0.4.1] - 2026-05-29
1045
-
1046
- Consistency patch — packaging and documentation surface aligned to the ai*js family. **No runtime API change; `dist/` is byte-identical to 0.4.0 apart from the bumped `VERSION` string.**
1047
-
1048
- ### Changed
1049
-
1050
- - **`package.json` packaging metadata aligned to family conventions**: `engines.node` `">=18"` → `">=18.0.0"`; `repository.url` gains the `git+` prefix (`git+https://github.com/islumina/aiecsjs.git`). Both are semantically equivalent — registry/tooling hygiene only.
1051
- - **`files[]` trimmed to the family-minimal set plus `api.json`**: the npm tarball now ships `dist`, `README.md`, `README_ZHTW.md`, `LICENSE`, `llms.txt`, `llms-full.txt`, and `api.json`. `LICENSE` is now listed explicitly (it was already published via npm's automatic root-LICENSE inclusion). `STABILITY.md`, `CHANGELOG.md`, and `docs/` are no longer bundled — they remain in the repository and stay reachable from the README/`llms.txt` links on GitHub. `api.json` is **deliberately retained**: it is the machine-readable export manifest (stability + `since` per entry) that this package's "AI-readable docs" contract advertises, so it remains the tarball's stability surface for tooling.
1052
-
1053
- ### Removed
1054
-
1055
- - **Redundant Traditional-Chinese doc duplicates**: `STABILITY_ZHTW.md` and `CHANGELOG_ZHTW.md` removed. The family keeps `README_ZHTW.md` as the single Traditional-Chinese entry point; per-export stability and the changelog are English-canonical (with `api.json` carrying the machine-readable stability surface). The plain-pipe language-switcher line atop `STABILITY.md` / `CHANGELOG.md` and the now-dangling `_ZHTW` references inside `README_ZHTW.md` were removed accordingly.
1056
-
1057
- ## [0.4.0] - 2026-05-29
1058
-
1059
- ### Added
1060
-
1061
- - **`getRelationData(world, source, rel, target)`**: new stable export on `aiecsjs/relations`. Returns the `data` payload attached via `addRelation`, or `undefined` when no such edge exists or no data was stored. Closes the write-only-data asymmetry present since 0.1: `addRelation` accepted a data argument but there was no corresponding public read path.
1062
-
1063
- ### Changed
1064
-
1065
- - **`aiecsjs/relations` graduated from experimental to stable.** The graph API (`defineRelation`, `addRelation`, `removeRelation`, `getRelationTargets`, `getRelationData`) and the built-in `ChildOf` relation are now frozen for the 1.x track. See [`STABILITY.md`](./STABILITY.md) for the full stability contract, including the raw slot-keying ABA semantic.
1066
- - **`aiecsjs/worker` remains experimental.** True SAB shared-memory column aliasing is deferred; the worker sub-path continues on snapshot-copy semantics.
1067
-
1068
- ### Build & Tooling
1069
-
1070
- - **size-limit → `scripts/check-size.mjs`**: replaced the `size-limit` + `@size-limit/file` dev dependencies with a zero-dependency script that measures transitive chunk-closure gzip size per ESM entry. Required because `tsup splitting: true` (introduced in 0.3.1) makes each entry a thin re-export shell; the vanilla single-file measurement reported ~899 B for index when the true closure is ~7295 B. The new script resolves chunk imports recursively via BFS, sums per-file gzip, and enforces per-entry budgets.
1071
- - **npm → pnpm**: migrated from `package-lock.json` to `pnpm-lock.yaml`. Added `"packageManager": "pnpm@9.12.3"` and `"publishConfig": { "access": "public" }`. CI and publish workflows updated to use `pnpm/action-setup@v6` + `pnpm install --frozen-lockfile`. `npm publish --provenance --access public` in the publish workflow is intentionally preserved (OIDC trusted publishing requires npm CLI, not pnpm publish).
1072
- - **Coverage tests added + unreachable gaps documented**: new tests cover previously-unreachable paths in `serialize.ts`, `component.ts`, `query.ts`, and `loop.ts`. Thresholds updated to the honestly-achieved floor (statements 95 / branches 81 / functions 98 / lines 99). Unreachable-by-design gaps are now documented in `vitest.config.ts` with Chesterton rationale.
1073
-
1074
- ## [0.3.1] - 2026-05-29
1075
-
1076
- ### Fixed
1077
-
1078
- - **Packed EntityId signed-overflow for generation ≥ 128**: `createEntity` returned a negative number diverging from the unsigned value stored in archetype row arrays (`Uint32Array`), so query iteration (`runQuery`/`iterQuery`/`forEachEntity`) yielded an eid that failed `entityRow` lookups; `refOf`/`entityExists`/`deref` on a query-iterated high-generation entity misbehaved (`refOf` threw on a live entity). `packEid`/`packEntity` now normalise with `>>> 0`. No public-bundle behaviour change beyond the corrected eid representation (EntityId is opaque + in-memory-only).
1079
- - **`toJSON` silently dropped high-generation entities** (gen ≥ 128 with default 8-bit generation): `toJSON` contained its own inline pack expression that produced a signed (negative) result, diverging from the unsigned key stored in `arch.entityRow`. The affected entity passed the archetype check but failed `entityRow.has()`, so it was omitted from every snapshot and `serializeWorld` call. Fixed by replacing the inline expression with the canonical `packEid` (which applies `>>> 0`). SPOT principle: one pack source of truth.
1080
- - **Cross-subpath registry isolation** (`tsup splitting: false` → `splitting: true`): each compiled entry point (`dist/index.js`, `dist/serialize.js`, etc.) previously bundled its own private copy of `internal/world.ts`, including the module-scope `worldRegistry`. A world created via the core subpath was invisible to `serializeWorld`/`getRelationTargets`/`transferableSnapshot` imported from their respective subpaths, causing `world N is destroyed or unknown` at runtime. With `splitting: true`, esbuild extracts a shared chunk used by all entries; ESM and CJS are both verified by the new `scripts/check-dist-subpaths.mjs` smoke script.
1081
- - **`getRelationTargets` returned raw index as `EntityId`** (gen always 0): `addRelation` stores the target as a raw slot index (`& indexMask`). The previous return path cast this raw index directly to `EntityId`, which is equivalent to a packed id with generation 0. For any target that had been recycled (gen > 0), callers received a stale id that failed `entityExists`, `entityRow` lookups, and component access. Fixed by re-packing each raw index against the current generation via `packEid` before returning.
1082
- - **`resolveOptions` did not validate `indexBits + generationBits ≤ 32`**: the individual range checks (`indexBits ∈ [1, 24]`, `generationBits ∈ [0, 16]`) allowed combinations such as `indexBits=24, generationBits=16` (40 bits), where `gen << 24` silently overflowed and high-generation bits were lost. A sum check is now enforced with a clear error message. The `[Unreleased]` example corrected accordingly (`indexBits: 16, generationBits: 16` = 32 bits).
1083
-
1084
- ### Known Limitations
1085
-
1086
- - **`createDeltaSerializer.apply` with a recycled target world**: `apply` uses the raw entity index from the delta snapshot as the `EntityId` directly. When the target world has already recycled any of those slots (generation > 0), component operations silently act on the wrong packed id. This is a known limitation of the experimental delta API; the common usage (delta → a fresh gen-0 render-mirror world) is unaffected. A proper raw-index-to-packed-id mapping is planned for 0.4. Avoid `apply` against a world that has previously destroyed entities.
1087
-
1088
- ### Documentation
1089
-
1090
- - README / README_ZHTW updated to reflect the shipped 0.3.0 `EntityRef` API: the previous README still described EntityRef as "targeted for 0.3+" and `getEntityGeneration`/`packEntity` as experimental. Both files now correctly state EntityId has been packed since 0.3, and `EntityRef` / `refOf` / `deref` / `aliveRef` / `EntityNotAliveError` are all stable since 0.3.0. API table entries for these symbols added.
1091
-
1092
- ### Build & Tooling
103
+ ## [0.5.8] - 2026-06-14
1093
104
 
1094
- - Coverage gate: `@vitest/coverage-v8` installed and wired into `prepublishOnly` (replaces `npm run test`) and CI. Thresholds: statements 95 / branches 80 / functions 97 / lines 98 — the achievable bar on pristine source. The branch figure honours the `?? 0` / `noUncheckedIndexedAccess` idiom on TypedArray reads (nullish-fallback branches unreachable by design); thresholds are raised only by adding tests, never by stripping defensive guards or scattering `/* v8 ignore */`.
1095
- - `fast-check` property tests (`tests/properties.test.ts`): pack/unpack round-trip invariant (asserts `e >= 0` to guard the P0 regression) and ABA-deref always-null invariant.
1096
- - Dispose three-cycle tests, error-path tests, and observer handler-throw behaviour documented in `tests/world.test.ts` / `tests/observers.test.ts`.
1097
- - `scripts/check-dist-subpaths.mjs` (`npm run verify:dist`): post-build smoke test that imports `createWorld`+`createEntity` from the core subpath and calls `serializeWorld`, `addRelation`/`getRelationTargets`, and `transferableSnapshot` from their respective subpaths for both ESM (`dist/*.js`) and CJS (`dist/*.cjs`). Wired into `prepublishOnly` (after `build`) and CI.
105
+ - Changed: exclusive-relation destroy cleanup now clears incoming edges in O(incoming) via a reverse index instead of scanning the full relation capacity per destroy. Behaviour is unchanged; large sparse relation tables no longer pay a per-destroy capacity scan.
106
+ - Changed: reduced `noExplicitAny` lint warnings in source (154 to 140) with no behaviour change.
107
+ - Documentation-only slimming pass across README, stability notes, review backlog, and LLM context. Reactive query world-local indexing remains a deferred follow-up (design note in the review backlog).
1098
108
 
1099
- ## [0.3.0] - 2026-05-29
109
+ ## [0.5.7] - 2026-06-10
1100
110
 
1101
- ### Added (API)
111
+ - Hardened serialization restore capacity and hostile snapshot handling.
112
+ - Fixed query iteration safety around archetype size changes.
113
+ - Clarified worker snapshot buffer types and runtime validation boundaries.
114
+ - Regenerated LLM context from the canonical docs.
1102
115
 
1103
- - **`EntityRef<T>`** — ABA-safe entity reference. `refOf(world, eid)` builds one;
1104
- `deref(world, ref)` returns the entity id when still alive (generation match)
1105
- or `null` otherwise; `aliveRef(world, ref)` is the boolean guard form. Phantom
1106
- type `T` lets callers distinguish ref kinds (e.g. `EntityRef<'bullet'>`) without
1107
- runtime cost. Refs are in-memory only — not serializable across worker / disk.
1108
- - **`EntityNotAliveError`** — thrown by `refOf` when the entity is dead or invalid.
1109
- `deref` / `aliveRef` never throw.
116
+ ## Older releases
1110
117
 
1111
- ### Changed
1112
-
1113
- - **`EntityId` now packs index + generation** into a single 32-bit number
1114
- `(generation << indexBits) | index` (default `indexBits=24, generationBits=8`).
1115
- `EntityId` remains opaque per STABILITY contract; the layout is implementation
1116
- detail. **Migration note**: do not compare `EntityId` numbers directly
1117
- (`eid === 42` will break across slot recycles); use
1118
- `getEntityIndex(eid)` for index comparison or `refOf(world, eid).id` for
1119
- identity matching that survives slot reuse.
1120
- - **`getEntityGeneration` / `packEntity` graduate to `stable`** (were `experimental`
1121
- since 0.2.0). Both now return real values. These functions use default 24/8 bit
1122
- layout; for non-default `createWorld({ indexBits, generationBits })`, use
1123
- `EntityRef` and `deref` instead of manual unpacking.
1124
-
1125
- ### Fixed
1126
-
1127
- - **ABA bug on entity slot recycle**: previously `entityExists` and `isAliveInternal`
1128
- only checked archetype membership; a stale `EntityId` pointing at a recycled slot
1129
- would silently report alive. With packed generation + `deref` generation match,
1130
- stale refs now correctly invalidate.
1131
- - **`destroyEntity` generation wrap mask aligned with `options.generationBits`**
1132
- (was hard-coded `& 0xffff`). The mask now correctly uses
1133
- `state.options.generationMask`, fixing inconsistency for non-default
1134
- `generationBits` values.
1135
-
1136
- ### Documentation
1137
-
1138
- - `onSet` JSDoc clarifies that `addComponent` does NOT trigger `onSet`, and
1139
- direct writes to column views returned by `getComponent` (e.g. `col.x[idx] = 5`)
1140
- also do NOT trigger `onSet`. Only `setComponent` on an already-present
1141
- component fires the callback. Anti-pattern example included.
1142
-
1143
- ### Compatibility
1144
-
1145
- - `EntityId` layout change is **not** breaking at the type system level (opaque
1146
- branded number), but consumers who relied on `eid === N` direct comparison
1147
- will need to migrate (see Migration note above).
1148
- - All existing `stable` exports unchanged.
1149
- - `aiecsjs/worker` snapshot wire format unchanged (still uses raw indices).
1150
- - `aiecsjs/serialize` wire format unchanged.
1151
-
1152
- ### Build & tooling
1153
-
1154
- - `VERSION` constant bumped to `0.3.0`.
1155
-
1156
- ## [0.2.1] - 2026-05-28
1157
-
1158
- ### Security
1159
-
1160
- - **Resolve two Dependabot moderate advisories** on the transitive dev-only graph by upgrading `vitest` 1.6.0 → 4.1.7. Adds `vite` 8.0.14 as a direct devDependency to satisfy vitest 4's peer range (`^6 || ^7 || ^8`). These are dev-only — runtime surface unchanged.
1161
- - [GHSA-67mh-4wv8-2f99](https://github.com/advisories/GHSA-67mh-4wv8-2f99) `esbuild <=0.24.2` CORS development server data leak (fixed in 0.25.0).
1162
- - [GHSA-4w7w-66w2-5vf9](https://github.com/advisories/GHSA-4w7w-66w2-5vf9) `vite <=6.4.1` path traversal in optimized deps `.map` handling (fixed in 6.4.2 / 7.3.2 / 8.0.5).
1163
-
1164
- ### Changed
1165
-
1166
- - **README opening unified across the ai*js family**: five-badge shields row (npm + CI + License + AI Generated + 繁體中文/English), one-line tagline as blockquote, ecosystem footer linking to the other two packages. Replaces the previous mixed style (text language switcher + 5 ad-hoc badges).
1167
- - **`VERSION` constant bumped to 0.2.1** ([src/version.ts](src/version.ts)) so `world.version` and snapshot meta reflect this release.
1168
-
1169
- Runtime surface unchanged. Production bundles are byte-identical to 0.2.0.
1170
-
1171
- ## [0.2.0] - 2026-05-28
1172
-
1173
- ### Fixed (correctness + security)
1174
-
1175
- - **Prototype-pollution hardening in AoS `writeInitial`** ([src/internal/component.ts](src/internal/component.ts)): replaced `Object.assign(inst, initial)` with an explicit own-key copy that filters `__proto__` / `constructor` / `prototype`. Closes a path where a malicious `JSON.parse` payload reaching `addComponent` / `setComponent` / `fromJSON` / `deserializeWorld` could clobber the per-instance prototype.
1176
- - **Observer dispatch is now safe against unsubscribe-during-iteration** ([src/observers.ts](src/observers.ts)): every `fire*` walks a snapshot of `state.observers` (`Array.from(...)` + `includes` guard) so a handler that calls its own returned disposer no longer skips sibling observers in the same fire round.
1177
- - **`removeComponent` writes the new entity mask BEFORE firing observers** ([src/internal/component.ts](src/internal/component.ts)): query-targeted `remove` observers read `state.entityMask` to decide if the entity left the matching set; with the previous ordering the bit was still set during dispatch and the remove never fired. Brings `removeComponent` in line with `addComponent`'s "mutate then fire" order.
1178
- - **`destroyEntity` now emits query-targeted `remove` events** ([src/observers.ts](src/observers.ts) `dispatchDestroyObservers`): in addition to per-component `onRemove`, the destroy hook now walks query observers and fires `remove` for any query the entity was matching pre-destroy. `wasMatch` is computed against a **snapshot of the pre-destroy mask** (not live `state.entityMask`) so a Phase 1 reentrant handler that mutates the entity's mask cannot suppress query removes in Phase 2 (regression caught by the round-2 review).
1179
- - **`deserializeWorld` / `attachWorld` / `adoptSnapshot` binary length fields are bounds-checked** ([src/serialize.ts](src/serialize.ts)): `verLen` and `jsonLen` carry explicit `off + len <= bytes.length` assertions and a 64 MiB cap. `attachWorld` and `adoptSnapshot` ([src/worker.ts](src/worker.ts)) both carry SECURITY JSDocs that document the trust boundary expectation for SAB / TransferableSnapshot transports.
1180
-
1181
- ### Added (API)
1182
-
1183
- - **`disposeWorld(world)`** — new export that aliases `destroyWorld`. Aligns with the ai*js ecosystem `dispose()` convention (`aifsmjs.Runtime.dispose`, `aibridgejs.Bridge.dispose`). Prefer this name in new code; `destroyWorld` is retained as a deprecated alias and is scheduled for removal in 1.0.
1184
- - **`{ signal?: AbortSignal }` on every observer**: `onAdd`, `onRemove`, `onSet`, and `observe` now accept an options object. When the signal aborts, the observer auto-unsubscribes. The returned unsubscribe function remains valid and idempotent. New exported type `ObserverOptions` documents the shape. This closes a long-running gap noted in the AI ecosystem audit — long-lived observers on user-controlled lifecycles (UI components, async pipelines) no longer require manual cleanup wiring.
1185
-
1186
- ### Changed (stability)
1187
-
1188
- - `getEntityGeneration` and `packEntity` re-classified from `stable` → `experimental` in `STABILITY.md` and `api.json`. In 0.1 these returned `0` / identity and that has not changed — the relabel honestly admits the deferred encoding work. Real values arrive when ABA-safe `EntityRef` lands.
1189
- - `destroyWorld` re-classified from `stable` → `deprecated`. Behaviour unchanged; the deprecation is the API-naming alignment described above. Use `disposeWorld` instead.
1190
-
1191
- ### Documentation
1192
-
1193
- - `onSet` now carries a JSDoc and README paragraph clarifying that it is a **low-level mutation hook**, not a reactive value-predicate query. `enterQuery` / `exitQuery` continue to be the structural-change surface; reactive value tracking remains an explicit non-goal of the core.
1194
- - README observer section gains an `AbortController`-based unsubscribe example.
1195
-
1196
- ### Build & tooling
1197
-
1198
- - Added [Biome](https://biomejs.dev/) lint + format (`biome.json`, `npm run lint`, `npm run format`). Brings parity with `aifsmjs` and `aibridgejs` and surfaces `noExplicitAny` warnings in legacy `src/internal/*` for follow-up cleanup.
1199
- - Added `scripts/verify-exports.mjs` and the `npm run verify:exports` script; gates that every `package.json#exports` entry has a real file in `dist/`. Wired into `prepublishOnly`.
1200
- - New `CONTRIBUTING.md` with the same shape used by `aifsmjs` (quick start, scope policy, release flow).
1201
-
1202
- ### Compatibility
1203
-
1204
- This release is **non-breaking at runtime**. All existing code that called `destroyWorld(world)`, registered observers without options, or read `getEntityGeneration` continues to work. The stability label change is documentation-only.
1205
-
1206
- ## [0.1.4] - 2026-05-28
1207
-
1208
- Docs-only release. Adds a cross-package integration section pointing at the `aibridgejs` JSON envelope contract; no source code changes.
1209
-
1210
- ### Documentation
1211
-
1212
- - README and README_ZHTW gained an "Integration with aibridgejs" section explaining that `bridge.call` / `bridge.emit` enforce JSON-safe payloads and silently drop `Date`, `Map`, `Set`, and class instances. The correct shape for streaming world state across the bridge is `toJSON(world)` (or `serializeWorld(world)` wrapped in a JSON envelope) before emitting, not `getComponent(...)` direct. See [aiecsjs README · Integration with aibridgejs](README.md#integration-with-aibridgejs).
1213
- - Verified via the `aijs-integration-smoke` companion project: every named export from `aifsmjs@0.1.2`, `aibridgejs@0.1.3`, and `aiecsjs@0.1.3` can coexist in a single TypeScript module with zero identifier collisions under `tsc --noEmit --strict`.
1214
-
1215
- ## [0.1.3] - 2026-05-28
1216
-
1217
- A "no known silent bugs" release. Two correctness fixes, one hot-path allocation removal, and a small batch of style cleanups. No public API behaviour changes; `_getWorldState` is removed from the root export (was undocumented, unused by every sub-path, leading underscore signalled internal).
1218
-
1219
- ### Fixed
1220
-
1221
- - `aiecsjs/relations` relation data store no longer keys edges by `srcEid * worldCapacity + tgtEid`. After the world grew, the same `(src, tgt)` pair computed a different key and earlier entries became orphaned. Storage is now a nested `Map<srcEid, Map<tgtEid, data>>`, independent of capacity. The cleanup hook on `destroyEntity` was updated to match. v0.1 has no public retrieve API so the bug was user-invisible, but it would have surfaced the moment a retrieve surface landed in 0.2.
1222
- - Per-world resolved query bitmasks no longer live on the module-global `QueryInternal`. When the same `defineQuery(...)` handle was used by two worlds whose component registration orders differed, the second world's per-world mask overwrote the first world's, and `runQuery` silently returned wrong rows in world A. Masks now live in `WorldState.queryMasks: Map<queryId, QueryMaskBundle>`, isolated per world. Regression test in `tests/multi-world.test.ts` exercises the cross-order scenario.
1223
-
1224
- ### Changed (internal)
1225
-
1226
- - Observer dispatch (`dispatchQueryObservers`) no longer allocates a temporary `Uint32Array` on every mutation event. Added `matchesEntityMask` helper in `bitmask.ts` that reads directly from `state.entityMask` at a base offset.
1227
- - Shared bit-iteration extracted as `forEachSetBit(mask, base, words, fn)` in `bitmask.ts`. `clearAllEntityStorages` (`component.ts`) and `dispatchDestroyObservers` (`observers.ts`) now share that single implementation instead of inlining the same `word & -word` / `Math.clz32` pattern three times.
1228
- - `state.generations[idx]` is written without an `as any` cast. `Uint8Array | Uint16Array` already supports indexed read/write.
1229
- - Removed the `void oldCap` no-op from `growEntityArrays`.
1230
- - Removed `_getWorldState` from the root `aiecsjs` export. Sub-paths (`aiecsjs/serialize`, `aiecsjs/worker`) already import `getWorldState` directly from the internal module; the leading-underscore root re-export had no consumer.
1231
-
1232
- ### Planned for 0.3
1233
-
1234
- - Promote `aiecsjs/relations` and `aiecsjs/worker` to `stable`.
1235
- - Stabilize the network delta wire format.
1236
- - Add automated benchmark suite committed to repo.
1237
-
1238
- ### Planned for 1.0
1239
-
1240
- - API freeze for the 1.x line.
1241
- - Drop the experimental status label.
1242
-
1243
- ## [0.1.2] - 2026-05-28
1244
-
1245
- CI/CD smoke-test release. No user-facing source or behavioural changes since 0.1.1; this bump exists solely to validate the tag-triggered publish workflow (see `.github/workflows/publish.yml`) end-to-end against the npm registry with provenance attestation.
1246
-
1247
- ### Build & tooling
1248
-
1249
- - Confirmed that pushing a `v*.*.*` tag triggers `.github/workflows/publish.yml`, runs `prepublishOnly` (typecheck + tests + build + size budget), and publishes to npm with sigstore provenance.
1250
-
1251
- ## [0.1.1] - 2026-05-28
1252
-
1253
- The "documentation honesty + test backstop" release. No new public APIs; this is the version of 0.1.0 that ships with the public surface, the documentation, and the test coverage in agreement.
1254
-
1255
- ### Fixed
1256
-
1257
- - `destroyEntity` now clears the SoA columns and undefines the AoS slots that the destroyed entity owned. Previously only the entity mask was cleared, leaving stale data at the slot visible to debug snapshots and the serialisation path. Public `hasComponent` / query behaviour was already correct, so user-visible behaviour is unchanged; this closes the gap surfaced by the new `destroyEntity zeroes the destroyed entity’s SoA slot` test.
1258
-
1259
- ### Changed (docs hygiene)
1260
-
1261
- - README and STABILITY now describe `aiecsjs/worker` honestly as a snapshot-copy transport for 0.1; true shared columns remain a 0.2 target. README description and `package.json` description updated accordingly.
1262
- - README clarifies that 0.1 `EntityId` is a bare slot index; internal generation is tracked for slot reuse but not encoded in the ID. ABA-safe `EntityRef` is on the 0.2 roadmap.
1263
- - Sub-paths (`loop` / `commands` / `observers` / `serialize` / `worker` / `relations`) re-positioned in STABILITY as utility / adapter sub-paths; the root `aiecsjs` is the stable core surface. Tree-shakers should drop any sub-path the app does not import.
1264
- - README adds a "What aiecsjs does NOT do" section listing explicit non-goals (system scheduler, render binding, physics, network replication, value-predicate reactive queries, prefab/inheritance).
1265
- - Language version filenames renamed from `*.zh-TW.md` to `*_ZHTW.md`. Cross-links, `llms.txt`, and `package.json` `files` updated. Future language variants follow the same uppercase ISO 639-1 pattern.
1266
- - Removed emoji from documentation prose (language switchers, status banners).
1267
-
1268
- ### Build & tooling
1269
-
1270
- - tsup build now runs with `minify: true`.
1271
- - `size-limit` added as a dev dependency; per-export gzip budgets enforced via `npm run size`. Current measurements: core 5.49 kB, all sub-paths combined 12.6 kB gzip.
1272
- - GitHub Actions CI workflow added: typecheck → test → build → size check on push and PR to `main`.
1273
- - `prepublishOnly` now runs typecheck, tests, build, and the size budget gate before allowing publish.
1274
-
1275
- ### Tests
1276
-
1277
- - Test count increased from 84 to 140. New file `tests/internal/bitmask.test.ts` covers the multi-word bitmask helpers in isolation (27 cases including `matches` truth table). New file `tests/multi-world.test.ts` covers per-world isolation when the same component is reused. Existing files gained: naive linear-filter cross-check against `runQuery` for all clause combinations, archetype migration boundary path, query mid-traversal stability and lazy cache behaviour, SoA field clear assertions on both `removeComponent` and `destroyEntity`, SoA vector-length round trip, `maxEntities` / `maxComponents` boundary throws, observer fan-out for destroy across multiple components, `onSet` value content, query observer ignores unrelated mutation, relation source-side destroy cleanup, exclusive relation storage resize, worker `readOnly` rejects add / remove / destroy, serialize `options.components` filter, `onUnknownVersion: throw | best-effort` paths, command buffer placeholder resolves into a queryable entity, slot-reuse limitation made explicit. Loop tests rewritten on top of `vi.useFakeTimers({ toFake: ['performance', ...] })` for deterministic dt validation.
1278
-
1279
- ## [0.1.0] - 2026-05-27
1280
-
1281
- **Initial release.** All 50 documented exports across 7 modules are implemented and covered by 84 passing Vitest behaviour tests. Built with tsup to dual ESM + CJS, ships `.d.ts` declarations and source maps.
1282
-
1283
- ### Implementation notes
1284
-
1285
- - **Storage**: world-level TypedArray columns per SoA component field, sized to world capacity. Archetypes track entity membership (a `Uint32Array entities[]`) but do not own column data. This makes archetype migration O(1) and lets columns be indexed by the entity **index** (`getEntityIndex(eid)`) directly, without per-archetype indirection. (In 0.1 `EntityId` *was* the index, so `Position.x[eid]` worked literally; since 0.3 packs a generation into the id, hot-loop code must index with `Position.x[getEntityIndex(eid)]` — the raw packed id is no longer the column offset.) Trade-off: iteration over archetypes reads columns at potentially non-contiguous offsets; for hot data this stays in L1.
1286
- - **EntityId is unversioned in 0.1**: `EntityId` is the entity index. Generation is tracked internally for slot reuse but not encoded in the ID. `getEntityIndex` / `getEntityGeneration` / `packEntity` are identity helpers. ABA-safe references via a separate `EntityRef` type are planned for 0.2.
1287
- - **Bitmask queries**: multi-word Uint32 masks, default 8 words (256 components). Per-world bit allocation, global component identity.
1288
- - **Worker / SAB**: 0.1 implements snapshot-copy semantics (serialize-into-SAB on send, deserialize-on-adopt) rather than true shared-memory column aliasing. The API surface matches the documented contract; true shared columns ship in 0.2.
1289
- - **Binary serialization**: a JSON payload wrapped in a 4-byte magic + version header. Compact binary column encoding is planned for 0.2.
1290
-
1291
- ### Added
1292
-
1293
- - `README.md` (English) and `README_ZHTW.md` (Traditional Chinese) with quick start, guide, API reference, performance notes, multi-threading guide, WebGPU interop section, serialization guide, migration guides, and "For AI Agents" section.
1294
- - `llms.txt` — Jeremy Howard format AI-discovery file.
1295
- - `llms-full.txt` — Single-file complete reference for LLM consumption.
1296
- - `api.json` — Machine-readable export manifest with stability and `since` fields on every entry.
1297
- - `STABILITY.md` and `STABILITY_ZHTW.md` — Per-export stability contract.
1298
- - `docs/MIGRATION.md` and `docs/MIGRATION_ZHTW.md` — Migration guides from bitECS 0.4, miniplex 2.0, and ECSY.
1299
-
1300
- ### API surface declared
1301
-
1302
- - Core: `createWorld`, `destroyWorld`, `resetWorld`, `getWorldSize`, `getWorldCapacity`.
1303
- - Entity: `createEntity`, `destroyEntity`, `entityExists`, `getEntityIndex`, `getEntityGeneration`, `packEntity`.
1304
- - Component: `defineComponent`, `defineTag`, `defineObjectComponent`, `addComponent`, `removeComponent`, `hasComponent`, `getComponent`, `setComponent`, `Types`.
1305
- - Query: `defineQuery`, `runQuery`, `forEachEntity`, `iterQuery`, `enterQuery`, `exitQuery`, `queryArchetypes` (experimental).
1306
- - System: `pipe`.
1307
- - Subpath `aiecsjs/loop`: `createLoop`.
1308
- - Subpath `aiecsjs/commands`: `createCommandBuffer`, `flush`, `withCommandBuffer`.
1309
- - Subpath `aiecsjs/observers`: `observe`, `onAdd`, `onRemove`, `onSet`.
1310
- - Subpath `aiecsjs/serialize`: `serializeWorld`, `deserializeWorld`, `toJSON`, `fromJSON`, `createDeltaSerializer` (experimental).
1311
- - Subpath `aiecsjs/worker` (experimental): `transferableSnapshot`, `adoptSnapshot`, `attachWorld`, `detachWorld`.
1312
- - Subpath `aiecsjs/relations` (experimental, not implemented): `defineRelation`, `addRelation`, `removeRelation`, `getRelationTargets`, `ChildOf`.
1313
- - Utility: `VERSION`, `IS_SAB_SUPPORTED`, `isWorld`, `isEntity`.
1314
-
1315
- ### Known limitations in 0.1
1316
-
1317
- - `aiecsjs/relations` and `aiecsjs/worker` are implemented but tagged experimental; API may shift.
1318
- - Network delta wire format is JSON-based; binary patch format is planned for 0.2.
1319
- - AoS components are main-thread only; cannot be shared via SharedArrayBuffer.
1320
- - No automatic system scheduler / parallel execution.
1321
- - Worker/SAB uses snapshot-copy in 0.1 rather than true shared-memory aliasing.
1322
- - EntityId is unversioned; ABA-safe references arrive with `EntityRef` in 0.2.
1323
-
1324
- [Unreleased]: https://github.com/islumina/aiecsjs/compare/v0.5.6...HEAD
1325
- [0.5.6]: https://github.com/islumina/aiecsjs/compare/v0.5.5...v0.5.6
1326
- [0.5.1]: https://github.com/islumina/aiecsjs/compare/v0.5.0...v0.5.1
1327
- [0.1.0]: https://github.com/islumina/aiecsjs/releases/tag/v0.1.0
118
+ - `0.5.6` through `0.5.1` focused on release hygiene, docs accuracy, ECS safety fixes, and family SLSA/provenance metadata.
119
+ - `0.5.0` aligned the package with the broader ai*js family release line.
120
+ - `0.4.x` added relations and declared the 1.0-track stability policy.
121
+ - `0.3.x` expanded serialization, worker/SAB helpers, command buffers, observers, and docs.
122
+ - `0.2.x` hardened entity/component correctness and security-sensitive registry behavior.
123
+ - `0.1.x` introduced the root world/entity/component/query API and TypedArray SoA storage.
1328
124
 
1329
125
  ---
1330
126
 
@@ -1332,158 +128,35 @@ The "documentation honesty + test backstop" release. No new public APIs; this is
1332
128
 
1333
129
  # Stability Contract
1334
130
 
1335
- This document is the per-export stability promise for `aiecsjs`. It is the contract AI tools and human users can rely on when pinning versions and writing import paths.
1336
-
1337
- ## Policy
1338
-
1339
- aiecsjs follows [semver](https://semver.org/). Within the **0.x** series:
1340
- - **`stable`** exports do not change in breaking ways across minor versions (e.g. 0.1 → 0.2).
1341
- - **`experimental`** exports may change shape, name, or behaviour in any minor release. Pin the exact version if you depend on them.
1342
- - **`internal`** is not part of the API. May change in any patch release. Do not import.
1343
- - **`deprecated`** still works as documented but is scheduled for removal. The deprecation notice states the target version.
1344
-
1345
- At **1.0**, the `stable` surface freezes for the entire 1.x series.
1346
-
1347
- The full machine-readable export list lives in [`api.json`](./api.json), with the `stability` and `since` fields on every entry.
1348
-
1349
- ## By module
1350
-
1351
- The **root** entry (`aiecsjs`) is the stable core: world, entity, component, query, system. Everything under a sub-path (`aiecsjs/<name>`) is a **utility or adapter sub-path** — useful but non-essential, decoupled from the core, and importable a la carte. Tree-shakers should be able to drop any sub-path the application does not import.
1352
-
1353
- ### `aiecsjs` (root core)
1354
-
1355
- | Export | Stability | Since | Notes |
1356
- |---|---|---|---|
1357
- | `createWorld` | stable | 0.1.0 | |
1358
- | `disposeWorld` | stable | 0.2.0 | Alias for `destroyWorld`; aligns with the ai*js ecosystem `dispose()` convention. Prefer this name in new code. |
1359
- | `destroyWorld` | **deprecated** | 0.1.0 | Use `disposeWorld` instead. Scheduled for removal in 1.0. |
1360
- | `resetWorld` | stable | 0.1.0 | |
1361
- | `getWorldSize` | stable | 0.1.0 | |
1362
- | `getWorldCapacity` | stable | 0.1.0 | |
1363
- | `createEntity` | stable | 0.1.0 | |
1364
- | `destroyEntity` | stable | 0.1.0 | |
1365
- | `entityExists` | stable | 0.1.0 | |
1366
- | `getEntityIndex` | stable | 0.1.0 | |
1367
- | `getEntityGeneration` | stable | 0.3.0 | Returns real generation value packed into EntityId (default 24-bit index, 8-bit generation). For non-default `createWorld({ indexBits, generationBits })`, use `EntityRef` + `deref` instead. |
1368
- | `packEntity` | stable | 0.3.0 | Packs index + generation into an EntityId using default 24/8 bit layout. For non-default bit sizes, use `EntityRef` + `deref` instead. |
1369
- | `refOf` | stable | 0.3.0 | Throws `EntityNotAliveError` for dead entity. |
1370
- | `deref` | stable | 0.3.0 | Returns null for stale / cross-world refs; never throws. |
1371
- | `aliveRef` | stable | 0.3.0 | Boolean guard form of `deref`; never throws. |
1372
- | `EntityRef` (type) | stable | 0.3.0 | In-memory only; not serializable. |
1373
- | `EntityNotAliveError` | stable | 0.3.0 | Thrown only by `refOf`. |
1374
- | `defineComponent` | stable | 0.1.0 | |
1375
- | `defineTag` | stable | 0.1.0 | |
1376
- | `defineObjectComponent` | stable | 0.1.0 | AoS components are main-thread only; not SAB-shareable. |
1377
- | `addComponent` | stable | 0.1.0 | Argument order `(world, eid, component, init?)` is final. |
1378
- | `removeComponent` | stable | 0.1.0 | |
1379
- | `hasComponent` | stable | 0.1.0 | |
1380
- | `getComponent` | stable | 0.1.0 | |
1381
- | `setComponent` | stable | 0.1.0 | |
1382
- | `Types` | stable | 0.1.0 | Constant map; field names are part of the contract. |
1383
- | `defineQuery` | stable | 0.1.0 | |
1384
- | `runQuery` | stable | 0.1.0 | |
1385
- | `forEachEntity` | stable | 0.1.0 | |
1386
- | `iterQuery` | stable | 0.1.0 | |
1387
- | `enterQuery` | stable | 0.1.0 | |
1388
- | `exitQuery` | stable | 0.1.0 | |
1389
- | `queryArchetypes` | **experimental** | 0.1.0 | `Archetype.id` is opaque-internal; the shape of `Archetype` may grow. |
1390
- | `pipe` | stable | 0.1.0 | |
1391
- | `VERSION` | stable | 0.1.0 | |
1392
- | `IS_SAB_SUPPORTED` | stable | 0.1.0 | |
1393
- | `isWorld` | stable | 0.1.0 | |
1394
- | `isEntity` | stable | 0.1.0 | |
1395
-
1396
- ### `aiecsjs/loop` (utility sub-path)
1397
-
1398
- Fixed-timestep accumulator loop. Drop this sub-path if you already drive frame updates yourself (PixiJS `Ticker`, requestAnimationFrame, server-side simulation).
1399
-
1400
- | Export | Stability | Since | Notes |
1401
- |---|---|---|---|
1402
- | `createLoop` | stable | 0.1.0 | |
1403
-
1404
- ### `aiecsjs/commands` (utility sub-path)
1405
-
1406
- Deferred structural mutations so systems can mutate world structure mid-iteration without invalidating queries.
1407
-
1408
- | Export | Stability | Since | Notes |
1409
- |---|---|---|---|
1410
- | `createCommandBuffer` | stable | 0.1.0 | |
1411
- | `flush` | stable | 0.1.0 | |
1412
- | `withCommandBuffer` | stable | 0.1.0 | |
1413
-
1414
- ### `aiecsjs/observers` (utility sub-path)
1415
-
1416
- Component lifecycle hooks. The core does not require observers; install this sub-path only if a system needs add/remove/set callbacks.
1417
-
1418
- | Export | Stability | Since | Notes |
1419
- |---|---|---|---|
1420
- | `observe` | stable | 0.1.0 | Accepts `{ signal?: AbortSignal }` since 0.2.0. |
1421
- | `onAdd` | stable | 0.1.0 | Accepts `{ signal?: AbortSignal }` since 0.2.0. |
1422
- | `onRemove` | stable | 0.1.0 | Accepts `{ signal?: AbortSignal }` since 0.2.0. |
1423
- | `onSet` | stable | 0.1.0 | Low-level mutation hook; NOT a reactive value-predicate query. Accepts `{ signal?: AbortSignal }` since 0.2.0. |
1424
-
1425
- ### `aiecsjs/serialize` (utility sub-path)
1426
-
1427
- | Export | Stability | Since | Notes |
1428
- |---|---|---|---|
1429
- | `serializeWorld` | stable | 0.1.0 | Binary format includes a version stamp. |
1430
- | `deserializeWorld` | stable | 0.1.0 | |
1431
- | `toJSON` | stable | 0.1.0 | |
1432
- | `fromJSON` | stable | 0.1.0 | |
1433
- | `createDeltaSerializer` | **experimental** | 0.1.0 | Wire format may change before 1.0. |
1434
-
1435
- ### `aiecsjs/worker` (experimental adapter sub-path)
131
+ aiecsjs keeps the root ECS surface stable and treats subpaths as explicit public modules.
1436
132
 
1437
- The entire subpath is **experimental** in 0.x. **In 0.x the implementation is a snapshot-copy transport** — serialize the world into the SAB on send, deserialize into a fresh world on adopt. It is not true shared-memory column aliasing. The API surface matches the documented contract; true shared columns are targeted for **0.3+**. Snapshot layout and capability flags may change.
133
+ ## Stable Surface
1438
134
 
1439
- | Export | Stability | Since | Notes |
1440
- |---|---|---|---|
1441
- | `transferableSnapshot` | experimental | 0.1.0 | |
1442
- | `adoptSnapshot` | experimental | 0.1.0 | |
1443
- | `attachWorld` | experimental | 0.1.0 | |
1444
- | `detachWorld` | experimental | 0.1.0 | |
135
+ | Surface | Status | Notes |
136
+ | --- | --- | --- |
137
+ | `aiecsjs` root | Stable | World/entity/component/query/system helpers, `Types`, refs, `VERSION`, `EcsError`. |
138
+ | `aiecsjs/loop` | Stable utility | Loop helper only; scheduler policy remains app-owned. |
139
+ | `aiecsjs/commands` | Stable utility | Command buffers for deferred structural mutations. |
140
+ | `aiecsjs/observers` | Stable utility | Add/remove/set observer helpers. |
141
+ | `aiecsjs/serialize` | Stable utility | Binary and JSON snapshots with capacity clamps. |
142
+ | `aiecsjs/worker` | Experimental adapter | Environment-dependent SAB/transfer helpers. |
143
+ | `aiecsjs/relations` | Stable | Relations and `ChildOf`; destroy cleanup cost remains documented. |
144
+ | `aiecsjs/internal/*` | Private | No compatibility guarantee. |
1445
145
 
1446
- ### `aiecsjs/relations` (stable sub-path since 0.4.0)
146
+ ## Behavioral Boundaries
1447
147
 
1448
- The relations sub-path is **stable** as of 0.4.0. The graph API (`defineRelation`, `addRelation`, `removeRelation`, `getRelationTargets`, `getRelationData`) and the built-in `ChildOf` relation are frozen for the 1.x track.
148
+ - Entity ids are generational numeric ids. Use refs (`refOf`, `deref`, `aliveRef`) when storing ids across time.
149
+ - Query iteration is synchronous and direct. Use command buffers for structural changes inside systems.
150
+ - Reactive query buffers must be drained by the caller.
151
+ - Serialization accepts trusted snapshots; hostile input is bounded but not a sandbox.
152
+ - No build-mode-gated runtime validation policy is promised.
153
+ - Worker support depends on `SharedArrayBuffer`, transfer support, and browser isolation policy.
1449
154
 
1450
- **Raw slot-keying ABA semantic:** relation storage keys edges by raw entity slot index (`entityId & indexMask`), not by the full packed EntityId (which includes a generation counter). If entity A is destroyed and a different entity B is later created occupying the same slot, B will inherit A's outgoing and incoming edges unless the destroy cleanup hook ran. The cleanup hook fires automatically when `destroyEntity` is called, so normal usage is safe. Callers holding cached EntityId values across destroy/recreate cycles should validate liveness with `entityExists` before reading relation data if ABA is a concern.
155
+ ## Current Caveats
1451
156
 
1452
- | Export | Stability | Since | Notes |
1453
- |---|---|---|---|
1454
- | `defineRelation` | stable | 0.1.0 | |
1455
- | `addRelation` | stable | 0.1.0 | |
1456
- | `removeRelation` | stable | 0.1.0 | |
1457
- | `getRelationTargets` | stable | 0.1.0 | |
1458
- | `ChildOf` (constant) | stable | 0.1.0 | Built-in exclusive relation. |
1459
- | `getRelationData` | stable | 0.4.0 | Returns the data payload attached via `addRelation`, or `undefined` if no such edge or no data was stored. Subject to the raw slot-keying ABA semantic described above. |
1460
-
1461
- ### `aiecsjs/internal/*`
1462
-
1463
- Everything under this prefix is **internal**. It exists for the implementation's own use and may break in any release. Do not import.
1464
-
1465
- ## Roadmap
1466
-
1467
- | Version | Focus | Stability shift |
1468
- |---|---|---|
1469
- | 0.1.x | Core surface (world, entity, component, query, system, loop, commands, observers, serialize) | Initial publish; all marked experimental at the package level but per-export stable where listed. |
1470
- | 0.2.0 | Safety + alignment | Prototype-pollution hardening, observer `{ signal? }`, `disposeWorld` alias, `getEntityGeneration` / `packEntity` re-labelled experimental, `verify:llms` gate. See [CHANGELOG.md](./CHANGELOG.md#020---2026-05-28). |
1471
- | 0.3.x | EntityRef + generation packing | ABA-safe; `getEntityGeneration` / `packEntity` → stable. |
1472
- | 0.4.0 | Relations stabilisation | `aiecsjs/relations` graduated to stable; `getRelationData` added. `aiecsjs/worker` remains experimental (true SAB shared-memory columns deferred). |
1473
- | 0.6+ | Multi-World snapshot diff transport (placeholder) | experimental — design TBD. |
1474
- | 1.0.0 | API freeze | All `stable` exports frozen for 1.x. |
1475
-
1476
- ## How to check stability at runtime
1477
-
1478
- ```ts
1479
- import { VERSION } from 'aiecsjs'
1480
-
1481
- if (VERSION.startsWith('0.')) {
1482
- console.warn('aiecsjs is in pre-1.0; API surface may shift')
1483
- }
1484
- ```
1485
-
1486
- For programmatic introspection, parse [`api.json`](./api.json) — each entry has `stability` and `since` fields.
157
+ - Reactive query registration scans a module-level query cache on structural changes.
158
+ - Exclusive relation cleanup scans relation capacity when an entity is destroyed.
159
+ - Lint has many `noExplicitAny` warnings pending cleanup.
1487
160
 
1488
161
  ---
1489
162
 
@@ -1491,98 +164,34 @@ For programmatic introspection, parse [`api.json`](./api.json) — each entry ha
1491
164
 
1492
165
  # Contributing to aiecsjs
1493
166
 
1494
- Thanks for taking the time to look. aiecsjs is a deliberately small ECS core;
1495
- contributions that keep the surface narrow and the iteration path hot are
1496
- easier to accept than ones that expand it.
1497
-
1498
- ## Quick start
1499
-
1500
- ```bash
1501
- npm install
1502
- npm run test # vitest, ~150 behaviour tests + multi-world isolation
1503
- npm run typecheck # tsc --noEmit on strict mode
1504
- npm run lint # biome check (added in 0.2.0)
1505
- npm run build # tsup; dual ESM/CJS + .d.ts
1506
- npm run verify:exports # ensures package.json#exports matches dist/ (added in 0.2.0)
1507
- npm run size # size-limit per-subpath gzip budget
1508
- ```
1509
-
1510
- The full pre-publish gate is `npm run prepublishOnly`, which runs typecheck,
1511
- tests, build, and the size budget check — in that order. Once 0.2.0 lands,
1512
- `lint` and `verify:exports` should also be wired into the gate (see
1513
- `package.json`).
1514
-
1515
- ## What gets in easily
1516
-
1517
- - Bug fixes with a failing test added first.
1518
- - README / typing corrections — especially in `STABILITY.md` or `api.json`
1519
- when an export's stability label drifts from reality.
1520
- - Tests that lock down existing behaviour (multi-world isolation, archetype
1521
- migration boundaries, observer fan-out on destroy, etc).
1522
- - New `aiecsjs/<subpath>` opt-in modules that follow the same shape as
1523
- `loop`, `commands`, `observers`, `serialize`, `worker`, `relations`:
1524
- independent, named exports only, no side effects, single responsibility,
1525
- tree-shakable.
1526
-
1527
- ## What needs discussion first
1528
-
1529
- - Anything that changes the storage layout (archetype tables, TypedArray
1530
- columns, bitmask layout). The Caesar-III-style growth invariants matter.
1531
- - New required fields on `World`, `Component`, or `Snapshot`.
1532
- - A change that would push any subpath past its `size-limit` budget.
1533
- - Reactive value-predicate queries (see "What aiecsjs does NOT do" in the
1534
- README — open an issue with the use case first).
1535
-
1536
- ## Design principles
1537
-
1538
- aiecsjs follows the core priority order:
1539
-
1540
- > Security > Correctness > Simplicity > YAGNI > Performance
1541
-
1542
- In particular, the public API stays **functional and tree-shakable** — no
1543
- class constructors on the public surface, factory functions only.
1544
- `destroyWorld` is the original 0.1.x export and is now **deprecated** since
1545
- 0.2.0 — see `STABILITY.md`. New code should use `disposeWorld`, which is the
1546
- same function under the ai*js ecosystem `dispose()` convention.
1547
- `destroyWorld` is scheduled for removal in 1.0.
1548
-
1549
- ## Commit & PR style
1550
-
1551
- - Commit messages: imperative subject under 70 chars; body explains *why*.
1552
- - PRs: keep scope to one topic. Link the issue if any.
1553
- - Tests required for any behaviour change. Property-based tests welcome for
1554
- invariants (`tests/multi-world.test.ts` is the reference shape).
1555
-
1556
- ## Reporting issues
1557
-
1558
- - Minimal reproduction welcome: paste the smallest
1559
- `createWorld + addComponent + runQuery` triple that shows the bug.
1560
- - For security issues (e.g. snapshot/SAB validation bypass), please email
1561
- the maintainer rather than filing publicly.
1562
-
1563
- ## Release flow
167
+ Keep ECS changes explicit, benchmarkable, and compatible with the public subpath contracts.
1564
168
 
1565
- Releases are tag-triggered via the GitHub Actions workflow
1566
- (`.github/workflows/publish.yml`). From a clean tree on `main`:
169
+ ## Local workflow
1567
170
 
1568
171
  ```bash
1569
- npm version patch # or `minor` / `major`
1570
- git push --follow-tags
172
+ pnpm install
173
+ pnpm typecheck
174
+ pnpm test
175
+ pnpm verify:docs
176
+ pnpm build:llms
177
+ pnpm verify:llms
178
+ pnpm verify:exports
179
+ pnpm verify:dist
180
+ pnpm check:size
1571
181
  ```
1572
182
 
1573
- The workflow triggers on `v*` tag push and runs the full gate before
1574
- publishing:
183
+ Run `pnpm lint` before PRs; existing `noExplicitAny` warnings are known backlog, not an excuse to add more.
1575
184
 
1576
- 1. typecheck / tests / build
1577
- 2. size budget gate
1578
- 3. `npm publish --provenance --access public`
185
+ ## Rules
1579
186
 
1580
- A failed gate stops the publish; the tag stays on the repo but nothing
1581
- ships.
187
+ - Do not expose `internal/*` as public API.
188
+ - Use command buffers in examples that mutate structure during iteration.
189
+ - Add regression tests for entity lifetime, archetype moves, relation cleanup, serialization, and worker transport changes.
190
+ - Keep docs short and update `llms-full.txt` after docs edits.
191
+ - Discuss storage layout or entity id compatibility changes before implementation.
1582
192
 
1583
193
  ## License
1584
194
 
1585
- By contributing, you agree your changes will be licensed under the MIT
1586
- license that covers this project.
195
+ MIT
1587
196
 
1588
197
  ---