@vibecook/ice 0.3.0 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -4
- package/dist/{chunk-2GUYATUM.js → chunk-BFT7YWS2.js} +44 -11
- package/dist/chunk-BFT7YWS2.js.map +1 -0
- package/dist/{chunk-PKK6GLSA.js → chunk-ELCBCTKY.js} +138 -13
- package/dist/chunk-ELCBCTKY.js.map +1 -0
- package/dist/{chunk-5QY7HK6G.js → chunk-JLXETATP.js} +5594 -2712
- package/dist/chunk-JLXETATP.js.map +1 -0
- package/dist/devtools.js +5 -2
- package/dist/devtools.js.map +1 -1
- package/dist/dom.js +16 -2
- package/dist/ground.js +1 -1
- package/dist/index.js +39 -1
- package/dist/r3f.js +3 -3
- package/dist/react.js +5 -3
- package/dist/types/packages/core/src/behavior/compile.d.ts +74 -0
- package/dist/types/packages/core/src/behavior/define-behavior.d.ts +55 -0
- package/dist/types/packages/core/src/behavior/differ.d.ts +91 -0
- package/dist/types/packages/core/src/behavior/harness.d.ts +65 -0
- package/dist/types/packages/core/src/behavior/migrate.d.ts +87 -0
- package/dist/types/packages/core/src/behavior/public-reads.d.ts +31 -0
- package/dist/types/packages/core/src/behavior/runtime.d.ts +88 -0
- package/dist/types/packages/core/src/behavior/types.d.ts +312 -0
- package/dist/types/packages/core/src/behavior/world-view.d.ts +36 -0
- package/dist/types/packages/core/src/catalog/pointer.d.ts +11 -0
- package/dist/types/packages/core/src/catalog/selection-presence.d.ts +10 -0
- package/dist/types/packages/core/src/doc/rename-sweep.d.ts +3 -0
- package/dist/types/packages/core/src/doc/rename.d.ts +7 -0
- package/dist/types/packages/core/src/doc/version-gate.d.ts +14 -1
- package/dist/types/packages/core/src/engine/engine.d.ts +38 -1
- package/dist/types/packages/core/src/engine/guests.d.ts +196 -0
- package/dist/types/packages/core/src/engine/reflectors.d.ts +8 -0
- package/dist/types/packages/core/src/facade/create-canvas-engine.d.ts +16 -0
- package/dist/types/packages/core/src/guards/guarded-tx.d.ts +57 -0
- package/dist/types/packages/core/src/index.d.ts +10 -3
- package/dist/types/packages/core/src/input/queue.d.ts +9 -0
- package/dist/types/packages/core/src/schema/meta.d.ts +12 -0
- package/dist/types/packages/core/src/widget/define-widget.d.ts +89 -0
- package/dist/types/packages/core/src/widget/props.d.ts +35 -1
- package/dist/types/packages/core/src/widget/spawn.d.ts +14 -0
- package/dist/types/packages/dom/src/index.d.ts +2 -0
- package/dist/types/packages/dom/src/input-ownership.d.ts +52 -0
- package/dist/types/packages/dom/src/loop.d.ts +9 -0
- package/dist/types/packages/dom/src/pointer-adapter.d.ts +16 -3
- package/dist/types/packages/dom/src/widget-focus.d.ts +58 -0
- package/dist/types/packages/react/src/hooks.d.ts +12 -1
- package/dist/types/packages/react/src/index.d.ts +1 -1
- package/dist/types/packages/react/src/infinite-canvas.d.ts +20 -2
- package/dist/types/packages/react/src/keymap.d.ts +23 -4
- package/package.json +5 -5
- package/dist/chunk-2GUYATUM.js.map +0 -1
- package/dist/chunk-5QY7HK6G.js.map +0 -1
- package/dist/chunk-PKK6GLSA.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../core/src/boot/hmr.ts","../../core/src/schema/meta.ts","../../core/src/schema/prefab.ts","../../core/src/engine/instantiate.ts","../../core/src/settings/defaults.ts","../../core/src/engine/frame-info.ts","../../core/src/engine/pipeline.ts","../../core/src/engine/reflectors.ts","../../core/src/catalog/camera-derived.ts","../../core/src/guards/dev.ts","../../core/src/engine/frame-control.ts","../../core/src/engine/guests.ts","../../core/src/engine/engine.ts","../../core/src/widget/props.ts","../../core/src/catalog/settings-resources.ts","../../core/src/catalog/scene.ts","../../core/src/catalog/graph.ts","../../core/src/catalog/selection-presence.ts","../../core/src/helpers/phase-set.ts","../../core/src/catalog/gesture.ts","../../core/src/behavior/types.ts","../../core/src/behavior/public-reads.ts","../../core/src/behavior/define-behavior.ts","../../core/src/behavior/compile.ts","../../core/src/catalog/pointer.ts","../../core/src/catalog/insert.ts","../../core/src/guards/guarded-tx.ts","../../core/src/behavior/migrate.ts","../../core/src/engine/commit-sink.ts","../../core/src/input/queue.ts","../../core/src/systems/camera-sim.ts","../../core/src/helpers/version-stamps.ts","../../core/src/guards/resource-writer.ts","../../core/src/systems/nav-flight.ts","../../core/src/widget/define-widget.ts","../../core/src/nav/nested-canvas.ts","../../core/src/ops/sibling-order.ts","../../core/src/ops/point-pick.ts","../../core/src/ops/port-geometry.ts","../../core/src/systems/l1-wires.ts","../../core/src/tools/define-tool.ts","../../core/src/systems/l2-recognize.ts","../../core/src/ops/selection.ts","../../core/src/systems/l3-connect.ts","../../core/src/systems/l3-ports.ts","../../core/src/helpers/churn-guard.ts","../../core/src/systems/chrome.ts","../../core/src/systems/l3-draw.ts","../../core/src/widget/spawn.ts","../../core/src/doc/doc-commit-sink.ts","../../core/src/systems/l4-cursor.ts","../../core/src/interaction/install.ts","../../core/src/systems/cleanup.ts","../../core/src/systems/l0-input.ts","../../core/src/systems/l1-pick.ts","../../core/src/systems/l2-arbitrate.ts","../../core/src/systems/l3-behave.ts","../../core/src/systems/l3-claim.ts","../../core/src/systems/l3-drop.ts","../../core/src/systems/l3-marquee.ts","../../core/src/systems/l3-resize.ts","../../core/src/systems/l3-snap.ts","../../core/src/systems/insert-ghost.ts","../../core/src/ops/gestures.ts","../../core/src/doc/envelope.ts","../../core/src/doc/migrate.ts","../../core/src/guards/live-writer.ts","../../core/src/ops/claims.ts","../../core/src/doc/version-gate.ts","../../core/src/doc/doc-kit.ts","../../core/src/doc/rename.ts","../../core/src/doc/rename-sweep.ts","../../core/src/doc/schema-migrate.ts","../../core/src/behavior/harness.ts","../../core/src/behavior/runtime.ts","../../core/src/behavior/differ.ts","../../core/src/behavior/world-view.ts","../../core/src/ops/arrange.ts","../../core/src/ops/cascade.ts","../../core/src/interaction/gesture-status.ts","../../core/src/widget/equip.ts","../../core/src/widget/set-props.ts","../../core/src/systems/measure-ingest.ts","../../core/src/widget/mount-store.ts","../../core/src/settings/ground-config.ts","../../core/src/doc/autosave.ts","../../core/src/doc/broadcast-relay.ts","../../core/src/input/measure-queue.ts","../../core/src/presence/presence-kit.ts","../../core/src/presence/publish.ts","../../core/src/presence/remote-cursors.ts","../../core/src/doc/bootstrap.ts","../../core/src/doc/channels.ts","../../core/src/facade/create-canvas-engine.ts","../../core/src/ops/insert.ts","../../core/src/index.ts"],"sourcesContent":["/**\n * HMR-safe schema/prefab boot kit (M0 deliverable; the strata+Vite reference pattern).\n *\n * strata's define* registry is process-global: a re-executed schema module throws\n * \"already defined\". Apps register ALL schema/prefabs through defineSchemaOnce from\n * one module, and call hmrInvalidateOnSchemaChange(import.meta.hot) so any edit to\n * that module forces a full reload instead of a broken hot-swap.\n */\nexport function defineSchemaOnce<T>(key: string, build: () => T): T {\n const g = globalThis as { __iceSchemas?: Map<string, unknown> };\n g.__iceSchemas ??= new Map<string, unknown>();\n const map = g.__iceSchemas;\n if (!map.has(key)) map.set(key, build());\n return map.get(key) as T;\n}\n\nexport function hmrInvalidateOnSchemaChange(hot: { invalidate(): void } | undefined): void {\n hot?.invalidate();\n}\n","/**\n * Schema metadata registry (design-001 §2, design-005 §1).\n *\n * Components/tags/relations stay PURE (rev-2 sovereignty) — but prefab\n * validation (eid ban, required-field defaults) and devtools badges need to\n * know what a component's fields look like. strata does not expose schema\n * introspection publicly, so ALL engine + userland definitions go through\n * these thin wrappers: they record the raw schema in a side registry, then\n * delegate to strata unchanged. The returned handles are strata's own.\n */\nimport {\n defineComponent as strataDefineComponent,\n defineRelation as strataDefineRelation,\n defineResource as strataDefineResource,\n defineTag as strataDefineTag,\n type Component,\n type FieldInput,\n type Relation,\n type Resource,\n type Tag,\n} from \"@vibecook/strata-ecs\";\n\nexport type RawSchema = Record<string, FieldInput>;\n\nexport interface ComponentMeta {\n name: string;\n schema: RawSchema;\n /** Field names whose type is `eid` (runtime-local handles — banned in durable cells). */\n eidFields: string[];\n /** Field names with no default (strata requires them at spawn). */\n requiredFields: string[];\n}\n\nexport interface RelationMeta {\n name: string;\n arity: \"one\" | \"many\";\n}\n\nexport interface ResourceMeta {\n name: string;\n /** design-001 §2 rule 7: resources declare durable|runtime at definition. */\n durable: boolean;\n}\n\nconst componentMeta = new Map<Component, ComponentMeta>();\nconst componentsByIceName = new Map<string, Component>();\nconst tagNames = new Map<Tag, string>();\nconst relationMeta = new Map<Relation, RelationMeta>();\nconst resourceMeta = new Map<Resource, ResourceMeta>();\n\nfunction isEidField(input: FieldInput): boolean {\n if (input === \"eid\") return true;\n return (\n typeof input === \"object\" &&\n input !== null &&\n (input as { type?: unknown }).type === \"eid\"\n );\n}\n\nfunction hasDefault(input: FieldInput): boolean {\n // Bare string types (\"f32\", \"string\", …) and bare EnumTypes carry no default;\n // field(type, { default }) specs carry a `default` key.\n return typeof input === \"object\" && input !== null && \"default\" in input;\n}\n\nexport function defineComponent<const Sch extends RawSchema>(\n name: string,\n schema: Sch,\n): ReturnType<typeof strataDefineComponent<Sch>> {\n const c = strataDefineComponent(name, schema);\n const fields = Object.entries(schema);\n componentMeta.set(c as Component, {\n name,\n schema,\n eidFields: fields.filter(([, f]) => isEidField(f)).map(([k]) => k),\n requiredFields: fields.filter(([, f]) => !hasDefault(f)).map(([k]) => k),\n });\n componentsByIceName.set(name, c as Component);\n return c;\n}\n\n/**\n * Reuse-or-define by NAME (design-008 §3.1): strata's schema registry throws\n * on duplicate identifiers (its registry.ts:38), and rename legacy components\n * (`<oldType>:<group>`) can legitimately re-enter the process — a test that\n * defined the old widget before resetting ice registries, or a hot-reload\n * double-eval — while strata's global registry survives. An existing\n * SAME-SHAPED component is the same component: reuse its handle. A mismatched\n * shape under the same name is a real collision: throw. The shape compare is\n * JSON-stringify over the recorded raw schema — sound here because both sides\n * are built by the same `strataFieldOf` constructors in the same field order.\n */\nexport function ensureComponent<const Sch extends RawSchema>(\n name: string,\n schema: Sch,\n): Component {\n const existing = componentsByIceName.get(name);\n if (existing === undefined) return defineComponent(name, schema) as Component;\n const recorded = componentMeta.get(existing);\n if (recorded === undefined || JSON.stringify(recorded.schema) !== JSON.stringify(schema)) {\n throw new Error(`ice: ensureComponent(\"${name}\") — a component with this name exists with a DIFFERENT shape.`);\n }\n return existing;\n}\n\nexport function defineTag(name: string): Tag {\n const t = strataDefineTag(name);\n tagNames.set(t, name);\n return t;\n}\n\nexport function defineRelation(\n name: string,\n opts?: { arity?: \"one\" | \"many\"; ordered?: boolean },\n): Relation {\n const r = strataDefineRelation(name, opts);\n relationMeta.set(r, { name, arity: opts?.arity ?? \"one\" });\n return r;\n}\n\nexport function defineResource<const Sch extends RawSchema>(\n name: string,\n schema: Sch,\n opts?: { durable?: boolean },\n): ReturnType<typeof strataDefineResource<Sch>> {\n const res = strataDefineResource(name, schema);\n resourceMeta.set(res as Resource, { name, durable: opts?.durable ?? false });\n return res;\n}\n\nexport const schemaMeta = {\n component(c: Component): ComponentMeta | undefined {\n return componentMeta.get(c);\n },\n tagName(t: Tag): string | undefined {\n return tagNames.get(t);\n },\n relation(r: Relation): RelationMeta | undefined {\n return relationMeta.get(r);\n },\n resource(r: Resource): ResourceMeta | undefined {\n return resourceMeta.get(r);\n },\n};\n","/**\n * Prefabs — sovereignty at the entity level (design-001 §2, rev 2).\n *\n * A prefab declares an entity kind's ESSENTIAL component set, its\n * durable-ELIGIBLE extras, and its class; the class IS the spawn path:\n * durable → tx.spawn · runtime → world/ctx.spawn · ephemeral → eph.spawn\n *\n * Validation set (design-005 §1, all DEV-throw at definition time):\n * - eligible components eid-free (durable prefabs)\n * - every essential component's required fields supplied by its init value\n * - ephemeral prefabs: components + tags only (no relations)\n * - owner:\"derive\" only on runtime prefabs\n * - prefab ids unique\n */\nimport type { Component, Entity, EntityKey, Relation, Tag } from \"@vibecook/strata-ecs\";\nimport { defineComponent, schemaMeta } from \"./meta\";\n\n/** Durable identity stamp (design-001 §2 rule 5) — subsumes WidgetType. */\nexport const PrefabId = defineComponent(\"PrefabId\", { id: \"string\" });\n\nexport type PrefabClass = \"durable\" | \"runtime\" | \"ephemeral\";\n\n/** Scalar shapes strata accepts as field writes at spawn. */\nexport type FieldWrite = string | number | boolean | Entity | EntityKey | null;\n\nexport type ComponentInit = readonly [Component, Record<string, FieldWrite>];\n\n/**\n * Typed component-init pair: `init(Position, { x: 0, y: 0 })` gets full\n * compile-time field checking (missing/extra/mistyped fields error) before\n * erasing to the registry's loose `ComponentInit`. Prefer this in every\n * prefab definition and instantiate override; raw pairs remain legal for\n * dynamic construction (review finding B4).\n */\nexport function init<S extends Record<string, FieldWrite>>(c: Component<S>, v: S): ComponentInit {\n return [c as Component, v];\n}\n\nexport interface PrefabDef {\n store: PrefabClass;\n /** Essential set: spawned with, committed for durable prefabs. */\n components: readonly ComponentInit[];\n tags?: readonly Tag[];\n /** Durable-eligible beyond essential (attachable later via tx); facets for ephemeral. */\n optional?: readonly Component[];\n /** Eligible outgoing relations (durable prefabs; runtime relations are unrestricted). */\n relations?: readonly Relation[];\n /** Write-ownership badge (devtools) — runtime prefabs only. */\n owner?: \"derive\";\n /**\n * Pack version for the document version gate (design-001 §5.2, design-005\n * §6.3): stamped as an `engine.pack.<id>.<v>` marker key at doc creation and\n * compared at open. Bump when the prefab's durable shape changes. Default 1.\n */\n version?: number;\n}\n\nexport interface Prefab extends PrefabDef {\n id: string;\n /** Eligible component set = essential ∪ optional ∪ {PrefabId}. */\n eligible: ReadonlySet<Component>;\n eligibleRelations: ReadonlySet<Relation>;\n}\n\nconst registry = new Map<string, Prefab>();\n\nexport function definePrefab(id: string, def: PrefabDef): Prefab {\n if (registry.has(id)) {\n throw new Error(`ice: prefab \"${id}\" is already defined — prefab ids are unique per process.`);\n }\n if (def.owner === \"derive\" && def.store !== \"runtime\") {\n throw new Error(`ice: prefab \"${id}\": owner \"derive\" is only valid on runtime prefabs.`);\n }\n if (def.store === \"ephemeral\" && def.relations && def.relations.length > 0) {\n throw new Error(\n `ice: prefab \"${id}\": the presence store supports components + tags only — no relations (design-001 §1).`,\n );\n }\n\n const eligible = new Set<Component>();\n for (const [c] of def.components) eligible.add(c);\n for (const c of def.optional ?? []) eligible.add(c);\n eligible.add(PrefabId as Component);\n\n if (def.store === \"durable\") {\n for (const c of eligible) {\n const meta = schemaMeta.component(c);\n if (meta && meta.eidFields.length > 0) {\n throw new Error(\n `ice: prefab \"${id}\": component \"${meta.name}\" carries eid field(s) [${meta.eidFields.join(\", \")}] — eid is banned in durable cells; use keys or relations (design-001 §2 rule 3).`,\n );\n }\n }\n }\n\n for (const [c, value] of def.components) {\n const meta = schemaMeta.component(c);\n if (!meta) continue; // defined outside @ice/core wrappers — validation is best-effort\n for (const f of meta.requiredFields) {\n if (!(f in value)) {\n throw new Error(\n `ice: prefab \"${id}\": essential component \"${meta.name}\" is missing required field \"${f}\" (no default declared — strata would throw at spawn; supply it in the prefab).`,\n );\n }\n }\n }\n\n const prefab: Prefab = {\n ...def,\n id,\n eligible,\n eligibleRelations: new Set(def.relations ?? []),\n };\n registry.set(id, prefab);\n return prefab;\n}\n\nexport const prefabs = {\n get(id: string): Prefab | undefined {\n return registry.get(id);\n },\n /** Every registered prefab (the version gate stamps/compares the full set). */\n all(): Prefab[] {\n return [...registry.values()];\n },\n};\n\n/**\n * TEST-ONLY registry wipe. Deliberately a standalone export that the public\n * barrel does NOT re-export (review finding A8) — tests import it from this\n * module path directly.\n */\nexport function __resetPrefabsForTests(): void {\n registry.clear();\n}\n","/**\n * Prefab instantiation — THE spawn routing (design-001 §2: the class is the\n * spawn path). Durable → tx · runtime → world/ctx · ephemeral → eph.\n * Every spawn stamps `PrefabId` (uniform identity for guards + devtools;\n * for durable prefabs it is the document identity stamp, §2 rule 5).\n */\nimport type { Component, Entity, SystemCtx, Tag, World } from \"@vibecook/strata-ecs\";\nimport type { Mutator } from \"@vibecook/strata-ecs/durable\";\nimport { PrefabId, type ComponentInit, type Prefab } from \"../schema/prefab\";\n\n/** Structural shape of the ephemeral store's write surface (components+tags only). */\nexport interface EphSpawner {\n spawn(init?: { components?: readonly ComponentInit[] }): Entity;\n addTag(e: Entity, t: Tag): void;\n}\n\nexport type SpawnTarget =\n | { into: \"world\"; world: World }\n | { into: \"ctx\"; ctx: SystemCtx }\n | { into: \"tx\"; tx: Mutator }\n | { into: \"eph\"; eph: EphSpawner };\n\nfunction mergedComponents(prefab: Prefab, overrides?: readonly ComponentInit[]): ComponentInit[] {\n const out = new Map<Component, ComponentInit[1]>();\n for (const [c, v] of prefab.components) out.set(c, v);\n for (const [c, v] of overrides ?? []) {\n if (!prefab.eligible.has(c)) {\n throw new Error(\n `ice: instantiate(\"${prefab.id}\"): override component is not in the prefab's eligible set.`,\n );\n }\n out.set(c, v);\n }\n out.set(PrefabId as Component, { id: prefab.id });\n return [...out.entries()].map(([c, v]) => [c, v] as const);\n}\n\nconst ROUTE: Record<Prefab[\"store\"], SpawnTarget[\"into\"][]> = {\n durable: [\"tx\"],\n runtime: [\"world\", \"ctx\"],\n ephemeral: [\"eph\"],\n};\n\nexport interface InstantiateOpts {\n /**\n * DRAFT spawn (design-001 §3, two-phase promote): a durable prefab spawned\n * into the runtime store — its cells are plain session data (not in the doc,\n * live writes free) until `promote` commits a durable twin. Explicit opt-in:\n * without it, durable→world/ctx throws (never a silent downgrade, §6.3).\n */\n draft?: boolean;\n overrides?: readonly ComponentInit[];\n}\n\n/**\n * Spawn a prefab into the correct store. Wrong-store spawns fail loudly —\n * notably: a durable prefab without an attached doc/tx has NO fallback\n * (design-001 §6.3: never a silent world.spawn downgrade).\n */\nexport function instantiate(\n prefab: Prefab,\n target: SpawnTarget,\n opts?: InstantiateOpts | readonly ComponentInit[],\n): Entity {\n const norm: InstantiateOpts = Array.isArray(opts) ? { overrides: opts } : ((opts as InstantiateOpts | undefined) ?? {});\n const overrides = norm.overrides;\n const draftOk =\n norm.draft === true &&\n prefab.store === \"durable\" &&\n (target.into === \"world\" || target.into === \"ctx\");\n if (!ROUTE[prefab.store].includes(target.into) && !draftOk) {\n const extra = prefab.store === \"durable\" ? \", or world/ctx with { draft: true }\" : \"\";\n throw new Error(\n `ice: instantiate(\"${prefab.id}\"): a ${prefab.store} prefab cannot spawn into \"${target.into}\" (allowed: ${ROUTE[prefab.store].join(\", \")}${extra}). The spawn path IS the sovereignty class (design-001 §2).`,\n );\n }\n const components = mergedComponents(prefab, overrides);\n const tags = prefab.tags ?? [];\n\n switch (target.into) {\n case \"world\": {\n const e = target.world.spawn({ components });\n for (const t of tags) target.world.addTag(e, t);\n return e;\n }\n case \"ctx\": {\n const e = target.ctx.spawn({ components });\n for (const t of tags) target.ctx.addTag(e, t);\n return e;\n }\n case \"tx\": {\n const e = target.tx.spawn({ components });\n for (const t of tags) target.tx.addTag(e, t);\n return e;\n }\n case \"eph\": {\n const e = target.eph.spawn({ components });\n for (const t of tags) target.eph.addTag(e, t);\n return e;\n }\n }\n}\n","/**\n * Runtime default constants transcribed from the reviewed design docs.\n * Not exported from the package barrel yet (design-005 §4 engine facade wires these in later).\n */\n\n/** Recognizer timing/slop defaults (design-003 §4.2 kind table; inertia constants from §5 item 9; multi-tap from v2 gesture.ts). */\nexport const GESTURE_DEFAULTS = {\n tapMaxMs: 250,\n tapSlopPx: 8,\n longPressMs: 500,\n longPressSlopPx: 10,\n dragSlopPx: 10,\n pinchSlopPx: 6,\n wheelEndSilenceMs: 150,\n inertiaMinVelocityPxPerS: 120,\n inertiaDecayMs: 325,\n multiTapWindowMs: 280,\n multiTapSlopPx: 20,\n // Wheel/pinch zoom speed — the v2 prototype curve (gesture.ts:444-449),\n // adopted 2026-07-13: factor = 2^(−clamp(Δ, ±maxStep) · sensitivity).\n // The CLAMP is the load-bearing half: a trackpad pinch sends tiny frequent\n // deltas (~0.5–3) while a mouse notch sends ~100 — capping the per-frame\n // step at ±10 makes one notch ≈ one strong pinch frame (×2^0.1 ≈ 1.07),\n // so both devices share one feel.\n wheelZoomSensitivity: 0.01,\n wheelZoomMaxStep: 10,\n} as const;\n\n/** Pick radii + retarget dead-band (design-003 §3 L1 targeting). */\nexport const POINTER_DEFAULTS = {\n radiusMousePx: 0,\n radiusTouchPx: 12,\n radiusPenPx: 4,\n hoverReleaseDeadBandPx: 4,\n} as const;\n\n/**\n * Wire/port picking geometry (design-003 §3 wires-below-widgets; design-004 §6).\n * `wirePickSlopPx` is added to the pointer radius (screen px, `/zoom` at use) so a\n * thin bezier stays grab-able; `portIndexHalfWorld` is the half-extent of the tiny\n * world AABB a materialized port occupies in the spatial index (design-004 §6 —\n * ports are pickable but carry no Position/Size, so spatialSync never sees them).\n */\nexport const GRAPH_PICK_DEFAULTS = {\n wirePickSlopPx: 8,\n portIndexHalfWorld: 6,\n} as const;\n\n/** SnapConfig resource defaults (design-005 §4 engine facade). */\nexport const SNAP_DEFAULTS = {\n enabled: true,\n thresholdPx: 5,\n} as const;\n\n/**\n * Selection-chrome knobs (2026-07-17). `liftScale` mirrors the app's visual\n * drag-lift scale (widgetlab CardShell: 1.05) so the union box can inflate a\n * grabbed member's rect and keep WRAPPING the card it sees; 1 = no lift\n * visual, no inflation.\n */\nexport const CHROME_DEFAULTS = {\n liftScale: 1,\n} as const;\n\n/** Zoom clamp (design-003 §5 item 9 cameraControl) and frame dt clamp (design-002 §1). */\nexport const CAMERA_DEFAULTS = {\n minZoom: 0.1,\n maxZoom: 5,\n dtClampMs: 64,\n} as const;\n\n/**\n * The natural auto-framing band (2026-07-18, James: \"not super zoomed in\n * nor super zoomed out, should feel natural\"): every DEFAULT framing —\n * `ops.frameContent` at boot, the folder arrival camera, and the folder\n * minis' portal affine (widgetlab keeps its preview in lockstep) — fits\n * content via kernel `fitCamera` but never lands outside\n * [fitMinZoom, fitMaxZoom], intersected with the session's hard\n * CameraLimits. `ops.zoomToFit` stays UNCAPPED: an explicit \"show me\n * everything\" beats natural.\n */\nexport const FIT_DEFAULTS = {\n pad: 80,\n minZoom: 0.5,\n maxZoom: 1,\n} as const;\n\n/**\n * Nav-transition motion constants (design-006 §4/§5, tuned in the approved\n * 2026-07-15 mock). `responseMs` is the critically-damped spring response for\n * ENTER; exit runs at `exitResponseFactor ×` (returning is lighter). Response\n * scales `durationPerOctave` per zoom-octave beyond `baseOctaves` (Apple's\n * duration-with-distance). Beyond `freezeOctaves` a flight cannot be presented\n * geometrically (Chromium raster-scale swing — design-006 §5): the start depth\n * caps at `capFactor ×` arrival and the transition presents as a crossfade.\n */\nexport const NAV_TRANSITION_DEFAULTS = {\n responseMs: 420,\n exitResponseFactor: 0.8,\n durationPerOctave: 0.12,\n baseOctaves: 3.5,\n freezeOctaves: 4.2,\n capFactor: 10,\n settleP: 0.999,\n settleV: 0.02,\n} as const;\n\n/** Widget/FBO/port budgets (design-004 §2 host pipeline, §3 FBO pool, §6 port materialization; ported into design-005 §4 engine facade). */\nexport const RUNTIME_BUDGETS = {\n keepMountedWidgets: 256,\n fboBytes: 268_435_456,\n portSpawnPerFrame: 64,\n portLightUpRadiusPx: 600,\n portReapGraceMs: 1000,\n cullOverscanWorldPerZoom: 200,\n} as const;\n","/**\n * FrameInfo — the pre-tick frame clock (design-002 §1).\n *\n * Written by `engine.step()` BEFORE `world.sync()` every frame (a plain resource\n * value write, legal outside the tick). Systems read it via `ctx.getResource` —\n * time-based systems are correct by construction (F1: tick-by-default), and dt\n * clamps at `CAMERA_DEFAULTS.dtClampMs` so a background-tab hiccup never turns\n * into a teleport (design-002 §1: \"dt clamps at 64 ms\").\n */\nimport { field } from \"@vibecook/strata-ecs\";\nimport type { World } from \"@vibecook/strata-ecs\";\nimport { defineResource } from \"../schema/meta\";\nimport { CAMERA_DEFAULTS } from \"../settings/defaults\";\n\n/**\n * { tick, dt ≤ dtClampMs (ms), now (ms timeline of the caller's clock),\n * clock (accumulated CLAMPED dt — the gesture clock) }.\n *\n * `clock` exists because `now` cannot be trusted for HUMAN timing windows:\n * rAF timestamps are the compositor's frame clock, and under throttling\n * (occluded window, headless BeginFrame control, software rendering) they lag\n * wall time by 100s of ms to SECONDS (measured 0.3–5.8s, 2026-07-17) — and\n * event.timeStamp does NOT lag, so any `now − eventTs` mixes two clocks and\n * tap/long-press windows evaluate garbage. `clock` is monotonic, advances by\n * the clamped dt each frame (a 640ms stall counts 64ms — the 2026-07-12\n * \"stall must not eat the window\" intent), and is never compared against\n * event timestamps.\n */\nexport const FrameInfo = defineResource(\"FrameInfo\", {\n tick: field(\"u32\", { default: 0 }),\n dt: field(\"f32\", { default: 0 }),\n now: field(\"f64\", { default: 0 }),\n clock: field(\"f64\", { default: 0 }),\n});\n\n/**\n * Advance the frame clock. First frame gets dt 0 (no previous `now` to diff\n * against); negative deltas (clock adjustment) clamp to 0.\n */\nexport function setFrameInfo(world: World, now: number): void {\n const prev = world.getResource(FrameInfo);\n const dt =\n prev === undefined ? 0 : Math.min(Math.max(now - prev.now, 0), CAMERA_DEFAULTS.dtClampMs);\n world.setResource(FrameInfo, { tick: (prev?.tick ?? 0) + 1, dt, now, clock: (prev?.clock ?? 0) + dt });\n}\n","/**\n * The phase-group pipeline (design-002 §2).\n *\n * Seven canonical GROUPS over eleven strata phases — a strata phase boundary\n * (command-buffer flush) is the only structural settle point, so every stage\n * that must SEE the previous stage's spawns/tags/relations within one frame is\n * a separate strata phase. The `ctl:*` sub-phases are the control sweep's\n * settle points (design-002 decision 2; rev 1's \"tail idiom\" is dead — the\n * whole system body is iteration-guarded).\n *\n * Registration order within a group is run order; group order is fixed here\n * and is the sole ordering contract (Law: phases/sub-phases only — never\n * registration-time coupling between groups).\n */\nimport { phase } from \"@vibecook/strata-ecs\";\nimport type { Pipeline, System, TickSystem } from \"@vibecook/strata-ecs\";\n\n/** Either system form (strata 0.5.0): chunk-bodied or once-per-dispatch tick. */\nexport type AnySystem = System | TickSystem;\n\n/** The eleven strata phases, in run order (design-002 §2 table). */\nexport const PHASE_GROUPS = [\n \"input\",\n \"react\",\n \"ctl:spawn\",\n \"ctl:recognize\",\n \"ctl:arbitrate\",\n \"ctl:claim\",\n \"ctl:behave\",\n \"simulate\",\n \"derive\",\n \"present\",\n \"cleanup\",\n] as const;\n\nexport type PhaseGroup = (typeof PHASE_GROUPS)[number];\n\nexport interface PipelineRegistry {\n /** Append systems to a group (run order = registration order). Returns a remover (HMR). */\n add(group: PhaseGroup, ...systems: readonly AnySystem[]): () => void;\n /**\n * The pipeline value for this frame (design-002 §1: \"pipeline is a value,\n * rebuilt per frame\"). Cached until the registry changes; empty groups are\n * omitted (an empty phase would flush nothing anyway).\n */\n assemble(): Pipeline;\n}\n\nexport function createPipelineRegistry(): PipelineRegistry {\n const groups = new Map<PhaseGroup, AnySystem[]>();\n let cached: Pipeline | undefined;\n\n return {\n add(group, ...systems) {\n let list = groups.get(group);\n if (list === undefined) {\n list = [];\n groups.set(group, list);\n }\n list.push(...systems);\n cached = undefined;\n return () => {\n const current = groups.get(group);\n if (current === undefined) return;\n for (const s of systems) {\n const i = current.indexOf(s);\n if (i !== -1) current.splice(i, 1);\n }\n cached = undefined;\n };\n },\n\n assemble() {\n if (cached === undefined) {\n const phases = [];\n for (const name of PHASE_GROUPS) {\n const systems = groups.get(name);\n if (systems !== undefined && systems.length > 0) phases.push(phase(name, [...systems]));\n }\n cached = phases;\n }\n return cached;\n },\n };\n}\n","/**\n * The reflector registry (design-002 §5).\n *\n * Reflectors are the ONLY writers of DOM/GL/R3F, run AFTER `notify()`, and\n * never write ECS (L10). The registry arms strata observers ONCE per reflector\n * at registration; observer fires during `notify()` coalesce into a per-\n * reflector dirty flag; `flushAll()` (called by `engine.step()` post-notify)\n * flushes dirty (or `always`) reflectors in registration order.\n *\n * - **First paint**: every reflector registers dirty, so its first `flushAll`\n * paints unconditionally — `observeResource` has no `immediate` option and a\n * world populated before registration never stamps for it (same seed\n * `observeQuery`'s `immediate` would give, applied uniformly).\n * - **Fault isolation**: a throwing reflector is skipped this frame (its dirty\n * flag clears — a faulty reflector must not re-fire hot on a static scene);\n * system throws, by contrast, propagate loudly out of `world.tick()`.\n * - **Write ban**: strata's emit-flag rejects ECS writes inside observer\n * callbacks, but reflector `flush` runs after the emit window — DEV\n * enforcement of the reflect write-ban is deferred (design-002 §8);\n * the contract still binds.\n * - Arming any observer permanently arms reactivity stamping (+17–28% on\n * write-heavy paths — design-002 §4, budgeted).\n */\nimport type { Component, Query, Resource, World } from \"@vibecook/strata-ecs\";\n\nexport interface ReflectorQuerySpec {\n readonly q: Query;\n /** Narrow the Tier-1 wake set to these value columns (plus membership). */\n readonly cols?: readonly Component[];\n}\n\nexport interface ReflectorObserve {\n readonly queries?: readonly ReflectorQuerySpec[];\n // biome-ignore lint/suspicious/noExplicitAny: heterogeneous resource list; S is erased at observe time\n readonly resources?: readonly Resource<any>[];\n}\n\nexport interface ReflectorDef {\n /** Display name (telemetry, fault reports). */\n readonly name: string;\n readonly observe?: ReflectorObserve;\n /** Flush every frame regardless of dirt (cheap-overlay style, v1 lesson). */\n readonly always?: boolean;\n /** Batched output writes; NEVER write ECS, never read layout (L10). */\n readonly flush: (world: World) => void;\n}\n\nexport interface ReflectorRegistry {\n /** Arm observers and enroll; returns an unregister (unsubscribes, removes). */\n register(def: ReflectorDef): () => void;\n /** Post-notify: flush dirty/`always` reflectors in registration order. */\n flushAll(): void;\n /** Names flushed on the most recent `flushAll` (telemetry). */\n lastFlushed(): readonly string[];\n /** Every registered reflector, registration order (devtools enumeration —\n * independent of telemetry; a reflector idle since boot still lists). */\n names(): readonly string[];\n /** Arm flush timing (idempotent). Costs one `performance.now()` pair per\n * flushed reflector per frame, so it rides `engine.enableTelemetry()` and is\n * off by default — the same opt-in posture as per-system timing. */\n armTelemetry(): void;\n /** Total µs of the most recent `flushAll` (0 until armed). */\n lastFlushMicros(): number;\n /** Per-reflector µs of the most recent `flushAll` (empty until armed). */\n lastFlushDetail(): ReadonlyMap<string, number>;\n}\n\ninterface Entry {\n readonly def: ReflectorDef;\n dirty: boolean;\n /** Cleared by the unregister so a reflector removed DURING a flush is not\n * flushed from that frame's snapshot (see `flushAll`). */\n alive: boolean;\n readonly unsubs: (() => void)[];\n}\n\nexport function createReflectorRegistry(\n world: World,\n opts?: { onFault?: (name: string, err: unknown) => void },\n): ReflectorRegistry {\n const entries: Entry[] = [];\n // Snapshot + liveness, for the same reason as the publish-hook loop\n // (engine.ts): `flushAll` iterated the live array, so a reflector whose flush\n // unregistered itself — or an earlier one — skipped its neighbour that frame.\n let snapshot: Entry[] = [];\n let snapshotDirty = true;\n let flushed: string[] = [];\n let telemetryArmed = false;\n let flushMicros = 0;\n let flushDetail = new Map<string, number>();\n const onFault =\n opts?.onFault ??\n ((name: string, err: unknown) => {\n console.error(`[ice] reflector \"${name}\" threw — skipped this frame`, err);\n });\n\n return {\n register(def) {\n const entry: Entry = { def, dirty: true, alive: true, unsubs: [] };\n const wake = () => {\n entry.dirty = true;\n };\n for (const spec of def.observe?.queries ?? []) {\n entry.unsubs.push(\n world.reactive.observeQuery(spec.q, wake, spec.cols ? { cols: spec.cols } : undefined),\n );\n }\n for (const res of def.observe?.resources ?? []) {\n entry.unsubs.push(world.reactive.observeResource(res, wake));\n }\n entries.push(entry);\n snapshotDirty = true;\n return () => {\n if (!entry.alive) return;\n entry.alive = false;\n for (const u of entry.unsubs) u();\n entry.unsubs.length = 0;\n const i = entries.indexOf(entry);\n if (i !== -1) entries.splice(i, 1);\n snapshotDirty = true;\n };\n },\n\n flushAll() {\n flushed = [];\n if (snapshotDirty) {\n snapshot = entries.slice();\n snapshotDirty = false;\n }\n if (telemetryArmed) {\n flushDetail = new Map();\n flushMicros = 0;\n }\n for (const entry of snapshot) {\n if (!entry.alive) continue;\n if (!entry.dirty && entry.def.always !== true) continue;\n entry.dirty = false;\n const t0 = telemetryArmed ? performance.now() : 0;\n try {\n entry.def.flush(world);\n flushed.push(entry.def.name);\n } catch (err) {\n onFault(entry.def.name, err);\n }\n if (telemetryArmed) {\n // Charged whether or not it threw — a faulting reflector's cost is\n // real, and hiding it would make a slow-then-throwing one invisible.\n const us = (performance.now() - t0) * 1000;\n flushDetail.set(entry.def.name, (flushDetail.get(entry.def.name) ?? 0) + us);\n flushMicros += us;\n }\n }\n },\n\n lastFlushed() {\n return flushed;\n },\n\n names() {\n return entries.map((e) => e.def.name);\n },\n\n armTelemetry() {\n telemetryArmed = true;\n },\n\n lastFlushMicros() {\n return flushMicros;\n },\n\n lastFlushDetail() {\n return flushDetail;\n },\n };\n}\n","/**\n * Camera/viewport/tools (design-001 §5.7) + culling, chrome, cursors,\n * breakpoints, navigation (design-001 §5.8, reconciled additions).\n *\n * These are the §2 rule-7 residue (resources with no entity) plus the\n * derive-owned runtime prefabs. All resources here are runtime — Camera writes\n * go through the resource only (no shadow copy). Widgets are positioned in world\n * units inside their plane; the camera is applied as one transform per plane, so\n * there is deliberately no per-widget screen-bounds component — screen-space\n * values are derived only for chrome and cursors (small N).\n *\n * Defaults policy (see catalog/index.ts): resources carry full defaults (a single\n * live value that must initialize sanely — origin, zoom 1, select tool). Derived\n * fields carry zero/identity defaults; enum-identity fields that must be specific\n * per entity (HandleSpec.anchor, GuideLine.axis, CursorVisual.kind) stay bare.\n */\nimport { enumOf, field } from \"@vibecook/strata-ecs\";\nimport { defineComponent, defineRelation, defineResource, defineTag } from \"../schema/meta\";\nimport { SNAP_DEFAULTS } from \"../settings/defaults\";\n\n// --- runtime resources (design-001 §5.7) ---\n\n/** The single live camera (F2). `gesturing` gates the compositor DPR (design-004). */\nexport const Camera = defineResource(\"Camera\", {\n x: field(\"f64\", { default: 0 }),\n y: field(\"f64\", { default: 0 }),\n zoom: field(\"f32\", { default: 1 }),\n gesturing: field(\"bool\", { default: false }),\n});\n\n/** Viewport size + device pixel ratio. */\nexport const Viewport = defineResource(\"Viewport\", {\n w: field(\"f32\", { default: 0 }),\n h: field(\"f32\", { default: 0 }),\n dpr: field(\"f32\", { default: 1 }),\n});\n\n/** The active tool id (defaults to select). */\nexport const ActiveTool = defineResource(\"ActiveTool\", { id: field(\"string\", { default: \"select\" }) });\n\n/**\n * Stage presentation phase (2026-07-19, the widget-tray quiesce): app chrome\n * that covers or recedes the canvas takes a BACKGROUND HOLD via\n * `ce.stage.background(name)` — refcounted here (facade-owned tokens, this\n * resource is the world-truth mirror). While holds > 0 the stage stops\n * DISCRETIONARY per-frame work — animated GL islands freeze on their retained\n * textures (compositor gate, the design-006 §8.2 flight-freeze posture) —\n * but the world STAYS LIVE: systems tick, ops reflect, remote edits apply,\n * tweens land. Backgrounding is rendering policy; whether the canvas is\n * INTERACTABLE stays the overlay's own concern (its backdrop). Deliberately\n * NOT a full step-pause: a menu panel floats over a still-visible canvas,\n * and a frozen world would leave undo/collab visually stale (rev-2 decision,\n * recorded — a stricter frozen-world mode would be a separate concept).\n * That separate concept is now BUILT (2026-08-04): see {@link FrameMode}.\n * Holds keep their exact meaning — nothing here stretched.\n */\nexport const StageMode = defineResource(\"StageMode\", {\n backgroundHolds: field(\"u32\", { default: 0 }),\n});\n\n/**\n * Frame gate mirror (2026-08-04) — the stricter sibling {@link StageMode}'s\n * rev-2 decision named and left for later.\n *\n * A background hold is presentation policy over a LIVE world. A freeze\n * (`engine.frame.freeze(name)`) stops the host loop outright: no step, so no\n * systems, no publish, no notify, no reflectors, no rAF — for chrome that\n * COVERS the canvas, where every frame drawn behind it is work nobody can see.\n * This resource is the world-truth mirror of that refcount; the tokens live on\n * the control, out of ECS, exactly as stage holds do.\n *\n * Reading it tells you the engine is frozen. It cannot tell you a frame is\n * coming, because while the count is non-zero none is — and for the same\n * reason nothing can OBSERVE it while frozen (a parked world fires no\n * observers). It exists for inspection: devtools, tests, and consumers that\n * want the fact in hand on thaw.\n */\nexport const FrameMode = defineResource(\"FrameMode\", {\n freezeHolds: field(\"u32\", { default: 0 }),\n});\n\n/** Global snap toggle + threshold in screen px (scaled by zoom at use, design-003 §5.2). */\nexport const SnapConfig = defineResource(\"SnapConfig\", {\n enabled: field(\"bool\", { default: SNAP_DEFAULTS.enabled }),\n thresholdPx: field(\"f32\", { default: SNAP_DEFAULTS.thresholdPx }),\n});\n\n/** Per-container view-state memory — a runtime rider on container widgets (design-001 §5.7). */\nexport const ContainerCamera = defineComponent(\"ContainerCamera\", {\n x: field(\"f64\", { default: 0 }),\n y: field(\"f64\", { default: 0 }),\n zoom: field(\"f32\", { default: 1 }),\n});\n\n// --- derived tags (design-001 §5.8) ---\n\n/** Widget's ChildOf chain roots in the CURRENT nav frame (activeMembership system). */\nexport const Active = defineTag(\"Active\");\n\n/** In the viewport. Invariant: Active widgets are Visible ⊕ Culled. */\nexport const Visible = defineTag(\"Visible\");\n\n/** Outside the viewport. */\nexport const Culled = defineTag(\"Culled\");\n\n/** LOD tier + the effective size it was computed from (5 thresholds, width AND height). */\nexport const WidgetBreakpoint = defineComponent(\"WidgetBreakpoint\", {\n tier: field(enumOf([\"micro\", \"compact\", \"normal\", \"expanded\", \"detailed\"]), { default: \"normal\" }),\n w: field(\"u16\", { default: 0 }),\n h: field(\"u16\", { default: 0 }),\n});\n\n/** Session rider on auto-sized widgets (ResizeObserver → queue → ingest; never committed). */\nexport const MeasuredSize = defineComponent(\"MeasuredSize\", {\n w: field(\"f32\", { default: 0 }),\n h: field(\"f32\", { default: 0 }),\n});\n\n// --- chrome prefabs (pooled entities, reaped when the source empties) ---\n\n/** Selection outline rect. */\nexport const SelectionBox = defineComponent(\"SelectionBox\", {\n x: field(\"f64\", { default: 0 }),\n y: field(\"f64\", { default: 0 }),\n w: field(\"f32\", { default: 0 }),\n h: field(\"f32\", { default: 0 }),\n});\n\n/** A resize handle's anchor (the one chrome kind behaviors capture). */\nexport const HandleSpec = defineComponent(\"HandleSpec\", {\n anchor: enumOf([\"nw\", \"n\", \"ne\", \"e\", \"se\", \"s\", \"sw\", \"w\"]),\n});\n\n/** A snap guide line along one axis. `from == to` ⇒ full-viewport line (v1's full-canvas alignment look — design-003 §6). */\nexport const GuideLine = defineComponent(\"GuideLine\", {\n axis: enumOf([\"x\", \"y\"]),\n at: field(\"f64\", { default: 0 }),\n from: field(\"f64\", { default: 0 }),\n to: field(\"f64\", { default: 0 }),\n});\n\n/**\n * One equal-spacing gap segment (snap chrome's second visual, design-003 §6):\n * a bar along `axis` spanning `from`→`to` at perpendicular position `perp`,\n * marking a gap of `gap` world units. The kernel indicator's two segments\n * flatten to two entities (v1 `u_spacings` parity).\n */\nexport const SpacingBar = defineComponent(\"SpacingBar\", {\n axis: enumOf([\"x\", \"y\"]),\n from: field(\"f64\", { default: 0 }),\n to: field(\"f64\", { default: 0 }),\n perp: field(\"f64\", { default: 0 }),\n gap: field(\"f32\", { default: 0 }),\n});\n\n/** Marquee selection rect. */\nexport const MarqueeBox = defineComponent(\"MarqueeBox\", {\n x: field(\"f64\", { default: 0 }),\n y: field(\"f64\", { default: 0 }),\n w: field(\"f32\", { default: 0 }),\n h: field(\"f32\", { default: 0 }),\n});\n\n/** Cursor appearance — local (OS cursor) vs remote (custom node). */\nexport const CursorVisual = defineComponent(\"CursorVisual\", {\n kind: enumOf([\"local\", \"remote\"]),\n pressed: field(\"bool\", { default: false }),\n});\n\n/** cursor → pointer or presence peer. */\nexport const Follows = defineRelation(\"Follows\", { arity: \"one\" });\n\n/** chrome → its source (recognizer, selection). */\nexport const VisualOf = defineRelation(\"VisualOf\", { arity: \"one\" });\n\n// --- navigation stack (session NavEntry prefab, design-004 §7) ---\n\n/** Depth of a nav entry (root = 0). */\nexport const NavDepth = defineComponent(\"NavDepth\", { d: field(\"u8\", { default: 0 }) });\n\n/** Camera stored on a nav entry. */\nexport const NavCamera = defineComponent(\"NavCamera\", {\n x: field(\"f64\", { default: 0 }),\n y: field(\"f64\", { default: 0 }),\n zoom: field(\"f32\", { default: 1 }),\n});\n\n/** nav entry → container widget. */\nexport const NavFrame = defineRelation(\"NavFrame\", { arity: \"one\" });\n\n/** The canvas background entity, so picking always resolves to *something* (design-001 §4). */\nexport const CanvasSurface = defineTag(\"CanvasSurface\");\n","/** DEV-guard toggle. Guards are on by default; production apps may disable. */\nlet enabled = true;\n\nexport function setDevGuards(on: boolean): void {\n enabled = on;\n}\n\nexport function devGuardsEnabled(): boolean {\n return enabled;\n}\n","/**\n * The frame gate (design-002 §1 amendment, 2026-08-04) — the frozen-world mode\n * design-005 §7 named and deliberately left unbuilt.\n *\n * Stage holds are PRESENTATION policy: `StageMode.backgroundHolds` freezes the\n * compositor on its retained textures while the world keeps stepping, which is\n * exactly what makes a hold safe under a PARTIAL overlay — a menu panel floats\n * over a still-live canvas, undo reflects, collab applies, tweens land. The\n * rev-2 decision recorded that a stricter mode \"would be a SEPARATE concept\".\n * This is that concept: while a freeze is held the host loop stops calling\n * `step` at all — no systems, no publish, no notify, no reflectors, no rAF\n * callback. It is for chrome that COVERS the canvas outright, where every\n * frame drawn behind it is work nobody can see.\n *\n * THE SETTLE — why a freeze does not park on the spot. Parking the instant a\n * freeze is taken would strand the canvas mid-churn: a cancelled gesture that\n * has not reached its commit tick, islands still owed a first paint, a\n * reflector holding a write that landed this frame. So a freeze walks the loop\n * to QUIET — every registered settle reporter idle — then takes ONE further\n * step so the quiet state itself reflects, and only then closes the gate. The\n * walk is bounded by {@link SETTLE_CAP}: a reporter that never goes quiet makes\n * a freeze park LATE, never never.\n *\n * Core stays scheduler-free (design-002 §1). This module owns no timer and\n * starts nothing — it answers {@link FrameControl.claimStep} and announces\n * transitions. The DOM package's rAF loop is what actually parks and restarts;\n * `engine.step(now)` itself stays callable by hand (headless hosts, traces),\n * because the gate governs the LOOP, not the primitive.\n */\nimport type { World } from \"@vibecook/strata-ecs\";\nimport { FrameMode } from \"../catalog/camera-derived\";\nimport { devGuardsEnabled } from \"../guards/dev\";\n\n/**\n * Frames a freeze may spend walking to quiet before it parks regardless.\n * Two seconds at 60 Hz: comfortably longer than a cancelled gesture's path to\n * its commit tick or a cold board's first paints, short enough that a wedged\n * reporter reads as a hiccup rather than a hang.\n */\nexport const SETTLE_CAP = 120;\n\nexport interface FrameControl {\n /**\n * Take a named freeze. Returns an IDEMPOTENT thaw — the disposer pattern\n * that makes overlay lifecycles leak-proof (release on unmount), the name\n * that makes \"why is the engine parked?\" answerable. Refcounted: the loop\n * resumes when the LAST freeze thaws.\n */\n freeze(name: string): () => void;\n /** A freeze is held — the loop is settling or already parked. */\n isFrozen(): boolean;\n /** The settle finished and the gate closed: no further steps are being run. */\n isParked(): boolean;\n /** Live freeze names, in take order (debug/devtools). */\n holds(): readonly string[];\n /**\n * Register a settle reporter: while `busy()` is true, a taken freeze keeps\n * stepping instead of parking. This is how a subsystem that owes visible\n * work — the GL compositor's pending first paints, a gesture walking to its\n * commit — keeps a freeze from landing on a half-finished image. Returns an\n * idempotent unregister.\n */\n settleWhile(name: string, busy: () => boolean): () => void;\n /** Reporters answering busy right now (\"why hasn't it parked yet?\"). */\n settling(): readonly string[];\n /**\n * The loop gate. CONSUMING — each call advances the settle walk, so it is\n * for frame hosts only, never a predicate to poll. Use {@link isFrozen} /\n * {@link isParked} to ask questions.\n */\n claimStep(): boolean;\n /** Wake on any freeze/thaw transition (the host loop restarts here). */\n onChange(fn: () => void): () => void;\n}\n\nexport function createFrameControl(world: World): FrameControl {\n const freezes = new Map<symbol, string>();\n const reporters = new Map<symbol, { readonly name: string; readonly busy: () => boolean }>();\n const listeners = new Set<() => void>();\n let settleLeft = 0;\n let parked = false;\n\n const sync = (): void => {\n world.setResource(FrameMode, { freezeHolds: freezes.size });\n };\n // Copy before iterating: a listener that thaws (and so unsubscribes) mid-\n // announce must not mutate the set being walked.\n const announce = (): void => {\n for (const fn of [...listeners]) fn();\n };\n const busyNames = (): string[] => {\n const names: string[] = [];\n for (const r of reporters.values()) if (r.busy()) names.push(r.name);\n return names;\n };\n\n return {\n freeze(name) {\n const token = Symbol(name);\n const first = freezes.size === 0;\n freezes.set(token, name);\n // Only the 0→1 transition arms a settle walk; a second freeze taken\n // while the engine is already parked changes nothing but the refcount.\n if (first) {\n settleLeft = SETTLE_CAP;\n parked = false;\n }\n sync();\n announce();\n let released = false;\n return () => {\n if (released) return; // idempotent — double-thaw must not eat another freeze\n released = true;\n freezes.delete(token);\n if (freezes.size === 0) {\n settleLeft = 0;\n parked = false;\n }\n sync();\n announce();\n };\n },\n\n isFrozen: () => freezes.size > 0,\n isParked: () => parked,\n holds: () => [...freezes.values()],\n\n settleWhile(name, busy) {\n const token = Symbol(name);\n reporters.set(token, { name, busy });\n let released = false;\n return () => {\n if (released) return;\n released = true;\n reporters.delete(token);\n };\n },\n\n settling: () => busyNames(),\n\n claimStep() {\n if (freezes.size === 0) return true;\n if (parked) return false;\n if (settleLeft <= 0) {\n // Cap reached with work still outstanding. Park anyway — a freeze that\n // never lands is worse than one that lands on a stale pixel — but name\n // the reporters, because this is always someone's bug.\n parked = true;\n if (devGuardsEnabled()) {\n console.warn(\n `ice: frame.freeze — settle cap (${SETTLE_CAP} frames) reached with reporters still busy: ${busyNames().join(\", \")}. Parking on a possibly unsettled frame.`,\n );\n }\n return false;\n }\n settleLeft -= 1;\n // Quiet: this is the LAST step, taken so the settled state reflects.\n if (busyNames().length === 0) parked = true;\n return true;\n },\n\n onChange(fn) {\n listeners.add(fn);\n return () => {\n listeners.delete(fn);\n };\n },\n };\n}\n","/**\n * The guest runtime (petition I14 — the literal PA-28 \"spine scheduler\").\n *\n * A GUEST is frame-cadence work the engine did not write: a plugin's declared\n * system, a host's derived-state job, and (from design-009) every compiled\n * behavior. Guests get a NAMED slot in the frame contract — design-002 §1 as\n * amended 2026-08-15:\n *\n * setFrameInfo → sync → tick → GUESTS → publish hooks → notify → reflect\n *\n * Guests run BEFORE the publish hooks so derived state has settled by the time\n * presence I/O reads it, and before `notify()` so the same frame reflects their\n * writes. Three properties the engine owes anything it hosts here:\n *\n * 1. **Fault isolation.** A throwing guest is caught, struck, and skipped — it\n * never kills the loop, its neighbours, or the frame. (Engine systems and\n * publish hooks keep propagating loudly by design; guests are the untrusted\n * tier, and the breaker below is what makes hosting them honest.)\n * 2. **The snapshot rule.** `runAll` iterates a snapshot with a liveness check,\n * so a guest that adds or removes guests mid-run never skips a neighbour —\n * the bug this same release fixed in the publish-hook and reflector loops.\n * A guest added during a run starts NEXT frame.\n * 3. **A circuit breaker, named honestly.** A main-thread body cannot be\n * preempted: by the time we measure, the frame is already spent. What the\n * breaker guarantees is that no guest hurts the canvas TWICE sustained.\n *\n * GENERATIONS. `make(gen)` builds a per-generation instance; the generation\n * boundary in ICE is `world.reset()` (doc close/switch — the world is reset in\n * place, so systems, observers and this registry all survive while every entity\n * dies). On reset we mark the generation dirty and rebuild at the TOP of the\n * next guest step — never inside the observer emit, where structural writes are\n * illegal and user code has no business running. `gen.signal` aborts when the\n * generation ends or the guest is removed.\n *\n * THE LEDGER IS HOST-INJECTABLE. Downstream (VibeField) an engine is per-doc, so\n * a registry-local ledger would reset on every doc switch and hand chronic\n * offenders a fresh probation forever. `add({ledger})` seeds prior state and\n * `onLedgerChange` reports every transition, so the host persists across\n * generations it owns.\n */\nimport type { World } from \"@vibecook/strata-ecs\";\nimport { devGuardsEnabled } from \"../guards/dev\";\n\n/** Frame facts a guest may read (FrameInfo, pre-read by the engine). */\nexport interface GuestFrame {\n readonly dtMs: number;\n readonly tick: number;\n /** Accumulated CLAMPED dt — under-reports across freezes; never accumulate\n * wall time from it (frame-info.ts). */\n readonly clock: number;\n}\n\nexport type GuestRun = (frame: GuestFrame) => void;\n\nexport interface GuestInstance {\n run: GuestRun;\n dispose?: () => void;\n /**\n * \"I still owe visible work.\" Feeds the frame gate's settle walk, so a\n * freeze taken mid-derive parks only AFTER the guest has caught up — the\n * canvas is never photographed between a structural change and its reflow.\n * A guest with no owed-work notion simply omits it (the frame gate then\n * treats it as quiet, which is the honest default).\n */\n busy?: () => boolean;\n}\n\nexport interface GuestGeneration {\n readonly world: World;\n /** Aborts at generation teardown (world reset), removal, or engine dispose. */\n readonly signal: AbortSignal;\n}\n\nexport type GuestFactory = (gen: GuestGeneration) => GuestInstance | GuestRun;\n\n/** The persistable half of a guest's breaker state. */\nexport interface GuestLedgerRecord {\n /** Cumulative over-budget/fault strikes (never reset by resume — honesty). */\n readonly strikes: number;\n readonly suspended: boolean;\n}\n\nexport interface GuestSpec {\n /** Stable id — the ledger key, the profiler lane name, the doctor's row. */\n readonly id: string;\n readonly make: GuestFactory;\n /** Per-invocation budget request; the effective budget is\n * `min(budgetMs, seamCapMs)` — no single guest may claim the whole seam. */\n readonly budgetMs?: number;\n /** RESERVED. v1 hosts the publish slot only; pipeline-group values arrive\n * with the behavior framework (design-009 M13a), wrapped by this breaker. */\n readonly phase?: \"publish\";\n /** Seed prior breaker state (host-persisted across engine generations). */\n readonly ledger?: GuestLedgerRecord;\n}\n\nexport interface GuestStatus {\n readonly id: string;\n readonly status: \"running\" | \"suspended\" | \"failed\";\n /** Last invocation, ms. */\n readonly lastMs: number;\n /** p95 over the rolling window, ms. */\n readonly p95Ms: number;\n readonly strikes: number;\n readonly budgetMs: number;\n}\n\n/**\n * A guest whose CADENCE its owner drives (design-009 §7): compiled behaviors\n * run as ordinary pipeline systems, in their declared phase, inside the tick —\n * so nothing here can call their bodies. What they still need is everything\n * ELSE a guest gets: one breaker, one ledger, one doctor row, one seam total.\n * That is what this handle is — the breaker, detached from the scheduler.\n */\nexport interface DrivenGuest {\n /** Breaker verdict. Cheap and never throws — poll it from a system `runIf`. */\n suspended(): boolean;\n /**\n * Run `body` inside this guest's fault domain, ACCRUING its cost into the\n * current frame's charge. Returns false when the guest is suspended (the\n * body did not run) or the body threw (contained).\n *\n * Accrual, not per-call recording, is what makes the budget mean \"per frame\"\n * for a CHUNKED body: a tick system's body runs once per matching chunk, and\n * recording each chunk as its own invocation would compare a 2ms frame budget\n * against a fraction of the work it was meant to bound. The accrued total is\n * closed as ONE invocation at the guest slot, every frame.\n */\n run(body: () => void): boolean;\n /**\n * Report a fault the caller already CONTAINED — a per-instance hook throw\n * that the delivery loop caught so one bad node cannot kill a 1000-node\n * behavior (BF-D18). It takes the ordinary throw ladder.\n */\n fault(err: unknown): void;\n /** Idempotent. */\n remove(): void;\n}\n\nexport interface DrivenGuestSpec {\n readonly id: string;\n readonly budgetMs?: number;\n readonly ledger?: GuestLedgerRecord;\n /** Owed-work reporter for the frame gate's settle walk. */\n readonly busy?: () => boolean;\n}\n\nexport interface GuestRegistry {\n /** Register a guest. Returns a remover (idempotent; disposes the instance). */\n add(spec: GuestSpec): () => void;\n /**\n * Register a guest the registry does NOT call (see {@link DrivenGuest}).\n * Its cost still lands in this frame's seam total, its strikes in the same\n * ledger, and its row in `list()`.\n */\n addDriven(spec: DrivenGuestSpec): DrivenGuest;\n /** Live status for devtools/doctor — never throws, safe to poll. */\n list(): readonly GuestStatus[];\n /** Fires whenever a guest's persistable breaker state changes. */\n onLedgerChange(cb: (id: string, record: GuestLedgerRecord) => void): () => void;\n /** Clear a suspension (the doctor's explicit action). Cumulative strikes\n * survive; the rolling window is cleared so probation starts fresh. */\n resume(id: string): void;\n}\n\n/** The engine-facing half (step drives it; hosts never see these). */\nexport interface GuestRegistryInternal extends GuestRegistry {\n runAll(frame: GuestFrame): void;\n /** Any live guest reporting owed work — the engine's settle reporter. */\n anyBusy(): boolean;\n dispose(): void;\n}\n\n/**\n * Breaker constants (design-009 §12 / door ED-D3). Exported so tests and the\n * downstream doctor cite ONE source rather than re-deriving thresholds.\n */\nexport const GUEST_BUDGET = {\n /** Default per-invocation budget when a guest declares none. */\n defaultBudgetMs: 2,\n /** The whole guest seam's sustained budget — also the per-guest ceiling. */\n seamCapMs: 8,\n /** Rolling window length, in invocations. */\n window: 120,\n /** Trip: more than this many of the last `window` invocations over budget. */\n overBudgetTrip: 30,\n /** Trip: this many CONSECUTIVE invocations at ≥ `heavyFactor` × budget. */\n consecutiveHeavy: 3,\n heavyFactor: 4,\n /** Trip: this many CONSECUTIVE invocations over `stallMs` (one GC pause or\n * debugger breakpoint must never suspend — hence 2, not 1). */\n consecutiveStall: 2,\n stallMs: 50,\n /** Trip: this many consecutive throws. */\n consecutiveThrows: 3,\n /** Frames the whole seam may sit over `seamCapMs` before the worst offender\n * is suspended. */\n seamOverFrames: 3,\n} as const;\n\ninterface Entry {\n readonly spec: GuestSpec;\n readonly budgetMs: number;\n /** Driven entries have no factory and no instance — their owner calls them. */\n readonly driven: boolean;\n /** Driven entries report owed work directly (there is no instance to ask). */\n readonly busyFn: (() => boolean) | undefined;\n /** ms accrued by `DrivenGuest.run` since the last settle (see the doc there). */\n accruedMs: number;\n accrued: boolean;\n /** Any contained fault since the last settle — the ladder counts frames. */\n faultedThisFrame: boolean;\n instance: GuestInstance | null;\n controller: AbortController | null;\n alive: boolean;\n /** `make` threw — no instance, no runs, reported once. */\n failed: boolean;\n suspended: boolean;\n /** The first invocation of each generation is exempt from TIMING strikes\n * (module warmup, JIT, first-touch allocation — not a hostile body). */\n warmupPending: boolean;\n /** Rolling durations, ms (bounded by GUEST_BUDGET.window). */\n window: number[];\n overInWindow: number;\n consecutiveHeavy: number;\n consecutiveStall: number;\n consecutiveThrows: number;\n lastMs: number;\n strikes: number;\n}\n\nexport interface GuestRegistryOpts {\n /**\n * Dev leniency: while true, TIMING strikes log and never suspend (the throw\n * ladder still bites). Wired to `engine.enableTelemetry()` — i.e. devtools\n * attached — so stepping in a debugger cannot suspend a healthy guest.\n */\n readonly lenient?: () => boolean;\n readonly onFault?: (id: string, err: unknown) => void;\n readonly onNotice?: (message: string) => void;\n}\n\nexport function createGuestRegistry(world: World, opts?: GuestRegistryOpts): GuestRegistryInternal {\n const entries: Entry[] = [];\n let snapshot: Entry[] = [];\n let snapshotDirty = true;\n let generationDirty = false;\n let disposed = false;\n let seamOverFrames = 0;\n const ledgerSubs = new Set<(id: string, record: GuestLedgerRecord) => void>();\n\n const lenient = opts?.lenient ?? (() => false);\n const onFault =\n opts?.onFault ??\n ((id: string, err: unknown) => {\n console.error(`[ice] guest \"${id}\" threw — skipped this frame`, err);\n });\n const onNotice =\n opts?.onNotice ??\n ((message: string) => {\n console.warn(`[ice] ${message}`);\n });\n\n const emitLedger = (e: Entry): void => {\n const record: GuestLedgerRecord = { strikes: e.strikes, suspended: e.suspended };\n for (const cb of ledgerSubs) cb(e.spec.id, record);\n };\n\n const strike = (e: Entry, reason: string, suspendNow: boolean): void => {\n e.strikes++;\n if (suspendNow && !e.suspended) {\n e.suspended = true;\n disposeInstance(e); // a suspended guest holds no live resources\n onNotice(`guest \"${e.spec.id}\" SUSPENDED — ${reason}`);\n }\n emitLedger(e);\n };\n\n const disposeInstance = (e: Entry): void => {\n const inst = e.instance;\n const controller = e.controller;\n e.instance = null;\n e.controller = null;\n // dispose() FIRST, abort SECOND (design-009 §4.3): a teardown that guards\n // on `signal.aborted` — a thoroughly reasonable thing to write — would\n // skip its own cleanup if the signal fired first.\n if (inst?.dispose !== undefined) {\n try {\n inst.dispose();\n } catch (err) {\n // Teardown-sweep discipline: a throwing dispose must not stop the sweep.\n onFault(e.spec.id, err);\n }\n }\n controller?.abort();\n };\n\n const makeInstance = (e: Entry): void => {\n if (e.driven || e.suspended || !e.alive || disposed) return;\n const controller = new AbortController();\n try {\n const made = e.spec.make({ world, signal: controller.signal });\n e.instance = typeof made === \"function\" ? { run: made } : made;\n e.controller = controller;\n e.failed = false;\n e.warmupPending = true;\n } catch (err) {\n controller.abort();\n e.instance = null;\n e.controller = null;\n e.failed = true;\n onFault(e.spec.id, err);\n }\n };\n\n const stopResetWatch = world.observe({\n onReset: () => {\n // Do NOT rebuild here: user factories may write structurally, which is\n // illegal inside an observer emit. Mark and rebuild at the next step's\n // top, before any guest runs against dead handles.\n generationDirty = true;\n },\n });\n\n const rebuildGeneration = (): void => {\n for (const e of entries) disposeInstance(e);\n for (const e of entries) makeInstance(e);\n // A driven guest keeps no instance to rebuild, but it DOES get a fresh\n // warmup exemption: the first frame of a new generation pays the same\n // first-touch costs (rebuilt caches, cold paths) that exempt hosted guests.\n for (const e of entries) if (e.driven) e.warmupPending = true;\n };\n\n const p95 = (samples: readonly number[]): number => {\n if (samples.length === 0) return 0;\n const sorted = [...samples].sort((a, b) => a - b);\n const idx = Math.min(sorted.length - 1, Math.floor(sorted.length * 0.95));\n return sorted[idx] ?? 0;\n };\n\n /** The guest whose suspension buys the seam the most: most strikes, then p95. */\n const worstOffender = (): Entry | null => {\n let worst: Entry | null = null;\n for (const e of snapshot) {\n if (!e.alive || e.suspended || e.instance === null) continue;\n if (worst === null) {\n worst = e;\n continue;\n }\n if (e.overInWindow !== worst.overInWindow) {\n if (e.overInWindow > worst.overInWindow) worst = e;\n continue;\n }\n if (p95(e.window) > p95(worst.window)) worst = e;\n }\n return worst;\n };\n\n const record = (e: Entry, ms: number): void => {\n e.lastMs = ms;\n e.window.push(ms);\n if (ms > e.budgetMs) e.overInWindow++;\n if (e.window.length > GUEST_BUDGET.window) {\n const dropped = e.window.shift() ?? 0;\n if (dropped > e.budgetMs) e.overInWindow--;\n }\n\n // Warmup: the first invocation of a generation is measured and reported,\n // but cannot itself strike (module eval + first-touch costs are not a\n // hostile body). Consecutive counters start clean after it.\n if (e.warmupPending) {\n e.warmupPending = false;\n e.consecutiveHeavy = 0;\n e.consecutiveStall = 0;\n return;\n }\n\n e.consecutiveStall = ms > GUEST_BUDGET.stallMs ? e.consecutiveStall + 1 : 0;\n e.consecutiveHeavy = ms >= e.budgetMs * GUEST_BUDGET.heavyFactor ? e.consecutiveHeavy + 1 : 0;\n\n const timingTrip =\n e.overInWindow > GUEST_BUDGET.overBudgetTrip ||\n e.consecutiveHeavy >= GUEST_BUDGET.consecutiveHeavy ||\n e.consecutiveStall >= GUEST_BUDGET.consecutiveStall;\n\n if (!timingTrip) return;\n\n const why =\n e.consecutiveStall >= GUEST_BUDGET.consecutiveStall\n ? `${e.consecutiveStall} consecutive invocations over ${GUEST_BUDGET.stallMs}ms`\n : e.consecutiveHeavy >= GUEST_BUDGET.consecutiveHeavy\n ? `${e.consecutiveHeavy} consecutive invocations ≥ ${GUEST_BUDGET.heavyFactor}× its ${e.budgetMs}ms budget`\n : `${e.overInWindow} of the last ${e.window.length} invocations over its ${e.budgetMs}ms budget`;\n\n if (lenient()) {\n // Devtools attached: report, never suspend. Counters reset so one paused\n // breakpoint does not queue a suspension for the moment devtools detach.\n e.consecutiveHeavy = 0;\n e.consecutiveStall = 0;\n e.overInWindow = 0;\n e.window.length = 0;\n onNotice(`guest \"${e.spec.id}\" over budget (${why}) — not suspended: devtools attached`);\n return;\n }\n strike(e, why, true);\n };\n\n const makeEntry = (spec: GuestSpec, driven: boolean, busy: (() => boolean) | undefined): Entry => ({\n spec,\n // No guest may claim more than the whole seam.\n budgetMs: Math.max(0, Math.min(spec.budgetMs ?? GUEST_BUDGET.defaultBudgetMs, GUEST_BUDGET.seamCapMs)),\n driven,\n busyFn: busy,\n accruedMs: 0,\n accrued: false,\n faultedThisFrame: false,\n instance: null,\n controller: null,\n alive: true,\n failed: false,\n suspended: spec.ledger?.suspended ?? false,\n warmupPending: true,\n window: [],\n overInWindow: 0,\n consecutiveHeavy: 0,\n consecutiveStall: 0,\n consecutiveThrows: 0,\n lastMs: 0,\n strikes: spec.ledger?.strikes ?? 0,\n });\n\n return {\n add(spec) {\n if (disposed) throw new Error(`ice: guests.add(\"${spec.id}\") after the registry was disposed`);\n if (spec.phase !== undefined && spec.phase !== \"publish\") {\n throw new Error(\n `ice: guests.add(\"${spec.id}\") — phase \"${spec.phase}\" is reserved; v1 hosts the publish slot only (pipeline phases arrive with the behavior framework)`,\n );\n }\n if (entries.some((e) => e.spec.id === spec.id && e.alive)) {\n throw new Error(`ice: guest \"${spec.id}\" is already registered`);\n }\n\n const entry = makeEntry(spec, false, undefined);\n entries.push(entry);\n snapshotDirty = true;\n makeInstance(entry);\n\n return () => {\n if (!entry.alive) return;\n entry.alive = false;\n disposeInstance(entry);\n const i = entries.indexOf(entry);\n if (i !== -1) entries.splice(i, 1);\n snapshotDirty = true;\n };\n },\n\n addDriven(spec) {\n if (disposed) throw new Error(`ice: guests.addDriven(\"${spec.id}\") after the registry was disposed`);\n if (entries.some((e) => e.spec.id === spec.id && e.alive)) {\n throw new Error(`ice: guest \"${spec.id}\" is already registered`);\n }\n const entry = makeEntry(\n { id: spec.id, make: DRIVEN_NO_FACTORY, ...(spec.budgetMs !== undefined ? { budgetMs: spec.budgetMs } : {}), ...(spec.ledger !== undefined ? { ledger: spec.ledger } : {}) },\n true,\n spec.busy,\n );\n entries.push(entry);\n snapshotDirty = true;\n\n return {\n suspended: () => entry.suspended || !entry.alive || disposed,\n run(body) {\n if (entry.suspended || !entry.alive || disposed) return false;\n const t0 = performance.now();\n try {\n body();\n entry.accruedMs += performance.now() - t0;\n entry.accrued = true;\n return true;\n } catch (err) {\n entry.accruedMs += performance.now() - t0;\n entry.accrued = true;\n entry.faultedThisFrame = true;\n entry.consecutiveThrows++;\n onFault(entry.spec.id, err);\n strike(\n entry,\n `${entry.consecutiveThrows} consecutive throws`,\n entry.consecutiveThrows >= GUEST_BUDGET.consecutiveThrows,\n );\n return false;\n }\n },\n fault(err) {\n if (!entry.alive || disposed) return;\n entry.faultedThisFrame = true;\n entry.accrued = true; // ensure the settle pass sees this frame\n entry.consecutiveThrows++;\n onFault(entry.spec.id, err);\n strike(\n entry,\n `${entry.consecutiveThrows} consecutive throws`,\n entry.consecutiveThrows >= GUEST_BUDGET.consecutiveThrows,\n );\n },\n remove() {\n if (!entry.alive) return;\n entry.alive = false;\n const i = entries.indexOf(entry);\n if (i !== -1) entries.splice(i, 1);\n snapshotDirty = true;\n },\n };\n },\n\n runAll(frame) {\n if (disposed) return;\n if (generationDirty) {\n generationDirty = false;\n rebuildGeneration();\n }\n if (snapshotDirty) {\n snapshot = entries.slice();\n snapshotDirty = false;\n }\n\n // Close out every driven guest's frame FIRST: they ran during the tick,\n // so their cost is already spent by the time this slot opens, and the\n // seam total below has to include it or the cap it enforces is fiction.\n let seamMs = 0;\n for (const e of snapshot) {\n if (!e.driven || !e.accrued) continue;\n const ms = e.accruedMs;\n e.accruedMs = 0;\n e.accrued = false;\n seamMs += ms;\n // The throw ladder counts FRAMES, not calls: a chunked body runs many\n // times per frame, and clearing the counter on the first clean chunk\n // after a faulting one would mean three consecutive bad frames never\n // add up to three.\n if (!e.faultedThisFrame) e.consecutiveThrows = 0;\n e.faultedThisFrame = false;\n record(e, ms);\n }\n\n for (const e of snapshot) {\n if (e.driven || !e.alive || e.suspended || e.instance === null) continue;\n const t0 = performance.now();\n try {\n const returned: unknown = e.instance.run(frame);\n // An async body evades BOTH the bracket and the catch: the awaited\n // remainder runs outside the frame with no budget and no fault\n // domain. `(frame) => void` accepts any return type, so only a\n // runtime check catches it. Treated as a FAULT, not a slow frame:\n // under dev guards it suspends immediately (a contract violation is\n // a bug to fix, not a perf blip to ride out); in production it takes\n // the ordinary throw ladder. It is never re-thrown — a guest must not\n // be able to kill the frame, which is the whole point of this tier.\n if (typeof (returned as { then?: unknown } | null | undefined)?.then === \"function\") {\n const ms = performance.now() - t0;\n seamMs += ms;\n e.consecutiveThrows++;\n onFault(\n e.spec.id,\n new Error(\n `guest \"${e.spec.id}\" run() returned a thenable — guest bodies MUST be synchronous`,\n ),\n );\n strike(\n e,\n \"an async run() body\",\n devGuardsEnabled() || e.consecutiveThrows >= GUEST_BUDGET.consecutiveThrows,\n );\n continue;\n }\n const ms = performance.now() - t0;\n seamMs += ms;\n e.consecutiveThrows = 0;\n record(e, ms);\n } catch (err) {\n const ms = performance.now() - t0;\n seamMs += ms;\n e.lastMs = ms;\n e.consecutiveThrows++;\n onFault(e.spec.id, err);\n strike(\n e,\n `${e.consecutiveThrows} consecutive throws`,\n e.consecutiveThrows >= GUEST_BUDGET.consecutiveThrows,\n );\n }\n }\n\n // The seam cap: the canvas never pays twice for the whole guest tier.\n if (seamMs > GUEST_BUDGET.seamCapMs) {\n seamOverFrames++;\n if (seamOverFrames >= GUEST_BUDGET.seamOverFrames && !lenient()) {\n const worst = worstOffender();\n seamOverFrames = 0;\n if (worst !== null) {\n strike(\n worst,\n `the guest seam ran over ${GUEST_BUDGET.seamCapMs}ms for ${GUEST_BUDGET.seamOverFrames} consecutive frames and this was its worst offender`,\n true,\n );\n }\n }\n } else {\n seamOverFrames = 0;\n }\n },\n\n anyBusy() {\n for (const e of entries) {\n if (!e.alive || e.suspended) continue;\n const busy = e.driven ? e.busyFn : e.instance?.busy;\n if (busy === undefined) continue;\n try {\n if (busy()) return true;\n } catch (err) {\n // A throwing predicate must not wedge the settle walk at the cap.\n onFault(e.spec.id, err);\n }\n }\n return false;\n },\n\n list() {\n return entries.map((e) => ({\n id: e.spec.id,\n status: e.suspended ? \"suspended\" : e.failed ? \"failed\" : \"running\",\n lastMs: e.lastMs,\n p95Ms: p95(e.window),\n strikes: e.strikes,\n budgetMs: e.budgetMs,\n }));\n },\n\n onLedgerChange(cb) {\n ledgerSubs.add(cb);\n return () => {\n ledgerSubs.delete(cb);\n };\n },\n\n resume(id) {\n const e = entries.find((x) => x.spec.id === id && x.alive);\n if (e === undefined || !e.suspended) return;\n e.suspended = false;\n e.window.length = 0;\n e.overInWindow = 0;\n e.consecutiveHeavy = 0;\n e.consecutiveStall = 0;\n e.consecutiveThrows = 0;\n makeInstance(e); // a fresh instance: the suspended one was disposed\n emitLedger(e);\n },\n\n dispose() {\n if (disposed) return;\n disposed = true;\n stopResetWatch();\n for (const e of entries) {\n e.alive = false;\n disposeInstance(e);\n }\n entries.length = 0;\n snapshot = [];\n ledgerSubs.clear();\n },\n };\n}\n\n/** Placeholder factory for driven entries — never called (see `makeInstance`). */\nconst DRIVEN_NO_FACTORY: GuestFactory = () => {\n throw new Error(\"ice: internal — a driven guest has no factory\");\n};\n","/**\n * The engine facade — owner of the outer frame (design-002 §1):\n *\n * step(now):\n * setFrameInfo FrameInfo resource — value write, pre-tick\n * world.sync() durable + presence drains land; projections place\n * world.tick(...) the phase-group pipeline (pipeline.ts)\n * guests [2026-08-15, petition I14] the NAMED guest slot:\n * plugin/host frame work under a circuit breaker\n * (guests.ts). BEFORE publish so derived state has\n * settled when presence I/O reads it, and before\n * notify so the same frame reflects it. Guests are\n * fault-ISOLATED — the one tier here that is.\n * publish hooks POST-TICK, PRE-NOTIFY: presence I/O home — eph\n * structural ops are illegal for the whole tick, this\n * step is theirs; `world.*` is legal here (outside the\n * tick). Hooks throw LOUDLY (unlike reflectors) — a\n * broken publish pre-notify must not be silently\n * half-applied.\n * notify() THE settled point — observers fire once per frame\n * reflect reflector registry flush (post-notify, output-only)\n *\n * The engine is scheduler-free: `step(now)` is the whole surface, and the DOM\n * package owns the rAF loop (core never touches the platform). Telemetry is\n * opt-in — `world.observe` costs a `performance.now()` pair per system when\n * armed, so benches leave it off.\n */\nimport type { World } from \"@vibecook/strata-ecs\";\nimport type { AnySystem } from \"./pipeline\";\nimport { createFrameControl, type FrameControl } from \"./frame-control\";\nimport { FrameInfo, setFrameInfo } from \"./frame-info\";\nimport { createGuestRegistry, type GuestRegistry, type GuestRegistryInternal } from \"./guests\";\nimport { createPipelineRegistry, type PhaseGroup } from \"./pipeline\";\nimport { createReflectorRegistry, type ReflectorDef } from \"./reflectors\";\n\nexport type PublishHook = (world: World) => void;\n\n/**\n * One registered publish hook. The `alive` flag is what makes removal exact\n * under the snapshot rule (below): the same function may be registered twice,\n * so liveness cannot be a Set membership test on the function itself.\n */\ninterface PublishEntry {\n readonly hook: PublishHook;\n alive: boolean;\n}\n\nexport interface SystemRunRecord {\n readonly phase: string;\n readonly system: string;\n readonly ran: boolean;\n readonly micros: number;\n}\n\n/** One frame's run/skip + timing readout (design-002 §4: F1's honest telemetry). */\nexport interface FrameTelemetry {\n readonly tick: number;\n readonly totalMicros: number;\n readonly systems: readonly SystemRunRecord[];\n readonly phaseFlushMicros: ReadonlyMap<string, number>;\n readonly reflectorsFlushed: readonly string[];\n /**\n * Total reflector-flush cost, µs (post-notify — OUTSIDE the tick, which is\n * why it can never appear in `phaseFlushMicros`: that map is keyed by strata\n * PHASE names and reflect is not a phase. Devtools' \"reflect\" lane read that\n * map until 2026-08-15 and therefore never reported at all).\n */\n readonly reflectMicros: number;\n /** Per-reflector flush cost, µs, for the same frame (registration order). */\n readonly reflectorMicros: ReadonlyMap<string, number>;\n}\n\nexport interface EngineOpts {\n /** Reflector fault sink (default: console.error, skip this frame). */\n readonly onReflectorFault?: (name: string, err: unknown) => void;\n /** Guest fault sink (default: console.error). A guest throwing is contained\n * by the breaker; hosts route this to their own diagnostics. */\n readonly onGuestFault?: (id: string, err: unknown) => void;\n /**\n * Guest breaker notices — suspensions and lenient-mode overruns (default:\n * console.warn). Hosts SHOULD route this: a suspended derived guest means\n * derived state silently stops updating, which reads to a user as a broken\n * document rather than a broken plugin (design-009 §7).\n */\n readonly onGuestNotice?: (message: string) => void;\n}\n\nexport interface Engine {\n readonly world: World;\n /** Register systems into a canonical phase group. Returns a remover. */\n addSystems(group: PhaseGroup, ...systems: readonly AnySystem[]): () => void;\n /** Register a post-notify output reflector (design-002 §5). Returns an unregister. */\n registerReflector(def: ReflectorDef): () => void;\n /** All registered reflector names (devtools; telemetry-independent). */\n reflectorNames(): readonly string[];\n /** Register a publish-step hook (post-tick, pre-notify presence I/O). Returns a remover. */\n onPublish(hook: PublishHook): () => void;\n /**\n * The guest runtime (petition I14): frame-cadence work the engine did not\n * write — plugin systems, host derived-state jobs, compiled behaviors — run\n * in a named slot between the tick and the publish hooks, each fault-isolated\n * and budgeted by a circuit breaker (guests.ts).\n */\n readonly guests: GuestRegistry;\n /** Run one full frame. `now` in ms (rAF timestamp or a test counter). */\n step(now: number): void;\n /**\n * The frame gate (2026-08-04): freeze/thaw plus the settle protocol a host\n * loop consults before each frame. It lives HERE, next to the step it\n * governs, so every host gets it without a new argument — and so a\n * subsystem holding only the `Engine` (the GL compositor) can report itself\n * busy. `step()` itself stays unconditional: the gate governs the loop, not\n * the primitive, which keeps headless hosts and traces driving frames by\n * hand exactly as before.\n */\n readonly frame: FrameControl;\n /** Arm per-system run/skip + µs collection (idempotent; costs timer calls per system).\n * Also puts the guest breaker in LENIENT mode — devtools attached means a\n * debugger breakpoint must not suspend a healthy guest. */\n enableTelemetry(): void;\n /** Tear down guest instances (the facade calls this from `dispose()`). */\n disposeGuests(): void;\n /** The most recent completed frame's readout (undefined until telemetry armed + one step). */\n lastFrame(): FrameTelemetry | undefined;\n}\n\nexport function createEngine(world: World, opts?: EngineOpts): Engine {\n const pipeline = createPipelineRegistry();\n const reflectors = createReflectorRegistry(\n world,\n opts?.onReflectorFault ? { onFault: opts.onReflectorFault } : undefined,\n );\n const publishHooks: PublishEntry[] = [];\n // The per-frame SNAPSHOT (rebuilt only when the registration set changes, so\n // steady state allocates nothing). Iterating the live array let a hook that\n // removed itself — or an earlier hook — shift the array under the index-based\n // iterator and silently SKIP its neighbour that frame. The contract now:\n // every hook registered at frame start runs exactly once, unless it is\n // unregistered before its turn; a hook registered DURING publish runs next\n // frame (deterministic, and the same rule design-009 gives behaviors).\n let publishSnapshot: PublishEntry[] = [];\n let publishDirty = true;\n const frame = createFrameControl(world);\n\n let telemetryArmed = false;\n // Telemetry armed ⇒ devtools attached ⇒ the breaker reports timing overruns\n // instead of suspending (the throw ladder still bites). Read through a\n // closure so arming later still reaches the registry.\n const guests: GuestRegistryInternal = createGuestRegistry(world, {\n lenient: () => telemetryArmed,\n ...(opts?.onGuestFault ? { onFault: opts.onGuestFault } : {}),\n ...(opts?.onGuestNotice ? { onNotice: opts.onGuestNotice } : {}),\n });\n // A freeze must not photograph the canvas between a structural change and the\n // guest-owned reflow that answers it (design-002 §1's settle protocol).\n frame.settleWhile(\"guests\", () => guests.anyBusy());\n let last: FrameTelemetry | undefined;\n let building: {\n tick: number;\n systems: SystemRunRecord[];\n phaseFlushMicros: Map<string, number>;\n } | null = null;\n\n return {\n world,\n frame,\n guests,\n\n addSystems(group, ...systems) {\n return pipeline.add(group, ...systems);\n },\n\n reflectorNames() {\n return reflectors.names();\n },\n registerReflector(def) {\n return reflectors.register(def);\n },\n\n onPublish(hook) {\n const entry: PublishEntry = { hook, alive: true };\n publishHooks.push(entry);\n publishDirty = true;\n return () => {\n if (!entry.alive) return;\n entry.alive = false;\n const i = publishHooks.indexOf(entry);\n if (i !== -1) publishHooks.splice(i, 1);\n publishDirty = true;\n };\n },\n\n step(now) {\n setFrameInfo(world, now);\n world.sync();\n world.tick(pipeline.assemble());\n const info = world.getResource(FrameInfo);\n guests.runAll({\n dtMs: info?.dt ?? 0,\n tick: info?.tick ?? 0,\n clock: info?.clock ?? 0,\n });\n if (publishDirty) {\n publishSnapshot = publishHooks.slice();\n publishDirty = false;\n }\n for (const entry of publishSnapshot) {\n if (entry.alive) entry.hook(world);\n }\n world.reactive.notify();\n reflectors.flushAll();\n },\n\n enableTelemetry() {\n if (telemetryArmed) return;\n telemetryArmed = true;\n reflectors.armTelemetry();\n world.observe({\n onTickStart(tick) {\n building = { tick, systems: [], phaseFlushMicros: new Map() };\n },\n onSystemRun(phaseName, system, ran, micros) {\n building?.systems.push({ phase: phaseName, system, ran, micros });\n },\n onPhaseFlush(phaseName, micros) {\n building?.phaseFlushMicros.set(phaseName, micros);\n },\n onTickEnd(tick, micros) {\n if (building === null || building.tick !== tick) return;\n last = {\n tick,\n totalMicros: micros,\n systems: building.systems,\n phaseFlushMicros: building.phaseFlushMicros,\n // step() overwrites these post-notify — captured lazily below.\n reflectorsFlushed: [],\n reflectMicros: 0,\n reflectorMicros: new Map(),\n };\n building = null;\n },\n });\n },\n\n disposeGuests() {\n guests.dispose();\n },\n\n lastFrame() {\n if (last === undefined) return undefined;\n // Reflector flush happens after onTickEnd, so splice the registry's\n // latest readout in at read time (same frame: step() is synchronous).\n return {\n ...last,\n reflectorsFlushed: reflectors.lastFlushed(),\n reflectMicros: reflectors.lastFlushMicros(),\n reflectorMicros: reflectors.lastFlushDetail(),\n };\n },\n };\n}\n","/**\n * The engine props DSL (design-005 §2, amending design-001 §5.2).\n *\n * Standard Schema is validation-only — it exposes `validate()` but no\n * introspectable shape, so arbitrary schemas cannot compile to typed\n * components. This DSL is the compiler's input: it (a) maps 1:1 onto strata\n * field types plus explicit `p.json` string cells, (b) implements the\n * Standard Schema v1 interface so it plugs into ecosystem tooling, and\n * (c) enforces the definition-time rules — every top-level field defaulted\n * (json derives an empty default from its root shape), enums additive-only\n * across versions (checked by the M9 migrator against pack history; recorded\n * here), `p.json` as the ONLY nesting escape hatch (visibly conflict-coarse:\n * one string cell, last-writer-wins whole-value).\n */\n\n// --- Standard Schema v1 (interface only — no runtime dependency) ---\n\nexport interface StandardSchemaV1<Input = unknown, Output = Input> {\n readonly \"~standard\": {\n readonly version: 1;\n readonly vendor: string;\n readonly validate: (\n value: unknown,\n ) => { value: Output } | { issues: readonly { message: string }[] };\n };\n}\n\n// --- spec kinds ---\n\nexport type PropSpec =\n | StringSpec\n | NumberSpec\n | BooleanSpec\n | EnumSpec\n | JsonSpec\n | EntityKeySpec;\n\nexport interface StringSpec extends StandardSchemaV1<unknown, string> {\n readonly kind: \"string\";\n readonly default?: string;\n}\nexport interface NumberSpec extends StandardSchemaV1<unknown, number> {\n readonly kind: \"number\";\n readonly default?: number;\n readonly min?: number;\n readonly max?: number;\n}\nexport interface BooleanSpec extends StandardSchemaV1<unknown, boolean> {\n readonly kind: \"boolean\";\n readonly default?: boolean;\n}\nexport interface EnumSpec extends StandardSchemaV1<unknown, string> {\n readonly kind: \"enum\";\n readonly options: readonly string[];\n readonly default?: string;\n}\n/** One conflict-coarse string cell; `inner` validates the PARSED value. */\nexport interface JsonSpec extends StandardSchemaV1<unknown, unknown> {\n readonly kind: \"json\";\n readonly inner: JsonShape;\n /** Serialized default (derived from the inner root when not given). */\n readonly default?: string;\n}\n/**\n * A DURABLE entity reference (design-009 §4.2): the doc key of another entity,\n * stored as a plain string cell. This is the ONLY legal cross-entity reference\n * in behavior data — Law 7 bans `eid` from durable cells because a runtime\n * handle means nothing to the peer that receives it, while a doc key survives\n * the wire, the file, and a reload. Empty string = no reference; resolution is\n * `ctx.entityFor(key)`, which may legitimately return undefined while the\n * target is not yet projected.\n */\nexport interface EntityKeySpec extends StandardSchemaV1<unknown, string> {\n readonly kind: \"entityKey\";\n readonly default?: string;\n}\n\n/** Shapes legal only INSIDE p.json (validation-only, never components). */\nexport type JsonShape =\n | { readonly kind: \"string\" }\n | { readonly kind: \"number\" }\n | { readonly kind: \"boolean\" }\n | { readonly kind: \"enum\"; readonly options: readonly string[] }\n | { readonly kind: \"array\"; readonly item: JsonShape }\n | { readonly kind: \"object\"; readonly fields: Readonly<Record<string, JsonShape>> };\n\nexport interface ObjectSpec {\n readonly kind: \"object\";\n readonly fields: Readonly<Record<string, PropSpec>>;\n}\n\n// --- validators ---\n\nfunction fail(message: string): { issues: readonly { message: string }[] } {\n return { issues: [{ message }] };\n}\n\nfunction validateShape(shape: JsonShape, v: unknown, path: string): { message: string } | null {\n switch (shape.kind) {\n case \"string\":\n return typeof v === \"string\" ? null : { message: `${path}: expected string` };\n case \"number\":\n return typeof v === \"number\" && Number.isFinite(v) ? null : { message: `${path}: expected number` };\n case \"boolean\":\n return typeof v === \"boolean\" ? null : { message: `${path}: expected boolean` };\n case \"enum\":\n return typeof v === \"string\" && shape.options.includes(v)\n ? null\n : { message: `${path}: expected one of ${shape.options.join(\"|\")}` };\n case \"array\": {\n if (!Array.isArray(v)) return { message: `${path}: expected array` };\n for (let i = 0; i < v.length; i++) {\n const err = validateShape(shape.item, v[i], `${path}[${i}]`);\n if (err) return err;\n }\n return null;\n }\n case \"object\": {\n if (typeof v !== \"object\" || v === null || Array.isArray(v)) {\n return { message: `${path}: expected object` };\n }\n for (const [k, f] of Object.entries(shape.fields)) {\n const err = validateShape(f, (v as Record<string, unknown>)[k], `${path}.${k}`);\n if (err) return err;\n }\n return null;\n }\n }\n}\n\nfunction std<T>(validate: (v: unknown) => { value: T } | { issues: readonly { message: string }[] }) {\n return { version: 1 as const, vendor: \"ice\", validate };\n}\n\n/** Empty value for a json root shape (the derived default). */\nfunction emptyOf(shape: JsonShape): unknown {\n switch (shape.kind) {\n case \"string\":\n return \"\";\n case \"number\":\n return 0;\n case \"boolean\":\n return false;\n case \"enum\":\n return shape.options[0];\n case \"array\":\n return [];\n case \"object\": {\n const out: Record<string, unknown> = {};\n for (const [k, f] of Object.entries(shape.fields)) out[k] = emptyOf(f);\n return out;\n }\n }\n}\n\n// --- the public DSL ---\n\nexport const p = {\n string(opts: { default?: string } = {}): StringSpec {\n return {\n kind: \"string\",\n ...(opts.default !== undefined ? { default: opts.default } : {}),\n \"~standard\": std((v) => (typeof v === \"string\" ? { value: v } : fail(\"expected string\"))),\n };\n },\n\n number(opts: { default?: number; min?: number; max?: number } = {}): NumberSpec {\n return {\n kind: \"number\",\n ...(opts.default !== undefined ? { default: opts.default } : {}),\n ...(opts.min !== undefined ? { min: opts.min } : {}),\n ...(opts.max !== undefined ? { max: opts.max } : {}),\n \"~standard\": std((v) => {\n if (typeof v !== \"number\" || !Number.isFinite(v)) return fail(\"expected number\");\n if (opts.min !== undefined && v < opts.min) return fail(`min ${opts.min}`);\n if (opts.max !== undefined && v > opts.max) return fail(`max ${opts.max}`);\n return { value: v };\n }),\n };\n },\n\n boolean(opts: { default?: boolean } = {}): BooleanSpec {\n return {\n kind: \"boolean\",\n ...(opts.default !== undefined ? { default: opts.default } : {}),\n \"~standard\": std((v) => (typeof v === \"boolean\" ? { value: v } : fail(\"expected boolean\"))),\n };\n },\n\n enum(options: readonly string[], opts: { default?: string } = {}): EnumSpec {\n if (options.length === 0) throw new Error(\"ice: p.enum needs at least one option.\");\n if (opts.default !== undefined && !options.includes(opts.default)) {\n throw new Error(`ice: p.enum default \"${opts.default}\" is not among its options.`);\n }\n return {\n kind: \"enum\",\n options,\n ...(opts.default !== undefined ? { default: opts.default } : {}),\n \"~standard\": std((v) =>\n typeof v === \"string\" && options.includes(v) ? { value: v } : fail(`expected one of ${options.join(\"|\")}`),\n ),\n };\n },\n\n json(inner: JsonShape, opts: { default?: unknown } = {}): JsonSpec {\n const fallback = opts.default !== undefined ? opts.default : emptyOf(inner);\n const err = validateShape(inner, fallback, \"$default\");\n if (err) throw new Error(`ice: p.json default does not match its shape — ${err.message}`);\n return {\n kind: \"json\",\n inner,\n default: JSON.stringify(fallback),\n \"~standard\": std((v) => {\n const e = validateShape(inner, v, \"$\");\n return e ? { issues: [e] } : { value: v };\n }),\n };\n },\n\n /**\n * A durable reference to another entity by DOC KEY (design-009 §4.2).\n * Behavior-facing: `defineWidget` props have no use for it (a widget's\n * references are relations), but nothing rejects it there either — it is an\n * ordinary string cell with a declared meaning.\n */\n entityKey(opts: { default?: string } = {}): EntityKeySpec {\n return {\n kind: \"entityKey\",\n default: opts.default ?? \"\",\n \"~standard\": std((v) => (typeof v === \"string\" ? { value: v } : fail(\"expected an entity key (string)\"))),\n };\n },\n\n // json-only inner shapes (validation, never components):\n array(item: JsonShape): JsonShape {\n return { kind: \"array\", item };\n },\n object(fields: Readonly<Record<string, JsonShape>>): JsonShape {\n return { kind: \"object\", fields };\n },\n};\n\n/** A widget props declaration: top-level named specs (the compiler's input). */\nexport type PropsDecl = Readonly<Record<string, PropSpec>>;\n\n/**\n * The CELL default for a spec — the value a whole-component write fills in for\n * an untouched field, and the value a generated strata field declares.\n *\n * One function, three callers (widget spawn defaults, `defineWidget`'s\n * essential set, `defineBehavior`'s attach defaults): each used to carry its\n * own else-if chain over `spec.kind`, and each chain had to be found and\n * amended when `p.entityKey` was added — one of them by inspection rather than\n * by a type error, since the chains end in a catch-all `else`. It lives here,\n * beside the specs whose shape it reads.\n */\nexport function defaultValueOf(spec: PropSpec): string | number | boolean {\n switch (spec.kind) {\n case \"json\":\n return spec.default ?? \"null\";\n case \"enum\":\n return spec.default ?? spec.options[0] ?? \"\";\n case \"string\":\n case \"entityKey\":\n return spec.default ?? \"\";\n case \"number\":\n return spec.default ?? 0;\n case \"boolean\":\n return spec.default ?? false;\n }\n}\n","/**\n * Live-tunable settings resources (design-005 §4 engine facade surface;\n * design-003 §4.2 kind table + §3 L1 targeting).\n *\n * These are the live-tunable mirrors of the compile-time defaults in\n * `../settings/defaults` — systems read the RESOURCE first, falling back to\n * the constant, but that read-path wiring happens at integration, not here.\n * Defaults are sourced from `GESTURE_DEFAULTS`/`POINTER_DEFAULTS`, never\n * inlined (the `SnapConfig`-reads-`SNAP_DEFAULTS` pattern in camera-derived.ts\n * exists because an inline-number drift bug shipped once).\n */\nimport { field } from \"@vibecook/strata-ecs\";\nimport { defineResource } from \"../schema/meta\";\nimport {\n CAMERA_DEFAULTS,\n CHROME_DEFAULTS,\n GESTURE_DEFAULTS,\n NAV_TRANSITION_DEFAULTS,\n POINTER_DEFAULTS,\n} from \"../settings/defaults\";\n\n/**\n * Selection-chrome live mirror (2026-07-17): `liftScale` = the app's visual\n * drag-lift scale factor; `selectionChrome` inflates a Grab-bed member's rect\n * by it (about the rect center) so the union box always wraps the card the\n * user SEES, not just its ECS footprint.\n */\nexport const ChromeSettings = defineResource(\"ChromeSettings\", {\n liftScale: field(\"f32\", { default: CHROME_DEFAULTS.liftScale }),\n});\n\n/** Recognizer timing/slop live mirror (design-003 §4.2 kind table; inertia constants §5 item 9). */\nexport const GestureSettings = defineResource(\"GestureSettings\", {\n tapMaxMs: field(\"f32\", { default: GESTURE_DEFAULTS.tapMaxMs }),\n tapSlopPx: field(\"f32\", { default: GESTURE_DEFAULTS.tapSlopPx }),\n longPressMs: field(\"f32\", { default: GESTURE_DEFAULTS.longPressMs }),\n longPressSlopPx: field(\"f32\", { default: GESTURE_DEFAULTS.longPressSlopPx }),\n dragSlopPx: field(\"f32\", { default: GESTURE_DEFAULTS.dragSlopPx }),\n pinchSlopPx: field(\"f32\", { default: GESTURE_DEFAULTS.pinchSlopPx }),\n wheelEndSilenceMs: field(\"f32\", { default: GESTURE_DEFAULTS.wheelEndSilenceMs }),\n inertiaMinVelocityPxPerS: field(\"f32\", { default: GESTURE_DEFAULTS.inertiaMinVelocityPxPerS }),\n inertiaDecayMs: field(\"f32\", { default: GESTURE_DEFAULTS.inertiaDecayMs }),\n multiTapWindowMs: field(\"f32\", { default: GESTURE_DEFAULTS.multiTapWindowMs }),\n multiTapSlopPx: field(\"f32\", { default: GESTURE_DEFAULTS.multiTapSlopPx }),\n wheelZoomSensitivity: field(\"f32\", { default: GESTURE_DEFAULTS.wheelZoomSensitivity }),\n wheelZoomMaxStep: field(\"f32\", { default: GESTURE_DEFAULTS.wheelZoomMaxStep }),\n});\n\n/** Pick radii + retarget dead-band live mirror (design-003 §3 L1 targeting). */\nexport const PointerSettings = defineResource(\"PointerSettings\", {\n radiusMousePx: field(\"f32\", { default: POINTER_DEFAULTS.radiusMousePx }),\n radiusTouchPx: field(\"f32\", { default: POINTER_DEFAULTS.radiusTouchPx }),\n radiusPenPx: field(\"f32\", { default: POINTER_DEFAULTS.radiusPenPx }),\n hoverReleaseDeadBandPx: field(\"f32\", { default: POINTER_DEFAULTS.hoverReleaseDeadBandPx }),\n});\n\n/** Zoom clamp live mirror (design-005 §4 `settings.zoom`; camera-sim consumes). */\nexport const CameraLimits = defineResource(\"CameraLimits\", {\n minZoom: field(\"f32\", { default: CAMERA_DEFAULTS.minZoom }),\n maxZoom: field(\"f32\", { default: CAMERA_DEFAULTS.maxZoom }),\n});\n\n/** Nav-transition spring response live mirror (design-006 §4; navFlight consumes). */\nexport const NavTransitionSettings = defineResource(\"NavTransitionSettings\", {\n responseMs: field(\"f32\", { default: NAV_TRANSITION_DEFAULTS.responseMs }),\n});\n","/**\n * Scene & geometry catalog (design-001 §5.1).\n *\n * Pure components — \"durable-eligible\" is a property of the prefab that carries\n * them, never of the component (design-001 §2, rev 2). `Position` is reused by\n * cursor/chrome/pointer-adjacent runtime prefabs; that reuse is the point.\n *\n * Defaults policy (see catalog/index.ts): essential geometry that a prefab\n * always supplies stays bare (required at spawn — Position/Size/StackZ). The\n * optional-eligible `Rotation` carries its identity default so an ad-hoc attach\n * is ergonomic.\n */\nimport { field } from \"@vibecook/strata-ecs\";\nimport { defineComponent, defineRelation, defineResource } from \"../schema/meta\";\n\n/** Frame-local position, world units. f64 — the infinite canvas loses integer precision in f32 past ~16.7M. */\nexport const Position = defineComponent(\"Position\", { x: \"f64\", y: \"f64\" });\n\n/** Widget size, world units. f32 — sizes never need f64's range. */\nexport const Size = defineComponent(\"Size\", { w: \"f32\", h: \"f32\" });\n\n/** Optional-eligible rotation, radians. Identity default so a bare attach is ergonomic. */\nexport const Rotation = defineComponent(\"Rotation\", { r: field(\"f32\", { default: 0 }) });\n\n/**\n * Optional-eligible widget opacity, 0..1 (design-004 §3: `{opacity}` is the\n * neutral composite's WHOLE per-widget fact). Reflected by the dom host\n * (style.opacity) and the gl composite quad (uOpacity) alike; absent = 1.\n * Identity default so a bare attach is ergonomic.\n */\nexport const Opacity = defineComponent(\"Opacity\", { a: field(\"f32\", { default: 1 }) });\n\n/**\n * LEGACY (petition 8, engineSchema 2): scalar stacking order, superseded by ordered `ChildOf`\n * sibling sequences. Stays REGISTERED so v1 docs' z cells keep projecting — the schema\n * migration sorts by them, and a v1 doc opened read-only still paints z-correct through the\n * renderers' legacy fallback. Never written for new entities; no new reader outside the\n * migration and the read-only sort fallback.\n */\nexport const StackZ = defineComponent(\"StackZ\", { z: \"f64\" });\n\n/**\n * child → parent frame (durable-eligible), ORDERED (petition 8): each parent's `getReverse` is\n * its children in SIBLING ORDER — paint/pick order within a frame IS this sequence (the\n * per-frame sibling-order law; design-004 §1 amendment). Placement rides\n * `setRelation(child, ChildOf, parent, place)` / `moveRelation`; order converges\n * collaboratively (CRDT movable list). Children-of-x = `Related(ChildOf, x)`; ancestor walk =\n * forward `getRelation`; engine cascade walks `getReverse(e, ChildOf)` (see ops/cascade.ts).\n */\nexport const ChildOf = defineRelation(\"ChildOf\", { arity: \"one\", ordered: true });\n\n/**\n * The BOARD ROOT (petition 8): the componentless durable entity every root-level widget hangs\n * its `ChildOf` edge on, so the root frame has a sibling sequence like any container. Minted\n * once per document (key recorded first-writer-wins in the meta map, `engine.boardRoot`);\n * componentless BY LAW — it must dodge every widget/pick/cull query. This RUNTIME resource\n * names it post-attach; absent = a pre-schema-2 read-only doc (renderers fall back to the\n * legacy StackZ sort).\n */\nexport const BoardRoot = defineResource(\"BoardRoot\", { root: \"eid\" });\n","/**\n * Node graph — wires, ports, and containment contracts (design-001 §5.3, §5.8).\n *\n * Wires bind to widgets + port *ids* (durable); port *entities* are runtime and\n * materialize on demand (never per-visible-widget). Wire geometry comes from the\n * kernel's pure `portAnchor(...)`, so rendering never reads a port entity and\n * culled endpoints resolve by construction (design-001 §5.3 decision).\n *\n * Defaults policy (see catalog/index.ts): identity/essential fields a wire or\n * derive system always supplies stay bare (WirePorts.from/to, Port.id/side).\n * Derive-owned anchors and the container JSON lists carry ergonomic defaults.\n */\nimport { enumOf, field } from \"@vibecook/strata-ecs\";\nimport { defineComponent, defineRelation, defineTag } from \"../schema/meta\";\nimport { definePrefab, init } from \"../schema/prefab\";\n\n// --- durable wire prefab: a reified edge entity (relations carry no data) ---\n\n/** Marks an entity as a wire. */\nexport const Wire = defineTag(\"Wire\");\n\n/** wire → source widget (durable-eligible). */\nexport const WireFrom = defineRelation(\"WireFrom\", { arity: \"one\" });\n\n/** wire → target widget (durable-eligible). */\nexport const WireTo = defineRelation(\"WireTo\", { arity: \"one\" });\n\n/** The port ids (from each widget's port schema) the wire binds to. */\nexport const WirePorts = defineComponent(\"WirePorts\", { from: \"string\", to: \"string\" });\n\n// --- runtime port prefab: materializes on demand, derive-owned ---\n\n/** A widget port descriptor — spawned only for interaction (connect tool / hover proximity). */\nexport const Port = defineComponent(\"Port\", {\n id: \"string\",\n side: enumOf([\"n\", \"e\", \"s\", \"w\"]),\n index: field(\"u8\", { default: 0 }),\n});\n\n/** port → widget. */\nexport const PortOf = defineRelation(\"PortOf\", { arity: \"one\" });\n\n/** Derive-owned world coordinates of a port anchor. */\nexport const PortAnchor = defineComponent(\"PortAnchor\", {\n x: field(\"f64\", { default: 0 }),\n y: field(\"f64\", { default: 0 }),\n});\n\n// --- containment contracts (durable-eligible on container widget prefabs, RFC-004) ---\n\n/** Marks a widget as a container (accepts children via the drop system). */\nexport const Container = defineTag(\"Container\");\n\n/** JSON list of provides-keys this container accepts. */\nexport const Accepts = defineComponent(\"Accepts\", { list: field(\"string\", { default: \"[]\" }) });\n\n/** JSON list of provides-keys this widget offers to containers. */\nexport const Provides = defineComponent(\"Provides\", { list: field(\"string\", { default: \"[]\" }) });\n\n/**\n * The durable wire prefab (design-001 §5.3): WirePorts + the Wire tag +\n * eligible WireFrom/WireTo edges — the COMPLETE contract, so the doc commit\n * sink spawns through the paved `tx.spawnPrefab` path instead of a raw spawn\n * that bypassed eligibility checks (2026-07-13 review). Registered here so the\n * version gate stamps `engine.pack.wire.<v>` like every durable pack.\n */\nexport const WirePrefab = definePrefab(\"wire\", {\n store: \"durable\",\n version: 1,\n components: [init(WirePorts, { from: \"\", to: \"\" })],\n tags: [Wire],\n relations: [WireFrom, WireTo],\n});\n","/**\n * Selection & presence (design-001 §5.6) + capability tags (design-001 §5.8).\n *\n * Selection is a runtime rider (`Selected`) — local truth, queried not stored,\n * restored on undo via history hooks. It is broadcast as an ephemeral presence\n * facet (`SelectionSummary` — a capped summary, not a key dump). Capability tags\n * are runtime, re-derived per peer from the prefab's interaction profile so pack\n * differences can never corrupt the document.\n *\n * Defaults policy (see catalog/index.ts): presence identity strings (name/color/\n * device) stay bare — they must be real; numeric summary/cursor fields carry zero\n * defaults, and `keys` an empty JSON list.\n */\nimport { enumOf, field } from \"@vibecook/strata-ecs\";\nimport { defineComponent, defineTag } from \"../schema/meta\";\n\n/** Runtime selection rider on widgets. */\nexport const Selected = defineTag(\"Selected\");\n\n// --- capability tags (runtime, stamped from the prefab interaction profile) ---\n\nexport const Selectable = defineTag(\"Selectable\");\nexport const Movable = defineTag(\"Movable\");\nexport const Resizable = defineTag(\"Resizable\");\nexport const SnapSource = defineTag(\"SnapSource\");\nexport const SnapTarget = defineTag(\"SnapTarget\");\n/**\n * Comment-box group drag (2026-07-18, James: the UE-Blueprint comment): a\n * move claim on this widget ALSO claims every widget fully inside its bounds\n * at claim time — spatial membership, never reparenting (that's the folder\n * path). Drag a member out and it simply stops being inside.\n */\nexport const SweepsContained = defineTag(\"SweepsContained\");\n/**\n * `interaction.keyboard: \"exclusive\"` (design-007 §3.1, petitions I1/I4): while\n * a node inside this widget holds browser focus, the engine's keyboard surfaces\n * (keymap shortcuts, the adapter's Space pan modifier) stand down. The ROUTING\n * truth is the DOM — the dom-widgets reflector writes a `data-canvas-keyboard`\n * marker on the widget host and the keymap/adapter read the event-target chain\n * against `document.activeElement`; this tag is the ECS-side mirror of the\n * declaration (queryable by devtools/presence), never a routing input.\n */\nexport const KeyboardExclusive = defineTag(\"KeyboardExclusive\");\n\n// --- ephemeral presence-peer prefab facets (components + tags only — no relations/resources) ---\n\n/**\n * Marks an ephemeral presence-peer entity (design-001 §5.6). Rides the presence\n * blob so remote peers project it — a peer query is `[PresencePeer, Not(Local)]`\n * (remote peers) or `[PresencePeer, Local]` (self). `Local` is strata-owned and\n * auto-applied by the ephemeral store on spawn (never transmitted); this is the\n * ONLY presence tag the engine mints, so pack differences can't corrupt it.\n */\nexport const PresencePeer = defineTag(\"PresencePeer\");\n\n/** Peer display identity. */\nexport const PresenceInfo = defineComponent(\"PresenceInfo\", { name: \"string\", color: \"string\" });\n\n/** Peer cursor in world coords. */\nexport const PresenceCursor = defineComponent(\"PresenceCursor\", {\n x: field(\"f64\", { default: 0 }),\n y: field(\"f64\", { default: 0 }),\n device: enumOf([\"mouse\", \"touch\", \"pen\"]),\n});\n\n/**\n * Selection broadcast: count + combined bbox + a JSON key list capped at 32 (peers outline the\n * listed widgets; beyond the cap they render the bbox only). Facet semantics: present only while the\n * selection is non-empty.\n */\nexport const SelectionSummary = defineComponent(\"SelectionSummary\", {\n count: field(\"u16\", { default: 0 }),\n x: field(\"f64\", { default: 0 }),\n y: field(\"f64\", { default: 0 }),\n w: field(\"f32\", { default: 0 }),\n h: field(\"f32\", { default: 0 }),\n keys: field(\"string\", { default: \"[]\" }),\n});\n","/**\n * PhaseSet — an exclusive tag-encoded state machine with one-tick transition markers\n * (design-003 §4.2, design-002 §2/§3).\n *\n * A phase set is a small, fixed list of mutually-exclusive phases (e.g. a recognizer's\n * `Possible → Active → Ended`). For each phase it mints two tags via the schema wrapper,\n * named by PLAIN CONCATENATION so the doc vocabulary holds (design-001 §5.5: the catalog's\n * gesture set is definePhaseSet(\"Gesture\", [\"Possible\", …]) → \"GesturePossible\"):\n * - a persistent phase tag `${name}${phase}` — \"the entity is in this phase\"\n * - a one-tick `Just` marker `${name}Just${phase}` — \"the entity ENTERED this phase this frame\"\n *\n * Why two tags: terminal phases persist through the reap window (design-003 §4.1), so a\n * behavior that acted on the persistent tag would fire on every frame the tag lingers.\n * Behaviors therefore **edge-trigger on the `Just*` markers only** — discrete actions and\n * terminal handling fire exactly once (design-003 §4.2: shift-tap toggles once, commits\n * never double). The persistent tag is for per-frame work that legitimately repeats.\n *\n * Transition timing: `set` mutates through the caller's structural writer. When that writer\n * is a {@link SystemCtx} the add/remove are DEFERRED to the current strata-phase flush\n * (design-002 §3); consumers in a LATER sub-phase see the new phase the same frame, and\n * that ordering is guaranteed by the sub-phase pipeline layout (design-002 §2), never by\n * immediate application. When the writer is the `World` (app handlers / setup) the writes\n * are immediate. The one-tick markers are cleared by the cleanup phase via\n * {@link PhaseSet.clearMarkers} over {@link PhaseSet.allMarkerTags}.\n */\n\nimport type { Entity, Tag } from \"@vibecook/strata-ecs\";\nimport { devGuardsEnabled } from \"../guards/dev\";\nimport { defineTag } from \"../schema/meta\";\n\n/**\n * The minimal structural-write surface `set`/`clearMarkers` need. Both `SystemCtx` (deferred\n * to the phase flush) and `World` (immediate) satisfy it structurally — the transition is\n * agnostic to which, and the timing follows from the writer (see the module doc).\n */\nexport interface StructuralTagWriter {\n addTag(e: Entity, t: Tag): void;\n removeTag(e: Entity, t: Tag): void;\n}\n\n/** The minimal read surface `current` needs — again satisfied by both `SystemCtx` and `World`. */\nexport interface TagReader {\n hasTag(e: Entity, t: Tag): boolean;\n}\n\n/** The handle returned by {@link definePhaseSet}. `P` is the literal union of phase names. */\nexport interface PhaseSet<P extends string> {\n /** The set name — the prefix of every minted tag. */\n readonly name: string;\n /** The phases in declaration order (the scan order of {@link PhaseSet.current}). */\n readonly phases: readonly P[];\n /** Persistent phase tags, keyed by phase name. */\n readonly tags: Readonly<Record<P, Tag>>;\n /** One-tick `Just<Phase>` marker tags, keyed by phase name. */\n readonly justTags: Readonly<Record<P, Tag>>;\n /** Every marker tag — the cleanup phase clears these once the frame's edges are consumed. */\n readonly allMarkerTags: readonly Tag[];\n /**\n * Transition `e` into `next`: drop the current phase tag + its now-stale marker and add\n * `next` + its fresh `Just` marker (exclusivity is enforced by clearing every phase tag,\n * so a mis-set entity converges). Unknown `next` throws. A transition to the phase the\n * entity is already in is a no-op with a DEV warn (detected only when `m` can also read —\n * `SystemCtx`/`World` both can).\n */\n set(m: StructuralTagWriter, e: Entity, next: P): void;\n /** The entity's current phase, or `undefined` if it holds none. Small-N `hasTag` scan. */\n current(world: TagReader, e: Entity): P | undefined;\n /** Clear every one-tick marker off `e` (the cleanup-phase step). */\n clearMarkers(m: StructuralTagWriter, e: Entity): void;\n}\n\n/** Narrow a structural writer that also happens to read (for the DEV double-set guard). */\nfunction hasReader(m: object): m is TagReader {\n return \"hasTag\" in m && typeof (m as TagReader).hasTag === \"function\";\n}\n\n/**\n * Define an exclusive PhaseSet: one persistent tag + one one-tick `Just` marker per phase.\n * Handles are process-global schema constants (hold them as module constants). See the module\n * doc for transition timing and the edge-trigger contract.\n */\nexport function definePhaseSet<const P extends string>(name: string, phases: readonly P[]): PhaseSet<P> {\n const tags = {} as Record<P, Tag>;\n const justTags = {} as Record<P, Tag>;\n const allMarkerTags: Tag[] = [];\n for (const phase of phases) {\n tags[phase] = defineTag(`${name}${phase}`);\n const marker = defineTag(`${name}Just${phase}`);\n justTags[phase] = marker;\n allMarkerTags.push(marker);\n }\n\n const set: PhaseSet<P>[\"set\"] = (m, e, next) => {\n const nextTag = tags[next];\n if (nextTag === undefined) {\n throw new Error(\n `ice: definePhaseSet(\"${name}\").set — unknown phase \"${next}\" (known: ${phases.join(\", \")}).`,\n );\n }\n if (devGuardsEnabled() && hasReader(m) && m.hasTag(e, nextTag)) {\n // Already in `next` — the transition is a no-op. Warn and skip so the fresh marker\n // is not re-emitted (which would edge-trigger downstream behaviors a second time).\n // BEST-EFFORT detection only: a SystemCtx's hasTag reads pre-flush state, so a\n // deferred same-body double-set is invisible here. That miss is harmless — the\n // clear-then-add below is idempotent and tags dedupe, so the marker still fires\n // exactly once. Reliable detection holds for immediate writers (World).\n console.warn(`ice: definePhaseSet(\"${name}\").set — entity is already in phase \"${next}\"; no-op.`);\n return;\n }\n // Exclusivity: clear every phase tag + every marker (no-op for absent ones), then set\n // `next` + its marker. This subsumes \"remove the current phase + its stale marker\" and\n // converges a mis-set entity to exactly one phase.\n for (const phase of phases) {\n m.removeTag(e, tags[phase]);\n m.removeTag(e, justTags[phase]);\n }\n m.addTag(e, nextTag);\n m.addTag(e, justTags[next]);\n };\n\n const current: PhaseSet<P>[\"current\"] = (world, e) => {\n for (const phase of phases) {\n if (world.hasTag(e, tags[phase])) return phase;\n }\n return undefined;\n };\n\n const clearMarkers: PhaseSet<P>[\"clearMarkers\"] = (m, e) => {\n for (const marker of allMarkerTags) m.removeTag(e, marker);\n };\n\n return { name, phases, tags, justTags, allMarkerTags, set, current, clearMarkers };\n}\n","/**\n * Recognizers & gestures — the L2 runtime recognizer prefabs (design-001 §5.5,\n * design-003 §4).\n *\n * Identity is the KIND component (its presence is the kind; its fields are the\n * working value). Phase is a tag-of-set flipped by the engine PhaseSet helper\n * (strata has no one-of primitive; `Pending` was dropped as dead machinery). All\n * in-flight state lives on the recognizer entity or the grabbed widgets — no\n * singleton trackers — so N concurrent same-kind gestures are structural.\n *\n * Field set for each kind matches design-003 §4.2's revised table (which adds\n * `zoomAtClaim` to Drag and Pinch over design-001 §5.5).\n *\n * Defaults policy (see catalog/index.ts): kind components and per-frame working\n * riders are runtime scratch spawned/written by systems, so they carry full\n * zero/identity defaults (ergonomic `ctx.spawn`). Origin-latch riders that MUST\n * carry real values (Grab, Down) stay bare so a defaulted origin can't silently\n * corrupt a cancel-restore.\n */\nimport { enumOf, field, type Entity } from \"@vibecook/strata-ecs\";\nimport { definePhaseSet } from \"../helpers/phase-set\";\nimport { defineComponent, defineRelation, defineTag } from \"../schema/meta\";\nimport { GESTURE_DEFAULTS } from \"../settings/defaults\";\n\n// --- kind components (design-003 §4.2) ---\n\n/** Continuous drag. Origin from dead-zone exit; totals/velocities accumulate; `zoomAtClaim` anchors widget-move math. */\nexport const Drag = defineComponent(\"Drag\", {\n startX: field(\"f64\", { default: 0 }),\n startY: field(\"f64\", { default: 0 }),\n totalX: field(\"f32\", { default: 0 }),\n totalY: field(\"f32\", { default: 0 }),\n velX: field(\"f32\", { default: 0 }),\n velY: field(\"f32\", { default: 0 }),\n zoomAtClaim: field(\"f32\", { default: 1 }),\n});\n\n/**\n * Discrete tap — claims at up within the tap window & slop. `count` is the\n * multi-tap tally (v2 gesture.ts): 0 while the (next) tap is in progress; each\n * clean release increments it. Without a `MultiTap` opt-in on the capture\n * target the first release Recognizes at count 1 — zero added latency.\n */\nexport const Tap = defineComponent(\"Tap\", {\n downAt: field(\"f64\", { default: 0 }),\n count: field(\"u32\", { default: 0 }),\n});\n\n/** Discrete-with-tail: claims at the long-press hold, then tracks cur X/Y per frame (touch marquee rides it). */\nexport const LongPress = defineComponent(\"LongPress\", {\n downAt: field(\"f64\", { default: 0 }),\n startX: field(\"f64\", { default: 0 }),\n startY: field(\"f64\", { default: 0 }),\n curX: field(\"f64\", { default: 0 }),\n curY: field(\"f64\", { default: 0 }),\n});\n\n/** Continuous two-finger pinch. `startDist` re-baselines at activation; `cx/cy` is the centroid. */\nexport const Pinch = defineComponent(\"Pinch\", {\n startDist: field(\"f32\", { default: 0 }),\n startZoom: field(\"f32\", { default: 1 }),\n cx: field(\"f64\", { default: 0 }),\n cy: field(\"f64\", { default: 0 }),\n zoomAtClaim: field(\"f32\", { default: 1 }),\n});\n\n/** Continuous wheel pan (`Simultaneous` — never claims pointers). `anchorX/Y` is the screen anchor. */\nexport const WheelPan = defineComponent(\"WheelPan\", {\n dx: field(\"f32\", { default: 0 }),\n dy: field(\"f32\", { default: 0 }),\n anchorX: field(\"f32\", { default: 0 }),\n anchorY: field(\"f32\", { default: 0 }),\n});\n\n/** Continuous wheel zoom (`Simultaneous`). `pinch` is the accumulated zoom signal; `anchorX/Y` the pin point. */\nexport const WheelZoom = defineComponent(\"WheelZoom\", {\n pinch: field(\"f32\", { default: 0 }),\n anchorX: field(\"f32\", { default: 0 }),\n anchorY: field(\"f32\", { default: 0 }),\n});\n\n// --- phases (exclusive set + one-tick Just* markers; flipped via the PhaseSet helper) ---\n\n/**\n * The recognizer lifecycle as ONE PhaseSet (design-003 §4.2): seven mutually-exclusive\n * phases. Each mints a persistent `Gesture<Phase>` tag AND a one-tick `GestureJust<Phase>`\n * marker (plain concatenation — the doc vocabulary \"GesturePossible\"… is unchanged), so\n * behaviors edge-trigger discrete/terminal actions on the markers exactly once while a\n * terminal tag lingers through the reap window (§4.2, §4.1). The named phase tags below\n * are re-exports of `GesturePhases.tags.*` for ergonomics + `ops/claims` compatibility.\n * `GesturePossible` etc. is the ONLY definition path for these tag names (strata's schema\n * registry is process-global — a second `defineTag(\"GesturePossible\")` would throw).\n *\n * `Pending` (restored from v2 gesture.ts — the design-003 §4.2 \"dead machinery\" drop is\n * superseded now that a real gesture ships it): criteria met but recognition withheld —\n * a multi-tap awaiting its inter-tap window, or a recognizer parked behind a\n * `Sequence`/`RequiresFail` edge. NEVER reaped; exempt from integrity's watched-pointer\n * count (a pending multi-tap legitimately outlives its lifted touch pointer).\n */\nexport const GesturePhases = definePhaseSet(\"Gesture\", [\n \"Possible\",\n \"Active\",\n \"Pending\",\n \"Recognized\",\n \"Ended\",\n \"Failed\",\n \"Cancelled\",\n] as const);\n\n/** Recognizer alive, not yet claiming. */\nexport const GesturePossible = GesturePhases.tags.Possible;\n\n/** Continuous kinds' claiming phase + per-frame work gate. */\nexport const GestureActive = GesturePhases.tags.Active;\n\n/** Recognition withheld (multi-tap window / dependency edge); never reaped. */\nexport const GesturePending = GesturePhases.tags.Pending;\n\n/** Discrete kinds' terminal claim. */\nexport const GestureRecognized = GesturePhases.tags.Recognized;\n\n/** Continuous kinds' terminal (release). */\nexport const GestureEnded = GesturePhases.tags.Ended;\n\n/** Recognizer failed its predicate or lost arbitration. */\nexport const GestureFailed = GesturePhases.tags.Failed;\n\n/** Recognizer cancelled (pointercancel / integrity / CancelRequest). */\nexport const GestureCancelled = GesturePhases.tags.Cancelled;\n\n/** Suspended (a pinch suspends the single-pointer recognizers) — \"suspend, don't kill\". */\nexport const GestureSuspended = defineTag(\"GestureSuspended\");\n\n/**\n * The recognizer latched a `Captures` target at spawn (design-003 §4.1 integrity).\n * Relations auto-clear on target despawn, so \"had a capture, has none now\" is\n * detectable only with this spawn-time mark — integrity cancels on that edge loss.\n */\nexport const HadCapture = defineTag(\"HadCapture\");\n\n/** Runs alongside claims without competing (wheel pan/zoom) — keeps zoom-while-dragging legal. */\nexport const Simultaneous = defineTag(\"Simultaneous\");\n\n// --- route tags (latched at drag activation; never change mid-gesture, design-003 §4.4) ---\n\nexport const RoutedMove = defineTag(\"RoutedMove\");\nexport const RoutedResize = defineTag(\"RoutedResize\");\nexport const RoutedConnect = defineTag(\"RoutedConnect\");\nexport const RoutedMarquee = defineTag(\"RoutedMarquee\");\nexport const RoutedPan = defineTag(\"RoutedPan\");\n/** Draw-tool drag: the release rect creates a widget (design-005 §3, M10). */\nexport const RoutedDraw = defineTag(\"RoutedDraw\");\n\n/**\n * Per-target multi-tap opt-in (v2 gesture.ts): declares \"this target counts\n * multi-taps\", read via the recognizer's `Captures` target. Absent → max 1,\n * zero latency (a plain widget stays instant). `windowMs` = the inter-tap\n * wait; `slopPx` = max screen gap between taps for the rejoin.\n */\nexport const MultiTap = defineComponent(\"MultiTap\", {\n max: field(\"u32\", { default: 2 }),\n windowMs: field(\"f32\", { default: GESTURE_DEFAULTS.multiTapWindowMs }),\n slopPx: field(\"f32\", { default: GESTURE_DEFAULTS.multiTapSlopPx }),\n});\n\n// --- recognizer relations ---\n\n/** recognizer → watched pointer(s). */\nexport const Watches = defineRelation(\"Watches\", { arity: \"many\" });\n\n/**\n * Sequencing edges (v2 gesture.ts; resolved by the dependency system at the end\n * of `ctl:recognize`). `Sequence` gates the ENTRANCE: a `Pending` recognizer\n * waits for `after` to pass (Active/Recognized), then hands off — Down rebases\n * to the current pointer and the source retires. `RequiresFail` gates the EXIT:\n * a `Pending` recognizer finishes only once `other` fails (discrete →\n * Recognized, continuous → Active); if `other` wins, it loses. Edges auto-clear\n * on despawn, so each carries a `Had*` spawn-time mark (the `HadCapture`\n * pattern): \"had an edge, has none\" = orphaned → Failed.\n */\nexport const Sequence = defineRelation(\"Sequence\", { arity: \"one\" });\nexport const RequiresFail = defineRelation(\"RequiresFail\", { arity: \"one\" });\n\n/** The recognizer was given a `Sequence` edge (orphan detection — see above). */\nexport const HadSequence = defineTag(\"HadSequence\");\n\n/** The recognizer was given a `RequiresFail` edge (orphan detection — see above). */\nexport const HadRequiresFail = defineTag(\"HadRequiresFail\");\n\n/** recognizer → grabbed entity (widget/port/handle/canvas), latched at down. */\nexport const Captures = defineRelation(\"Captures\", { arity: \"one\" });\n\n/** recognizer → affected widgets (live edge set; remote despawns auto-clear their edge). */\nexport const Drags = defineRelation(\"Drags\", { arity: \"many\" });\n\n/** pointer → the recognizer that claimed it (arbitration output, design-003 §4.3). */\nexport const ClaimedBy = defineRelation(\"ClaimedBy\", { arity: \"one\" });\n\n/** recognizer → candidate container under the dragged bounds (design-003 §5 dropSystem). */\nexport const DropTarget = defineRelation(\"DropTarget\", { arity: \"one\" });\n\n// --- per-gesture riders ---\n\n/**\n * \"None\" sentinel for Grab's eid fields — strata's reserved null handle\n * (entity 0 is never live; generations start at 1).\n */\nexport const NO_ENTITY = 0 as Entity;\n\n/**\n * Per-dragged-widget origin, attached at claim time with the CURRENT transform embedded\n * (design-001 §3, design-003 §4.5). Bare on purpose: a defaulted zero origin would corrupt\n * the cancel-restore of Position and sibling order.\n *\n * `parent`/`prev`/`ord` are the ORDER MEMO (petition 8) — the claim-time\n * elevate is `moveRelation(w, ChildOf, \"last\")`, so cancel/fly-back must\n * remember where the widget SAT: its `ChildOf` parent (NO_ENTITY = no edge —\n * legacy world, nothing to restore), its nearest non-dragged predecessor\n * sibling (NO_ENTITY = it was first), and its original sibling index (`ord` —\n * the members' relative order at reinsert; see l3-behave's restore walk).\n */\nexport const Grab = defineComponent(\"Grab\", {\n x: \"f64\",\n y: \"f64\",\n w: \"f32\",\n h: \"f32\",\n parent: \"eid\",\n prev: \"eid\",\n ord: \"f64\",\n});\n\n/** Snap offset — in the Drag prefab's essential set (present from spawn, zeroed — writers never race an attach). */\nexport const SnapState = defineComponent(\"SnapState\", {\n dx: field(\"f32\", { default: 0 }),\n dy: field(\"f32\", { default: 0 }),\n});\n\n/**\n * The down point + timestamp latched on the recognizer at spawn (design-003 §4.1). Bare: it must\n * carry the real down sample.\n */\nexport const Down = defineComponent(\"Down\", { x: \"f64\", y: \"f64\", ms: \"f64\" });\n\n/** On widgets, toggled O(1) when the drop candidate changes (design-001 §5.5). */\nexport const OverlapCandidate = defineTag(\"OverlapCandidate\");\n\n/**\n * Capability: a SOLID widget is a drop-REJECTING target — dragging another\n * widget onto it and releasing flies the dragged set back (v1's iOS-card\n * overlap contract, field report 2026-07-12). Opt-in via `defineWidget`\n * `interaction.solid`; free-overlap apps (moodboard) never equip it.\n */\nexport const Solid = defineTag(\"Solid\");\n\n/**\n * Capability: this widget's drag starts on LONG-PRESS (the iOS home-screen\n * model — hold to lift, then move; taps and widget-internal interactions stay\n * instant). Opt-in via `defineWidget` `interaction.dragOn: \"longPress\"`.\n * Mechanically: `recognizerSpawn` parks the widget's Drag recognizer\n * `Pending` behind a `Sequence` edge to the same pointer's LongPress — the\n * restored Pending machinery's hand-off does the rest (design-003 §4.2\n * amendment; first production wiring, 2026-07-12).\n */\nexport const LongPressDrag = defineTag(\"LongPressDrag\");\n\n/**\n * On a hovered Solid widget (or a mismatched container) while a drag's bounds\n * overlap it: the REJECT half of the drop signal pair (OverlapCandidate is the\n * accept half) — chrome renders the weak \"won't take it\" glow. Change-only,\n * cleared on move-off and on every move terminal.\n */\nexport const OverlapRejected = defineTag(\"OverlapRejected\");\n\n/**\n * Fly-back tween easing Position → target (design-003 §5 move outcome; design-001 §3 amends the\n * per-cell guard so a live tween IS the diverging authority until reconvergence).\n *\n * Minimal shape not spelled out field-by-field in design-001 §5: the target (`toX/toY`) and\n * `durationMs` are supplied at attach (bare); `elapsedMs` starts at 0 and the tween system advances\n * it, removing the component on arrival.\n */\nexport const TransformTween = defineComponent(\"TransformTween\", {\n toX: \"f64\",\n toY: \"f64\",\n durationMs: \"f32\",\n elapsedMs: field(\"f32\", { default: 0 }),\n});\n","/**\n * `defineBehavior` — the type surface (design-009 §3–§4, the pinned API).\n *\n * ICE's userland surface is a triad: `defineWidget` (faces) · **behaviors**\n * (logic + state) · `defineTool` (input policy). A behavior is the A-Frame-class\n * unit — ONE named declaration carrying a data schema, a REQUIRED store class,\n * and lifecycle hooks the engine runs on a curated phase set.\n *\n * `store:` is the load-bearing word: it routes where data lives, who sees it,\n * what survives, WHICH WRITE VOCABULARY the hooks receive, at which cadence.\n * That last routing is the reason the ctx types below are three interfaces and\n * not one with optional members — a durable behavior must not see `ctx.write`\n * in autocomplete at all, or \"store routes everything\" is a doc claim rather\n * than a property of the product.\n */\nimport type { Component, Entity, Relation, Resource, Tag } from \"@vibecook/strata-ecs\";\nimport type { GuardedTx } from \"../guards/guarded-tx\";\nimport type {\n BooleanSpec,\n EntityKeySpec,\n EnumSpec,\n JsonSpec,\n NumberSpec,\n PropSpec,\n StringSpec,\n} from \"../widget/props\";\n\n// --- store class + phases ----------------------------------------------------\n\nexport type BehaviorStore = \"durable\" | \"runtime\" | \"ephemeral\";\n\n/**\n * The CURATED phase set (design-009 §4.4, BF-D8) — a deliberate subset of the\n * eleven pipeline groups. Authors get the four that mean something to logic;\n * the control sweep (`ctl:*`), `input`, `react` and `cleanup` stay engine\n * vocabulary. `publish` is not a pipeline group at all — it is the post-tick\n * slot where ephemeral mutation is legal.\n */\nexport type BehaviorPhase = \"simulate\" | \"derive\" | \"present\" | \"publish\";\n\n/** Legal `phase` per store class — the §4.1 validation table, as data. */\nexport const BEHAVIOR_PHASES: Readonly<Record<BehaviorStore, readonly BehaviorPhase[]>> = {\n // Durable is derive-ONLY and the reason is stated: its sole write path is\n // transactional, and `derive` is the settled-input phase — the one place a\n // commit reads inputs that will not move again this frame.\n durable: [\"derive\"],\n runtime: [\"simulate\", \"derive\", \"present\", \"publish\"],\n ephemeral: [\"publish\"],\n};\n\n/** Default phase per store (the one most declarations want). */\nexport const BEHAVIOR_DEFAULT_PHASE: Readonly<Record<BehaviorStore, BehaviorPhase>> = {\n durable: \"derive\",\n runtime: \"simulate\",\n ephemeral: \"publish\",\n};\n\n// --- schema → data typing ----------------------------------------------------\n\n/** A behavior's declared data: the SAME `p.*` DSL `defineWidget` uses. */\nexport type BehaviorSchema = Readonly<Record<string, PropSpec>>;\n\ntype ValueOfSpec<S extends PropSpec> = S extends NumberSpec\n ? number\n : S extends BooleanSpec\n ? boolean\n : S extends EnumSpec\n ? string\n : S extends JsonSpec\n ? unknown\n : S extends StringSpec | EntityKeySpec\n ? string\n : never;\n\n/**\n * The hook-facing data view. `p.json` fields arrive PARSED (the cell is a\n * string; the snapshot carries the value) — parsing happens once per delivery,\n * and delivery only runs on change, so the cost is keyed to churn rather than\n * to frame rate. `ctx.write`/`tx.write` serialize back.\n */\nexport type DataOf<Sch extends BehaviorSchema> = { readonly [K in keyof Sch]: ValueOfSpec<Sch[K]> };\n\n// --- reads ------------------------------------------------------------------\n\n/**\n * Anything a behavior may declare in `reads:` — components, tags, relations,\n * resources, or another behavior (its data component). Each kind is routed to\n * a different change mechanism by the compiler (§5.2), which is why the\n * partition is compiler work and not an author concern.\n */\nexport type BehaviorRead = Component | Tag | Relation | Resource | AnyBehaviorDef;\n\n/** The drained journal summary, valid only for the duration of the hook call. */\nexport interface BehaviorChanges {\n /** Rebuild everything: first run, `world.reset()`, coarse writes, or a poll fired. */\n readonly full: boolean;\n /** Journaled entities — re-read current state to act. */\n readonly changed: readonly Entity[];\n /** DESTROYED entities (packed handles; safe as removal keys). */\n readonly removed: readonly Entity[];\n}\n\n// --- the world wrapper -------------------------------------------------------\n\n/**\n * `ctx.world` is a HOST-BUILT WRAPPER, not a `World` alias and not\n * `ReadonlyWorld` (BF-D19): that type is `Omit<World, WorldMutatorName>`, which\n * keeps `.runtime` — the full mutable store — so it is a naming convention, not\n * a sandbox. This interface exposes exactly the read surface and nothing else.\n *\n * Honesty note: point reads through this wrapper are ATTRIBUTION-ONLY — strata\n * enforces declared reads solely at `batch.col()`, so the compiled delivery\n * walk (`ctx.query`) is where enforcement is real.\n */\nexport interface BehaviorWorld {\n read<S>(e: Entity, c: Component<S>): S;\n get<S>(e: Entity, c: Component<S>): S | undefined;\n readField<S, K extends keyof S & string>(e: Entity, c: Component<S>, field: K): S[K] | undefined;\n has(e: Entity, c: Component): boolean;\n hasTag(e: Entity, t: Tag): boolean;\n getRelation(e: Entity, r: Relation): Entity | undefined;\n getRelations(e: Entity, r: Relation): Entity[];\n getReverse(e: Entity, r: Relation): Entity[];\n /** Sibling-sequence version for one parent — ordered relations (petition 8). */\n orderStamp(parent: Entity, r: Relation): number;\n getResource<S>(res: Resource<S>): S | undefined;\n componentsOf(e: Entity): readonly Component[];\n tagsOf(e: Entity): readonly Tag[];\n isAlive(e: Entity): boolean;\n}\n\n/** A reads-scoped query walk. Terms are restricted to the behavior's `reads`. */\nexport interface BehaviorQuery {\n /** Every matching entity. The array is FRESH per call — retaining it is legal. */\n entities(): Entity[];\n /** Iterate matches one at a time (no array allocated). */\n each(fn: (e: Entity) => void): void;\n /** First match, or undefined. */\n first(): Entity | undefined;\n}\n\n/** Query terms a behavior may build — its declared reads, positively or negatively. */\nexport interface BehaviorQuerySpec {\n /** Entities must carry ALL of these (components/tags from `reads`). */\n readonly all?: readonly (Component | Tag | AnyBehaviorDef)[];\n /** Entities must carry NONE of these. */\n readonly none?: readonly (Component | Tag | AnyBehaviorDef)[];\n}\n\n// --- ctx --------------------------------------------------------------------\n\n/** Frame facts a `tick` hook reads. */\nexport interface BehaviorFrame {\n readonly dtMs: number;\n readonly tick: number;\n /** Accumulated CLAMPED dt — under-reports across freezes; never wall time. */\n readonly clock: number;\n}\n\n/** One remote peer's facet of an ephemeral behavior (`ctx.peers()`). */\nexport interface PeerFacet<Data> {\n /** The remote presence-peer entity (runtime handle — do not persist). */\n readonly entity: Entity;\n readonly data: Readonly<Data>;\n}\n\nexport interface BehaviorCtxBase<Data> {\n /** The read wrapper (above). */\n readonly world: BehaviorWorld;\n /**\n * A reads-SCOPED query. The framework compiles and caches one Query per\n * distinct spec and walks it ATTRIBUTED — strata's only enforced read path,\n * and its only zero-allocation bulk path. Without this, navigation was\n * instances-outward only and `changed` got abused as a discovery channel.\n *\n * The navigation model, stated: behaviors navigate from their instances\n * outward via relations, the change journal, and reads-scoped queries. There\n * is no global search.\n */\n query(spec: BehaviorQuerySpec): BehaviorQuery;\n /** This behavior's own instances, this frame (snapshot — do not retain). */\n entities(): readonly Entity[];\n /** The drained journal summary. Meaningful during `changed`; do not retain. */\n changes(): BehaviorChanges;\n /** The journal ∩ this behavior's instances — the exact set. Do not retain. */\n changedEntities(): readonly Entity[];\n /** Durable doc key for an entity (undefined when not doc-bound). */\n keyOf(e: Entity): string | undefined;\n /** The entity for a durable key — undefined while it is not yet projected. */\n entityFor(key: string): Entity | undefined;\n /** Aborts at generation teardown (`world.reset`), detach, or engine dispose. */\n readonly signal: AbortSignal;\n /** Namespaced logging — routed to the host's diagnostics, never raw console. */\n log(message: string, ...rest: readonly unknown[]): void;\n}\n\nexport interface DurableBehaviorCtx<Data> extends BehaviorCtxBase<Data> {\n /**\n * ONE labeled transaction. The transaction opens INSIDE the hook, in-system\n * (design-002-blessed): values land synchronously and this frame's `notify`\n * sees them — never queued past the tick. `label` is a stable MACHINE id\n * (namespaced), never display text: it feeds undo and in-CRDT provenance.\n *\n * Refuses on a read-only document. `tx.setResource` is MASKED (the §9\n * resource-write fence, made mechanical) — a behavior calling it DEV-throws\n * naming the `singleton` v1.1 seam.\n */\n commit(label: string, fn: (tx: BehaviorTx<Data>) => void, opts?: { undoable?: boolean }): void;\n}\n\nexport interface RuntimeBehaviorCtx<Data> extends BehaviorCtxBase<Data> {\n /** Write this behavior's OWN data on `e` (immediate; session-local). */\n write(e: Entity, patch: Partial<Data>): void;\n /** Write a declared runtime-store `writes:` target (immediate). */\n set<S>(e: Entity, c: Component<S>, v: S): void;\n attach(e: Entity, data?: Partial<Data>): void;\n detach(e: Entity): void;\n /** A runtime behavior may also commit durable state (a settle writing finals once). */\n commit(label: string, fn: (tx: BehaviorTx<Data>) => void, opts?: { undoable?: boolean }): void;\n}\n\nexport interface EphemeralBehaviorCtx<Data> extends BehaviorCtxBase<Data> {\n /**\n * Publish THIS PEER's facet. No entity argument — the instance IS the local\n * presence peer, and there is exactly one. Legal here because ephemeral hooks\n * run at the publish slot, post-tick, where eph mutation is allowed.\n */\n write(patch: Partial<Data>): void;\n /** REMOTE peers' facets of this behavior (read-only; `Not(Local)` projections). */\n peers(): readonly PeerFacet<Data>[];\n}\n\nexport type BehaviorCtxFor<S extends BehaviorStore, Data> = S extends \"durable\"\n ? DurableBehaviorCtx<Data>\n : S extends \"runtime\"\n ? RuntimeBehaviorCtx<Data>\n : EphemeralBehaviorCtx<Data>;\n\n/**\n * The door's transaction: `GuardedTx` plus behavior attachment and typed\n * own-data writes. `setResource` is absent by construction (§4.4's mask).\n */\nexport interface BehaviorTx<Data> extends Omit<GuardedTx, \"setResource\"> {\n /** Write this behavior's own data on `e` (absolute, whole-value). */\n write(e: Entity, patch: Partial<Data>): void;\n /** Attach a behavior as a DOCUMENT op — syncs, undoes, runs on every peer. */\n attach<D>(e: Entity, behavior: BehaviorHandle<D>, data?: Partial<D>): void;\n detach(e: Entity, behavior: AnyBehaviorDef): void;\n}\n\n// --- hooks -------------------------------------------------------------------\n\nexport interface BehaviorHooks<S extends BehaviorStore, Data> {\n /**\n * Instance appeared: attached locally, projected in (REMOTE included), or\n * existing at generation start. Runs before that instance's first `tick`.\n * A throw here marks the INSTANCE failed — no further hooks until re-attach.\n */\n init?(e: Entity, data: Readonly<Data>, ctx: BehaviorCtxFor<S, Data>): void;\n /**\n * OWN declared data changed since the last delivery — by ANY writer: this\n * behavior's commit, another plugin's tx, UNDO, or a remote peer.\n * Per-instance; `prev` is the last-delivered snapshot. \"update is about you.\"\n */\n update?(e: Entity, data: Readonly<Data>, prev: Readonly<Data>, ctx: BehaviorCtxFor<S, Data>): void;\n /**\n * The reads-set changed. ONCE PER BEHAVIOR per frame, not per instance —\n * N instances × one tag flip must not mean N journal scans.\n * \"changed is about the world.\"\n */\n changed?(ctx: BehaviorCtxFor<S, Data>): void;\n /**\n * Per frame per instance — OPT-IN cost. Default is ALL instances (Law 14: an\n * off-screen spring still settles); `tick: { while: \"visible\" }` is the\n * author's DECLARED suspension. `init`/`update`/`changed`/`dispose` never\n * suspend: culling is not lifecycle, and state must be right the moment it\n * becomes visible again.\n */\n tick?(e: Entity, data: Readonly<Data>, frame: BehaviorFrame, ctx: BehaviorCtxFor<S, Data>): void;\n /**\n * Instance gone: detached, despawned, disabled, or generation end. `e` may\n * already be dead (world access is DEV-guarded) — this is for cache cleanup.\n * Runs for ALL instances BEFORE `ctx.signal` aborts.\n */\n dispose?(e: Entity, ctx: BehaviorCtxFor<S, Data>): void;\n}\n\n// --- the declaration ---------------------------------------------------------\n\nexport interface BehaviorSpec<S extends BehaviorStore, Sch extends BehaviorSchema> {\n /** REQUIRED — routes everything (§3). */\n readonly store: S;\n /**\n * This behavior's durable writes are COMPUTED from other state. Durable only.\n * Bundles three protections: non-undoable output, the differ, and\n * claim-scoped delivery suppression (§5.3).\n */\n readonly derived?: boolean;\n /**\n * Opt out of suppression: derive live during gestures (costs accepted).\n * `derived` only.\n */\n readonly deriveDuringGesture?: boolean;\n /** Durable only — the `engine.behavior.<name>.<v>` marker family (§5.6). */\n readonly version?: number;\n readonly schema?: Sch;\n /** Durable only: fromVersion → idempotent absolute transform. */\n readonly migrate?: Readonly<Record<number, (prev: Record<string, unknown>) => Record<string, unknown>>>;\n /** Defaults per store (§4.4); validated against the legal set. */\n readonly phase?: BehaviorPhase;\n /** Per-frame budget request, ms. The breaker caps it at the seam ceiling. */\n readonly budgetMs?: number;\n readonly reads?: readonly BehaviorRead[];\n readonly writes?: readonly Component[];\n /**\n * `tick` scope. `{ while: \"visible\" }` compiles a `Not(Culled)` term into the\n * chunked tick system — declared suspension, never discovered.\n */\n readonly tick?: { readonly while?: \"visible\" | \"all\" };\n readonly on?: BehaviorHooks<S, DataOf<Sch>>;\n}\n\n/** A behavior pre-attachment: `Layout.with({ gapX: 32 })`. */\nexport interface BehaviorAttachSpec<Data = Record<string, unknown>> {\n readonly behavior: BehaviorHandle<Data>;\n readonly data: Partial<Data>;\n}\n\n/**\n * The compiled declaration. Usable wherever a behavior is expected —\n * `reads: [Glow]`, `behaviors: [Layout]`, `tx.attach(e, Layout)` — plus\n * `.with(data)` for pre-attachment and `.component` for advanced read paths.\n */\nexport interface BehaviorHandle<Data> {\n /** `<namespace>:<name>` — the process-global identity. */\n readonly name: string;\n readonly namespace: string;\n readonly store: BehaviorStore;\n readonly derived: boolean;\n readonly deriveDuringGesture: boolean;\n readonly version: number;\n readonly phase: BehaviorPhase;\n readonly budgetMs: number | undefined;\n readonly schema: BehaviorSchema;\n /** The generated data component (`behavior:<name>`). Advanced read paths. */\n readonly component: Component<Record<string, string | number | boolean>>;\n /** Every field at its declared default (the attach fill). */\n readonly defaults: Readonly<Data>;\n readonly reads: readonly BehaviorRead[];\n readonly writes: readonly Component[];\n readonly migrate: Readonly<Record<number, (prev: Record<string, unknown>) => Record<string, unknown>>>;\n readonly tickWhile: \"all\" | \"visible\";\n /**\n * The hook set. MUTABLE by design: a same-shape re-definition (hot reload,\n * a test re-importing a module) refreshes these in place, so the cached\n * handle keeps its component and collector identity while the new code\n * actually runs. Stale-hook HMR is the wart this avoids.\n */\n on: BehaviorHooks<BehaviorStore, Data>;\n /** Pre-attachment with data: `behaviors: [Layout.with({ gapX: 32 })]`. */\n with(data: Partial<Data>): BehaviorAttachSpec<Data>;\n /** @internal brand — how `reads:` tells a behavior from a component. */\n readonly __behavior: true;\n}\n\n/** A behavior handle of unknown data shape (registries, `reads:` lists). */\n// biome-ignore lint/suspicious/noExplicitAny: the registry is data-shape-agnostic by construction.\nexport type AnyBehaviorDef = BehaviorHandle<any>;\n\n/**\n * A pre-attachment of unknown data shape — what a LIST of them has to be typed\n * as. `BehaviorAttachSpec<never>` looks like the shape-agnostic form and is\n * not: `Layout.with({gapX: 32})` produces `BehaviorAttachSpec<{gapX: number}>`,\n * which is not assignable to it, so the documented `with()` form would not\n * typecheck in `defineWidget({behaviors})` at all.\n */\n// biome-ignore lint/suspicious/noExplicitAny: same reason as AnyBehaviorDef.\nexport type AnyBehaviorAttachSpec = BehaviorAttachSpec<any>;\n","/**\n * The CURATED public read surface for behaviors (design-009 §9).\n *\n * The engine catalog is exposed to behaviors DELIBERATELY, not accidentally.\n * Every name on this list is a published contract: it is what a behavior may\n * declare in `reads:` and expect to keep working across engine versions. Adding\n * a name here is a product decision — it is a promise about a shape, not a\n * convenience.\n *\n * Everything else in the catalog is ENGINE VOCABULARY: recognizers, claims,\n * gesture bookkeeping, one-tick markers. Reading it from a behavior is not\n * forbidden (the escape hatch stays open for engine-grade code), but it\n * dev-WARNS, because those shapes change whenever the interaction stack does\n * and no one will think to tell a plugin author.\n *\n * Two notes authors need and will not guess:\n * - One-tick markers (`WentDown`, the `Just*` family) are already CLEARED by\n * the time the publish slot runs, so an ephemeral behavior can never see\n * them. That is not a bug to route around; it is what \"one tick\" means.\n * - `Grab` and the claim relations are deliberately OFF the list. A behavior\n * that wants to know \"is this being dragged right now\" is usually asking\n * for claim-scoped suppression, which it already gets for free.\n */\nimport type { Component, Relation, Resource, Tag } from \"@vibecook/strata-ecs\";\nimport { CameraLimits } from \"../catalog/settings-resources\";\nimport { Camera, Culled, MeasuredSize, Viewport, Visible } from \"../catalog/camera-derived\";\nimport { ChildOf, Opacity, Position, Size } from \"../catalog/scene\";\nimport { Accepts, Container, Provides } from \"../catalog/graph\";\nimport { Movable, Resizable, Selectable, Selected } from \"../catalog/selection-presence\";\nimport { Solid } from \"../catalog/gesture\";\nimport { PrefabId } from \"../schema/prefab\";\n\n/**\n * The published set. Ordered by what an author reaches for first: geometry,\n * then structure, then state, then the view.\n */\nexport const PUBLIC_READS: ReadonlySet<Component | Tag | Relation | Resource> = new Set<\n Component | Tag | Relation | Resource\n>([\n // Geometry — the whole reason most behaviors exist.\n Position as Component,\n Size as Component,\n MeasuredSize as Component,\n Opacity as Component,\n // Structure.\n ChildOf as Relation,\n PrefabId as Component,\n Accepts as Component,\n Provides as Component,\n // Interaction STATE (never the machinery that produces it).\n Selected as Tag,\n Selectable as Tag,\n Movable as Tag,\n Resizable as Tag,\n Solid as Tag,\n Container as Tag,\n // The view.\n Visible as Tag,\n Culled as Tag,\n Camera as Resource,\n CameraLimits as Resource,\n Viewport as Resource,\n]);\n\n/** Is this handle part of the published behavior read surface? */\nexport function isPublicRead(handle: Component | Tag | Relation | Resource): boolean {\n return PUBLIC_READS.has(handle);\n}\n","/**\n * `defineBehavior` — definition, validation, and the process-global registry\n * (design-009 §4.1).\n *\n * Compile output is one generated component per behavior (`behavior:<name>`),\n * which is also the CONFLICT UNIT: one behavior = one component = one\n * committer-wins cell. The guidance line for authors, worth repeating here\n * because it is the rule that keeps collaboration sane: *would two peers\n * plausibly edit these fields concurrently? Then they are two behaviors.*\n *\n * Everything in this file is definition-time. The compiler (compile.ts) owns\n * the checks that need a populated world — above all the durable-eligibility\n * refusal, which cannot run here: at module-eval time the prefab registry may\n * not yet hold the widget whose Position the behavior writes, and a check that\n * depends on import order is a check that reports differently on a good day.\n */\nimport type { Component, Relation, Resource, Tag } from \"@vibecook/strata-ecs\";\nimport { devGuardsEnabled } from \"../guards/dev\";\nimport { ensureComponent, schemaMeta } from \"../schema/meta\";\nimport { defaultValueOf, type JsonSpec, type PropSpec } from \"../widget/props\";\nimport { isPublicRead } from \"./public-reads\";\nimport { field } from \"@vibecook/strata-ecs\";\nimport { enumOf } from \"@vibecook/strata-ecs\";\nimport {\n BEHAVIOR_DEFAULT_PHASE,\n BEHAVIOR_PHASES,\n type AnyBehaviorDef,\n type BehaviorHandle,\n type BehaviorHooks,\n type BehaviorRead,\n type BehaviorSchema,\n type BehaviorSpec,\n type BehaviorStore,\n type DataOf,\n} from \"./types\";\n\nconst STORES: readonly BehaviorStore[] = [\"durable\", \"runtime\", \"ephemeral\"];\n\n/**\n * `<namespace>:<name>` — exactly one colon, both halves non-empty, and no\n * whitespace. The namespace is what a plugin host validates against the\n * declaring plugin id (the harness precedent): without that check two\n * colliding same-shape names would silently share one component with BOTH\n * hook sets running.\n */\nconst NAME_RE = /^[A-Za-z0-9][A-Za-z0-9._-]*:[A-Za-z0-9][A-Za-z0-9._-]*$/;\n\n/**\n * The generated component's name. Prefixed so a behavior can never collide\n * with `defineWidget`'s `<type>:<group>` components — and, because this string\n * is the DURABLE key that projection is driven by, it is a permanent wire\n * format decision, not an implementation detail. A collision anywhere is loud\n * (`ensureComponent` throws on same-name/different-shape), never silent.\n */\nexport function behaviorComponentName(name: string): string {\n return `behavior:${name}`;\n}\n\nconst registry = new Map<string, AnyBehaviorDef>();\nconst byComponent = new Map<Component, AnyBehaviorDef>();\n\nexport const behaviors = {\n get(name: string): AnyBehaviorDef | undefined {\n return registry.get(name);\n },\n all(): AnyBehaviorDef[] {\n return [...registry.values()];\n },\n /** The behavior that owns a generated data component, if any. */\n forComponent(c: Component): AnyBehaviorDef | undefined {\n return byComponent.get(c);\n },\n /** Is `c` a behavior's own data component? (the BF-D6 eligibility branch). */\n isBehaviorComponent(c: Component): boolean {\n return byComponent.has(c);\n },\n};\n\n// --- reads classification ----------------------------------------------------\n\nexport type ReadKind = \"component\" | \"tag\" | \"relation\" | \"resource\" | \"behavior\";\n\n/**\n * Classify a `reads:` entry. Handles are opaque and structurally ambiguous\n * (Component and Resource have IDENTICAL shapes), so classification goes\n * through ICE's own schema registries — which doubles as the §4.1 rule that\n * reads must name REGISTERED schema: anything defined outside the `@ice/core`\n * wrappers is unclassifiable here and is rejected rather than guessed at.\n */\nexport function classifyRead(r: BehaviorRead): { kind: ReadKind; name: string } | undefined {\n if (typeof r === \"object\" && r !== null && (r as AnyBehaviorDef).__behavior === true) {\n return { kind: \"behavior\", name: (r as AnyBehaviorDef).name };\n }\n const c = schemaMeta.component(r as Component);\n if (c !== undefined) return { kind: \"component\", name: c.name };\n const t = schemaMeta.tagName(r as Tag);\n if (t !== undefined) return { kind: \"tag\", name: t };\n const rel = schemaMeta.relation(r as Relation);\n if (rel !== undefined) return { kind: \"relation\", name: rel.name };\n const res = schemaMeta.resource(r as Resource);\n if (res !== undefined) return { kind: \"resource\", name: res.name };\n return undefined;\n}\n\n/** The read component a `reads:` entry contributes, if it contributes one. */\nexport function readComponentOf(r: BehaviorRead): Component | undefined {\n if (typeof r === \"object\" && r !== null && (r as AnyBehaviorDef).__behavior === true) {\n return (r as AnyBehaviorDef).component as Component;\n }\n return schemaMeta.component(r as Component) !== undefined ? (r as Component) : undefined;\n}\n\n// --- schema compilation ------------------------------------------------------\n\nfunction strataFieldOf(behavior: string, name: string, spec: PropSpec) {\n switch (spec.kind) {\n case \"string\":\n return field(\"string\", { default: spec.default ?? \"\" });\n case \"entityKey\":\n return field(\"string\", { default: spec.default ?? \"\" });\n case \"number\":\n return field(\"f64\", { default: spec.default ?? 0 });\n case \"boolean\":\n return field(\"bool\", { default: spec.default ?? false });\n case \"enum\": {\n const fallback = spec.default ?? spec.options[0] ?? \"\";\n return field(enumOf([...spec.options]), { default: fallback });\n }\n case \"json\":\n return field(\"string\", { default: (spec as JsonSpec).default ?? \"null\" });\n default:\n throw new Error(\n `ice: defineBehavior(\"${behavior}\") field \"${name}\" is not a p.* spec — behavior data is declared with the same DSL as widget props.`,\n );\n }\n}\n\n/** The whole-value default record (the attach fill; also the cell defaults). */\nfunction defaultsOf(schema: BehaviorSchema): Record<string, string | number | boolean> {\n const out: Record<string, string | number | boolean> = {};\n for (const [name, spec] of Object.entries(schema)) out[name] = defaultValueOf(spec);\n return out;\n}\n\n// --- the definition-shape signature (re-definition compare) ------------------\n\n/**\n * What \"the same declaration\" means for the ensure-cache. Hooks are\n * DELIBERATELY excluded: a hot reload hands us new function identities for the\n * same behavior, and refusing that would make HMR throw — so a matching\n * signature refreshes the hooks on the cached handle instead (see below).\n */\nfunction signatureOf(spec: BehaviorSpec<BehaviorStore, BehaviorSchema>, phase: string): string {\n const schema = spec.schema ?? {};\n return JSON.stringify({\n store: spec.store,\n derived: spec.derived === true,\n deriveDuringGesture: spec.deriveDuringGesture === true,\n version: spec.version ?? 1,\n phase,\n tickWhile: spec.tick?.while ?? \"all\",\n // Field ORDER is part of the shape: it is the generated component's column\n // order, which the durable cell layout depends on.\n schema: Object.entries(schema).map(([k, s]) => [k, s.kind, defaultValueOf(s)]),\n reads: (spec.reads ?? []).map((r) => classifyRead(r)?.name ?? \"<unregistered>\"),\n writes: (spec.writes ?? []).map((c) => schemaMeta.component(c)?.name ?? \"<unregistered>\"),\n migrate: Object.keys(spec.migrate ?? {}).sort(),\n });\n}\n\nconst signatures = new Map<string, string>();\n\n// --- validation --------------------------------------------------------------\n\nfunction fail(name: string, message: string): never {\n throw new Error(`ice: defineBehavior(\"${name}\") — ${message}`);\n}\n\nfunction validate(name: string, spec: BehaviorSpec<BehaviorStore, BehaviorSchema>, phase: string): void {\n if (!NAME_RE.test(name)) {\n fail(\n name,\n 'names are \"<namespace>:<name>\" (letters, digits, dot, dash, underscore; exactly one colon) — the namespace is what a plugin host validates against the declaring plugin id.',\n );\n }\n if (!STORES.includes(spec.store)) {\n fail(name, `store must be one of ${STORES.join(\" | \")} — it is REQUIRED and it routes everything (§3).`);\n }\n\n const durableOnly: readonly [string, unknown][] = [\n [\"derived\", spec.derived],\n [\"version\", spec.version],\n [\"migrate\", spec.migrate],\n ];\n if (spec.store !== \"durable\") {\n for (const [key, value] of durableOnly) {\n if (value !== undefined) {\n fail(name, `\"${key}\" is durable-only — a ${spec.store} behavior has no document cells to derive, version, or migrate.`);\n }\n }\n }\n if (spec.deriveDuringGesture !== undefined && spec.derived !== true) {\n fail(name, '\"deriveDuringGesture\" opts OUT of claim-scoped suppression, which only derived behaviors are subject to (§5.3).');\n }\n\n const legal = BEHAVIOR_PHASES[spec.store];\n if (!legal.includes(phase as (typeof legal)[number])) {\n fail(\n name,\n `phase \"${phase}\" is not legal for a ${spec.store} behavior — legal: ${legal.join(\" | \")}.${\n spec.store === \"durable\"\n ? \" Durable is derive-only because its sole write path is transactional and derive is the settled-input phase (§3).\"\n : \"\"\n }`,\n );\n }\n\n if (spec.budgetMs !== undefined && (!Number.isFinite(spec.budgetMs) || spec.budgetMs <= 0)) {\n fail(name, `budgetMs must be a positive number (got ${String(spec.budgetMs)}).`);\n }\n\n // Schema: every field must be a recognized p.* spec. That single check\n // carries two of the design's rules for free — the DSL has no `eid` spec at\n // all (Law 7's ban is structural, not policed), and every spec kind yields a\n // default (`defaultValueOf` is total), so \"every field defaulted\" holds by\n // construction rather than by inspection.\n for (const [fieldName, s] of Object.entries(spec.schema ?? {})) {\n if (fieldName.length === 0) fail(name, \"schema field names must be non-empty.\");\n if (typeof s !== \"object\" || s === null || typeof (s as PropSpec).kind !== \"string\") {\n fail(name, `schema field \"${fieldName}\" is not a p.* spec (use p.string/number/boolean/enum/json/entityKey).`);\n }\n if ((s as PropSpec).kind === \"json\" && (s as JsonSpec).inner === undefined) {\n fail(name, `schema field \"${fieldName}\" is a p.json with no declared shape — json cells are BOUNDED, never free-form.`);\n }\n }\n\n for (const r of spec.reads ?? []) {\n const kind = classifyRead(r);\n if (kind === undefined) {\n fail(\n name,\n \"every reads: entry must be a component, tag, relation, resource, or behavior defined through @ice/core — an unregistered handle cannot be routed to a change mechanism.\",\n );\n }\n // The engine catalog is exposed DELIBERATELY (design-009 §9): the curated\n // list is a published contract, everything else is engine vocabulary whose\n // shape moves whenever the interaction stack does. Warn rather than throw —\n // engine-grade code legitimately reaches past the list, and turning that\n // into an error would make the escape hatch a wall.\n if (kind.kind !== \"behavior\" && !isPublicRead(r as Component)) {\n console.warn(\n `ice: defineBehavior(\"${name}\") reads \"${kind.name}\", which is not on the published behavior read surface (design-009 §9). It works, but its shape is engine vocabulary and may change without notice.`,\n );\n }\n }\n for (const c of spec.writes ?? []) {\n if (schemaMeta.component(c) === undefined) {\n fail(name, \"every writes: entry must be a component defined through @ice/core (tags and relations are not value-write targets).\");\n }\n }\n if (spec.store === \"ephemeral\" && (spec.writes?.length ?? 0) > 0) {\n fail(\n name,\n \"an ephemeral behavior writes only its OWN facet through ctx.write(patch) — it has no cross-entity write vocabulary (strata's eph partition is absolute: every mutator refuses entities this peer did not mint).\",\n );\n }\n\n for (const [hook, fn] of Object.entries(spec.on ?? {})) {\n if (typeof fn !== \"function\") fail(name, `hook \"${hook}\" is not a function.`);\n }\n if (spec.tick?.while !== undefined && spec.on?.tick === undefined) {\n fail(name, '\"tick.while\" scopes the tick hook, but no on.tick is declared.');\n }\n\n // Migration chain: contiguous 1..version-1. Unlike defineWidget (which warns\n // — its docs predate the check), a gap here THROWS: behaviors are a new\n // surface with no legacy chains to be kind to, and a gap means documents at\n // the uncovered version silently keep stale derived state.\n const version = spec.version ?? 1;\n const migrate = spec.migrate ?? {};\n const keys = Object.keys(migrate).map(Number);\n if (keys.length > 0) {\n const gaps: number[] = [];\n for (let v = 1; v < version; v++) if (typeof migrate[v] !== \"function\") gaps.push(v);\n if (gaps.length > 0) {\n fail(name, `migrate chain has gaps at fromVersion(s) [${gaps.join(\", \")}] — docs written there cannot reach v${version}.`);\n }\n const stray = keys.filter((v) => v <= 0 || v >= version);\n if (stray.length > 0) {\n fail(name, `migrate declares transform(s) for fromVersion(s) [${stray.join(\", \")}] outside the migratable range 1..${version - 1}.`);\n }\n }\n}\n\n// --- defineBehavior ----------------------------------------------------------\n\nexport function defineBehavior<const S extends BehaviorStore, const Sch extends BehaviorSchema = BehaviorSchema>(\n name: string,\n spec: BehaviorSpec<S, Sch>,\n): BehaviorHandle<DataOf<Sch>> {\n const phase = spec.phase ?? BEHAVIOR_DEFAULT_PHASE[spec.store];\n if (devGuardsEnabled()) validate(name, spec as BehaviorSpec<BehaviorStore, BehaviorSchema>, phase);\n\n const signature = signatureOf(spec as BehaviorSpec<BehaviorStore, BehaviorSchema>, phase);\n const existing = registry.get(name);\n if (existing !== undefined) {\n if (signatures.get(name) !== signature) {\n throw new Error(\n `ice: defineBehavior(\"${name}\") — a behavior with this name is already defined with a DIFFERENT shape. Behavior names are process-global; namespace yours.`,\n );\n }\n // Same declaration, re-evaluated (hot reload, a test re-importing a\n // module). Reuse the handle — its component, its collector and every\n // attached instance stay valid — but adopt the NEW hooks: keeping the old\n // ones is how a framework ends up running yesterday's code after a reload.\n existing.on = (spec.on ?? {}) as BehaviorHooks<BehaviorStore, unknown>;\n return existing as BehaviorHandle<DataOf<Sch>>;\n }\n\n const schema = (spec.schema ?? {}) as BehaviorSchema;\n const raw: Record<string, ReturnType<typeof strataFieldOf>> = {};\n for (const [fieldName, s] of Object.entries(schema)) raw[fieldName] = strataFieldOf(name, fieldName, s);\n const component = ensureComponent(behaviorComponentName(name), raw);\n\n const handle: BehaviorHandle<DataOf<Sch>> = {\n name,\n namespace: name.slice(0, name.indexOf(\":\")),\n store: spec.store,\n derived: spec.derived === true,\n deriveDuringGesture: spec.deriveDuringGesture === true,\n version: spec.version ?? 1,\n phase,\n budgetMs: spec.budgetMs,\n schema,\n component: component as Component<Record<string, string | number | boolean>>,\n defaults: defaultsOf(schema) as unknown as Readonly<DataOf<Sch>>,\n reads: spec.reads ?? [],\n writes: spec.writes ?? [],\n migrate: spec.migrate ?? {},\n tickWhile: spec.tick?.while ?? \"all\",\n on: (spec.on ?? {}) as BehaviorHooks<BehaviorStore, DataOf<Sch>>,\n with(data) {\n return { behavior: handle, data };\n },\n __behavior: true,\n };\n\n registry.set(name, handle as AnyBehaviorDef);\n byComponent.set(component, handle as AnyBehaviorDef);\n signatures.set(name, signature);\n return handle;\n}\n\n/**\n * TEST-ONLY registry wipe (mirrors `__resetPrefabsForTests`; deliberately NOT\n * on the barrel). strata's schema registry has no reset, so a test that wipes\n * this must still use file-unique behavior names.\n */\nexport function __resetBehaviorsForTests(): void {\n registry.clear();\n byComponent.clear();\n signatures.clear();\n}\n","/**\n * The behavior compiler (design-009 §7, BF-D16/BF-D17) — declaration → systems.\n *\n * Three things happen here, and each one was broken twice in review before it\n * settled:\n *\n * 1. **The SPLIT rule.** A behavior compiles to UP TO TWO systems per phase.\n * The DELIVERY system is collector-gated and carries `access.write` = own\n * component + ALL `writes:` targets, DURABLE ONES INCLUDED (design-002\n * decision 7 charges in-system commits to the running system's declared\n * writes — the earlier \"runtime targets only\" formula would have DEV-thrown\n * the flagship mind map's very first commit). The TICK system exists only\n * when an `on.tick` hook does, and carries `access.write` = the own\n * component ONLY. The split exists because strata blanket-stamps a ran\n * system's declared writes whether or not it wrote: a ticking system\n * carrying `writes: [Position]` would stamp Position every single frame and\n * wake every downstream observer. Say it to authors as the stamping tax —\n * declare minimally.\n *\n * 2. **The reads PARTITION.** `SystemAccess` is components-only, so tag ids\n * must never be spread into the component-id set: ids are dense per KIND, so\n * tag #7 would silently whitelist component #7 (the id-space trap).\n * Components → `access.read` + the collector; tags → the collector only;\n * relations and resources → polls, which the runtime arms.\n *\n * 3. **`coarse: false`.** Non-negotiable, and an engine-wide LAW rather than a\n * local option: strata blanket-marks coarse for every ran system with\n * declared writes, so without the attestation ANY ticking system with writes\n * would put every behavior collector on those components into a full rescan\n * every frame. The attestation says \"no raw `batch.col()` writes to\n * behavior-read components anywhere in ICE\" — ICE is the only party that can\n * make that promise (the engine already attests it at four sites; see\n * `systems/l1-pick.ts`). A future raw writer of a behavior-read component\n * silently degrades every behavior's precision.\n *\n * Systems are built ONCE here and registered once — never re-wrapped per\n * assemble, because strata memoizes per-system access in a WeakMap keyed on the\n * system OBJECT: a fresh wrapper each frame would leak entries and defeat the\n * memoization it was leaking into.\n */\nimport { Not, defineQuery, defineSystem, defineTickSystem } from \"@vibecook/strata-ecs\";\nimport type {\n Batch,\n CollectOptions,\n Component,\n Relation,\n Resource,\n System,\n SystemAccess,\n SystemCtx,\n Tag,\n TickSystem,\n} from \"@vibecook/strata-ecs\";\nimport { Culled } from \"../catalog/camera-derived\";\nimport type { AnySystem } from \"../engine/pipeline\";\nimport { prefabs } from \"../schema/prefab\";\nimport { schemaMeta } from \"../schema/meta\";\nimport { behaviors, classifyRead, readComponentOf } from \"./define-behavior\";\nimport type { AnyBehaviorDef, BehaviorPhase } from \"./types\";\n\n/**\n * The bodies the runtime supplies. Compilation owns SHAPE (query, access,\n * runIf, name, registration identity); the runtime owns behavior. Keeping the\n * seam here means the compiler's rules — the split, the partition, the gating —\n * are unit-testable without standing up a delivery loop.\n */\nexport interface BehaviorSystemHooks {\n /**\n * The delivery `runIf`: drains the collector, stashes the delta for the body,\n * evaluates the polls, and decides. Side-effecting BY DESIGN — there is no\n * non-destructive peek on a `ChangeCollector`, so the drain has to happen\n * in the gate or the gate cannot see the work (the `makeChurnGuard` idiom).\n */\n shouldDeliver(ctx: SystemCtx): boolean;\n deliver(ctx: SystemCtx): void;\n /** The tick `runIf` — cheap: instance count, suspension, freeze. */\n shouldTick(ctx: SystemCtx): boolean;\n tickChunk(batch: Batch, ctx: SystemCtx): void;\n /**\n * Run `body` inside this behavior's breaker bracket + fault domain. Returns\n * false when the breaker is holding the behavior down or the body threw.\n */\n charge(body: () => void): boolean;\n /** Breaker verdict — polled from `runIf`, so it must be cheap and never throw. */\n suspended(): boolean;\n /**\n * A frame the behavior sat out because the breaker suspended it. The runtime\n * DISCARDS its collectors here: a suspended behavior that stops draining\n * still journals, so its collectors would grow for as long as the suspension\n * lasts and then hand the resumed behavior a delta describing a world many\n * frames old.\n */\n onSuspendedFrame(): void;\n}\n\nexport interface CompiledBehavior {\n readonly behavior: AnyBehaviorDef;\n readonly phase: BehaviorPhase;\n /** The framework collector's subscription (always `coarse: false`). */\n readonly collect: CollectOptions;\n /** `reads:` partitioned by kind — each routed to a different mechanism. */\n readonly readComponents: readonly Component[];\n readonly readTags: readonly Tag[];\n readonly readRelations: readonly Relation[];\n readonly readResources: readonly Resource[];\n readonly deliveryAccess: SystemAccess;\n readonly tickAccess: SystemAccess | undefined;\n readonly delivery: TickSystem;\n /** Present only when the declaration has an `on.tick` hook. */\n readonly tick: System | undefined;\n /** Registration order: delivery first, then tick. */\n readonly systems: readonly AnySystem[];\n}\n\n/**\n * Is `c` a cell the document can hold? Two sources: a durable prefab's\n * eligible set, and (BF-D6) any durable behavior's own data component —\n * registered behavior components are UNIVERSALLY durable-eligible.\n *\n * This is deliberately compile-time and not definition-time. At module-eval\n * time the prefab registry may not yet hold the widget whose Position a\n * behavior writes, so a definition-time answer would depend on import order —\n * and an import-order-dependent refusal is worse than no refusal, because it\n * passes on the developer's machine and fails in the bundle.\n */\nexport function isDurableEligible(c: Component): boolean {\n if (behaviors.forComponent(c)?.store === \"durable\") return true;\n for (const p of prefabs.all()) {\n if (p.store === \"durable\" && p.eligible.has(c)) return true;\n }\n return false;\n}\n\n/** Hook names that can open a transaction (the only legal durable write path). */\nfunction hasCommitCapableHook(b: AnyBehaviorDef): boolean {\n return b.on.init !== undefined || b.on.update !== undefined || b.on.changed !== undefined;\n}\n\nexport function partitionReads(b: AnyBehaviorDef): {\n components: Component[];\n tags: Tag[];\n relations: Relation[];\n resources: Resource[];\n} {\n const components: Component[] = [];\n const tags: Tag[] = [];\n const relations: Relation[] = [];\n const resources: Resource[] = [];\n for (const r of b.reads) {\n const kind = classifyRead(r)?.kind;\n switch (kind) {\n case \"component\":\n case \"behavior\": {\n const c = readComponentOf(r);\n if (c !== undefined && !components.includes(c)) components.push(c);\n break;\n }\n case \"tag\":\n if (!tags.includes(r as Tag)) tags.push(r as Tag);\n break;\n case \"relation\":\n if (!relations.includes(r as Relation)) relations.push(r as Relation);\n break;\n case \"resource\":\n if (!resources.includes(r as Resource)) resources.push(r as Resource);\n break;\n default:\n // Unclassifiable reads are refused at definition time; a behavior built\n // with dev guards off can still reach here — drop it rather than\n // corrupt the id space.\n break;\n }\n }\n return { components, tags, relations, resources };\n}\n\nexport function compileBehavior(b: AnyBehaviorDef, hooks: BehaviorSystemHooks): CompiledBehavior {\n const own = b.component as Component;\n const { components: readComponents, tags: readTags, relations: readRelations, resources: readResources } =\n partitionReads(b);\n\n // The static divergence refusal (§3): a durable-eligible target in `writes:`\n // is reachable ONLY through `ctx.commit`, and only init/update/changed can\n // commit. A behavior whose sole hook is `tick` therefore declares a write it\n // has no legal way to make — and the way authors discover that today is a\n // divergence throw at runtime, on someone else's machine.\n if (!hasCommitCapableHook(b)) {\n for (const w of b.writes) {\n if (isDurableEligible(w)) {\n const name = schemaMeta.component(w)?.name ?? \"<component>\";\n throw new Error(\n `ice: behavior \"${b.name}\" declares writes: [${name}], a durable-eligible cell, but has no init/update/changed hook — durable cells are written ONLY inside ctx.commit, and a tick hook cannot commit (design-009 §3). Per-frame motion belongs in the behavior's own runtime data, or in tx.move.`,\n );\n }\n }\n }\n\n const writeSet = new Set<Component>([own, ...(b.writes as readonly Component[])]);\n // `read` is the literal declaration strata stores; a component in `write`\n // must not be repeated here (the write set already grants `col()` access, and\n // duplicating it only makes the diagnostics lie about intent).\n const declaredRead = readComponents.filter((c) => !writeSet.has(c));\n\n // The two systems of the SPLIT both write the own component, in the same\n // phase, on the same rows — which is exactly strata's same-phase writer-pair\n // advisory (001 §3.3). Here the pair is order-tolerant in the sanctioned\n // sense: the framework FIXES their order (delivery is registered before tick,\n // always), the writes are whole-cell absolute values, and delivery-then-tick\n // is last-write-wins-safe by construction. So both attest — and the\n // attestation is scoped to the own component ONLY. Declared `writes:` targets\n // are never attested: those DO have engine co-writers, and claiming\n // order-tolerance on the engine's behalf is not ours to do.\n //\n // Without this, every ticking behavior would print a strata advisory at\n // registration — a framework must not make its users read a warning that\n // describes its own deliberate design.\n const deliveryAccess: SystemAccess = {\n write: [...writeSet],\n ...(declaredRead.length > 0 ? { read: declaredRead } : {}),\n ...(b.on.tick !== undefined ? { orderIndependent: [own] } : {}),\n };\n\n const collect: CollectOptions = {\n // Own component FIRST: it is what makes appear/depart detectable at all.\n components: [own, ...readComponents.filter((c) => c !== own)],\n ...(readTags.length > 0 ? { tags: readTags } : {}),\n coarse: false,\n };\n\n const delivery = defineTickSystem(\n (ctx) => {\n hooks.charge(() => hooks.deliver(ctx));\n },\n {\n name: `behavior:${b.name}:deliver`,\n runIf: (ctx) => {\n if (hooks.suspended()) {\n hooks.onSuspendedFrame();\n return false;\n }\n return hooks.shouldDeliver(ctx);\n },\n access: deliveryAccess,\n },\n );\n\n let tick: System | undefined;\n let tickAccess: SystemAccess | undefined;\n if (b.on.tick !== undefined) {\n // `tick: { while: \"visible\" }` — declared suspension, compiled INTO the\n // query so culled instances never reach a chunk, rather than tested per\n // instance in the body. Default is every instance (Law 14).\n const query =\n b.tickWhile === \"visible\" ? defineQuery([own, Not(Culled)]) : defineQuery([own]);\n tickAccess = {\n write: [own],\n ...(declaredRead.length > 0 ? { read: declaredRead } : {}),\n orderIndependent: [own], // the delivery system's twin — see above\n };\n tick = defineSystem(\n query,\n (batch, ctx) => {\n hooks.charge(() => hooks.tickChunk(batch, ctx));\n },\n {\n name: `behavior:${b.name}:tick`,\n runIf: (ctx) => !hooks.suspended() && hooks.shouldTick(ctx),\n access: tickAccess,\n },\n );\n }\n\n return {\n behavior: b,\n phase: b.phase,\n collect,\n readComponents,\n readTags,\n readRelations,\n readResources,\n deliveryAccess,\n tickAccess,\n delivery,\n tick,\n systems: tick === undefined ? [delivery] : [delivery, tick],\n };\n}\n","/**\n * Pointers — the L0 runtime pointer prefab (design-001 §5.4, design-003 §2).\n *\n * Pointers are dumb: recognizers own the FSM. Hover is the pointer's outgoing\n * `Targets` edge (no widget-side Hovered tag — one fact, one owner). Transition\n * detection uses one-tick tags (`WentDown`/`WentUp`/`WentCancelled`) written by\n * ingest and cleared in the cleanup phase.\n *\n * Defaults policy (see catalog/index.ts): identity fields ingest always supplies\n * stay bare (Pointer.id/device); per-frame value writes and the remote-owner id\n * carry ergonomic zero/empty defaults.\n */\nimport { enumOf, field } from \"@vibecook/strata-ecs\";\nimport { defineComponent, defineRelation, defineResource, defineTag } from \"../schema/meta\";\n\n/** Pointer identity. `owner` is the peer/user id (\"\" for the local device). */\nexport const Pointer = defineComponent(\"Pointer\", {\n id: \"string\",\n device: enumOf([\"mouse\", \"touch\", \"pen\"]),\n owner: field(\"string\", { default: \"\" }),\n});\n\n/** Screen-space position, CSS px. */\nexport const PointerScreen = defineComponent(\"PointerScreen\", {\n x: field(\"f32\", { default: 0 }),\n y: field(\"f32\", { default: 0 }),\n});\n\n/** Button bitmask + the screen point/time where the current press began. */\nexport const PointerButtons = defineComponent(\"PointerButtons\", {\n buttons: field(\"u8\", { default: 0 }),\n downX: field(\"f32\", { default: 0 }),\n downY: field(\"f32\", { default: 0 }),\n /** The down EVENT's timestamp (0 = unknown ⇒ consumers fall back to frame now). */\n downMs: field(\"f64\", { default: 0 }),\n});\n\n/** Keyboard modifiers latched with the pointer sample. */\nexport const PointerMods = defineComponent(\"PointerMods\", {\n shift: field(\"bool\", { default: false }),\n ctrl: field(\"bool\", { default: false }),\n alt: field(\"bool\", { default: false }),\n meta: field(\"bool\", { default: false }),\n});\n\n/** Wheel deltas — accumulate within a tick, zeroed in cleanup. `pinch` is the ctrl-wheel zoom signal. */\nexport const PointerWheel = defineComponent(\"PointerWheel\", {\n dx: field(\"f32\", { default: 0 }),\n dy: field(\"f32\", { default: 0 }),\n pinch: field(\"f32\", { default: 0 }),\n});\n\n/** Touch-forgiveness radius, screen px (0 = exact, for mouse/pen). */\nexport const PointerRadius = defineComponent(\"PointerRadius\", { r: field(\"f32\", { default: 0 }) });\n\n/** One-tick: pointer went down this tick (cleared in cleanup). */\nexport const WentDown = defineTag(\"WentDown\");\n\n/** One-tick: pointer went up this tick. */\nexport const WentUp = defineTag(\"WentUp\");\n\n/** One-tick: pointer was cancelled this tick (pointercancel / touch lost / blur). */\nexport const WentCancelled = defineTag(\"WentCancelled\");\n\n/** The down was consumed by a widget's own DOM handler — recognizers skip it. */\nexport const HandledByWidget = defineTag(\"HandledByWidget\");\n\n/**\n * ONE-TICK: this tick's wheel deltas were ceded to scrollable widget content\n * (design-007 §3.5, petition I4) — the adapter let native scroll proceed and\n * flagged the fact `wheelHandled`. Deliberately NOT the shared `HandledByWidget`\n * latch: that tag rides the persistent mouse-pointer entity, and a same-tick\n * wheel-over-widget + down-over-canvas collision would silently drop the\n * legitimate canvas gesture (design-007 F6). Both wheel consumers honor it —\n * `wheelSpawn` skips the tick, `wheelSystem` treats it as wheel silence.\n * Cleared in cleanup like the Went* transition tags.\n */\nexport const WheelHandled = defineTag(\"WheelHandled\");\n\n/**\n * PERSISTENT (not one-tick): the pointer is hovering content that would opt a\n * down out — a native interactive / `[data-canvas-interactive]` (DOM) or\n * claim-capable island content (GL). Written change-only by ingest from the\n * adapters' hover-time `overInteractive` fact (design-002 §8 amendment,\n * 2026-07-18) and held across ticks with no fresh hover information (wheel,\n * blur). Presentation-grade truth — cursor affordances telegraph \"the widget\n * owns your input here\" BEFORE the down; recognizers never read it (the\n * gesture gate stays `HandledByWidget`).\n */\nexport const OverInteractive = defineTag(\"OverInteractive\");\n\n/** Marks the local device's pointer(s) (vs. presence projections). */\nexport const LocalPointer = defineTag(\"LocalPointer\");\n\n/** Derive-owned world position — screen × camera, recomputed every tick. */\nexport const PointerWorld = defineComponent(\"PointerWorld\", {\n x: field(\"f64\", { default: 0 }),\n y: field(\"f64\", { default: 0 }),\n});\n\n/**\n * Keyboard modifier state (design-003 §2 — minimal keyboard). Written by ingest\n * from adapter key events. `space` is the pan gesture modifier (design-003 §4.4);\n * shortcuts are app handlers between frames, never a tick system.\n */\nexport const Keyboard = defineResource(\"Keyboard\", {\n shift: field(\"bool\", { default: false }),\n ctrl: field(\"bool\", { default: false }),\n alt: field(\"bool\", { default: false }),\n meta: field(\"bool\", { default: false }),\n space: field(\"bool\", { default: false }),\n});\n\n/**\n * ONE-TICK cancel request (design-003 §4.1/§8): escape / tool switch / doc\n * detach all converge here via `cancelActiveGestures()`. The ctl:spawn sweep\n * consumes it; cleanup clears it — a latched cancel would kill every future\n * gesture forever.\n */\nexport const CancelRequest = defineResource(\"CancelRequest\", {\n active: field(\"bool\", { default: false }),\n});\n\n/** pointer → hovered entity (radiused pick — \"hover is forgiving\"). */\nexport const Targets = defineRelation(\"Targets\", { arity: \"one\" });\n\n/** pointer → r=0 point-pick target (\"grab is precise\"). */\nexport const TouchesExact = defineRelation(\"TouchesExact\", { arity: \"one\" });\n","/**\n * Tray-insert ghosts (2026-07-19, James: the widget tray — \"the widget\n * duplicate … and user drag it to canvas and drop\").\n *\n * A ghost is a DRAFT spawn (design-001 §3 two-phase promote; instantiate's\n * `{ draft: true }` world-path opt-in): a full, live, runtime-only instance of\n * a durable widget prefab that exists ONLY for the adoption drag. It is picked,\n * lifted, snapped and drop-evaluated exactly like a projected widget — the\n * whole point — and it NEVER touches the document: a successful release\n * promotes it through the gesture's single `create` commit (one tx, one undo\n * step) and the reap system swaps it for the projected twin; a cancel or a\n * rejected drop flies it back to the tray and despawns it, zero undo footprint.\n */\nimport { field } from \"@vibecook/strata-ecs\";\nimport { defineComponent, defineTag } from \"../schema/meta\";\n\n/**\n * The ghost marker + its promote payload, attached at `ops.insertByDrag`:\n * `type`/`props` (JSON) rebuild the widget in the commit's `CommitCreate`;\n * `screenX/screenY` remember the tray press point IN SCREEN SPACE so the\n * cancel fly-back re-projects it through the CURRENT camera — the ghost\n * returns to the tray on screen even if the user zoomed mid-drag.\n */\nexport const InsertGhost = defineComponent(\"InsertGhost\", {\n type: \"string\",\n props: field(\"string\", { default: \"{}\" }),\n screenX: \"f32\",\n screenY: \"f32\",\n});\n\n/**\n * Set by moveBehavior when the ghost's gesture committed its `create` intent.\n * The reap system despawns the ghost ONE tick later — the projected twin lands\n * at the next sync, so the swap happens inside a single reflect flush (no\n * one-frame blink of neither).\n */\nexport const GhostCommitted = defineTag(\"GhostCommitted\");\n\n/**\n * Set on the cancel / rejected-drop paths together with the fly-back\n * `TransformTween`: the reap system despawns the ghost when the tween lands\n * (component removed on arrival — camera-sim).\n */\nexport const GhostRetiring = defineTag(\"GhostRetiring\");\n","/**\n * Eligibility-guarded transactions (design-001 §2 rule 3): `tx.*` structural\n * writes are validated against the target entity's prefab — a component\n * outside the eligible set, a relation outside the eligible relations, or a\n * runtime-declared resource in a tx is a DEV error.\n *\n * Prefab resolution: entities spawned in THIS tx via `spawnPrefab` are known\n * from a tx-local map; pre-existing durable entities resolve via their\n * projected `PrefabId`. Entities from raw `tx.spawn` are unknown → checks\n * skip (the guard is best-effort by design; `spawnPrefab` is the paved road).\n * Tags are not eligibility-checked in M2 (essential tags spawn with the\n * prefab; optional-tag modeling is future work — documented).\n */\nimport type { Component, Entity, OrderPlace, Relation, Resource, Tag, World } from \"@vibecook/strata-ecs\";\nimport type { Mutator } from \"@vibecook/strata-ecs/durable\";\nimport { behaviors } from \"../behavior/define-behavior\";\nimport { Grab, Position, TransformTween } from \"../catalog\";\nimport { instantiate } from \"../engine/instantiate\";\nimport { schemaMeta } from \"../schema/meta\";\nimport { prefabs, PrefabId, type ComponentInit, type Prefab } from \"../schema/prefab\";\nimport { devGuardsEnabled } from \"./dev\";\nimport type { LiveWriter } from \"./live-writer\";\n\nexport interface GuardedTx {\n spawnPrefab(prefab: Prefab, overrides?: readonly ComponentInit[]): Entity;\n /** Raw spawn — entity is unknown to the guard (prefer spawnPrefab). */\n spawn: Mutator[\"spawn\"];\n destroy(e: Entity): void;\n addComponent<S>(e: Entity, c: Component<S>, v: S): void;\n removeComponent(e: Entity, c: Component): void;\n edit(e: Entity): { set<S>(c: Component<S>, v: S): GuardedEditor };\n addTag(e: Entity, t: Tag): void;\n removeTag(e: Entity, t: Tag): void;\n setRelation(e: Entity, r: Relation, target: Entity, place?: OrderPlace): void;\n addRelation(e: Entity, r: Relation, target: Entity): void;\n removeRelation(e: Entity, r: Relation, target?: Entity): void;\n /** Reorder within the current parent's sibling sequence — ordered relations only (petition 8). */\n moveRelation(e: Entity, r: Relation, place: OrderPlace): void;\n setResource<S>(res: Resource<S>, v: S): void;\n /**\n * Animation-integrated write (petition I15): ONE commit owns the capture, the\n * durable final, and the glide. `from` is read AT CALL TIME (pre-commit by\n * construction), the final lands in THIS transaction — inheriting its\n * `undoable` — and after a successful seal the tail installs the verified\n * public-surface glide: `TransformTween` (which GRANTS the divergence) then a\n * live rewind to `from`. One commit, one undo entry, no double-write.\n *\n * `animateMs` absent/0 = snap (no tween attached at all). A `Grab`-held\n * entity is SKIPPED — the gesture owns its divergence. An entity already\n * tweening is RETARGETED (its `toX/toY` rewritten) rather than restarted, so\n * a re-layout mid-glide re-aims instead of completing at a stale target.\n *\n * Requires `opts.live` (the session's LiveWriter) — without it the rewind\n * could not be divergence-guarded, so the call refuses rather than writing\n * around the guard.\n */\n move(e: Entity, to: { x: number; y: number }, opts?: { animateMs?: number }): void;\n}\n\ninterface GuardedEditor {\n set<S>(c: Component<S>, v: S): GuardedEditor;\n}\n\ninterface TxDoc {\n transaction(fn: (tx: Mutator) => void, opts?: { undoable?: boolean; meta?: Record<string, unknown> }): void;\n}\n\nexport interface GuardedTxOpts {\n /**\n * strata 0.3.0 passthrough: `false` excludes this commit from the LOCAL\n * undo stack (batch seeds, janitorial writes — retires the cardboard\n * first-⌘Z-removes-a-seed quirk). Default true: one tx = one undo step.\n */\n readonly undoable?: boolean;\n /**\n * The session's live writer. Required by {@link GuardedTx.move} (its\n * post-commit rewind is a live write to a doc cell, legal only under the\n * tween grant) and by the post-seal retarget sweep below.\n */\n readonly live?: LiveWriter;\n /** Optional entity → doc-key probe; when absent every entity is treated as\n * durable-if-Position-eligible. Used to skip runtime-only movers' tx write. */\n readonly keyOf?: (e: Entity) => string | undefined;\n /**\n * Per-commit PROVENANCE (strata 0.12.0, petition 9): a small record carried\n * in-CRDT with the batch, so a receiving peer can say who wrote this and why.\n * The behavior framework stamps `{ behavior, label }` on every `ctx.commit`\n * (design-009 §4.4 — `label` is a stable machine id, never display text).\n * Note that shallow saves erase provenance below the compaction boundary, so\n * it is diagnostics, never a data dependency.\n */\n readonly meta?: Record<string, unknown>;\n}\n\n/**\n * Retarget a live tween onto `to`, or start one from `from`.\n * Returns false when the entity is Grab-held (the gesture owns its divergence).\n */\nfunction glide(\n world: World,\n live: LiveWriter,\n e: Entity,\n from: { x: number; y: number },\n to: { x: number; y: number },\n durationMs: number,\n): boolean {\n if (!world.isAlive(e) || world.has(e, Grab)) return false;\n const existing = world.get(e, TransformTween);\n if (existing !== undefined) {\n // RETARGET, never restart: the ease continues from its captured origin at\n // current progress, so a re-layout mid-glide re-aims smoothly.\n world.edit(e).set(TransformTween, { ...existing, toX: to.x, toY: to.y });\n return true;\n }\n world.addComponent(e, TransformTween, {\n toX: to.x,\n toY: to.y,\n durationMs,\n elapsedMs: 0,\n });\n live.set(e, Position, { x: from.x, y: from.y });\n return true;\n}\n\nexport function guardedTransaction(\n doc: TxDoc,\n world: World,\n run: (tx: GuardedTx) => void,\n opts?: GuardedTxOpts,\n): void {\n // Post-commit work: the glide tail (tx.move) and the retarget sweep. Both\n // run ONLY if the seal succeeded — a throwing body propagates and skips them,\n // so a rolled-back transaction never leaves a tween pointing anywhere.\n const tail: Array<() => void> = [];\n /** Entities this tx moved through `move` — exempt from the sweep below. */\n const moved = new Set<Entity>();\n /** Entities whose Position this tx wrote by any OTHER path. */\n const positionWrites = new Map<Entity, { x: number; y: number }>();\n\n doc.transaction((tx) => {\n const spawned = new Map<Entity, Prefab>();\n\n const prefabOf = (e: Entity): Prefab | undefined => {\n const local = spawned.get(e);\n if (local) return local;\n const id = world.get(e, PrefabId)?.id;\n return typeof id === \"string\" ? prefabs.get(id) : undefined;\n };\n\n const checkComponent = (e: Entity, c: Component, op: string): void => {\n if (!devGuardsEnabled()) return;\n // BF-D6 (design-001 amendment): a registered DURABLE behavior's own data\n // component is universally durable-eligible. Behaviors attach to any\n // entity the host's write gate allows, so per-prefab eligibility cannot\n // express them — and design-001's eligibility rationale (\"typo/schema\n // safety\") is met a different way here, by definition-time name\n // registration: an unregistered component simply is not a behavior.\n //\n // This branch is LOAD-BEARING IN PRODUCTION, not a dev nicety: guards are\n // opt-OUT (guards/dev.ts), so without it every durable behavior write\n // would throw in a shipped build.\n if (behaviors.isBehaviorComponent(c) && behaviors.forComponent(c)?.store === \"durable\") return;\n const prefab = prefabOf(e);\n if (prefab && !prefab.eligible.has(c)) {\n const name = schemaMeta.component(c)?.name ?? \"<component>\";\n throw new Error(\n `ice: tx.${op}: component \"${name}\" is not durable-eligible on prefab \"${prefab.id}\" — declare it in the prefab's essential or optional set (design-001 §2 rule 3).`,\n );\n }\n };\n\n const checkRelation = (e: Entity, r: Relation, op: string): void => {\n if (!devGuardsEnabled()) return;\n const prefab = prefabOf(e);\n if (prefab && !prefab.eligibleRelations.has(r)) {\n const name = schemaMeta.relation(r)?.name ?? \"<relation>\";\n throw new Error(\n `ice: tx.${op}: relation \"${name}\" is not durable-eligible on prefab \"${prefab.id}\" — declare it in the prefab's relations (design-001 §2 rule 6).`,\n );\n }\n };\n\n const guarded: GuardedTx = {\n spawnPrefab(prefab, overrides) {\n const e = instantiate(prefab, { into: \"tx\", tx }, overrides);\n spawned.set(e, prefab);\n return e;\n },\n spawn: (init) => tx.spawn(init),\n destroy: (e) => tx.destroy(e),\n addComponent(e, c, v) {\n checkComponent(e, c as Component, \"addComponent\");\n if ((c as Component) === (Position as Component)) {\n positionWrites.set(e, v as { x: number; y: number });\n }\n tx.addComponent(e, c, v);\n },\n removeComponent: (e, c) => tx.removeComponent(e, c),\n edit(e) {\n const editor: GuardedEditor = {\n set(c, v) {\n checkComponent(e, c as Component, \"edit().set\");\n if ((c as Component) === (Position as Component)) {\n positionWrites.set(e, v as { x: number; y: number });\n }\n tx.edit(e).set(c, v);\n return editor;\n },\n };\n return editor;\n },\n addTag: (e, t) => tx.addTag(e, t),\n removeTag: (e, t) => tx.removeTag(e, t),\n setRelation(e, r, target, place) {\n checkRelation(e, r, \"setRelation\");\n tx.setRelation(e, r, target, place);\n },\n addRelation(e, r, target) {\n checkRelation(e, r, \"addRelation\");\n tx.addRelation(e, r, target);\n },\n removeRelation: (e, r, target) => tx.removeRelation(e, r, target),\n moveRelation(e, r, place) {\n checkRelation(e, r, \"moveRelation\");\n tx.moveRelation(e, r, place);\n },\n setResource(res, v) {\n if (devGuardsEnabled()) {\n const meta = schemaMeta.resource(res as Resource);\n if (meta && !meta.durable) {\n throw new Error(\n `ice: tx.setResource: resource \"${meta.name}\" is declared runtime — durable resources opt in at definition (design-001 §2 rule 7).`,\n );\n }\n }\n tx.setResource(res, v);\n },\n\n move(e, to, mopts) {\n const live = opts?.live;\n if (live === undefined) {\n throw new Error(\n \"ice: tx.move requires the session's live writer — pass `live` in the transaction options (the post-commit rewind is a guarded live write, not a raw one).\",\n );\n }\n if (!world.isAlive(e)) return;\n // A gesture already owns this entity's divergence; re-aiming it here\n // would fight the drag (arrange's own rule).\n if (world.has(e, Grab)) return;\n\n const from = world.get(e, Position) as { x: number; y: number } | undefined;\n if (from === undefined) return;\n const start = { x: from.x, y: from.y }; // captured PRE-commit, by construction\n\n // The durable final rides THIS transaction (inheriting its undoable);\n // runtime-only movers get their value write in the tail instead.\n const durable = opts?.keyOf === undefined || opts.keyOf(e) !== undefined;\n if (durable) {\n checkComponent(e, Position as Component, \"move\");\n tx.edit(e).set(Position, { x: to.x, y: to.y });\n }\n moved.add(e);\n\n const ms = mopts?.animateMs ?? 0;\n tail.push(() => {\n if (!world.isAlive(e)) return;\n if (ms > 0) {\n glide(world, live, e, start, to, ms);\n return;\n }\n // SNAP. If a glide is in flight it must END here, or the stale tween\n // would keep easing the runtime cell toward its old target and undo\n // the very write this call just committed. Order matters: write the\n // value FIRST (the tween still grants divergence, so the guard admits\n // it), THEN drop the tween — which leaves runtime == durable == `to`,\n // converged, with no divergence left to strand.\n const inFlight = world.get(e, TransformTween) !== undefined;\n if (inFlight) {\n live.set(e, Position, { x: to.x, y: to.y });\n world.removeComponent(e, TransformTween);\n return;\n }\n // No tween: a durable mover already landed via the commit's\n // write-through; a runtime-only one still needs its value write.\n if (!durable) world.edit(e).set(Position, { x: to.x, y: to.y });\n });\n },\n };\n\n run(guarded);\n }, opts);\n\n // ── THE POST-SEAL RETARGET CHOKEPOINT (petition I15) ──────────────────────\n // A durable Position write that did NOT come through `move` must retarget any\n // live tween on that entity. Without it the tween keeps gliding to a stale\n // target and lands there: runtime ≠ baseline with nothing banked, which is\n // divergence that NEVER reconciles (strata's `(own, value)` branch advances\n // the baseline alone) and poisons the cell against later remote updates.\n const live = opts?.live;\n if (live !== undefined) {\n for (const [e, to] of positionWrites) {\n if (moved.has(e)) continue;\n if (!world.isAlive(e) || world.get(e, TransformTween) === undefined) continue;\n const existing = world.get(e, TransformTween);\n if (existing === undefined) continue;\n world.edit(e).set(TransformTween, { ...existing, toX: to.x, toY: to.y });\n }\n }\n\n for (const t of tail) t();\n}\n\n/**\n * Retarget every live tween onto its DURABLE truth — the undo/redo chokepoint\n * (petition I15). Undo does not pass through {@link guardedTransaction}: it is\n * strata's own local batch, so a glide in flight when ⌘Z lands would otherwise\n * complete at the pre-undo target and strand the cell exactly as above.\n *\n * `durablePositionOf` reads the committed value (the doc's, not the runtime's).\n * A tween whose entity has no durable Position is left alone — nothing to\n * reconcile against.\n */\nexport function retargetTweensToDoc(\n world: World,\n entities: Iterable<Entity>,\n durablePositionOf: (e: Entity) => { x: number; y: number } | undefined,\n): void {\n for (const e of entities) {\n if (!world.isAlive(e)) continue;\n const tw = world.get(e, TransformTween);\n if (tw === undefined) continue;\n const doc = durablePositionOf(e);\n if (doc === undefined) continue;\n if (tw.toX === doc.x && tw.toY === doc.y) continue;\n world.edit(e).set(TransformTween, { ...tw, toX: doc.x, toY: doc.y });\n }\n}\n","/**\n * Behavior schema evolution (design-009 §5.5–§5.6, BF-D14) — M13g.\n *\n * Markers are `engine.behavior.<name>.<v>` write-once keys: a monotone key SET,\n * never a mutated cell, so concurrent peers converge on the union instead of\n * racing a single slot. They are a SEPARATE FAMILY from `engine.pack.*`, and\n * that separation is the whole point of this file.\n *\n * **Why not fold them into the pack compare.** The pack compare classifies a\n * doc marker with no local counterpart as `newerInDoc`, which read-onlys the\n * document. For prefabs that is right — an unknown prefab means the doc was\n * written by a newer build. For behaviors it is catastrophic: behaviors ship in\n * PLUGINS, so \"no local counterpart\" is the ordinary state of every document\n * whose author had a plugin this reader does not. Folding them in would brick a\n * document because a plugin is missing — design-008's exact failure shape,\n * which cost us a release to learn.\n *\n * So behaviors get their own compare with the **absent-is-not-newer** rule:\n * - a locally-unregistered behavior name is IGNORED ENTIRELY (its cells sit\n * in the doc un-projected and dormant — strata's projection is\n * name-registry-driven, so they are inert, not corrupt);\n * - `v > installed` for an INSTALLED behavior triggers per-behavior DORMANCY\n * (refuse hook delivery — projection is version-blind, so newer-shaped data\n * WOULD otherwise flow into older hooks), never a doc verdict;\n * - `v < installed` runs the migration chain.\n *\n * Behavior version state NEVER affects the document's gate verdict. That is a\n * standing guarantee, and the anti-brick test in CI is what keeps it one.\n */\nimport type { Component, Entity, World } from \"@vibecook/strata-ecs\";\nimport { guardedTransaction } from \"../guards/guarded-tx\";\nimport type { LiveWriter } from \"../guards/live-writer\";\nimport type { AnyBehaviorDef } from \"./types\";\n\nexport const BEHAVIOR_MARKER_PREFIX = \"engine.behavior.\";\n\n/**\n * Markers carry the STRING `\"1\"`, not the boolean `engine.pack.*` uses.\n * `readMeta` is the only key-addressed read the durable store offers and it\n * returns strings only, so a boolean marker would be invisible to every reader\n * that is not enumerating the raw Loro map — which mid-session installs cannot\n * do. Presence is still the semantics; the value is never read.\n */\nconst MARKER_VALUE = \"1\";\n\nexport function behaviorMarkerKey(name: string, version: number): string {\n return `${BEHAVIOR_MARKER_PREFIX}${name}.${version}`;\n}\n\n/**\n * How far ABOVE the installed version to probe for a newer marker. There is no\n * key enumeration on an attached store, so dormancy detection is a bounded\n * scan; a document more than this many versions ahead of this build reads as\n * \"not newer\" and runs normally, which is the same honest failure a doc from\n * the future has always had.\n */\nconst PROBE_AHEAD = 16;\n\nexport interface BehaviorMeta {\n readMeta(key: string): string | undefined;\n metaTransaction(fn: (meta: { get(key: string): unknown; set(key: string, value: string): void }) => void): void;\n}\n\n/** The highest marker version present for `name` (0 = never stamped). */\nexport function docBehaviorVersion(meta: BehaviorMeta, name: string, installed: number): number {\n let highest = 0;\n for (let v = 1; v <= installed + PROBE_AHEAD; v++) {\n if (meta.readMeta(behaviorMarkerKey(name, v)) !== undefined) highest = v;\n }\n return highest;\n}\n\n/** Stamp the marker for `version` if it is not already present (write-once). */\nexport function stampBehaviorMarker(meta: BehaviorMeta, name: string, version: number): void {\n const key = behaviorMarkerKey(name, version);\n if (meta.readMeta(key) !== undefined) return;\n meta.metaTransaction((m) => {\n if (m.get(key) === undefined) m.set(key, MARKER_VALUE);\n });\n}\n\nexport type BehaviorVerdict =\n | { readonly kind: \"ok\" }\n /** The doc is at a NEWER version than this build installs — refuse delivery. */\n | { readonly kind: \"dormant\"; readonly docVersion: number; readonly installed: number }\n /** The doc is OLDER — the chain has work to do. */\n | { readonly kind: \"migrate\"; readonly from: number; readonly installed: number }\n /** Older, but the chain cannot reach `installed` from there. */\n | { readonly kind: \"unreachable\"; readonly from: number; readonly installed: number };\n\nexport function classifyBehaviorVersion(b: AnyBehaviorDef, docVersion: number): BehaviorVerdict {\n if (docVersion === 0 || docVersion === b.version) return { kind: \"ok\" };\n if (docVersion > b.version) return { kind: \"dormant\", docVersion, installed: b.version };\n for (let v = docVersion; v < b.version; v++) {\n if (typeof b.migrate[v] !== \"function\") {\n return { kind: \"unreachable\", from: docVersion, installed: b.version };\n }\n }\n return { kind: \"migrate\", from: docVersion, installed: b.version };\n}\n\nexport interface MigrateDeps {\n readonly world: World;\n readonly meta: BehaviorMeta;\n /** The doc store, for the one `{undoable: false}` transaction. */\n // biome-ignore lint/suspicious/noExplicitAny: structural — the guarded-tx doc seam.\n readonly store: any;\n readonly liveWriter?: LiveWriter;\n /** Every entity currently carrying the behavior's component. */\n carriers(): readonly Entity[];\n}\n\n/**\n * Run `b`'s migrate chain over every carrier, in ONE non-undoable transaction,\n * then stamp the new marker.\n *\n * A SECOND plan+write pass, not a reuse of the M9 prefab runner: that one\n * filters by `PrefabId`, and a behavior rides entities of any kind — its own\n * component is the only thing that identifies its cells.\n *\n * Returns the number of migrated carriers.\n */\nexport function runBehaviorMigration(b: AnyBehaviorDef, from: number, deps: MigrateDeps): number {\n const c = b.component as Component;\n const carriers = deps.carriers();\n const plan: { e: Entity; value: Record<string, unknown> }[] = [];\n for (const e of carriers) {\n const current = deps.world.get(e, c) as Record<string, unknown> | undefined;\n if (current === undefined) continue;\n let value: Record<string, unknown> = { ...current };\n for (let v = from; v < b.version; v++) {\n const step = b.migrate[v];\n if (typeof step !== \"function\") break;\n value = { ...value, ...step(value) };\n }\n plan.push({ e, value });\n }\n if (plan.length > 0) {\n guardedTransaction(\n deps.store,\n deps.world,\n (tx) => {\n for (const { e, value } of plan) tx.edit(e).set(c as Component<unknown>, value);\n },\n // Never an undo step: a migration is not something a user did.\n { undoable: false, ...(deps.liveWriter !== undefined ? { live: deps.liveWriter } : {}) },\n );\n }\n // Stamp even when nothing needed migrating — the marker records that THIS\n // build's version is now represented in the document, which is what stops the\n // runner from re-planning on every registration.\n stampBehaviorMarker(deps.meta, b.name, b.version);\n return plan.length;\n}\n","/**\n * The commit seam (design-001 §3 gesture protocol × implementation-plan M4/M5).\n *\n * Behaviors end a gesture with ONE commit (design-002 decision 4). Until the\n * durable layer lands (M5), commits are recorded as INTENTS through this seam:\n * the M4 frame traces assert runtime state + commit intents, and M5 swaps in a\n * doc-backed sink that turns an intent into one `guardedTransaction` per\n * gesture (liveness guards re-checked inside the tx via live edges + keyOf —\n * the intent carries the already-liveness-filtered write set, but the doc sink\n * re-guards because the doc is the authority).\n *\n * The seam is deliberately dumb data: no callbacks into behaviors, no partial\n * application — a whole gesture outcome in one value.\n */\nimport type { Component, Entity, OrderPlace } from \"@vibecook/strata-ecs\";\n\n/** One absolute component write inside a commit (whole-value, design-001 §2). */\nexport interface CommitWrite {\n readonly entity: Entity;\n // biome-ignore lint/suspicious/noExplicitAny: heterogeneous write list; the value is validated against the component schema at apply time\n readonly component: Component<any>;\n readonly value: Record<string, unknown>;\n}\n\n/** A structural reparent riding a consume outcome (design-003 §5.5). */\nexport interface CommitReparent {\n readonly entity: Entity;\n readonly container: Entity;\n}\n\n/**\n * An ordered-relation placement riding a commit (petition 8): the gesture's\n * final sibling position lands IN the gesture's single transaction — one\n * gesture stays one undo step. `parent` is re-asserted absolutely (a\n * same-target `setRelation` WITH a place is a move, never a duplicate).\n */\nexport interface CommitOrder {\n readonly entity: Entity;\n readonly parent: Entity;\n readonly place: OrderPlace;\n}\n\n/**\n * A wire creation riding a connect outcome (design-003 §5.8; design-001\n * §5.3): wires bind WIDGET entities + port IDS — never port entities.\n */\nexport interface CommitWireSpawn {\n readonly from: Entity;\n readonly to: Entity;\n readonly fromPort: string;\n readonly toPort: string;\n}\n\n/**\n * A widget creation riding a create outcome (draw tool, design-005 §3;\n * tray-insert promote, 2026-07-19). `props`/`parent` extend the draw shape for\n * ghost promotes: prop overrides rebuild the tray instance, `parent` lands a\n * consume-into-container insert (x/y are container-LOCAL then, matching the\n * reparent convention). `select` asks the sink to hand the projected twin to\n * the reap system's selection transfer — the tray's select-on-drop.\n */\nexport interface CommitCreate {\n readonly type: string;\n readonly x: number;\n readonly y: number;\n readonly w: number;\n readonly h: number;\n readonly props?: Readonly<Record<string, unknown>>;\n readonly parent?: Entity;\n readonly select?: boolean;\n}\n\nexport interface CommitIntent {\n /** Outcome kind — traces assert on it. */\n readonly kind: \"move\" | \"consume\" | \"resize\" | \"connect\" | \"create\" | \"delete\";\n /** The recognizer (or op source) that owned the gesture. */\n readonly gesture: Entity;\n readonly writes: readonly CommitWrite[];\n readonly reparents?: readonly CommitReparent[];\n readonly orders?: readonly CommitOrder[];\n readonly wires?: readonly CommitWireSpawn[];\n readonly creates?: readonly CommitCreate[];\n}\n\nexport interface CommitSink {\n commit(intent: CommitIntent): void;\n}\n\n/** The M4 default: record intents for traces/devtools; commit nothing. */\nexport function createRecordingCommitSink(): CommitSink & { readonly intents: CommitIntent[] } {\n const intents: CommitIntent[] = [];\n return {\n intents,\n commit(intent) {\n intents.push(intent);\n },\n };\n}\n","/**\n * The input queue — the ONE input path's front door (Law 2, design-003 §2).\n *\n * Adapters (DOM pointer/wheel/keyboard, R3F router verdicts, test drivers) ONLY\n * enqueue normalized {@link InputEvent}s; `pointerIngest` drains the queue once\n * per tick and turns events into world facts. Handlers run mid-frame at\n * arbitrary times — the queue is what keeps every world write inside the frame\n * contract (design-002 §3). It is pre-ingest TRANSPORT, not world state: no\n * system reads it, nothing observes it, it holds nothing across a drain.\n *\n * Pointer identity: `pointerId` is the adapter's stable string for a device\n * pointer — `\"mouse\"` for the one mouse, `\"touch:<n>\"` per touch contact,\n * `\"pen\"` for a stylus. Ingest keys pointer entities off it (`Pointer.id`).\n */\n\nexport type InputEventKind = \"down\" | \"move\" | \"up\" | \"cancel\" | \"wheel\" | \"key\";\n\nexport interface InputMods {\n readonly shift: boolean;\n readonly ctrl: boolean;\n readonly alt: boolean;\n readonly meta: boolean;\n /** Space-held (pan gesture modifier, design-003 §4.4) — not a PointerMods field. */\n readonly space: boolean;\n}\n\nexport interface InputEvent {\n readonly kind: InputEventKind;\n /** Stable adapter pointer id (\"mouse\" | \"touch:<n>\" | \"pen\"). Empty for kind:\"key\". */\n readonly pointerId: string;\n readonly device: \"mouse\" | \"touch\" | \"pen\";\n /** Canvas-container-relative CSS px (the kernel screen space). */\n readonly screenX: number;\n readonly screenY: number;\n /** Button bitmask as of this event (PointerEvent.buttons semantics). */\n readonly buttons: number;\n readonly mods: InputMods;\n /** Wheel deltas for kind:\"wheel\" (`pinch` = ctrl-wheel / trackpad zoom signal). */\n readonly wheel?: { readonly dx: number; readonly dy: number; readonly pinch: number };\n /** GL-island opt-out (pinned widget-event contract, design-002 §8): fact still lands, recognizers skip. */\n readonly surfaceHandled?: boolean;\n /**\n * Wheel-only opt-out (design-007 §3.5, petition I4): this wheel's deltas were\n * ceded to scrollable widget content — the adapter skipped `preventDefault`\n * and native scroll consumed them. The fact still lands (one input path);\n * ingest stamps the one-tick `WheelHandled` tag so the wheel recognizers skip\n * the tick. DISTINCT from `surfaceHandled` on purpose: the shared latch on\n * the persistent mouse pointer would collide with a same-tick canvas down.\n */\n readonly wheelHandled?: boolean;\n /**\n * Hover-time widget-boundary fact (design-002 §8 amendment, 2026-07-18): the\n * pointer is currently over content that would opt a down out — a native\n * interactive / `[data-canvas-interactive]` (DOM) or claim-capable island\n * content (GL). Stamped on down/move by adapters that track it; ABSENT means\n * \"no hover information this event\" (wheel, key, blur-cancel) — ingest keeps\n * the pointer's `OverInteractive` tag unchanged, it never treats absent as\n * false. Presentation-grade truth (cursor affordances), never a gesture gate:\n * recognizers keep reading `surfaceHandled`/`HandledByWidget` only.\n */\n readonly overInteractive?: boolean;\n /**\n * Event timestamp (DOMHighResTimeStamp — the same clock rAF hands\n * `engine.step`). Gesture timing anchors on THIS, not the processing frame:\n * a stalled main thread (GC, cold paints) otherwise eats into hold windows —\n * a 640 ms stall at pointerdown made long-press unreachable (2026-07-12\n * field debugging). Absent ⇒ the processing frame's now.\n */\n readonly tMs?: number;\n}\n\nexport const NO_MODS: InputMods = { shift: false, ctrl: false, alt: false, meta: false, space: false };\n\nexport interface InputQueue {\n enqueue(event: InputEvent): void;\n /** Drain in arrival order. Called ONLY by `pointerIngest`, once per tick. */\n drain(): readonly InputEvent[];\n /** Events waiting (telemetry/tests). */\n size(): number;\n}\n\nexport function createInputQueue(): InputQueue {\n let buffer: InputEvent[] = [];\n return {\n enqueue(event) {\n buffer.push(event);\n },\n drain() {\n const drained = buffer;\n buffer = [];\n return drained;\n },\n size() {\n return buffer.length;\n },\n };\n}\n","/**\n * L3 camera slice — cameraControl (ctl:behave) + cameraInertia & tweenSystem\n * (simulate). Design-003 §5 item 9 + the `simulate` tail; design-001 §3 (a live\n * TransformTween holds the claim); design decision 14 (per-frame pan at CURRENT\n * zoom, never total/zoomAtClaim — mid-pan wheel-zoom keeps content under cursor).\n *\n * `cameraControl` is a PURE value consumer: it reads active camera-gesture\n * recognizers and writes ONLY the `Camera` resource (resources are access-exempt,\n * design-003 §10 — hence no `access.write`). It NEVER touches an entity's\n * components. It is a TICK system (strata 0.5.0): the scheduler runs the body\n * EXACTLY once per frame — the camera is a whole-frame aggregate over every\n * active camera gesture, written once, change-guarded (an unconditional write would churn `CameraVersion` and\n * wake the plane reflector every frame). Camera writes go through the closed-over\n * `world.setResource` (no `ctx` resource API; verified legal in systems).\n *\n * Camera-gesture kinds and their math:\n * - RoutedPan Drag (Active): integrate the PER-FRAME screen delta at the CURRENT\n * zoom via a per-recognizer last-total memo (design decision 14). Sign is\n * content-follows-pointer (`Camera -= Δ/zoom`, design-003 §5 item 9): the\n * drag GRABS the canvas, standard in every canvas app.\n * - WheelPan (Active): `Camera += d/zoom` — scroll direction = TRAVEL direction\n * (wheel-down/swipe-down moves the viewport down the world; content moves\n * opposite). This is the Figma/Freeform convention for both mouse wheels and\n * macOS natural-scroll trackpads; the sign was inverted until James's field\n * report (2026-07-10) and is now pinned by a trace.\n * - WheelZoom (Active): anchored zoom, `zoomAtPoint(cam, anchor, zoom·e^(-pinch·k))`.\n * - Pinch (Active): zoom `startZoom · spread/startDist`, anchored at the live centroid.\n * `Camera.gesturing` is true while ANY of these is Active (compositor DPR gate).\n * On pan JustEnded, inertia is seeded from the Drag's release velocity.\n */\nimport { field } from \"@vibecook/strata-ecs\";\nimport type { Entity, System, TickSystem, World } from \"@vibecook/strata-ecs\";\nimport { defineQuery, defineSystem, defineTickSystem } from \"@vibecook/strata-ecs\";\nimport { zoomAtPoint } from \"@ice/kernel\";\nimport {\n Camera,\n Drag,\n GesturePhases,\n LocalPointer,\n Pinch,\n Pointer,\n PointerScreen,\n Position,\n RoutedPan,\n TransformTween,\n Watches,\n WentDown,\n WheelPan,\n WheelZoom,\n} from \"../catalog\";\nimport { CameraLimits, GestureSettings } from \"../catalog/settings-resources\";\nimport { FrameInfo } from \"../engine/frame-info\";\nimport { defineResource } from \"../schema/meta\";\nimport { CAMERA_DEFAULTS, GESTURE_DEFAULTS } from \"../settings/defaults\";\n\nconst P = GesturePhases;\n\n// Wheel-zoom speed is the v2 prototype curve (2026-07-13, superseding the old\n// e^(−Δ·0.0015) demo constant): factor = 2^(−clamp(Δ, ±maxStep) · sensitivity),\n// live-tunable via GestureSettings. See GESTURE_DEFAULTS for why the clamp is\n// the load-bearing half (mouse-notch ≈ pinch-frame parity).\n\n/** Camera default when the resource is unset (tests may never seed it). */\nconst CAMERA_ZERO = { x: 0, y: 0, zoom: 1, gesturing: false } as const;\n\n/**\n * Runtime pan-inertia velocity (screen px/s), seeded by `cameraControl` at pan\n * release and decayed by `cameraInertia`. A resource (not closure state) so\n * devtools sees it and there is no hidden singleton (design-003 §9).\n */\nexport const CameraInertia = defineResource(\n \"CameraInertia\",\n { vx: field(\"f32\", { default: 0 }), vy: field(\"f32\", { default: 0 }) },\n { durable: false },\n);\n\nexport interface CameraSystems {\n cameraControl: TickSystem;\n cameraInertia: TickSystem;\n tweenSystem: System;\n}\n\nconst panDragQ = defineQuery([Drag, RoutedPan]);\nconst wheelPanQ = defineQuery([WheelPan]);\nconst wheelZoomQ = defineQuery([WheelZoom]);\nconst pinchQ = defineQuery([Pinch]);\nconst downPointerQ = defineQuery([Pointer, WentDown, LocalPointer]);\nconst tweenQ = defineQuery([Position, TransformTween]);\n\nfunction clampZoom(world: World, z: number): number {\n // Live-tunable limits (design-005 §4): resource first, const fallback.\n const lim = world.getResource(CameraLimits) ?? CAMERA_DEFAULTS;\n return Math.min(lim.maxZoom, Math.max(lim.minZoom, z));\n}\n\n/** Cubic ease-out (design-003 §5 item 5 fly-back easing). */\nfunction easeOutCubic(t: number): number {\n const inv = 1 - t;\n return 1 - inv * inv * inv;\n}\n\nexport function createCameraSystems(world: World): CameraSystems {\n // Per-RoutedPan-recognizer last screen total (design decision 14): the pan\n // integrates ONLY this frame's delta at the current zoom, so a Simultaneous\n // wheel-zoom mid-pan never retroactively re-converts the accumulated total.\n const panMemo = new Map<Entity, { x: number; y: number }>();\n\n // Per-entity tween start position: TransformTween carries only the target\n // (design-001 §5 minimal shape), so the eased lerp needs the fly-away origin\n // captured on the attach frame. Cleaned on arrival — and, since 2026-08-15\n // (petition I15), on DEATH too: an entity destroyed mid-glide never reaches\n // the landing branch, so its entry used to sit in this map for the world's\n // whole life. Bounded and harmless (generation-tagged handles never collide),\n // but a leak is a leak — and behaviors will make mid-glide despawns ordinary.\n const tweenStart = new Map<Entity, { x: number; y: number }>();\n world.observe({\n onDestroy: (e) => {\n tweenStart.delete(e);\n },\n onReset: () => {\n tweenStart.clear();\n panMemo.clear();\n },\n });\n\n // Tick system (strata 0.5.0, petition 5): the scheduler owns cardinality —\n // the whole-frame aggregate runs EXACTLY once per frame by construction.\n // (Pre-0.5.0 this was a CanvasSurface-anchored chunk system; a missing\n // count guard multiplied the non-idempotent integrations N-archetypes× —\n // caught by the wheel-pan direction trace, 2026-07-10.)\n const cameraControl = defineTickSystem(\n (ctx) => {\n const cam0 = world.getResource(Camera) ?? CAMERA_ZERO;\n let x = cam0.x;\n let y = cam0.y;\n let zoom = cam0.zoom;\n let anyActive = false;\n\n // 1) RoutedPan drags — per-frame delta at CURRENT zoom (design decision 14).\n ctx.query(panDragQ).each((b) => {\n for (const r of b) {\n const rec = b.entity(r);\n if (world.hasTag(rec, P.tags.Active)) {\n anyActive = true;\n const d = world.read(rec, Drag);\n const last = panMemo.get(rec) ?? { x: 0, y: 0 };\n x -= (d.totalX - last.x) / zoom;\n y -= (d.totalY - last.y) / zoom;\n panMemo.set(rec, { x: d.totalX, y: d.totalY });\n }\n if (world.hasTag(rec, P.justTags.Ended)) {\n const d = world.read(rec, Drag);\n if (Math.hypot(d.velX, d.velY) > GESTURE_DEFAULTS.inertiaMinVelocityPxPerS) {\n world.setResource(CameraInertia, { vx: d.velX, vy: d.velY });\n }\n panMemo.delete(rec);\n } else if (world.hasTag(rec, P.justTags.Cancelled) || world.hasTag(rec, P.justTags.Failed)) {\n panMemo.delete(rec);\n }\n }\n });\n\n // 2) WheelPan — per-tick deltas (wheelSystem zeroes them on silent frames).\n // += : scroll direction is travel direction (see module note). The DRAG\n // pan above keeps -= (grab-the-canvas) — the two are deliberately opposed.\n ctx.query(wheelPanQ).each((b) => {\n for (const r of b) {\n const rec = b.entity(r);\n if (!world.hasTag(rec, P.tags.Active)) continue;\n anyActive = true;\n const w = world.read(rec, WheelPan);\n if (w.dx === 0 && w.dy === 0) continue;\n x += w.dx / zoom;\n y += w.dy / zoom;\n }\n });\n\n // 3) WheelZoom — anchored zoom about the (live) wheel anchor.\n ctx.query(wheelZoomQ).each((b) => {\n for (const r of b) {\n const rec = b.entity(r);\n if (!world.hasTag(rec, P.tags.Active)) continue;\n anyActive = true;\n const wz = world.read(rec, WheelZoom);\n if (wz.pinch === 0) continue;\n const gset = world.getResource(GestureSettings);\n const sens = gset?.wheelZoomSensitivity ?? GESTURE_DEFAULTS.wheelZoomSensitivity;\n const maxStep = gset?.wheelZoomMaxStep ?? GESTURE_DEFAULTS.wheelZoomMaxStep;\n const step = Math.max(-maxStep, Math.min(maxStep, wz.pinch));\n const next = zoomAtPoint(\n { x, y, zoom },\n wz.anchorX,\n wz.anchorY,\n clampZoom(world, zoom * 2 ** (-step * sens)),\n );\n x = next.x;\n y = next.y;\n zoom = next.zoom;\n }\n });\n\n // 4) Pinch — zoom by the spread ratio, anchored at the live centroid.\n ctx.query(pinchQ).each((b) => {\n for (const r of b) {\n const rec = b.entity(r);\n if (!world.hasTag(rec, P.tags.Active)) continue;\n const pointers = world.getRelations(rec, Watches);\n if (pointers.length !== 2) continue;\n const [pa, pbP] = pointers as [Entity, Entity];\n const pin = world.read(rec, Pinch);\n if (pin.startDist <= 0) continue;\n anyActive = true;\n const sa = world.read(pa, PointerScreen);\n const sb = world.read(pbP, PointerScreen);\n const spread = Math.hypot(sb.x - sa.x, sb.y - sa.y);\n const next = zoomAtPoint(\n { x, y, zoom },\n pin.cx,\n pin.cy,\n clampZoom(world, pin.startZoom * (spread / pin.startDist)),\n );\n x = next.x;\n y = next.y;\n zoom = next.zoom;\n }\n });\n\n if (x !== cam0.x || y !== cam0.y || zoom !== cam0.zoom || anyActive !== cam0.gesturing) {\n world.setResource(Camera, { x, y, zoom, gesturing: anyActive });\n }\n },\n { name: \"cameraControl\" },\n );\n\n const cameraInertia = defineTickSystem(\n (ctx) => {\n const inertia = world.getResource(CameraInertia);\n if (inertia === undefined || (inertia.vx === 0 && inertia.vy === 0)) return;\n\n // Touch-to-stop: any pointer going down this frame kills inertia dead (v2).\n let stopped = false;\n ctx.query(downPointerQ).each((b) => {\n if (b.count > 0) stopped = true;\n });\n if (stopped) {\n world.setResource(CameraInertia, { vx: 0, vy: 0 });\n return;\n }\n\n const dt = world.getResource(FrameInfo)?.dt ?? 16;\n const dtS = dt / 1000;\n const cam0 = world.getResource(Camera) ?? CAMERA_ZERO;\n const zoom = cam0.zoom;\n // Apply at the current zoom (design-003 §5 item 9), then exponential decay.\n const nx = cam0.x - (inertia.vx * dtS) / zoom;\n const ny = cam0.y - (inertia.vy * dtS) / zoom;\n const decay = Math.exp(-dt / GESTURE_DEFAULTS.inertiaDecayMs);\n let vx = inertia.vx * decay;\n let vy = inertia.vy * decay;\n if (Math.hypot(vx, vy) < 1) {\n vx = 0;\n vy = 0;\n }\n world.setResource(CameraInertia, { vx, vy });\n // gesturing unchanged — inertia is not a gesture (no recognizer holds a claim).\n world.setResource(Camera, { x: nx, y: ny, zoom, gesturing: cam0.gesturing });\n },\n {\n name: \"cameraInertia\",\n runIf: () => {\n const i = world.getResource(CameraInertia);\n return i !== undefined && (i.vx !== 0 || i.vy !== 0);\n },\n },\n );\n\n const tweenSystem = defineSystem(\n tweenQ,\n (b, ctx) => {\n const dt = ctx.getResource(FrameInfo)?.dt ?? 16;\n for (const r of b) {\n const e = b.entity(r);\n const tw = ctx.read(e, TransformTween);\n const pos = ctx.read(e, Position);\n let start = tweenStart.get(e);\n if (start === undefined) {\n // Attach frame: Position is still the fly-away origin (moveBehavior did\n // not write it this frame) — capture it as the eased lerp's start.\n start = { x: pos.x, y: pos.y };\n tweenStart.set(e, start);\n }\n const elapsed = tw.elapsedMs + dt;\n const dur = tw.durationMs > 0 ? tw.durationMs : 1;\n if (elapsed >= dur) {\n ctx.edit(e).set(Position, { x: tw.toX, y: tw.toY }); // snap exactly to target\n ctx.removeComponent(e, TransformTween); // reap the rider — cell reconverges\n tweenStart.delete(e);\n continue;\n }\n const t = easeOutCubic(elapsed / dur);\n ctx.edit(e).set(Position, { x: start.x + (tw.toX - start.x) * t, y: start.y + (tw.toY - start.y) * t });\n ctx.edit(e).set(TransformTween, { ...tw, elapsedMs: elapsed });\n }\n },\n { name: \"tweenSystem\", access: { write: [Position, TransformTween] } },\n );\n\n return { cameraControl, cameraInertia, tweenSystem };\n}\n","/**\n * Version-stamp resources + the runIf guard built on them (design-002 §4).\n *\n * These are the same-tick laziness lever: a writing system bumps a version as a plain value\n * write (v1's callback back-channels become world state — Laws 1/4), and a downstream system\n * gates on {@link makeVersionGuard} in its `runIf`. The guard rule (design-002 §4): guards\n * live in `runIf`, never the body — a `runIf`-skipped system runs no body and so blanket-stamps\n * NONE of its declared writes (strata over-fires stampWrites for any system that RUNS, even one\n * that early-outs). Bump/guard therefore form the \"writer stamps → reader skips wholesale\" pair.\n *\n * Resources are runtime (not durable): they are derived engine state, never persisted.\n */\n\nimport type { Resource, World } from \"@vibecook/strata-ecs\";\nimport { defineResource } from \"../schema/meta\";\n\n/** The shared shape of every version stamp — a wrap-around unsigned tick counter. */\nexport interface VersionValue {\n v: number;\n}\n\n/** A resource carrying a {@link VersionValue}. */\nexport type VersionResource = Resource<VersionValue>;\n\n/** Bumped by `pointerIngest` when the input queue drained anything (design-003 §2). */\nexport const PointerVersion = defineResource(\"PointerVersion\", { v: \"u32\" }, { durable: false });\n/** Bumped by `setSelection`/selection edits (design-003 §5). */\nexport const SelectionVersion = defineResource(\"SelectionVersion\", { v: \"u32\" }, { durable: false });\n/** Bumped when the spatial index changes (inserts/moves/removes). */\nexport const SpatialVersion = defineResource(\"SpatialVersion\", { v: \"u32\" }, { durable: false });\n\n/**\n * Increment a version stamp as a value write. Unset counts as 0, so the first bump lands 1.\n * Wraps at 2^32 via `>>> 0` — a wrapped counter still compares unequal frame-to-frame, which\n * is all the guard needs. Systems write resources through the closed-over `world.setResource`\n * (there is no `ctx` resource API — design-002 §3).\n */\nexport function bumpVersion(world: World, res: VersionResource): void {\n const cur = world.getResource(res);\n const v = cur === undefined ? 0 : cur.v;\n world.setResource(res, { v: (v + 1) >>> 0 });\n}\n\n/**\n * A `runIf`-compatible guard. Returns `true` iff any watched version differs from the value it\n * last observed, and records the new values each call. The first invocation always returns\n * `true` (it establishes the baseline — the gated system runs once at startup). A skipped system\n * stamps nothing, so pairing this guard with narrow `access.write` is the whole laziness win.\n *\n * Typed `() => boolean` so callers (and tests) can invoke it directly; it is width-assignable to\n * strata's `Condition` (`(ctx) => boolean`), so it drops straight into `runIf`.\n */\nexport type VersionGuard = () => boolean;\n\nexport function makeVersionGuard(world: World, resources: readonly VersionResource[]): VersionGuard {\n const watched = [...resources];\n const last: (number | undefined)[] = watched.map(() => undefined);\n let primed = false;\n return () => {\n let changed = !primed;\n for (let i = 0; i < watched.length; i++) {\n const res = watched[i];\n if (res === undefined) continue;\n const cur = world.getResource(res)?.v;\n if (cur !== last[i]) changed = true;\n last[i] = cur;\n }\n primed = true;\n return changed;\n };\n}\n","/**\n * The paved-road runtime-resource write (design-001 §2 rule 7) — the mirror\n * image of guarded-tx's `tx.setResource` check. A resource declares its write\n * path once at `defineResource` (`durable` vs `runtime`), and the two ends\n * enforce it symmetrically: `tx.setResource` rejects a RUNTIME resource inside\n * a transaction; `writeRuntimeResource` rejects a DURABLE resource on the\n * runtime world. Systems have no `ctx` resource API, so they write runtime\n * resources through the closed-over `world.setResource` (design-002 §3) — this\n * facade is that write, made DEV-checked.\n *\n * Unknown resources — anything not defined through `../schema/meta`'s\n * `defineResource` wrapper — carry no schemaMeta, so the check finds nothing\n * and the write passes untouched. The guard is best-effort by design, exactly\n * like guarded-tx's prefab-eligibility checks.\n */\nimport type { Resource, World } from \"@vibecook/strata-ecs\";\nimport { schemaMeta } from \"../schema/meta\";\nimport { devGuardsEnabled } from \"./dev\";\n\nexport function writeRuntimeResource<S>(world: World, res: Resource<S>, v: S): void {\n if (devGuardsEnabled()) {\n const meta = schemaMeta.resource(res as Resource);\n if (meta?.durable) {\n throw new Error(\n `ice: writeRuntimeResource: resource \"${meta.name}\" is declared durable — durable resources are written in transactions (tx.setResource), not through the runtime world (design-001 §2 rule 7).`,\n );\n }\n }\n world.setResource(res, v);\n}\n","/**\n * Nav-flight — the T1 camera-flight half of design-006 (portal zoom).\n *\n * CUT-FIRST, THEN FLY (§3): the nav ops perform the ECS cut synchronously\n * (frame switch, membership resweep, index rebuild) and then hand presentation\n * to this slice — `startNavFlight` snaps the camera to the continuity-solved\n * start `c0` and arms the `NavTransition` resource; the `navFlight` tick\n * system (simulate, beside cameraInertia) advances a closed-form critically-\n * damped progress spring each frame and writes the camera along the log-zoom\n * path until rest. The transition is PURE PRESENTATION: killing it at any\n * moment leaves a fully consistent world in the destination frame.\n *\n * - `NavTransition` is a RESOURCE, not closure state (the CameraInertia\n * pattern: devtools sees it, no hidden singleton — design-003 §9). Resources\n * cannot be removed, so `active` is the liveness flag; `epoch` bumps on\n * every (re)start so the T2 reflector can distinguish retarget from resume.\n * - Camera writes are UNCLAMPED (design-006 §3.1): flight paths transit far\n * outside the user-gesture zoom band; only the ARRIVAL camera (clamped by\n * the nav op) bounds where the flight rests.\n * - Gestures always win (§4): any active camera gesture — `Camera.gesturing`,\n * stamped by cameraControl in ctl:behave, i.e. EARLIER this same frame —\n * deactivates the flight without touching the camera.\n * - The portal affine (`as/aox/aoy`, departed-frame → destination-frame) and\n * `frozen` ride the resource for T2's departing-plane reflector; T1's camera\n * math only needs c0/c1.\n */\nimport type { TickSystem, World } from \"@vibecook/strata-ecs\";\nimport { defineTickSystem, enumOf, field } from \"@vibecook/strata-ecs\";\nimport type { CameraState, PortalAffine } from \"@ice/kernel\";\nimport { capFlightStart, flightCamera, flightOctaves, springStep } from \"@ice/kernel\";\nimport { Camera, Viewport } from \"../catalog/camera-derived\";\nimport { NavTransitionSettings } from \"../catalog/settings-resources\";\nimport { FrameInfo } from \"../engine/frame-info\";\nimport { writeRuntimeResource } from \"../guards/resource-writer\";\nimport { defineResource } from \"../schema/meta\";\nimport { NAV_TRANSITION_DEFAULTS } from \"../settings/defaults\";\n\nconst NAV = NAV_TRANSITION_DEFAULTS;\n\n/** The one in-flight nav transition (design-006 §3.1). Inactive = at rest. */\nexport const NavTransition = defineResource(\"NavTransition\", {\n active: field(\"bool\", { default: false }),\n kind: field(enumOf([\"enter\", \"exit\"]), { default: \"enter\" }),\n /** Progress spring state (closed-form critically damped, kernel springStep). */\n p: field(\"f32\", { default: 0 }),\n v: field(\"f32\", { default: 0 }),\n /** Depth-capped flight — T2 presents it as a crossfade, not geometry (§5). */\n frozen: field(\"bool\", { default: false }),\n /** Bumps on every flight start; T2 distinguishes retarget from resume. */\n epoch: field(\"u32\", { default: 0 }),\n /** Response multiplier from octave distance (locked at start; §4). */\n durMul: field(\"f32\", { default: 1 }),\n c0x: field(\"f64\", { default: 0 }),\n c0y: field(\"f64\", { default: 0 }),\n c0z: field(\"f64\", { default: 1 }),\n c1x: field(\"f64\", { default: 0 }),\n c1y: field(\"f64\", { default: 0 }),\n c1z: field(\"f64\", { default: 1 }),\n /** Portal affine A: departed-frame coords → destination-frame coords (T2). */\n as: field(\"f64\", { default: 1 }),\n aox: field(\"f64\", { default: 0 }),\n aoy: field(\"f64\", { default: 0 }),\n});\n\n/**\n * Arm a flight from the already-cut world: continuity-solve was done by the\n * caller (`exact` = c0 in destination-frame coords), the arrival `c1` is\n * already clamped. Applies the depth cap (§5), snaps the camera to c0, and\n * activates the resource. Callers guarantee a live Viewport — headless/no-\n * viewport paths snap to the arrival instead and never reach here.\n */\nexport function startNavFlight(\n world: World,\n kind: \"enter\" | \"exit\",\n A: PortalAffine,\n exact: CameraState,\n c1: CameraState,\n): void {\n const vp = world.getResource(Viewport);\n const vpW = vp?.w ?? 0;\n const vpH = vp?.h ?? 0;\n const { c0, capped } = capFlightStart(exact, c1, vpW, vpH, NAV.freezeOctaves, NAV.capFactor);\n const octaves = flightOctaves(c0, c1);\n const prev = world.getResource(NavTransition);\n writeRuntimeResource(world, Camera, { x: c0.x, y: c0.y, zoom: c0.zoom, gesturing: false });\n world.setResource(NavTransition, {\n active: true,\n kind,\n p: 0,\n v: 0,\n frozen: capped,\n epoch: (prev?.epoch ?? 0) + 1,\n durMul: 1 + NAV.durationPerOctave * Math.max(0, octaves - NAV.baseOctaves),\n c0x: c0.x,\n c0y: c0.y,\n c0z: c0.zoom,\n c1x: c1.x,\n c1y: c1.y,\n c1z: c1.zoom,\n as: A.s,\n aox: A.ox,\n aoy: A.oy,\n });\n}\n\n/** Deactivate without touching the camera (integrity pops, gesture yields). */\nexport function abortNavFlight(world: World): void {\n const t = world.getResource(NavTransition);\n if (t?.active) world.setResource(NavTransition, { ...t, active: false });\n}\n\n/**\n * Is a nav flight driving the camera right now? THE gate for flight-time\n * GPU/paint duty (design-006 §8.2, answered by field testing 2026-07-16):\n * heavy-motion consumers treat `Camera.gesturing ∨ navFlightActive` as one\n * \"camera in transient motion\" signal — composite DPR drop, band-repaint\n * suppression, Hot-island freeze, breakpoint retier deferral. `gesturing`\n * itself stays a pure user-gesture fact (the inertia precedent): flights\n * never stamp it, consumers OR the two.\n */\nexport function navFlightActive(world: World): boolean {\n return world.getResource(NavTransition)?.active === true;\n}\n\nexport function createNavFlight(world: World): TickSystem {\n return defineTickSystem(\n () => {\n const t = world.getResource(NavTransition);\n if (t === undefined || !t.active) return;\n const cam = world.getResource(Camera);\n if (cam?.gesturing === true) {\n // Touch always wins (§4): yield instantly; the camera stays wherever\n // the flight left it and the gesture composes from there.\n world.setResource(NavTransition, { ...t, active: false });\n return;\n }\n const vp = world.getResource(Viewport);\n const c1: CameraState = { x: t.c1x, y: t.c1y, zoom: t.c1z };\n if (vp === undefined || vp.w <= 0) {\n // Viewport died mid-flight (teardown) — settle instantly.\n writeRuntimeResource(world, Camera, { ...c1, gesturing: false });\n world.setResource(NavTransition, { ...t, p: 1, v: 0, active: false });\n return;\n }\n const dtMs = world.getResource(FrameInfo)?.dt ?? 16;\n const responseMs =\n (world.getResource(NavTransitionSettings)?.responseMs ?? NAV.responseMs) *\n (t.kind === \"exit\" ? NAV.exitResponseFactor : 1) *\n t.durMul;\n const omega = (2 * Math.PI) / (responseMs / 1000);\n const { p, v } = springStep(t.p, t.v, omega, dtMs / 1000);\n if (p > NAV.settleP && Math.abs(v) < NAV.settleV) {\n writeRuntimeResource(world, Camera, { ...c1, gesturing: false }); // land EXACTLY\n world.setResource(NavTransition, { ...t, p: 1, v: 0, active: false });\n return;\n }\n const c0: CameraState = { x: t.c0x, y: t.c0y, zoom: t.c0z };\n const c = flightCamera(c0, c1, Math.min(1, Math.max(0, p)), vp.w, vp.h);\n writeRuntimeResource(world, Camera, { x: c.x, y: c.y, zoom: c.zoom, gesturing: false });\n world.setResource(NavTransition, { ...t, p, v });\n },\n {\n name: \"navFlight\",\n runIf: () => world.getResource(NavTransition)?.active === true,\n },\n );\n}\n","/**\n * `defineWidget` v1 — the flagship compiler (design-005 §2).\n *\n * Sugar over `definePrefab` + registries — nothing here is unavailable to a\n * hand-rolled prefab. Compile output:\n * - one durable prefab: `PrefabId{type}` + Position/Size + ONE\n * generated component per conflict group (`<type>:<group>`; ungrouped\n * fields form the \"props\" default group) + Accepts/Provides when a\n * container contract is declared;\n * - a capability-stamp recipe (RUNTIME tags at projection — the equip system\n * consumes it; tags stay pure, design-001 §2);\n * - a view registration (surface, component, sizeMode, sizes) the React/dom\n * layers consume;\n * - the migration chain (stored now; the M9 migrator runs it).\n *\n * Definition-time rules enforced: every top-level field defaulted (p.json\n * derives one), group membership total and disjoint, enum defaults among\n * options (checked in the DSL), duplicate types rejected.\n */\nimport { field, enumOf } from \"@vibecook/strata-ecs\";\nimport type { Component, FieldInput, Tag } from \"@vibecook/strata-ecs\";\nimport { ensureComponent } from \"../schema/meta\";\nimport type { AnyBehaviorAttachSpec, AnyBehaviorDef } from \"../behavior/types\";\nimport {\n Accepts,\n ChildOf,\n Container,\n KeyboardExclusive,\n LongPressDrag,\n Movable,\n Opacity,\n Position,\n Provides,\n Resizable,\n Selectable,\n Size,\n SnapSource,\n SnapTarget,\n Solid,\n SweepsContained,\n} from \"../catalog\";\nimport { defineComponent, defineTag } from \"../schema/meta\";\nimport { definePrefab, init, type ComponentInit, type Prefab } from \"../schema/prefab\";\nimport { defaultValueOf } from \"./props\";\nimport type { JsonSpec, PropSpec, PropsDecl } from \"./props\";\n\nexport type WidgetSurface = \"dom\" | \"gl\";\nexport type SizeMode = \"fixed\" | \"auto-height\" | \"auto\";\n\nexport interface WidgetPortDecl {\n readonly id: string;\n readonly side: \"n\" | \"e\" | \"s\" | \"w\";\n /** Slot index along the side (0-based; anchor spacing is the kernel's). */\n readonly index?: number;\n /** Compatibility keys (empty = connects to anything). */\n readonly accepts?: readonly string[];\n}\n\n/**\n * A prior durable id of this widget type (design-008 §3, petition I5). Docs\n * written under the old id fold to this type at open (doc/rename.ts) and via\n * the live zombie sweep (doc/rename-sweep.ts) — replicas converge through\n * ordinary CRDT delivery, retiring offline byte surgery. Declares group-NAME\n * continuity at the rename boundary (the pack runner's existing fence).\n */\nexport interface WidgetRename {\n /** The old durable type id (`PrefabId.id` in pre-rename docs). */\n readonly type: string;\n /**\n * The pack version old-build writers of `type` were at (default 1). Only\n * the SWEEP consumes it — a late old-shape delivery carries no marker, so\n * its values chain-fold from here; the open-path runner reads the version\n * off the doc's own markers instead (design-008 §6.3).\n */\n readonly atVersion?: number;\n}\n\n/** A rename registry entry (doc/rename runner + sweep input). */\nexport interface WidgetRenameEntry {\n readonly widget: WidgetType;\n readonly oldType: string;\n readonly atVersion: number;\n /** Legacy `<oldType>:<group>` components, index-aligned with `widget.groups`. */\n readonly legacyGroups: readonly Component[];\n}\n\n/**\n * A behavior pre-attachment on a widget type: the bare handle for defaults, or\n * `Behavior.with({...})` for a starting value (design-009 §6).\n */\nexport type WidgetBehaviorDecl = AnyBehaviorDef | AnyBehaviorAttachSpec;\n\n/** Normalized pre-attachment (registry truth for the spawn + equip paths). */\nexport interface WidgetBehaviorEntry {\n readonly behavior: AnyBehaviorDef;\n readonly data: Readonly<Record<string, unknown>>;\n}\n\nexport interface WidgetInteraction {\n readonly selectable?: boolean;\n readonly movable?: boolean;\n readonly resizable?: boolean;\n readonly snap?: \"source\" | \"target\" | \"both\" | \"none\";\n /** Drop-REJECTING target: widgets dropped onto this one fly back (v1 iOS-card contract). */\n readonly solid?: boolean;\n /** \"longPress\": hold-to-lift dragging (iOS home-screen model); default \"press\". */\n readonly dragOn?: \"press\" | \"longPress\";\n /**\n * UE-Blueprint comment-box drag (2026-07-18): a move claim on this widget\n * also claims every widget FULLY INSIDE its bounds at claim time (spatial\n * membership — never reparenting). Default false.\n */\n readonly sweepContained?: boolean;\n /**\n * Keyboard claim (design-007 §3.1, petitions I1/I4). `\"exclusive\"`: while a\n * node inside this widget holds browser focus, the engine keymap and the\n * adapter's Space pan modifier stand down — keys flow to the widget's own\n * handlers (the engine stops competing; it never delivers behavior). The\n * dom-widgets reflector marks the host `data-canvas-keyboard` + `tabindex=-1`\n * so a click anywhere in the widget acquires focus, and plain wheel over the\n * widget's scrollable content cedes to native scroll (ctrl/pinch stays\n * canvas zoom always). Default `\"shared\"` — today's behavior, byte-identical.\n */\n readonly keyboard?: \"shared\" | \"exclusive\";\n /**\n * Escape ownership under an exclusive claim (design-007 §3.3 / §7-Q1).\n * `\"release\"` (default): Escape is the engine-reserved release gesture — it\n * blurs the widget; the NEXT Escape, with focus gone, cancels gestures.\n * `\"widget\"`: even Escape flows to the widget (vim-grade terminals); release\n * is click-away or `blurFocus()`. Ignored unless `keyboard: \"exclusive\"`.\n */\n readonly keyboardEscape?: \"release\" | \"widget\";\n}\n\nexport interface WidgetDef {\n readonly type: string;\n readonly version?: number;\n /** Top-level props: a plain record, or the DSL's `p.object(...)` result. */\n readonly props?: PropsDecl | { readonly kind: \"object\"; readonly fields: Readonly<Record<string, unknown>> };\n /** Conflict groups: group name → prop names. Ungrouped props → \"props\". */\n readonly groups?: Readonly<Record<string, readonly string[]>>;\n readonly surface: WidgetSurface;\n /** Framework component (opaque to core — the react package narrows it). */\n readonly component: unknown;\n /**\n * GL only: a DOM chrome component portaled into the widget's CONTENT-plane\n * host (P1), which stacks UNDER the GL canvas (P2) — v1's proven\n * CardChrome-beneath-the-canvas sandwich. The island renders ONLY the 3D\n * content; the card body (gradient, radius, ring, shadow, lift spring,\n * hover/overlap glow) is DOM and shares the app's CSS with DOM widgets.\n * Opaque to core — the react package narrows it. Ignored for dom-surface\n * widgets (their component IS the chrome).\n */\n readonly chrome?: unknown;\n readonly sizeMode?: SizeMode;\n readonly defaultSize?: { readonly w: number; readonly h: number };\n readonly minSize?: { readonly w: number; readonly h: number };\n /**\n * GL only: the island repaints every frame while visible (design-004 §3\n * animation contract — the EXPLICIT opt-in; plain `useFrame` inside a\n * portal cannot be attributed to an island, so it never drives repaints;\n * content-driven animation goes through `useIslandFrame`).\n */\n readonly animated?: boolean;\n readonly interaction?: WidgetInteraction;\n /**\n * Node-editor port schema (design-005 §2; design-001 §5.3): wires bind to\n * widget + port ID — port ENTITIES are runtime and on-demand. `accepts` is\n * the compatibility key list the connect gesture checks.\n */\n readonly ports?: readonly WidgetPortDecl[];\n /**\n * Palette/tray preview (design-005 §2 amendment, 2026-07-19). ENGINE-FREE\n * BY CONTRACT: a preview renders with no world, no entity, no ops — a pure\n * picture the host mounts inert (that is what makes it portable: trays,\n * docs sites, a widget store). Authored at `defaultSize`; hosts scale.\n * Three tiers, least effort first:\n * - absent → the REAL component mounts with default props in\n * the framework's preview sandbox (dom surfaces;\n * truthful by construction);\n * - `{ props: {…} }` → same sandbox mount with curated props;\n * - a component, or `{ component }` → author-owned preview (a static\n * mockup, a live self-ticking clock — the author's call). In P1 all\n * declared previews are DOM components — the sanctioned escape hatch\n * for GL widgets too (P2 adds the r3f snapshot pipeline).\n * Opaque to core — the react package narrows it (`component` precedent).\n */\n readonly preview?: unknown;\n readonly container?: { readonly accepts: readonly string[]; readonly provides?: readonly string[] };\n /**\n * Provides-keys WITHOUT container semantics (nodeboard field finding): a\n * leaf that only offers itself to containers must not become a Container\n * (drop target + Enter affordance). Ignored when `container` is present\n * (its `provides` wins).\n */\n readonly provides?: readonly string[];\n /**\n * Prior durable ids folded to this type (design-008; petition I5). Additive:\n * registers read-only LEGACY group components under the old names so\n * pre-rename cells project, gates pre-rename docs \"migrate\" instead of\n * read-only, and arms the live zombie sweep on every writable session.\n */\n readonly renamedFrom?: readonly WidgetRename[];\n /**\n * Behaviors every instance of this type carries (design-009 §6). The store\n * class routes HOW, exactly as it routes everything else:\n * - `durable` behaviors are attached as post-spawn `addComponent` calls in\n * the SAME spawn transaction — document truth, so they sync and undo with\n * the widget. (Not spawn-init overrides: those hit the prefab's\n * all-builds eligibility throw in `instantiate.ts`.)\n * - `runtime` behaviors are stamped at PROJECTION by the equip system,\n * beside the capability tags. That is the only mechanism that also equips\n * a widget arriving from a remote peer or a restored file, which a rider\n * attached at spawn time would miss on every peer but the author's.\n * Ephemeral behaviors are refused: an ephemeral instance IS the local\n * presence peer, so it cannot ride a widget at all.\n */\n readonly behaviors?: readonly WidgetBehaviorDecl[];\n /**\n * fromVersion → idempotent absolute transform (M9's `runMigrations` runs the\n * chain at open; `prev`/return are flat prop records spanning every group).\n *\n * No parallel `legacy` schema field is needed for field-level changes: strata\n * is field-tolerant within a known component name (extra stored fields dropped,\n * missing default-filled — every generated field carries a default), so a v1\n * cell projects into the v2 group component of the same name and the transform\n * reads the already-v2-shaped value. See doc/migrate.ts for the as-built note;\n * migrating data out of a group REMOVED wholesale in v2 is vNext (design-005\n * §6.4 cross-schema movement).\n */\n readonly migrate?: Readonly<Record<number, (prev: Record<string, unknown>) => Record<string, unknown>>>;\n}\n\nexport interface WidgetGroup {\n readonly name: string;\n readonly component: Component;\n /** prop name → spec (field order = component field order). */\n readonly fields: Readonly<Record<string, PropSpec>>;\n}\n\nexport interface WidgetType {\n readonly type: string;\n readonly version: number;\n readonly prefab: Prefab;\n readonly groups: readonly WidgetGroup[];\n readonly propToGroup: Readonly<Record<string, string>>;\n readonly surface: WidgetSurface;\n readonly component: unknown;\n /** GL widgets: DOM chrome under the canvas (see WidgetDef.chrome). */\n readonly chrome: unknown;\n readonly sizeMode: SizeMode;\n readonly defaultSize: { readonly w: number; readonly h: number };\n readonly minSize: { readonly w: number; readonly h: number };\n /** GL islands: repaint every visible frame (design-004 §3). */\n readonly animated: boolean;\n /** Node-editor ports (empty when not a node). */\n readonly ports: readonly WidgetPortDecl[];\n /** Runtime capability tags the equip system stamps at projection. */\n readonly capabilityTags: readonly Tag[];\n /** Keyboard claim (design-007): the dom layer reads THIS (registry truth), not the tag. */\n readonly keyboard: \"shared\" | \"exclusive\";\n /** Escape ownership under an exclusive claim (\"release\" = engine-reserved). */\n readonly keyboardEscape: \"release\" | \"widget\";\n readonly migrate: Readonly<Record<number, (prev: Record<string, unknown>) => Record<string, unknown>>>;\n /** Pre-attached behaviors, normalized (spawn tx for durable, equip for runtime). */\n readonly behaviors: readonly WidgetBehaviorEntry[];\n /** Normalized author preview component (opaque; react narrows). null = none declared. */\n readonly previewComponent: unknown;\n /** Prop overrides for the default real-component preview mount (validated names). */\n readonly previewProps?: Readonly<Record<string, unknown>>;\n}\n\n/** Stamped by the equip system once a projected widget carries its capability tags. */\nexport const WidgetEquipped = defineTag(\"WidgetEquipped\");\n\nconst registry = new Map<string, WidgetType>();\nconst renameRegistry = new Map<string, WidgetRenameEntry>();\n\nexport const widgets = {\n get(type: string): WidgetType | undefined {\n return registry.get(type);\n },\n all(): WidgetType[] {\n return [...registry.values()];\n },\n};\n\n/** The rename registry (design-008 §3): old durable id → fold target. */\nexport const renames = {\n get(oldType: string): WidgetRenameEntry | undefined {\n return renameRegistry.get(oldType);\n },\n all(): WidgetRenameEntry[] {\n return [...renameRegistry.values()];\n },\n};\n\nfunction normalizeProps(props: WidgetDef[\"props\"]): PropsDecl {\n if (props === undefined) return {};\n if (\"kind\" in props && props.kind === \"object\") {\n return props.fields as PropsDecl; // p.object(...) authored form\n }\n return props as PropsDecl;\n}\n\nfunction strataFieldOf(name: string, spec: PropSpec) {\n switch (spec.kind) {\n case \"string\":\n return field(\"string\", { default: spec.default ?? \"\" });\n case \"number\":\n return field(\"f64\", { default: spec.default ?? 0 });\n case \"boolean\":\n return field(\"bool\", { default: spec.default ?? false });\n case \"enum\": {\n const fallback = spec.default ?? spec.options[0] ?? \"\"; // p.enum enforces non-empty\n return field(enumOf([...spec.options]), { default: fallback });\n }\n case \"json\":\n return field(\"string\", { default: (spec as JsonSpec).default ?? \"null\" });\n case \"entityKey\":\n // A doc key is a string cell — `p.entityKey` is the DECLARED meaning, not\n // a distinct storage type (design-009 §4.2).\n return field(\"string\", { default: spec.default ?? \"\" });\n default:\n throw new Error(`ice: defineWidget prop \"${name}\" has an unknown spec kind.`);\n }\n}\n\n/**\n * Chain-coverage check (design-005 §6.4): to upgrade a doc written by ANY pack\n * version in `1..version-1`, the migrate chain needs an entry for every one of\n * those fromVersions. A gap means docs at the uncovered version stay read-only\n * (the M9 runner skips a type it cannot reach `version` from), so warn rather\n * than throw — a partial chain is a live-with-it degradation, not a definition\n * error. Keys ≥ `version` or ≤ 0 are meaningless fromVersions; flag them too.\n */\nfunction validateMigrateChain(\n type: string,\n version: number,\n migrate: Readonly<Record<number, unknown>>,\n): void {\n const keys = Object.keys(migrate).map(Number);\n if (keys.length === 0) return;\n const gaps: number[] = [];\n for (let v = 1; v < version; v++) {\n if (typeof migrate[v] !== \"function\") gaps.push(v);\n }\n if (gaps.length > 0) {\n console.warn(\n `ice: defineWidget(\"${type}\") migrate chain has gaps at fromVersion(s) [${gaps.join(\", \")}] — ` +\n `docs written at those versions cannot reach v${version} and will open read-only (design-005 §6.4).`,\n );\n }\n const stray = keys.filter((v) => v <= 0 || v >= version);\n if (stray.length > 0) {\n console.warn(\n `ice: defineWidget(\"${type}\") migrate declares transform(s) for fromVersion(s) [${stray.join(\", \")}] ` +\n `outside the migratable range 1..${version - 1} — they never run.`,\n );\n }\n}\n\n/**\n * Normalize the `preview` declaration: a bare component (function, or a\n * memo/forwardRef exotic — an object carrying `$$typeof`) vs. the options\n * form `{ component?, props? }`. Core never renders either — shape only.\n */\nfunction normalizePreview(preview: unknown): {\n component: unknown;\n props?: Readonly<Record<string, unknown>>;\n} {\n if (preview === undefined || preview === null) return { component: null };\n const isComponent =\n typeof preview === \"function\" || (typeof preview === \"object\" && \"$$typeof\" in (preview as object));\n if (isComponent) return { component: preview };\n const opts = preview as { component?: unknown; props?: Readonly<Record<string, unknown>> };\n return {\n component: opts.component ?? null,\n ...(opts.props !== undefined ? { props: opts.props } : {}),\n };\n}\n\nexport function defineWidget(def: WidgetDef): WidgetType {\n if (registry.has(def.type)) {\n throw new Error(`ice: widget type \"${def.type}\" is already defined.`);\n }\n const props = normalizeProps(def.props);\n const portIds = new Set<string>();\n for (const port of def.ports ?? []) {\n if (portIds.has(port.id)) throw new Error(`ice: widget \"${def.type}\" declares duplicate port id \"${port.id}\".`);\n portIds.add(port.id);\n }\n\n // Group membership: total and disjoint; ungrouped → the \"props\" group.\n const propToGroup: Record<string, string> = {};\n for (const [group, names] of Object.entries(def.groups ?? {})) {\n for (const name of names) {\n if (!(name in props)) {\n throw new Error(`ice: widget \"${def.type}\" group \"${group}\" lists unknown prop \"${name}\".`);\n }\n if (propToGroup[name] !== undefined) {\n throw new Error(`ice: widget \"${def.type}\" prop \"${name}\" is in two groups — groups must be disjoint.`);\n }\n propToGroup[name] = group;\n }\n }\n for (const name of Object.keys(props)) {\n propToGroup[name] ??= \"props\";\n }\n\n // One generated component per group, named `<type>:<group>`.\n const byGroup = new Map<string, Record<string, PropSpec>>();\n for (const [name, spec] of Object.entries(props)) {\n const g = propToGroup[name] as string;\n let fields = byGroup.get(g);\n if (fields === undefined) {\n fields = {};\n byGroup.set(g, fields);\n }\n fields[name] = spec;\n }\n const groups: WidgetGroup[] = [];\n // Raw strata field specs per group, kept for rename legacy compilation —\n // the legacy `<oldType>:<group>` components must be BYTE-IDENTICAL shapes.\n const rawByGroup = new Map<string, Record<string, FieldInput>>();\n for (const [g, fields] of byGroup) {\n const raw: Record<string, ReturnType<typeof strataFieldOf>> = {};\n for (const [name, spec] of Object.entries(fields)) raw[name] = strataFieldOf(name, spec);\n rawByGroup.set(g, raw);\n groups.push({ name: g, component: defineComponent(`${def.type}:${g}`, raw) as Component, fields });\n }\n\n // Rename declarations (design-008 §3): validate, then compile one legacy\n // component per CURRENT group under each old id. `ensureComponent` makes\n // re-evals (tests, hot reload) reuse instead of tripping strata's\n // duplicate-name throw; a same-name different-shape collision still throws.\n const renameDecls = def.renamedFrom ?? [];\n const legacyByOld = new Map<string, Component[]>();\n for (const decl of renameDecls) {\n if (decl.type === def.type) {\n throw new Error(`ice: widget \"${def.type}\" lists itself in renamedFrom.`);\n }\n if (registry.has(decl.type)) {\n throw new Error(`ice: widget \"${def.type}\" renamedFrom \"${decl.type}\" — that type is still a registered widget.`);\n }\n const holder = renameRegistry.get(decl.type);\n if (holder !== undefined && holder.widget.type !== def.type) {\n throw new Error(`ice: widget \"${def.type}\" renamedFrom \"${decl.type}\" — already claimed by \"${holder.widget.type}\".`);\n }\n if (legacyByOld.has(decl.type)) {\n throw new Error(`ice: widget \"${def.type}\" lists renamedFrom \"${decl.type}\" twice.`);\n }\n const legacy: Component[] = [];\n for (const g of groups) {\n legacy.push(ensureComponent(`${decl.type}:${g.name}`, rawByGroup.get(g.name) as Record<string, FieldInput>));\n }\n legacyByOld.set(decl.type, legacy);\n }\n\n // Essential set: geometry + every group at its defaults (+ container cells).\n const defaultSize = def.defaultSize ?? { w: 240, h: 160 };\n const essential: ComponentInit[] = [\n init(Position, { x: 0, y: 0 }),\n init(Size, { w: defaultSize.w, h: defaultSize.h }),\n // No StackZ (petition 8): stacking is the frame parent's ChildOf sibling\n // sequence — the spawn path hangs the edge (attachSpawnParent). Not a\n // group component, so no prefab-pack version bump rides its removal.\n ];\n for (const g of groups) {\n const defaults: Record<string, string | number | boolean> = {};\n for (const [name, spec] of Object.entries(g.fields)) defaults[name] = defaultValueOf(spec);\n essential.push([g.component, defaults] as ComponentInit);\n }\n if (def.container !== undefined) {\n essential.push(init(Accepts, { list: JSON.stringify(def.container.accepts) }));\n essential.push(init(Provides, { list: JSON.stringify(def.container.provides ?? []) }));\n } else if (def.provides !== undefined && def.provides.length > 0) {\n essential.push(init(Provides, { list: JSON.stringify(def.provides) })); // leaf: no Container tag\n }\n\n // Pre-attached behaviors: normalize the two authored forms and refuse the\n // one store class that cannot ride an entity.\n const behaviorEntries: WidgetBehaviorEntry[] = [];\n for (const decl of def.behaviors ?? []) {\n const entry: WidgetBehaviorEntry =\n \"behavior\" in (decl as AnyBehaviorAttachSpec)\n ? {\n behavior: (decl as AnyBehaviorAttachSpec).behavior as AnyBehaviorDef,\n data: ((decl as AnyBehaviorAttachSpec).data ?? {}) as Readonly<Record<string, unknown>>,\n }\n : { behavior: decl as AnyBehaviorDef, data: {} };\n if (entry.behavior?.__behavior !== true) {\n throw new Error(`ice: defineWidget(\"${def.type}\") behaviors: entry is not a defineBehavior handle.`);\n }\n if (entry.behavior.store === \"ephemeral\") {\n throw new Error(\n `ice: defineWidget(\"${def.type}\") lists ephemeral behavior \"${entry.behavior.name}\" — an ephemeral instance IS the local presence peer, so it cannot be pre-attached to a widget (design-009 §4.4).`,\n );\n }\n if (behaviorEntries.some((x) => x.behavior === entry.behavior)) {\n throw new Error(`ice: defineWidget(\"${def.type}\") lists behavior \"${entry.behavior.name}\" twice.`);\n }\n behaviorEntries.push(entry);\n }\n\n const version = def.version ?? 1;\n if (def.migrate !== undefined) validateMigrateChain(def.type, version, def.migrate);\n\n // Preview declaration: fail FAST on unknown previewProps names — a typo\n // would otherwise surface as a spawn throw inside the preview host's error\n // boundary (a silent placeholder), the worst place to find it.\n const previewDecl = normalizePreview(def.preview);\n for (const name of Object.keys(previewDecl.props ?? {})) {\n if (propToGroup[name] === undefined) {\n throw new Error(`ice: defineWidget(\"${def.type}\") preview.props names unknown prop \"${name}\".`);\n }\n }\n\n const prefab = definePrefab(def.type, {\n store: \"durable\",\n components: essential,\n // Every widget may carry a durable Opacity (design-004 §3: `{opacity}` is\n // the whole per-widget composite fact) — optional, not essential: widgets\n // pay no storage until one is attached, and readers default absent to 1.\n optional: [Opacity],\n // Every widget is containment-eligible: drop-to-consume commits\n // `ChildOf(widget → container)` in the SAME tx as the final position\n // (design-003 §5.5), and an undeclared relation throws at commit — the\n // widgetlab folder-drop field report (2026-07-12) hit exactly that.\n relations: [ChildOf],\n version,\n });\n\n // Capability recipe → runtime tags at projection (equip system).\n const interaction = def.interaction ?? {};\n const capabilityTags: Tag[] = [];\n if (interaction.selectable !== false) capabilityTags.push(Selectable);\n if (interaction.movable !== false) capabilityTags.push(Movable);\n if (interaction.resizable === true) capabilityTags.push(Resizable);\n if (interaction.solid === true) capabilityTags.push(Solid);\n if (interaction.dragOn === \"longPress\") capabilityTags.push(LongPressDrag);\n if (interaction.sweepContained === true) capabilityTags.push(SweepsContained);\n if (interaction.keyboard === \"exclusive\") capabilityTags.push(KeyboardExclusive);\n const snap = interaction.snap ?? \"target\";\n if (snap === \"source\" || snap === \"both\") capabilityTags.push(SnapSource);\n if (snap === \"target\" || snap === \"both\") capabilityTags.push(SnapTarget);\n if (def.container !== undefined) capabilityTags.push(Container);\n\n const widget: WidgetType = {\n type: def.type,\n version,\n prefab,\n groups,\n propToGroup,\n surface: def.surface,\n component: def.component,\n chrome: def.chrome,\n sizeMode: def.sizeMode ?? \"fixed\",\n defaultSize,\n minSize: def.minSize ?? { w: 40, h: 40 },\n animated: def.animated === true,\n ports: def.ports ?? [],\n capabilityTags,\n keyboard: interaction.keyboard ?? \"shared\",\n keyboardEscape: interaction.keyboardEscape ?? \"release\",\n migrate: def.migrate ?? {},\n behaviors: behaviorEntries,\n previewComponent: previewDecl.component,\n ...(previewDecl.props !== undefined ? { previewProps: previewDecl.props } : {}),\n };\n registry.set(def.type, widget);\n for (const decl of renameDecls) {\n renameRegistry.set(decl.type, {\n widget,\n oldType: decl.type,\n atVersion: decl.atVersion ?? 1,\n legacyGroups: legacyByOld.get(decl.type) as Component[],\n });\n }\n return widget;\n}\n\n/** TEST-ONLY wipe (mirrors __resetPrefabsForTests; not on the barrel). */\nexport function __resetWidgetsForTests(): void {\n registry.clear();\n renameRegistry.clear();\n}\n","/**\n * Nested canvas (design-004 §7 rev 2 — \"the missing systems\"; design-001\n * §5.7/§5.8 catalog).\n *\n * - `Active` = derived membership tag: a widget is Active iff the FIRST\n * container ancestor on its `ChildOf` chain is the current nav frame\n * (at root: no container ancestor at all). Children of a deeper container\n * are that container's content — not Active until you enter it.\n * - `activeMembership` (derive tick, before cull): recomputes membership and\n * flips Active/Visible/Culled CHANGE-ONLY, gated per design-004 §7\n * (`runIf: nav-change ∨ ChildOf churn`) as a drain-and-early-return tick\n * body — the spatialSync shape (petition 7 ChangeCollector; a `runIf`\n * cannot drain, and this system declares no writes so an early-out\n * blanket-stamps nothing). Idle frames cost one drain + one nav compare.\n * Full resweeps run on seed / reset / coarse / NAV CHANGE / container\n * despawn; everything else is delta-driven: a journaled entity whose\n * membership INPUTS (ChildOf edge, Container-ness) are unchanged is\n * skipped (drag frames journal Position every tick — O(1) each), a real\n * reparent/container-flip reclassifies its re-anchored subtree.\n * MEMBERSHIP-CHURN SIGNAL (why Position is the reparent proxy): relations\n * are not collector-journalable (strata CollectOptions = components +\n * tags), but coordinates are FRAME-LOCAL (design-001 §5.1) — a reparent\n * that does not rewrite Position into the new frame's space is already a\n * bug, and every real path co-writes: the doc sink commits reparent +\n * Position in ONE tx (doc-commit-sink.ts), and undo/redo/remote imports\n * project both rows of that tx. A bare runtime `world.setRelation(e,\n * ChildOf, …)` with no Position write on a pre-existing entity is OUTSIDE\n * the contract and goes stale until the next resweep.\n * - Nav stack = SESSION entities: `NavEntry` rows carry NavDepth + NavCamera\n * (the camera to restore on exit) + NavFrame(entry→container). Root =\n * empty stack. Current frame = deepest live entry's NavFrame target.\n * - `enterContainer`/`exitContainer` ops own the SPATIAL INDEX REBUILD:\n * membership flips don't move Transforms, so the incremental spatialSync\n * cache never fires on nav — the ops clear the index + caches and bump\n * `SpatialVersion`; spatialSync repopulates from the new Active set on the\n * next tick (its sweep-by-`seen` semantics make clear+repopulate exact).\n * - `navIntegrity` (react tick, before picking): if the current frame's\n * container died (undo/remote — NavFrame edge auto-cleared), pop to the\n * nearest LIVE ancestor entry (skipping dead ones) or root, restore that\n * camera, rebuild. The recognizer-integrity pattern applied to nav.\n * - Camera policy (design-006, amending design-004 §7; James 2026-07-15):\n * enter saves the live camera on the pushed entry (NavCamera) and ALWAYS\n * lands on the DEFAULT framing — zoom-to-fit over the frame's content, else\n * identity. The `ContainerCamera` rider is neither read nor written by the\n * engine anymore (per-canvas view memory made re-entry unpredictable); the\n * component stays in the catalog for userland. Exit restores the entry's\n * NavCamera — \"back where you came from\" is the nav stack, not view memory.\n * - Transitions (design-006 T1): with a live Viewport and `transition` not\n * \"none\", enter/exit CUT exactly as before and then FLY — the camera snaps\n * to the continuity-solved start and `navFlight` springs it to the arrival\n * (systems/nav-flight.ts). `exitTo(depth)` pops multi-level in ONE flight\n * through the composed portals (rebuilt from CURRENT container rects — a\n * collaborator may have moved a card). Headless (no Viewport) or opted-out\n * calls snap, preserving the pre-T1 behavior exactly.\n */\nimport type { ChangeCollector, Entity, TickSystem, World } from \"@vibecook/strata-ecs\";\nimport { defineQuery, defineTickSystem } from \"@vibecook/strata-ecs\";\nimport type { CameraState, PortalAffine, SpatialIndex } from \"@ice/kernel\";\nimport {\n composeAffine,\n fitCamera,\n invertAffine,\n portalAffine,\n solveFlightStart,\n visibleRect,\n} from \"@ice/kernel\";\nimport {\n Camera,\n CameraLimits,\n Container,\n Culled,\n MeasuredSize,\n NavCamera,\n NavDepth,\n NavFrame,\n Position,\n Size,\n Viewport,\n Visible,\n} from \"../catalog\";\nimport { abortNavFlight, startNavFlight } from \"../systems/nav-flight\";\nimport { Active } from \"../catalog/camera-derived\";\nimport { PrefabId } from \"../schema/prefab\";\nimport { SpatialVersion, bumpVersion } from \"../helpers/version-stamps\";\nimport { writeRuntimeResource } from \"../guards/resource-writer\";\nimport { ChildOf } from \"../catalog/scene\";\nimport { CAMERA_DEFAULTS, FIT_DEFAULTS } from \"../settings/defaults\";\nimport { WidgetEquipped, widgets } from \"../widget/define-widget\";\n\nconst navEntryQ = defineQuery([NavDepth, NavCamera]);\n// Keyed on PrefabId (present AT SPAWN — same flush as equip's WidgetEquipped\n// stamp), so Active lands the same tick projection does and the M6 mount\n// timing is unchanged. Chrome/pointers lack PrefabId; wires lack Position.\nconst equippedQ = defineQuery([Position, Size, PrefabId]);\n\n/** Deepest live nav entry, or undefined at root. */\nexport function currentNavEntry(world: World): Entity | undefined {\n let best: Entity | undefined;\n let bestDepth = -1;\n world.query(navEntryQ).each((b) => {\n for (const r of b) {\n const e = b.entity(r);\n const d = world.read(e, NavDepth).d;\n if (d > bestDepth) {\n bestDepth = d;\n best = e;\n }\n }\n });\n return best;\n}\n\n/** The container the user is inside, or undefined at root. */\nexport function currentNavFrame(world: World): Entity | undefined {\n const entry = currentNavEntry(world);\n if (entry === undefined) return undefined;\n const frame = world.getRelation(entry, NavFrame);\n return frame !== undefined && world.isAlive(frame) ? frame : undefined;\n}\n\n/**\n * Container-ness for MEMBERSHIP decisions, with the equip-lag fallback: the\n * `Container` capability tag lands at the equip flush, ONE FRAME after a\n * widget projects — but membership classifies on the projection frame (the\n * M6 mount-timing invariant). Answering from the runtime tag alone during\n * that window mis-anchors fresh container CONTENT to the root for a frame;\n * cull then mass-Visible-tags it in the same flush membership corrects it\n * (change-only writes let the conflict through), and the zombies stay\n * mounted forever (measured: 6,440 phantom mounts on a 10k-board seed,\n * 2026-07-15). Pre-equip, the WIDGET REGISTRY answers from PrefabId.\n */\nfunction isContainerForMembership(world: World, e: Entity): boolean {\n if (world.hasTag(e, Container)) return true;\n if (world.hasTag(e, WidgetEquipped)) return false; // equipped: the tag is truth\n const id = world.get(e, PrefabId)?.id;\n if (typeof id !== \"string\") return false;\n return widgets.get(id)?.capabilityTags.includes(Container) ?? false;\n}\n\n/** First container ancestor on the ChildOf chain (undefined = root-level). */\nfunction firstContainerAncestor(world: World, e: Entity): Entity | undefined {\n let cur = world.getRelation(e, ChildOf);\n let hops = 0;\n while (cur !== undefined && hops < 64) {\n if (isContainerForMembership(world, cur)) return cur;\n cur = world.getRelation(cur, ChildOf);\n hops += 1;\n }\n return undefined;\n}\n\n/** Per-op transition choice (design-006 §3.1); default is the portal zoom. */\nexport interface NavOpts {\n readonly transition?: \"zoom\" | \"none\";\n}\n\nexport interface NestedCanvas {\n readonly activeMembership: TickSystem;\n readonly navIntegrity: TickSystem;\n enterContainer(container: Entity, opts?: NavOpts): void;\n exitContainer(opts?: NavOpts): void;\n /** Pop to `targetDepth` in ONE transition (breadcrumb jumps; design-006 §5). */\n exitTo(targetDepth: number, opts?: NavOpts): void;\n /** Depth of the nav stack (0 = root). */\n depth(): number;\n}\n\nexport interface NestedCanvasOpts {\n /** THE spatial index (nav ops clear it; spatialSync repopulates). */\n readonly index: SpatialIndex<Entity>;\n /**\n * Clear spatialSync's private last-known cache alongside the index (the\n * install seam wires this; without it the compare-and-skip would believe\n * stale entries still exist).\n */\n readonly clearSpatialCaches: () => void;\n}\n\n/**\n * The membership stamper alone — installed by `installWidgetRuntime` (before\n * cull) so EVERY app partitions correctly, containers or not: a board with no\n * containers converges to all-Active on the first pass and never writes again.\n *\n * Gated per design-004 §7 (see the file header): the tick body drains a\n * petition-7 collector and early-returns on idle frames; membership work runs\n * only on nav change or membership-input churn. Baseline before this gate\n * (bench/membership-scale.test.ts, 2026-07-15): the full scan cost 19.0 ms\n * PER IDLE FRAME at 100k widgets nested 8 deep.\n */\nexport function createActiveMembership(world: World): TickSystem {\n // Created lazily on the FIRST run: both installWidgetRuntime and\n // createNestedCanvas construct an instance but rigs install only one — an\n // un-installed instance must never accumulate an undrained journal.\n let collector: ChangeCollector | undefined;\n let seeded = false;\n let lastFrame: Entity | undefined;\n let framePrimed = false;\n // Last-known membership INPUTS per equipped widget (the spatialSync `known`\n // pattern): ChildOf edge + Container-ness. A journaled entity whose inputs\n // are unchanged (Position-only churn — every drag frame) is skipped without\n // a chain walk. Rebuilt wholesale on every full resweep.\n let knownParent = new Map<Entity, Entity | undefined>();\n let knownContainer = new Set<Entity>();\n\n const isEquipped = (e: Entity): boolean =>\n world.has(e, PrefabId) && world.has(e, Position) && world.has(e, Size);\n\n return defineTickSystem(\n (ctx) => {\n if (collector === undefined) {\n // Position is the reparent proxy (frame-local co-write — file header);\n // PrefabId journals widget spawns/despawns; Container journals\n // container-ness flips (equip lands them one flush after spawn).\n // `coarse: false` is the same attestation spatialSync makes: every\n // writer of these components is store-visible (ctx/edit/projection).\n collector = world.changes.collect({\n components: [PrefabId, Position],\n tags: [Container],\n coarse: false,\n });\n }\n const delta = collector.drain();\n const frame = currentNavFrame(world);\n const navChanged = !framePrimed || frame !== lastFrame;\n framePrimed = true;\n lastFrame = frame;\n\n const classify = (e: Entity): void => {\n const member = firstContainerAncestor(world, e) === frame;\n if (member) {\n if (!ctx.hasTag(e, Active)) {\n ctx.addTag(e, Active); // cull re-classifies Visible next pass\n if (ctx.hasTag(e, Culled)) ctx.removeTag(e, Culled);\n }\n } else {\n // Canonical non-member state (never-was-active included): out of\n // Active, out of Visible, Culled — the mount store hides it and\n // the partition invariant (Visible ⊕ Culled over Active) holds.\n if (ctx.hasTag(e, Active)) ctx.removeTag(e, Active);\n if (ctx.hasTag(e, Visible)) ctx.removeTag(e, Visible);\n if (!ctx.hasTag(e, Culled)) ctx.addTag(e, Culled);\n }\n };\n\n // Container-despawn insurance: a dead container's ex-CHILDREN changed\n // first-ancestor without any journaled write of their own (a remote tx\n // can delete just the folder row; engine-local deletes cascade, so this\n // stays rare). Resweep rather than reconstruct the orphan set.\n let containerRemoved = false;\n for (const e of delta.removed) {\n if (knownContainer.delete(e)) containerRemoved = true;\n knownParent.delete(e);\n }\n\n // Structural resweeps rebuild the input caches; a NAV-ONLY resweep keeps\n // them — nav moves the frame, not the tree, and the cache rebuild is the\n // expensive half at scale (measured +80 ms on a 100k-entity enter).\n const structural = !seeded || delta.reset || delta.coarse.length > 0 || containerRemoved;\n if (structural || navChanged) {\n seeded = true;\n if (structural) {\n const nextParent = new Map<Entity, Entity | undefined>();\n const nextContainer = new Set<Entity>();\n ctx.query(equippedQ).each((b) => {\n for (const r of b) {\n const e = b.entity(r);\n classify(e);\n nextParent.set(e, world.getRelation(e, ChildOf));\n if (isContainerForMembership(world, e)) nextContainer.add(e);\n }\n });\n knownParent = nextParent;\n knownContainer = nextContainer;\n } else {\n ctx.query(equippedQ).each((b) => {\n for (const r of b) classify(b.entity(r));\n });\n }\n return;\n }\n\n if (delta.changed.length === 0) return; // the idle frame: one drain, one compare\n\n // Delta route: reclassify entities whose membership inputs changed plus\n // the subtree a reparent/container-flip re-anchors. The walk stops at\n // container CHILDREN (their content anchors to them — unaffected by a\n // move above), but the DFS ROOT recurses even when it is a container:\n // its container-ness may have just flipped, re-anchoring its children.\n const visited = new Set<Entity>();\n const reclassifySubtree = (root: Entity): void => {\n const stack: Entity[] = [root];\n while (stack.length > 0) {\n const e = stack.pop() as Entity;\n if (visited.has(e)) continue;\n visited.add(e);\n classify(e);\n if (e !== root && isContainerForMembership(world, e)) continue;\n for (const c of world.getReverse(e, ChildOf)) {\n if (isEquipped(c)) stack.push(c);\n }\n }\n };\n\n for (const e of delta.changed) {\n if (!world.isAlive(e) || !isEquipped(e)) continue;\n const parent = world.getRelation(e, ChildOf);\n const isCont = isContainerForMembership(world, e);\n if (knownParent.has(e) && knownParent.get(e) === parent && knownContainer.has(e) === isCont) {\n continue; // Position-only churn — membership inputs unchanged\n }\n knownParent.set(e, parent);\n if (isCont) knownContainer.add(e);\n else knownContainer.delete(e);\n reclassifySubtree(e);\n }\n },\n { name: \"activeMembership\" },\n );\n}\n\nexport function createNestedCanvas(world: World, opts: NestedCanvasOpts): NestedCanvas {\n const rebuildIndex = (): void => {\n opts.index.clear();\n opts.clearSpatialCaches();\n bumpVersion(world, SpatialVersion);\n };\n\n /**\n * THE VISIBILITY CUT (field glitch 2026-07-17): the op snaps the camera to\n * the flight start SYNCHRONOUSLY, but membership → cull → mount hide the\n * departed frame's content one to two ticks later — a few frames of the old\n * scene squeezed under the new camera at the portal. Nav member sets are\n * DISJOINT across a cut, so the op stamps the canonical non-member state\n * (¬Active ∧ ¬Visible ∧ Culled) on EVERY equipped widget right now (ops run\n * outside the tick — the index-rebuild legality); the next tick's membership\n * resweep re-derives the new frame's members, and every renderer (DOM\n * mounts, GL island phases, ground wires, selection chrome) reads the same\n * canonical signal, so the old frame vanishes on the same reflect pass that\n * first applies the new camera.\n */\n const cutVisibility = (): void => {\n // Two-phase: world.* tag writes are IMMEDIATE (archetype moves) and\n // illegal mid-iteration — collect, then mutate.\n const all: Entity[] = [];\n world.query(equippedQ).each((b) => {\n for (const r of b) all.push(b.entity(r));\n });\n for (const e of all) {\n if (world.hasTag(e, Active)) world.removeTag(e, Active);\n if (world.hasTag(e, Visible)) world.removeTag(e, Visible);\n if (!world.hasTag(e, Culled)) world.addTag(e, Culled);\n }\n };\n\n /**\n * The DEFAULT framing for a frame: kernel `fitCamera` over its direct\n * content — zoom-to-fit (FIT_DEFAULTS.pad) capped into the NATURAL band\n * (FIT_DEFAULTS ∩ the session's CameraLimits: never past 100%, never\n * below 50% — 2026-07-18, James: \"should feel natural\"); identity when\n * empty/headless. Sizes are measured-when-real (the folder minis' rule —\n * arrival and portal preview must agree). The flight PATH may transit\n * outside the band; only the arrival honors it. No `ContainerCamera`\n * rider (design-006).\n */\n const resolveArrivalCamera = (frame: Entity): CameraState => {\n const lim = world.getResource(CameraLimits) ?? CAMERA_DEFAULTS;\n // Band ∩ hard limits — when they don't overlap (e.g. minZoom 3), the\n // HARD limit wins: clamp each band edge into [lim.min, lim.max].\n const minZoom = Math.min(Math.max(FIT_DEFAULTS.minZoom, lim.minZoom), lim.maxZoom);\n const maxZoom = Math.max(Math.min(FIT_DEFAULTS.maxZoom, lim.maxZoom), lim.minZoom);\n let minX = Number.POSITIVE_INFINITY;\n let minY = Number.POSITIVE_INFINITY;\n let maxX = Number.NEGATIVE_INFINITY;\n let maxY = Number.NEGATIVE_INFINITY;\n let any = false;\n for (const child of world.getReverse(frame, ChildOf)) {\n const p = world.get(child, Position);\n const m = world.get(child, MeasuredSize);\n const s = m !== undefined && m.w > 0 ? m : world.get(child, Size);\n if (p === undefined || s === undefined) continue;\n minX = Math.min(minX, p.x);\n minY = Math.min(minY, p.y);\n maxX = Math.max(maxX, p.x + s.w);\n maxY = Math.max(maxY, p.y + s.h);\n any = true;\n }\n const vp = world.getResource(Viewport);\n if (!any || vp === undefined || vp.w === 0) {\n return { x: 0, y: 0, zoom: Math.min(maxZoom, Math.max(minZoom, 1)) };\n }\n return fitCamera(\n { x: minX, y: minY, width: maxX - minX, height: maxY - minY },\n vp.w,\n vp.h,\n { pad: FIT_DEFAULTS.pad, minZoom, maxZoom },\n );\n };\n\n const snapCamera = (c: CameraState): void => {\n writeRuntimeResource(world, Camera, { x: c.x, y: c.y, zoom: c.zoom, gesturing: false });\n };\n\n /** Flights need a real viewport and no opt-out; headless snaps (pre-T1 behavior). */\n const flightable = (opts: NavOpts | undefined): boolean => {\n const vp = world.getResource(Viewport);\n return opts?.transition !== \"none\" && vp !== undefined && vp.w > 0 && vp.h > 0;\n };\n\n /** Container body rect in its parent frame's coords — the portal (§8.5: full body for now). */\n const containerRect = (c: Entity): { x: number; y: number; width: number; height: number } | undefined => {\n const p = world.get(c, Position);\n const s = world.get(c, Size);\n if (p === undefined || s === undefined) return undefined;\n return { x: p.x, y: p.y, width: s.w, height: s.h };\n };\n\n const activeMembership = createActiveMembership(world);\n\n const navIntegrity = defineTickSystem(\n (ctx) => {\n // Pop past every entry whose frame died (undo/remote): destroy the dead\n // entry AND everything deeper (their return path is gone), restore the\n // shallowest doomed entry's saved camera, rebuild. Structural ops go\n // through ctx (law: systems never call structural world.*).\n let deadAt = Number.POSITIVE_INFINITY;\n ctx.query(navEntryQ).each((b) => {\n for (const r of b) {\n const e = b.entity(r);\n const frame = world.getRelation(e, NavFrame);\n if (frame === undefined || !world.isAlive(frame)) {\n deadAt = Math.min(deadAt, world.read(e, NavDepth).d);\n }\n }\n });\n if (!Number.isFinite(deadAt)) return;\n abortNavFlight(world); // integrity is never blocked on animation (design-006 §4)\n let restore: { x: number; y: number; zoom: number } | undefined;\n ctx.query(navEntryQ).each((b) => {\n for (const r of b) {\n const e = b.entity(r);\n const d = world.read(e, NavDepth).d;\n if (d < deadAt) continue;\n if (d === deadAt) {\n const cam = world.read(e, NavCamera);\n restore = { x: cam.x, y: cam.y, zoom: cam.zoom };\n }\n ctx.destroy(e);\n }\n });\n if (restore !== undefined) writeRuntimeResource(world, Camera, { ...restore, gesturing: false });\n // The same visibility cut the ops make (via ctx — this is a system):\n // an integrity pop swaps frames too, and stale content under the\n // restored camera is the same glitch.\n ctx.query(equippedQ).each((b) => {\n for (const r of b) {\n const e = b.entity(r);\n if (ctx.hasTag(e, Active)) ctx.removeTag(e, Active);\n if (ctx.hasTag(e, Visible)) ctx.removeTag(e, Visible);\n if (!ctx.hasTag(e, Culled)) ctx.addTag(e, Culled);\n }\n });\n rebuildIndex();\n },\n {\n name: \"navIntegrity\",\n runIf: () => {\n // Cheap guard: any nav entry at all? (root sessions skip entirely)\n return world.firstOf(navEntryQ) !== undefined;\n },\n },\n );\n\n const exitTo = (targetDepth: number, opts?: NavOpts): void => {\n // Live entries, depth ascending; the deepest is the current frame.\n const entries: { e: Entity; d: number }[] = [];\n world.query(navEntryQ).each((b) => {\n for (const r of b) {\n const e = b.entity(r);\n entries.push({ e, d: world.read(e, NavDepth).d });\n }\n });\n entries.sort((a, b) => a.d - b.d);\n const deepest = entries[entries.length - 1];\n if (deepest === undefined || targetDepth < 0 || targetDepth >= deepest.d) return;\n const doomed = entries.filter((x) => x.d > targetDepth);\n const shallowest = doomed[0] as { e: Entity; d: number }; // non-empty by the guard\n // The shallowest doomed entry's saved camera is the restore point (the\n // camera as it was the moment that level was entered).\n const restore = world.read(shallowest.e, NavCamera);\n const c1: CameraState = { x: restore.x, y: restore.y, zoom: restore.zoom };\n const camPre = world.getResource(Camera) ?? { x: 0, y: 0, zoom: 1, gesturing: false };\n\n // Compose the portal chain from CURRENT rects (containers move), outermost\n // first: A maps the departed frame's coords into the TARGET frame's. Any\n // dead/rect-less link degrades the whole jump to a snap — never half-fly.\n let A: PortalAffine | undefined;\n if (flightable(opts)) {\n const vp = world.getResource(Viewport) as { w: number; h: number };\n for (const { e } of doomed) {\n const frame = world.getRelation(e, NavFrame);\n const K = frame !== undefined && world.isAlive(frame) ? containerRect(frame) : undefined;\n if (frame === undefined || K === undefined) {\n A = undefined;\n break;\n }\n const M = portalAffine(visibleRect(resolveArrivalCamera(frame), vp.w, vp.h), K);\n A = A === undefined ? M : composeAffine(A, M);\n }\n }\n\n for (const { e } of doomed) world.destroy(e); // ops run OUTSIDE the tick — structural world.* is legal here\n cutVisibility(); // BEFORE the camera write (see enterContainer)\n if (A !== undefined) startNavFlight(world, \"exit\", A, solveFlightStart(A, camPre), c1);\n else snapCamera(c1);\n rebuildIndex();\n };\n\n return {\n activeMembership,\n navIntegrity,\n enterContainer(container, opts) {\n if (!world.isAlive(container) || !world.hasTag(container, Container)) {\n throw new Error(\"ice: enterContainer target is not a live container.\");\n }\n const cam = world.getResource(Camera) ?? { x: 0, y: 0, zoom: 1, gesturing: false };\n const depth = (currentNavEntry(world) !== undefined ? world.read(currentNavEntry(world) as Entity, NavDepth).d : 0) + 1;\n const entry = world.spawn({\n components: [\n [NavDepth, { d: depth }],\n [NavCamera, { x: cam.x, y: cam.y, zoom: cam.zoom }],\n ],\n });\n world.setRelation(entry, NavFrame, container);\n const c1 = resolveArrivalCamera(container);\n const K = containerRect(container);\n cutVisibility(); // BEFORE the camera write — no frame may render old content under the new camera\n if (flightable(opts) && K !== undefined) {\n const vp = world.getResource(Viewport) as { w: number; h: number };\n // A = M⁻¹: parent (departed) coords → child (destination) coords.\n const A = invertAffine(portalAffine(visibleRect(c1, vp.w, vp.h), K));\n startNavFlight(world, \"enter\", A, solveFlightStart(A, cam), c1);\n } else {\n snapCamera(c1);\n }\n rebuildIndex();\n },\n exitContainer(opts) {\n const entry = currentNavEntry(world);\n if (entry === undefined) return; // already at root\n exitTo(world.read(entry, NavDepth).d - 1, opts);\n },\n exitTo,\n depth() {\n const entry = currentNavEntry(world);\n return entry === undefined ? 0 : world.read(entry, NavDepth).d;\n },\n };\n}\n","/**\n * Sibling order — THE per-frame stacking source (petition 8; design-004 §1\n * amendment). Within a frame, paint/pick/drop order IS the frame parent's\n * ordered `ChildOf` sibling sequence: index 0 paints first (bottom), the tail\n * paints last (top). The frame parent is `currentNavFrame(world) ?? BoardRoot`\n * — every renderer/pick consumer shares this module so the orders can never\n * diverge (the point-pick lesson, extended to the comparator).\n *\n * LEGACY FALLBACK (must keep working): when the `BoardRoot` resource is absent\n * (a pre-schema-2 doc opened read-only, or a doc-less runtime world) OR an\n * entity carries no `ChildOf` edge (bare runtime spawns), stacking falls back\n * to the legacy `(StackZ.z asc, entity asc)` comparator. This module is the\n * ONLY sanctioned StackZ reader outside the schema migration.\n *\n * Mixed frames — some entities ordinal-mapped, some fallback — are nominally\n * impossible (the 1→2 migration hangs an edge on every durable widget, and a\n * pre-schema-2 read-only doc has no BoardRoot at all, so it is all-fallback).\n * The comparator still totals them: ordinal-mapped entities sort BELOW the\n * fallback set (ordinals first in paint order), each group internally ordered\n * by its own rule — documented so a stray bare spawn lands somewhere stable\n * rather than somewhere random.\n *\n * Invalidation is PULL-ONLY, the strata 0.8.0 contract: `world.orderStamp\n * (parent, ChildOf)` is a monotonic per-parent version consumers poll after a\n * reactive wake; the wake itself is an `observeQuery` whose grammar names the\n * relation (`Related(ChildOf)` — pure reorders turn it over).\n */\nimport type { Component, Entity, World } from \"@vibecook/strata-ecs\";\nimport { Related, defineQuery } from \"@vibecook/strata-ecs\";\nimport { BoardRoot, ChildOf, Position, StackZ } from \"../catalog/scene\";\nimport { currentNavFrame } from \"../nav/nested-canvas\";\n\n/** Structural read both `World` and `SystemCtx` provide — all the comparator needs. */\nexport interface StackOrderReader {\n get<S>(e: Entity, c: Component<S>): S | undefined;\n}\n\n/**\n * The frame parent — the entity whose `ChildOf` sibling sequence is the\n * current frame's stacking order: the nav frame when inside a container, else\n * the document's board root. `undefined` = a legacy world (pre-schema-2\n * read-only doc / doc-less runtime) — everything is fallback-ordered.\n */\nexport function frameParent(world: World): Entity | undefined {\n const frame = currentNavFrame(world);\n if (frame !== undefined) return frame;\n const root = world.getResource(BoardRoot)?.root;\n return root !== undefined && world.isAlive(root) ? root : undefined;\n}\n\n/** `parent`'s sibling sequence as entity → position (the renderers' sort key). */\nexport function buildOrdinals(world: World, parent: Entity): Map<Entity, number> {\n const seq = world.getReverse(parent, ChildOf);\n const map = new Map<Entity, number>();\n for (let i = 0; i < seq.length; i++) map.set(seq[i] as Entity, i);\n return map;\n}\n\n/**\n * THE stacking comparator (ascending = paint order; the pick tier takes the\n * max). Ordinal-mapped entities order by sibling position; entities missing\n * from the map use the legacy `(StackZ asc, entity asc)` fallback among\n * themselves and sort ABOVE the ordinal-mapped set (see the header note on\n * nominally-impossible mixed frames).\n */\nexport function compareStackOrder(\n reader: StackOrderReader,\n ordinals: ReadonlyMap<Entity, number>,\n a: Entity,\n b: Entity,\n): number {\n const oa = ordinals.get(a);\n const ob = ordinals.get(b);\n if (oa !== undefined && ob !== undefined) return oa - ob;\n if (oa !== undefined) return -1;\n if (ob !== undefined) return 1;\n const za = reader.get(a, StackZ)?.z ?? 0;\n const zb = reader.get(b, StackZ)?.z ?? 0;\n return za !== zb ? za - zb : Number(a) - Number(b);\n}\n\nexport interface SiblingOrderIndex {\n /** The frame parent backing the current ordinal map (undefined = legacy world). */\n parent(): Entity | undefined;\n /** The stamp-checked ordinal map — rebuilt only when the frame parent or its `orderStamp` moved. */\n ordinals(): ReadonlyMap<Entity, number>;\n /** True when the next `ordinals()` would rebuild (cheap pull; no rebuild). */\n stale(): boolean;\n /**\n * Arm the reorder wake: an `observeQuery` naming `ChildOf` (`Related`\n * grammar — pure reorders and edge turnover both fire it). Callers pair it\n * with `stale()`/`ordinals()` so other-frame churn stays a no-op.\n */\n observe(cb: () => void): () => void;\n}\n\n// Widgets all carry Position; naming ChildOf makes reorders (not just edge\n// membership) turn the watch over — the ordered-relations wake contract.\nconst orderWakeQ = defineQuery([Position, Related(ChildOf)]);\n\n/**\n * A pull-based ordinal cache over the CURRENT frame parent's sibling sequence.\n * Consumers each hold their own instance (the cache is a cheap `getReverse`\n * walk); correctness is shared through {@link compareStackOrder} and the\n * stamp, never through instance identity.\n */\nexport function createSiblingOrderIndex(world: World): SiblingOrderIndex {\n const empty: ReadonlyMap<Entity, number> = new Map();\n let built: ReadonlyMap<Entity, number> = empty;\n let builtParent: Entity | undefined;\n let builtStamp = 0;\n let hasBuilt = false;\n\n const stale = (): boolean => {\n const parent = frameParent(world);\n if (!hasBuilt || parent !== builtParent) return true;\n return parent !== undefined && world.orderStamp(parent, ChildOf) !== builtStamp;\n };\n\n return {\n parent: () => frameParent(world),\n ordinals() {\n if (!stale()) return built;\n const parent = frameParent(world);\n builtParent = parent;\n builtStamp = parent === undefined ? 0 : world.orderStamp(parent, ChildOf);\n built = parent === undefined ? empty : buildOrdinals(world, parent);\n hasBuilt = true;\n return built;\n },\n stale,\n observe: (cb) => world.reactive.observeQuery(orderWakeQ, cb),\n };\n}\n","/**\n * THE point-pick (Law 15: the spatial index is the only hit path; this\n * function is its only narrow-phase). Shared verbatim by the in-tick\n * `picking` system (L1, via SystemCtx) and the pointer router's synchronous\n * event-time pick (design-004 §4 GL path, via World — world reads outside\n * the tick are verified-unrestricted). One implementation so the two can\n * never disagree on ordering.\n *\n * Priority: HandleSpec chrome first (nearest edge), then widgets topmost by\n * SIBLING ORDER (petition 8: the frame parent's ChildOf sequence, legacy\n * (StackZ, entity) fallback for edge-less entities — compareStackOrder is the\n * ONE comparator paint and pick share). Deliberately NOT plane-stratified:\n * cross-plane z is stratified visually (P2 GL composites above P1 DOM), but\n * pick order is sibling order across all surfaces — design-004 §1 names the\n * mixed-overlap consequence and accepts it; do not \"fix\" it here.\n */\nimport type { Component, Entity } from \"@vibecook/strata-ecs\";\nimport type { Cubic, SpatialIndex } from \"@ice/kernel\";\nimport { distanceToCubic } from \"@ice/kernel\";\nimport { HandleSpec, Port, Position, Wire } from \"../catalog\";\nimport { compareStackOrder } from \"./sibling-order\";\n\n/** Structural reads both `World` and `SystemCtx` provide. */\nexport interface PickReader {\n isAlive(e: Entity): boolean;\n has(e: Entity, c: Component): boolean;\n hasTag(e: Entity, t: import(\"@vibecook/strata-ecs\").Tag): boolean;\n get<S>(e: Entity, c: Component<S>): S | undefined;\n}\n\n/** Wire narrow-phase source: cached cubics from wireSync (M8). */\nexport interface WirePickSource {\n cubicOf(e: Entity): Cubic | undefined;\n /** Pick slop in WORLD units (screen slop / zoom, caller-converted). */\n readonly slopWorld: number;\n}\n\n/** Distance from a point to the nearest edge of an AABB (0 iff inside). */\nexport function distPointToBox(\n px: number,\n py: number,\n minX: number,\n minY: number,\n maxX: number,\n maxY: number,\n): number {\n const dx = Math.max(minX - px, 0, px - maxX);\n const dy = Math.max(minY - py, 0, py - maxY);\n return Math.hypot(dx, dy);\n}\n\n/** No frame parent (legacy world) — every widget compares by the fallback. */\nconst NO_ORDINALS: ReadonlyMap<Entity, number> = new Map();\n\n/**\n * Top pick under a world point within `rWorld` (point-in-box when 0).\n * Tier order (design-003 §3, amended for M8): HandleSpec chrome → PORT\n * entities (interaction affordances sit atop their widget edge) → widgets by\n * sibling order (topmost = compareStackOrder max; `ordinals` is the caller's\n * frame ordinal map — SiblingOrderIndex — so paint and pick share one order)\n * → WIRES (render in P0 under content; pick below widgets, above\n * canvas — render order and pick order agree). The canvas fallback stays the\n * caller's. Wires narrow-phase against their cached cubic (`wires` source;\n * without one, wire entries are skipped — coarse AABB hits would make fat\n * bounding boxes steal canvas taps).\n */\nexport function pickTopAt(\n reader: PickReader,\n index: SpatialIndex<Entity>,\n wx: number,\n wy: number,\n rWorld: number,\n wires?: WirePickSource,\n ordinals: ReadonlyMap<Entity, number> = NO_ORDINALS,\n): Entity | undefined {\n let bestHandle: Entity | undefined;\n let bestHandleD = Number.POSITIVE_INFINITY;\n let bestPort: Entity | undefined;\n let bestPortD = Number.POSITIVE_INFINITY;\n let bestWidget: Entity | undefined;\n let bestWire: Entity | undefined;\n let bestWireD = Number.POSITIVE_INFINITY;\n for (const entry of index.searchPoint(wx, wy, rWorld)) {\n const e = entry.id;\n if (!reader.isAlive(e)) continue;\n const d = distPointToBox(wx, wy, entry.minX, entry.minY, entry.maxX, entry.maxY);\n if (d > rWorld) continue; // narrow: disc-vs-box\n if (reader.has(e, HandleSpec)) {\n if (d < bestHandleD) {\n bestHandleD = d;\n bestHandle = e;\n }\n } else if (reader.has(e, Port)) {\n if (d < bestPortD) {\n bestPortD = d;\n bestPort = e;\n }\n } else if (reader.hasTag(e, Wire)) {\n if (wires === undefined) continue;\n const cubic = wires.cubicOf(e);\n if (cubic === undefined) continue;\n const wd = distanceToCubic(wx, wy, cubic);\n if (wd <= rWorld + wires.slopWorld && wd < bestWireD) {\n bestWireD = wd;\n bestWire = e;\n }\n } else if (reader.has(e, Position)) {\n if (bestWidget === undefined || compareStackOrder(reader, ordinals, e, bestWidget) > 0) {\n bestWidget = e;\n }\n }\n }\n return bestHandle ?? bestPort ?? bestWidget ?? bestWire;\n}\n","/**\n * Port-slot resolution: a widget's port DECLARATIONS (from the widget registry,\n * design-005 §2) → kernel `PortSlot`s (side + even-distribution index/count).\n *\n * The single source of a port's world anchor is the kernel's pure\n * `portAnchor(widgetRect, slot)` — geometry NEVER reads a port ENTITY (design-001\n * §5.3), so wires, the connect preview, and materialized-port anchors all agree\n * by construction and culled endpoints resolve for free. Ports sharing a side are\n * numbered by their declared `index` when given, else by declaration order; the\n * side's `count` drives the even spacing.\n */\nimport type { PortSide, PortSlot } from \"@ice/kernel\";\nimport type { WidgetPortDecl } from \"../widget/define-widget\";\n\n/** Map every declared port id → its `PortSlot` (side/index/count for even spacing). */\nexport function portSlots(decls: readonly WidgetPortDecl[]): Map<string, PortSlot> {\n const bySide = new Map<PortSide, WidgetPortDecl[]>();\n for (const d of decls) {\n let list = bySide.get(d.side);\n if (list === undefined) {\n list = [];\n bySide.set(d.side, list);\n }\n list.push(d);\n }\n const out = new Map<string, PortSlot>();\n for (const [side, list] of bySide) {\n for (let i = 0; i < list.length; i++) {\n const d = list[i];\n if (d === undefined) continue;\n out.set(d.id, { side, index: d.index ?? i, count: list.length });\n }\n }\n return out;\n}\n\n/** The `PortSlot` for one port id (undefined if the widget declares no such port). */\nexport function portSlotOf(decls: readonly WidgetPortDecl[], portId: string): PortSlot | undefined {\n return portSlots(decls).get(portId);\n}\n","/**\n * L1 — wire geometry sync (design-004 §6 ports & wires runtime; `react` phase,\n * AFTER `spatialSync`).\n *\n * A wire is a durable reified edge (Wire tag + WireFrom/WireTo → widgets +\n * WirePorts ids). Its RENDER + PICK geometry is a pure function of the two\n * endpoint widget rects and their port declarations (design-001 §5.3: geometry\n * never reads a port entity — culled endpoints resolve by construction). This\n * TICK system (strata 0.5.0) recomputes each wire's cubic once per frame and\n * keeps a private cache so the shared spatial index only churns on real\n * movement — exactly the `spatialSync` idiom, and the reason it must run every\n * frame: it is a `SpatialVersion` writer and cannot gate on the version it bumps.\n *\n * Per wire: resolve WireFrom/WireTo → endpoint Position+Size + the port slot\n * (PrefabId → widget registry → decl → kernel `portAnchor`) → `wireCubic` →\n * `cubicAABB`. Endpoint or declaration unresolvable (mid-projection, a despawned\n * widget, a removed port id) ⇒ the wire leaves the index (invisible to picking;\n * the renderer draws nothing for it). The cache also feeds the `WirePickSource`\n * the point-pick narrow-phases against (`ops/point-pick`), and exposes the\n * screen-constant pick slop as `slopWorld = wirePickSlopPx / zoom`.\n */\nimport type { Component, Entity, TickSystem, World } from \"@vibecook/strata-ecs\";\nimport { defineQuery, defineTickSystem } from \"@vibecook/strata-ecs\";\nimport { type AABB, type Cubic, type SpatialIndex, cubicAABB, portAnchor, wireCubic } from \"@ice/kernel\";\nimport { Camera, Position, Size, Wire, WireFrom, WirePorts, WireTo } from \"../catalog\";\nimport { SpatialVersion, bumpVersion } from \"../helpers/version-stamps\";\nimport { portSlotOf } from \"../ops/port-geometry\";\nimport type { WirePickSource } from \"../ops/point-pick\";\nimport { PrefabId } from \"../schema/prefab\";\nimport { GRAPH_PICK_DEFAULTS } from \"../settings/defaults\";\nimport { widgets } from \"../widget/define-widget\";\n\n/** The structural read the endpoint resolver needs (World and SystemCtx both satisfy it). */\ninterface AnchorReader {\n get<S>(e: Entity, c: Component<S>): S | undefined;\n}\n\ninterface WireCacheEntry {\n fx: number;\n fy: number;\n tx: number;\n ty: number;\n fromSide: string;\n toSide: string;\n cubic: Cubic;\n aabb: AABB;\n}\n\nexport interface WireSyncSystem {\n wireSync: TickSystem;\n /** The narrow-phase source `pickTopAt` consults for wire entries. */\n wires: WirePickSource;\n}\n\nconst wireQ = defineQuery([Wire, WirePorts]);\n\n/** Endpoint anchor (world) for a wire's end, or undefined if unresolvable. */\nfunction endpointAnchor(\n reader: AnchorReader,\n widget: Entity | undefined,\n portId: string,\n): { x: number; y: number; side: string } | undefined {\n if (widget === undefined) return undefined;\n const pos = reader.get(widget, Position);\n const size = reader.get(widget, Size);\n if (pos === undefined || size === undefined) return undefined;\n const type = reader.get(widget, PrefabId)?.id;\n const decls = typeof type === \"string\" ? widgets.get(type)?.ports : undefined;\n if (decls === undefined) return undefined;\n const slot = portSlotOf(decls, portId);\n if (slot === undefined) return undefined;\n const a = portAnchor({ x: pos.x, y: pos.y, width: size.w, height: size.h }, slot);\n return { x: a.x, y: a.y, side: slot.side };\n}\n\nexport function createWireSync(world: World, index: SpatialIndex<Entity>): WireSyncSystem {\n // Private per-wire geometry cache — the compare-and-skip that keeps this cheap\n // while it runs every frame (it is the SpatialVersion writer, spatialSync idiom).\n const cache = new Map<Entity, WireCacheEntry>();\n\n const wireSync = defineTickSystem(\n (ctx) => {\n const seen = new Set<Entity>();\n let changed = false;\n\n ctx.query(wireQ).each((batch) => {\n for (const row of batch) {\n const wire = batch.entity(row);\n const ports = ctx.read(wire, WirePorts);\n const from = endpointAnchor(ctx, ctx.getRelation(wire, WireFrom), ports.from ?? \"\");\n const to = endpointAnchor(ctx, ctx.getRelation(wire, WireTo), ports.to ?? \"\");\n if (from === undefined || to === undefined) {\n // Unresolvable this frame — drop from the index (renderer draws nothing).\n if (cache.has(wire)) {\n index.remove(wire);\n cache.delete(wire);\n changed = true;\n }\n continue;\n }\n seen.add(wire);\n const prev = cache.get(wire);\n if (\n prev !== undefined &&\n prev.fx === from.x &&\n prev.fy === from.y &&\n prev.tx === to.x &&\n prev.ty === to.y &&\n prev.fromSide === from.side &&\n prev.toSide === to.side\n ) {\n continue; // geometry unchanged — no index churn\n }\n const cubic = wireCubic(\n { x: from.x, y: from.y },\n from.side as \"n\" | \"e\" | \"s\" | \"w\",\n { x: to.x, y: to.y },\n to.side as \"n\" | \"e\" | \"s\" | \"w\",\n );\n const aabb = cubicAABB(cubic);\n index.upsert(wire, aabb);\n cache.set(wire, {\n fx: from.x,\n fy: from.y,\n tx: to.x,\n ty: to.y,\n fromSide: from.side,\n toSide: to.side,\n cubic,\n aabb,\n });\n changed = true;\n }\n });\n\n // Sweep wires that despawned (or went unresolvable and were never re-added).\n const gone: Entity[] = [];\n for (const e of cache.keys()) if (!seen.has(e)) gone.push(e);\n for (const e of gone) {\n index.remove(e);\n cache.delete(e);\n changed = true;\n }\n\n if (changed) bumpVersion(world, SpatialVersion);\n },\n { name: \"wireSync\" },\n );\n\n const wires: WirePickSource = {\n cubicOf: (e) => cache.get(e)?.cubic,\n get slopWorld() {\n const zoom = world.getResource(Camera)?.zoom ?? 1;\n return GRAPH_PICK_DEFAULTS.wirePickSlopPx / (zoom || 1);\n },\n };\n\n return { wireSync, wires };\n}\n","/**\n * `defineTool` — tools are PURE CONFIGURATION (design-005 §3): a tool\n * introduces no new code paths, it only parameterizes L2 spawn (which\n * recognizer kinds a pointer-down mints), L4 cursor, the L3 dragRoute\n * policy, and capability gates. Custom behaviors register systems via the\n * engine's extension slot — same contract as built-ins (design-003 §5.0).\n *\n * Built-ins ship as configs of this same primitive:\n * - select: tap/longPress/drag; canvas drag → marquee (pan on touch /\n * space / middle-button — device conventions, honored ABOVE tool policy).\n * - pan: hand cursor; every drag pans.\n * - connect: crosshair; widget/port drags connect (design-003 §5.8).\n * - draw(widgetType): factory — canvas drag creates ONE widget from the\n * drag rect at JustEnded (one tx via the create intent; min-size floor;\n * drag preview is recorded polish, not v1 — design-001 §3's full\n * draft→promote protocol remains the vNext shape).\n *\n * Switching tools runs `cancelActiveGestures()` first (design-003 §8) —\n * `ops.setTool` owns that; nothing here touches the world.\n */\nimport type { SingleKindName } from \"../systems/l2-recognize\";\n\nexport type CanvasDragRoute = \"marquee\" | \"pan\" | \"connect\" | \"draw\" | \"none\";\nexport type WidgetDragRoute = \"move\" | \"pan\" | \"connect\" | \"none\";\n\nexport interface ToolRoute {\n /** Drag starting on empty canvas (after device overrides: touch/space/middle → pan). */\n readonly canvasDrag?: CanvasDragRoute;\n /** Drag starting on a widget body. */\n readonly widgetDrag?: WidgetDragRoute;\n /** Drag starting on a port entity (\"connect\" | \"none\"). */\n readonly portDrag?: \"connect\" | \"none\";\n}\n\nexport interface ToolGates {\n /** false ⇒ widget drags never route to move while this tool is active. */\n readonly movable?: boolean;\n /** false ⇒ resize-handle grabs are suppressed while this tool is active. */\n readonly resizable?: boolean;\n}\n\nexport interface ToolDef {\n readonly id: string;\n /** L4 cursor while active (OS cursor string; design-003 §7). */\n readonly cursor?: string;\n /** Recognizer kinds minted per pointer-down (design-003 §4.1). */\n readonly spawnProfile?: readonly SingleKindName[];\n readonly route?: ToolRoute;\n readonly gates?: ToolGates;\n /** Default keymap entry (the react keymap consumes; app-overridable). */\n readonly shortcut?: string;\n /** draw tools: the widget type the drag rect creates. */\n readonly draw?: { readonly widgetType: string };\n}\n\nexport interface Tool extends Required<Pick<ToolDef, \"id\">> {\n readonly cursor: string | undefined;\n readonly spawnProfile: readonly SingleKindName[];\n readonly route: Required<ToolRoute>;\n readonly gates: Required<ToolGates>;\n readonly shortcut: string | undefined;\n readonly draw: { readonly widgetType: string } | undefined;\n}\n\n/** The select tool's canonical shape — also every unknown tool's fallback. */\nconst SELECT_DEFAULTS: Omit<Tool, \"id\" | \"shortcut\"> = {\n cursor: undefined,\n spawnProfile: [\"tap\", \"longPress\", \"drag\"],\n route: { canvasDrag: \"marquee\", widgetDrag: \"move\", portDrag: \"connect\" },\n gates: { movable: true, resizable: true },\n draw: undefined,\n};\n\nconst registry = new Map<string, Tool>();\n\nexport function defineTool(def: ToolDef): Tool {\n if (registry.has(def.id)) {\n throw new Error(`ice: tool \"${def.id}\" is already defined.`);\n }\n const tool: Tool = {\n id: def.id,\n cursor: def.cursor,\n spawnProfile: def.spawnProfile ?? SELECT_DEFAULTS.spawnProfile,\n route: { ...SELECT_DEFAULTS.route, ...def.route },\n gates: { ...SELECT_DEFAULTS.gates, ...def.gates },\n shortcut: def.shortcut,\n draw: def.draw,\n };\n registry.set(def.id, tool);\n return tool;\n}\n\nexport const tools = {\n get(id: string): Tool | undefined {\n return registry.get(id);\n },\n all(): Tool[] {\n return [...registry.values()];\n },\n /** The active tool's policy, with select semantics for unknown ids. */\n resolve(id: string): Tool {\n return registry.get(id) ?? { ...SELECT_DEFAULTS, id, shortcut: undefined };\n },\n};\n\n/** TEST-ONLY wipe (mirrors __resetWidgetsForTests; not on the barrel). */\nexport function __resetToolsForTests(): void {\n registry.clear();\n registerBuiltinTools();\n}\n\n/** Idempotent — runs at module load (built-ins are the engine's canonical\n * vocabulary, DEFAULT_SPAWN_PROFILES precedent); safe under HMR. */\nexport function registerBuiltinTools(): void {\n if (!registry.has(\"select\")) {\n defineTool({ id: \"select\", shortcut: \"v\" });\n }\n if (!registry.has(\"pan\")) {\n defineTool({\n id: \"pan\",\n cursor: \"grab\",\n spawnProfile: [\"drag\"],\n route: { canvasDrag: \"pan\", widgetDrag: \"pan\", portDrag: \"none\" },\n gates: { movable: false, resizable: false },\n shortcut: \"h\",\n });\n }\n if (!registry.has(\"connect\")) {\n defineTool({\n id: \"connect\",\n cursor: \"crosshair\",\n spawnProfile: [\"drag\"],\n route: { canvasDrag: \"pan\", widgetDrag: \"connect\", portDrag: \"connect\" },\n gates: { movable: false, resizable: false },\n shortcut: \"c\",\n });\n }\n}\n\n/** Factory (design-005 §3): a drag on canvas creates `widgetType` from the rect. */\nexport function createDrawTool(widgetType: string, opts: { id?: string; shortcut?: string } = {}): Tool {\n return defineTool({\n id: opts.id ?? `draw:${widgetType}`,\n cursor: \"crosshair\",\n spawnProfile: [\"drag\"],\n route: { canvasDrag: \"draw\", widgetDrag: \"none\", portDrag: \"none\" },\n gates: { movable: false, resizable: false },\n ...(opts.shortcut !== undefined ? { shortcut: opts.shortcut } : {}),\n draw: { widgetType },\n });\n}\n\nregisterBuiltinTools();\n","/**\n * L2 — recognizer lifecycle + per-kind FSMs (design-003 §4.1–§4.2).\n *\n * `ctl:spawn` — cancelSweep (consumes the one-tick CancelRequest) →\n * recognizerSpawn (tool profiles; pinch on 2nd touch suspends\n * singles; wheel recognizers are `Simultaneous`) →\n * recognizerIntegrity (requiredWatches counts, capture death,\n * suspension lift). Newborns are identity-only until the\n * ctl:spawn flush, so integrity naturally skips them until the\n * next frame — by which time their edges are placed.\n * `ctl:recognize` — per-kind systems. Transitions go through the PhaseSet via\n * `ctx` (visible at this phase's flush — arbitration reads them\n * the same frame); field updates are immediate `edit().set`\n * under declared `access.write`.\n *\n * All timing reads FrameInfo.CLOCK — the accumulated CLAMPED-dt gesture clock\n * (2026-07-17, supersedes both raw FrameInfo.now and the 2026-07-12\n * event-timestamp anchor): rAF `now` lags wall time by up to SECONDS under\n * throttling/headless/software rendering while event.timeStamp does not, so\n * any window mixing the two evaluates garbage; `clock` is monotonic, stalls\n * contribute ≤ dtClampMs (the stall-protection intent), and no event\n * timestamp ever enters window math. All thresholds read the GestureSettings\n * RESOURCE (live-tunable, design-005 §4) with the GESTURE_DEFAULTS constants\n * as the unset fallback. Gesture math is screen-space totals + zoom-at-claim\n * — never live PointerWorld (design-002 §2 staleness rule).\n */\nimport type { Entity, SystemCtx, World } from \"@vibecook/strata-ecs\";\nimport { Any, Not, defineQuery, defineSystem, type System, type Tag } from \"@vibecook/strata-ecs\";\nimport {\n Camera,\n CancelRequest,\n Captures,\n ClaimedBy,\n Down,\n Drag,\n GesturePhases,\n GestureSuspended,\n HadCapture,\n InsertGhost,\n HadRequiresFail,\n HadSequence,\n HandledByWidget,\n LocalPointer,\n LongPress,\n LongPressDrag,\n MultiTap,\n Pinch,\n Pointer,\n PointerButtons,\n PointerScreen,\n PointerWheel,\n RequiresFail,\n Sequence,\n SnapState,\n Simultaneous,\n Tap,\n TouchesExact,\n Watches,\n WentCancelled,\n WentDown,\n WentUp,\n WheelHandled,\n WheelPan,\n WheelZoom,\n} from \"../catalog\";\nimport { ActiveTool } from \"../catalog/camera-derived\";\nimport { FrameInfo } from \"../engine/frame-info\";\nimport { GestureSettings } from \"../catalog/settings-resources\";\nimport { tools } from \"../tools/define-tool\";\nimport { GESTURE_DEFAULTS } from \"../settings/defaults\";\n\nexport type SingleKindName = \"tap\" | \"longPress\" | \"drag\";\n\n/** Tool id → single-pointer recognizer set spawned per down (design-003 §4.1). */\nexport type SpawnProfiles = Readonly<Record<string, readonly SingleKindName[]>>;\n\nexport const DEFAULT_SPAWN_PROFILES: SpawnProfiles = {\n select: [\"tap\", \"longPress\", \"drag\"],\n pan: [\"drag\"],\n};\n\nconst anyKindQ = defineQuery([Any(Tap, LongPress, Drag, Pinch, WheelPan, WheelZoom)]);\nconst downQ = defineQuery([Pointer, WentDown, Not(HandledByWidget), LocalPointer]);\nconst heldTouchQ = defineQuery([Pointer, PointerButtons, LocalPointer]);\n// `Not(WheelHandled)` mirrors downQ's `Not(HandledByWidget)` one line up — the\n// wheel-specific opt-out (design-007 §3.5): a ceded tick spawns no recognizer,\n// while a same-tick canvas DOWN on the same pointer is untouched.\nconst wheelSourceQ = defineQuery([Pointer, PointerWheel, LocalPointer, Not(WheelHandled)]);\nconst tapQ = defineQuery([Tap, Not(GestureSuspended)]);\nconst longPressQ = defineQuery([LongPress, Not(GestureSuspended)]);\nconst dragQ = defineQuery([Drag, Not(GestureSuspended)]);\nconst pinchQ = defineQuery([Pinch]);\nconst wheelKindQ = defineQuery([Any(WheelPan, WheelZoom)]);\nconst pendingTapQ = defineQuery([Tap, GesturePhases.tags.Pending]);\nconst pendingQ = defineQuery([Any(Tap, LongPress, Drag, Pinch), GesturePhases.tags.Pending]);\n\nconst P = GesturePhases;\n\n/** Live-tunable gesture settings (design-005 §4): resource first, const fallback. */\nfunction gs(ctx: SystemCtx): Readonly<Record<keyof typeof GESTURE_DEFAULTS, number>> {\n return ctx.getResource(GestureSettings) ?? GESTURE_DEFAULTS;\n}\n\n/** The gesture clock (see the header — NEVER FrameInfo.now for window math). */\nfunction clk(ctx: SystemCtx): number {\n return ctx.getResource(FrameInfo)?.clock ?? 0;\n}\n\n\n/** A recognizer is in a phase from which no further recognition can happen. */\nfunction isTerminal(ctx: SystemCtx | World, e: Entity): boolean {\n if (ctx.hasTag(e, P.tags.Failed) || ctx.hasTag(e, P.tags.Cancelled) || ctx.hasTag(e, P.tags.Ended)) {\n return true;\n }\n // Recognized is terminal for Tap only — LongPress keeps a continuous tail.\n return ctx.hasTag(e, P.tags.Recognized) && ctx.has(e, Tap);\n}\n\nfunction requiredWatches(ctx: SystemCtx | World, e: Entity): number {\n return ctx.has(e, Pinch) ? 2 : 1;\n}\n\nfunction dist(ax: number, ay: number, bx: number, by: number): number {\n return Math.hypot(bx - ax, by - ay);\n}\n\nexport interface L2Deps {\n readonly world: World;\n readonly profiles?: SpawnProfiles;\n}\n\nexport interface L2Systems {\n cancelSweep: System;\n recognizerSpawn: System;\n /** Same design slot as recognizerSpawn (design-002 §2) over the wheel-source query. */\n wheelSpawn: System;\n recognizerIntegrity: System;\n tapSystem: System;\n longPressSystem: System;\n dragSystem: System;\n pinchSystem: System;\n wheelSystem: System;\n /** Resolves Pending `Sequence`/`RequiresFail` edges; last in `ctl:recognize`. */\n dependencySystem: System;\n}\n\nexport function createL2Systems({ world, profiles = DEFAULT_SPAWN_PROFILES }: L2Deps): L2Systems {\n /** Non-terminal recognizers watching `pointer` (live reverse edges). */\n const watchersOf = (ctx: SystemCtx, pointer: Entity): Entity[] =>\n ctx.getReverse(pointer, Watches).filter((rec) => !isTerminal(ctx, rec));\n\n const cancelSweep = defineSystem(\n anyKindQ,\n (b, ctx) => {\n for (const r of b) {\n const e = b.entity(r);\n if (isTerminal(ctx, e)) continue;\n P.set(ctx, e, \"Cancelled\");\n }\n },\n {\n name: \"cancelSweep\",\n runIf: (ctx) => ctx.getResource(CancelRequest)?.active === true,\n },\n );\n\n const recognizerSpawn = defineSystem(\n downQ,\n (b, ctx) => {\n const now = clk(ctx);\n const tool = ctx.getResource(ActiveTool)?.id ?? \"select\";\n // Explicit profiles (test/app override) → tool registry (design-005 §3)\n // → select. Tools parameterize L2 spawn purely through config.\n const profile = profiles[tool] ?? tools.get(tool)?.spawnProfile ?? DEFAULT_SPAWN_PROFILES.select ?? [];\n\n for (const r of b) {\n const pointer = b.entity(r);\n\n // Skip pointers already claimed by a live, non-terminal recognizer.\n const claimant = ctx.getRelation(pointer, ClaimedBy);\n if (claimant !== undefined && !isTerminal(ctx, claimant)) continue;\n\n const screen = ctx.read(pointer, PointerScreen);\n const captureTarget = ctx.getRelation(pointer, TouchesExact);\n // Gesture timing anchors on the CLOCK at ingest. The 2026-07-12\n // event-timestamp anchor is retired (2026-07-17): event.timeStamp and\n // rAF now are DIFFERENT clocks under throttling (measured seconds of\n // skew), and the stall protection it bought is now the clock's own\n // property — a stalled frame contributes at most dtClampMs.\n const downMs = now;\n\n // Pinch rule: this down makes it TWO local touch pointers held — spawn a\n // Pinch watching both and suspend both pointers' single-pointer\n // recognizers (spawn this pointer's singles pre-suspended).\n let pinchPartner: Entity | undefined;\n if (ctx.read(pointer, Pointer).device === \"touch\") {\n world.query(heldTouchQ).each((pb) => {\n for (const pr of pb) {\n const other = pb.entity(pr);\n if (other === pointer) continue;\n if (world.read(other, Pointer).device !== \"touch\") continue;\n if (world.read(other, PointerButtons).buttons === 0) continue;\n // A partner already claimed by a live gesture never forms a pinch —\n // two touches dragging two widgets stay two independent gestures\n // (design-003 §9); pinch is for two FREE fingers.\n const partnerClaim = ctx.getRelation(other, ClaimedBy);\n if (partnerClaim !== undefined && !isTerminal(ctx, partnerClaim)) continue;\n pinchPartner = other;\n }\n });\n }\n const suspendedAtBirth = pinchPartner !== undefined;\n\n // iOS hold-to-lift (LongPressDrag capability, 2026-07-12): the widget's\n // Drag recognizer spawns PARKED (Pending + Sequence → this down's\n // LongPress). The dependency system hands off when the hold passes;\n // early movement fails the LongPress and the parked Drag dies with it\n // — taps and widget-internal interactions stay instant. Requires the\n // profile to spawn longPress BEFORE drag (the default select order).\n const holdToDrag =\n captureTarget !== undefined &&\n ctx.hasTag(captureTarget, LongPressDrag) &&\n profile.includes(\"longPress\");\n let lpRec: Entity | undefined;\n\n // Multi-tap REJOIN (v2 findPendingTap): a down on a MultiTap target near a\n // Pending tap's last down re-points that tap at the new pointer (count\n // preserved) instead of spawning fresh. Edge-parked Pendings never rejoin.\n let rejoined = false;\n if (captureTarget !== undefined && ctx.has(captureTarget, MultiTap)) {\n const mt = ctx.read(captureTarget, MultiTap);\n ctx.query(pendingTapQ).each((pb) => {\n for (const pr of pb) {\n if (rejoined) return;\n const cand = pb.entity(pr);\n if (ctx.getRelation(cand, Captures) !== captureTarget) continue;\n if (ctx.hasTag(cand, HadSequence) || ctx.hasTag(cand, HadRequiresFail)) continue;\n if (ctx.read(cand, Tap).count >= mt.max) continue;\n const d = ctx.read(cand, Down);\n if (dist(screen.x, screen.y, d.x, d.y) > mt.slopPx) continue;\n ctx.removeRelation(cand, Watches); // old finger lifted — re-point at the new one\n ctx.addRelation(cand, Watches, pointer);\n ctx.edit(cand).set(Down, { x: screen.x, y: screen.y, ms: now });\n if (suspendedAtBirth) ctx.addTag(cand, GestureSuspended);\n P.set(ctx, cand, \"Possible\"); // Pending → Possible; count preserved\n rejoined = true;\n return;\n }\n });\n }\n\n const spawnSingle = (kind: SingleKindName): Entity => {\n // A parked drag enters Pending (edge-gated) instead of Possible.\n const park = kind === \"drag\" && holdToDrag && lpRec !== undefined;\n const basePhase = park ? P.tags.Pending : P.tags.Possible;\n const baseTags = park ? [basePhase, HadSequence] : [basePhase];\n const tags = suspendedAtBirth ? ([...baseTags, GestureSuspended] as const) : (baseTags as readonly Tag[]);\n let rec: Entity;\n if (kind === \"tap\") {\n rec = ctx.spawn({\n components: [\n [Tap, { downAt: downMs }],\n [Down, { x: screen.x, y: screen.y, ms: downMs }],\n ],\n tags: [...tags],\n });\n } else if (kind === \"longPress\") {\n rec = ctx.spawn({\n components: [\n [LongPress, { downAt: downMs, startX: screen.x, startY: screen.y, curX: screen.x, curY: screen.y }],\n [Down, { x: screen.x, y: screen.y, ms: downMs }],\n ],\n tags: [...tags],\n });\n } else {\n rec = ctx.spawn({\n components: [\n [\n Drag,\n { startX: screen.x, startY: screen.y, totalX: 0, totalY: 0, velX: 0, velY: 0, zoomAtClaim: 1 },\n ],\n [SnapState, { dx: 0, dy: 0 }], // essential at spawn — writers never race an attach\n [Down, { x: screen.x, y: screen.y, ms: downMs }],\n ],\n tags: [...tags],\n });\n }\n ctx.addRelation(rec, Watches, pointer);\n if (captureTarget !== undefined) {\n ctx.setRelation(rec, Captures, captureTarget);\n ctx.addTag(rec, HadCapture);\n }\n if (park && lpRec !== undefined) ctx.setRelation(rec, Sequence, lpRec);\n return rec;\n };\n\n for (const kind of profile) {\n if (kind === \"tap\" && rejoined) continue; // the rejoined Pending tap IS this down's tap\n const rec = spawnSingle(kind);\n if (kind === \"longPress\") lpRec = rec;\n }\n\n if (pinchPartner !== undefined) {\n const partnerScreen = ctx.read(pinchPartner, PointerScreen);\n const spread = dist(screen.x, screen.y, partnerScreen.x, partnerScreen.y);\n const cx = (screen.x + partnerScreen.x) / 2;\n const cy = (screen.y + partnerScreen.y) / 2;\n const pinch = ctx.spawn({\n components: [\n [\n Pinch,\n {\n startDist: spread,\n startZoom: ctx.getResource(Camera)?.zoom ?? 1,\n cx,\n cy,\n zoomAtClaim: ctx.getResource(Camera)?.zoom ?? 1,\n },\n ],\n [Down, { x: cx, y: cy, ms: now }],\n ],\n tags: [P.tags.Possible],\n });\n ctx.addRelation(pinch, Watches, pointer);\n ctx.addRelation(pinch, Watches, pinchPartner);\n // Suspend the partner's existing singles (\"suspend, don't kill\").\n for (const rec of watchersOf(ctx, pinchPartner)) {\n if (!ctx.has(rec, Pinch)) ctx.addTag(rec, GestureSuspended);\n }\n }\n }\n },\n // The multi-tap REJOIN rebases a Pending tap's Down (edit().set above); spawns\n // are structural, not value writes. Sole declared Down writer in ctl:spawn\n // (cancelSweep/wheelSpawn/recognizerIntegrity write no cells) → no same-phase\n // co-writer, so no orderIndependent attestation.\n { name: \"recognizerSpawn\", access: { write: [Down] } },\n );\n\n // Wheel recognizer spawn rides the same ctl:spawn slot: wheel deltas landed\n // this tick (values — visible) and no live wheel recognizer watches the pointer.\n const wheelSpawn = defineSystem(\n wheelSourceQ,\n (b, ctx) => {\n const now = clk(ctx);\n for (const r of b) {\n const pointer = b.entity(r);\n const wheel = ctx.read(pointer, PointerWheel);\n const zooming = wheel.pinch !== 0;\n const panning = wheel.dx !== 0 || wheel.dy !== 0;\n if (!zooming && !panning) continue;\n const hasLive = ctx\n .getReverse(pointer, Watches)\n .some((rec) => (ctx.has(rec, WheelPan) || ctx.has(rec, WheelZoom)) && !isTerminal(ctx, rec));\n if (hasLive) continue;\n const screen = ctx.read(pointer, PointerScreen);\n const rec = zooming\n ? ctx.spawn({\n components: [\n [WheelZoom, { pinch: 0, anchorX: screen.x, anchorY: screen.y }],\n [Down, { x: screen.x, y: screen.y, ms: now }], // Down.ms = last wheel activity (silence timer)\n ],\n tags: [P.tags.Possible, Simultaneous],\n })\n : ctx.spawn({\n components: [\n [WheelPan, { dx: 0, dy: 0, anchorX: screen.x, anchorY: screen.y }],\n [Down, { x: screen.x, y: screen.y, ms: now }],\n ],\n tags: [P.tags.Possible, Simultaneous],\n });\n ctx.addRelation(rec, Watches, pointer);\n }\n },\n { name: \"wheelSpawn\" },\n );\n\n const recognizerIntegrity = defineSystem(\n anyKindQ,\n (b, ctx) => {\n for (const r of b) {\n const e = b.entity(r);\n if (isTerminal(ctx, e)) continue;\n\n // Suspension lift: no live non-terminal Pinch shares any watched pointer.\n if (ctx.hasTag(e, GestureSuspended) && !ctx.has(e, Pinch)) {\n const pointers = ctx.getRelations(e, Watches);\n const suspenderAlive = pointers.some((p) =>\n ctx.getReverse(p, Watches).some((rec) => ctx.has(rec, Pinch) && !isTerminal(ctx, rec)),\n );\n if (!suspenderAlive) ctx.removeTag(e, GestureSuspended);\n }\n\n // Required-watches count (edges to despawned pointers auto-clear). A\n // Pending recognizer is ALLOWED to outlive its watched pointer — a\n // multi-tap awaiting the next tap, or an edge-parked recognizer before\n // its source (v2 rule); only capture death cancels those (below).\n if (!ctx.hasTag(e, P.tags.Pending) && ctx.getRelations(e, Watches).length !== requiredWatches(ctx, e)) {\n P.set(ctx, e, \"Cancelled\");\n continue;\n }\n\n // Capture death — incl. remote despawns (edge auto-clears; HadCapture remembers).\n if (ctx.hasTag(e, HadCapture) && ctx.getRelation(e, Captures) === undefined) {\n P.set(ctx, e, \"Cancelled\");\n }\n }\n },\n { name: \"recognizerIntegrity\" },\n );\n\n // --- per-kind FSMs (ctl:recognize) ---\n\n const tapSystem = defineSystem(\n tapQ,\n (b, ctx) => {\n const now = clk(ctx);\n for (const r of b) {\n const e = b.entity(r);\n const pending = ctx.hasTag(e, P.tags.Pending);\n if (!ctx.hasTag(e, P.tags.Possible) && !pending) continue;\n\n if (pending) {\n // Edge-parked Pending (Sequence/RequiresFail) belongs to the dependency\n // system — never window-expire it here (v2 rule).\n if (ctx.hasTag(e, HadSequence) || ctx.hasTag(e, HadRequiresFail)) continue;\n // Multi-tap Pending: await a rejoin (recognizerSpawn) or the window closing.\n const down = ctx.read(e, Down);\n const cap = ctx.getRelation(e, Captures);\n const windowMs =\n cap !== undefined && ctx.has(cap, MultiTap)\n ? ctx.read(cap, MultiTap).windowMs\n : gs(ctx).multiTapWindowMs;\n if (now - down.ms > windowMs) P.set(ctx, e, \"Recognized\"); // window closed → final count stands\n continue;\n }\n\n const pointer = ctx.getRelations(e, Watches)[0];\n if (pointer === undefined) continue; // integrity cancels next frame\n if (ctx.hasTag(pointer, WentCancelled)) {\n P.set(ctx, e, \"Cancelled\");\n continue;\n }\n const down = ctx.read(e, Down);\n const screen = ctx.read(pointer, PointerScreen);\n const moved = dist(down.x, down.y, screen.x, screen.y);\n if (moved > gs(ctx).tapSlopPx) {\n P.set(ctx, e, \"Failed\");\n continue;\n }\n // Hold measured from Down.ms, not Tap.downAt: a rejoined multi-tap rebases\n // Down per tap while downAt keeps the FIRST down (the gesture's birth).\n const held = now - down.ms;\n if (ctx.hasTag(pointer, WentUp)) {\n if (held > gs(ctx).tapMaxMs) {\n P.set(ctx, e, \"Failed\");\n continue;\n }\n // Clean release — count it (v2): at the target count → Recognized now;\n // under it → park Pending (never reaped) until rejoin or window close.\n const tap = ctx.read(e, Tap);\n const cap = ctx.getRelation(e, Captures);\n const max = cap !== undefined && ctx.has(cap, MultiTap) ? ctx.read(cap, MultiTap).max : 1;\n const count = tap.count + 1;\n ctx.edit(e).set(Tap, { ...tap, count });\n if (count >= max) {\n P.set(ctx, e, \"Recognized\");\n } else {\n ctx.edit(e).set(Down, { ...down, ms: now }); // restart the inter-tap window from release\n P.set(ctx, e, \"Pending\");\n }\n } else if (held > gs(ctx).tapMaxMs) {\n P.set(ctx, e, \"Failed\");\n }\n }\n },\n // Down co-writers in ctl:recognize (tap park / wheel activity / dependency\n // rebase) touch DISJOINT rows — tap rows, wheel rows, edge-parked rows.\n { name: \"tapSystem\", access: { write: [Tap, Down], orderIndependent: [Down] } },\n );\n\n const longPressSystem = defineSystem(\n longPressQ,\n (b, ctx) => {\n const now = clk(ctx);\n for (const r of b) {\n const e = b.entity(r);\n const pointer = ctx.getRelations(e, Watches)[0];\n if (pointer === undefined) continue;\n const screen = ctx.read(pointer, PointerScreen);\n const lp = ctx.read(e, LongPress);\n\n if (ctx.hasTag(pointer, WentCancelled)) {\n P.set(ctx, e, \"Cancelled\");\n continue;\n }\n\n if (ctx.hasTag(e, P.tags.Possible)) {\n if (ctx.hasTag(pointer, WentUp)) {\n P.set(ctx, e, \"Failed\"); // released before the hold\n continue;\n }\n if (dist(lp.startX, lp.startY, screen.x, screen.y) > gs(ctx).longPressSlopPx) {\n P.set(ctx, e, \"Failed\");\n continue;\n }\n if (now - lp.downAt >= gs(ctx).longPressMs) {\n ctx.edit(e).set(LongPress, { ...lp, curX: screen.x, curY: screen.y });\n P.set(ctx, e, \"Recognized\"); // discrete claim; continuous tail follows\n }\n continue;\n }\n\n if (ctx.hasTag(e, P.tags.Recognized)) {\n ctx.edit(e).set(LongPress, { ...lp, curX: screen.x, curY: screen.y }); // the tail\n if (ctx.hasTag(pointer, WentUp)) P.set(ctx, e, \"Ended\");\n }\n }\n },\n { name: \"longPressSystem\", access: { write: [LongPress] } },\n );\n\n const dragSystem = defineSystem(\n dragQ,\n (b, ctx) => {\n const dtMs = ctx.getResource(FrameInfo)?.dt ?? 16;\n for (const r of b) {\n const e = b.entity(r);\n const pointer = ctx.getRelations(e, Watches)[0];\n if (pointer === undefined) continue;\n const screen = ctx.read(pointer, PointerScreen);\n const d = ctx.read(e, Drag);\n\n if (ctx.hasTag(pointer, WentCancelled)) {\n P.set(ctx, e, \"Cancelled\");\n continue;\n }\n\n if (ctx.hasTag(e, P.tags.Possible)) {\n const down = ctx.read(e, Down);\n // Adopted insert drags (tray ghosts, 2026-07-19) have NO tap-vs-drag\n // ambiguity — the user is already mid-drag when the synthetic down\n // lands, so the dead zone only adds anchor drift (the ghost sits\n // still while the pointer travels the slop). First move activates.\n const cap = ctx.getRelation(e, Captures);\n const ghostDrag = cap !== undefined && ctx.has(cap, InsertGhost);\n const slopPx = ghostDrag ? 0 : gs(ctx).dragSlopPx;\n if (dist(down.x, down.y, screen.x, screen.y) > slopPx) {\n // Origin measured FROM DEAD-ZONE EXIT (no jump on promote) —\n // EXCEPT ghost drags: the ghost spawned anchored AT the down, so\n // every pixel since the down belongs to it. PointerScreen is the\n // tick's FOLDED latest, so an exit-origin bakes in whatever\n // travel folded into the activation tick (46px at a starved\n // 2fps, 2–8px on a fast real-browser flick — the anchor-drift\n // field bug, 2026-07-19). The down IS the anchor; use it.\n ctx.edit(e).set(Drag, {\n startX: ghostDrag ? down.x : screen.x,\n startY: ghostDrag ? down.y : screen.y,\n totalX: 0,\n totalY: 0,\n velX: 0,\n velY: 0,\n zoomAtClaim: ctx.getResource(Camera)?.zoom ?? 1,\n });\n P.set(ctx, e, \"Active\");\n } else if (ctx.hasTag(pointer, WentUp)) {\n P.set(ctx, e, \"Failed\"); // released inside the dead zone\n }\n continue;\n }\n\n if (ctx.hasTag(e, P.tags.Active)) {\n const totalX = screen.x - d.startX;\n const totalY = screen.y - d.startY;\n const frameDx = totalX - d.totalX;\n const frameDy = totalY - d.totalY;\n const dtS = Math.max(dtMs, 1) / 1000;\n const alpha = 0.3; // EMA release velocity (v2 constant)\n ctx.edit(e).set(Drag, {\n ...d,\n totalX,\n totalY,\n velX: d.velX + alpha * (frameDx / dtS - d.velX),\n velY: d.velY + alpha * (frameDy / dtS - d.velY),\n });\n if (ctx.hasTag(pointer, WentUp)) P.set(ctx, e, \"Ended\");\n }\n }\n },\n { name: \"dragSystem\", access: { write: [Drag] } },\n );\n\n const pinchSystem = defineSystem(\n pinchQ,\n (b, ctx) => {\n for (const r of b) {\n const e = b.entity(r);\n const pointers = ctx.getRelations(e, Watches);\n if (pointers.length !== 2) continue; // integrity cancels\n const [pa, pb] = pointers as [Entity, Entity];\n if (ctx.hasTag(pa, WentCancelled) || ctx.hasTag(pb, WentCancelled)) {\n P.set(ctx, e, \"Cancelled\");\n continue;\n }\n const sa = ctx.read(pa, PointerScreen);\n const sb = ctx.read(pb, PointerScreen);\n const spread = dist(sa.x, sa.y, sb.x, sb.y);\n const cx = (sa.x + sb.x) / 2;\n const cy = (sa.y + sb.y) / 2;\n const pin = ctx.read(e, Pinch);\n const anyUp = ctx.hasTag(pa, WentUp) || ctx.hasTag(pb, WentUp);\n\n if (ctx.hasTag(e, P.tags.Possible)) {\n if (anyUp) {\n P.set(ctx, e, \"Cancelled\"); // lost a finger pre-activation\n continue;\n }\n if (Math.abs(spread - pin.startDist) > gs(ctx).pinchSlopPx) {\n const zoom = ctx.getResource(Camera)?.zoom ?? 1;\n // Re-baseline at activation (v2): the dead-zone spread never zooms.\n ctx.edit(e).set(Pinch, { startDist: spread, startZoom: zoom, cx, cy, zoomAtClaim: zoom });\n P.set(ctx, e, \"Active\");\n }\n continue;\n }\n\n if (ctx.hasTag(e, P.tags.Active)) {\n ctx.edit(e).set(Pinch, { ...pin, cx, cy });\n if (anyUp) P.set(ctx, e, \"Ended\");\n }\n }\n },\n { name: \"pinchSystem\", access: { write: [Pinch] } },\n );\n\n const wheelSystem = defineSystem(\n wheelKindQ,\n (b, ctx) => {\n const now = clk(ctx);\n for (const r of b) {\n const e = b.entity(r);\n if (isTerminal(ctx, e)) continue;\n const pointer = ctx.getRelations(e, Watches)[0];\n if (pointer === undefined) continue;\n const wheel = ctx.read(pointer, PointerWheel);\n const screen = ctx.read(pointer, PointerScreen);\n const down = ctx.read(e, Down);\n const isZoom = ctx.has(e, WheelZoom);\n // A ceded tick (WheelHandled — native scroll consumed the deltas) is\n // wheel SILENCE to a live recognizer: don't feed the deltas into the\n // camera, zero the per-frame values, let the end-silence timer run.\n // The spawn gate alone can't cover this — a recognizer already live\n // within `wheelEndSilenceMs` would otherwise pan from ceded deltas.\n const ceded = ctx.hasTag(pointer, WheelHandled);\n const active = !ceded && (isZoom ? wheel.pinch !== 0 : wheel.dx !== 0 || wheel.dy !== 0);\n\n if (active) {\n if (isZoom) {\n ctx.edit(e).set(WheelZoom, { pinch: wheel.pinch, anchorX: screen.x, anchorY: screen.y });\n } else {\n ctx.edit(e).set(WheelPan, { dx: wheel.dx, dy: wheel.dy, anchorX: screen.x, anchorY: screen.y });\n }\n ctx.edit(e).set(Down, { x: screen.x, y: screen.y, ms: now }); // last-activity timer\n if (ctx.hasTag(e, P.tags.Possible)) P.set(ctx, e, \"Active\");\n } else {\n // Zero the per-frame deltas so cameraControl never re-applies stale ones.\n if (isZoom) {\n const z = ctx.read(e, WheelZoom);\n if (z.pinch !== 0) ctx.edit(e).set(WheelZoom, { ...z, pinch: 0 });\n } else {\n const p = ctx.read(e, WheelPan);\n if (p.dx !== 0 || p.dy !== 0) ctx.edit(e).set(WheelPan, { ...p, dx: 0, dy: 0 });\n }\n if (ctx.hasTag(e, P.tags.Active) && now - down.ms > gs(ctx).wheelEndSilenceMs) {\n P.set(ctx, e, \"Ended\");\n }\n }\n }\n },\n { name: \"wheelSystem\", access: { write: [WheelPan, WheelZoom, Down], orderIndependent: [Down] } },\n );\n\n // dependency (last in ctl:recognize; v2 dependencySystem) — resolve the Pending\n // EDGE cases. `RequiresFail` gates the EXIT (finish once `other` fails);\n // `Sequence` gates the ENTRANCE (wait for `after` to pass, then hand off,\n // rebasing Down). A multi-tap Pending has neither edge → untouched (tapSystem\n // owns its window). TIMING (differs from v2's immediate-write model): phase\n // flips flush at the ctl:recognize boundary, so this system observes a\n // target's SAME-GROUP transition one frame later via its persistent tag —\n // safe because reap waits terminal+1 (cleanup.ts), and this system's own\n // flips flush before ctl:arbitrate reads their Just* markers this frame.\n const dependencySystem = defineSystem(\n pendingQ,\n (b, ctx) => {\n const now = clk(ctx);\n for (const r of b) {\n const e = b.entity(r);\n if (ctx.hasTag(e, HadRequiresFail)) {\n const other = ctx.getRelation(e, RequiresFail);\n if (other === undefined) {\n P.set(ctx, e, \"Failed\"); // orphaned edge (target despawned; edge auto-cleared)\n } else if (ctx.hasTag(other, P.tags.Failed) || ctx.hasTag(other, P.tags.Cancelled)) {\n // `other` failed → this may finish: discrete (Tap) → Recognized, continuous → Active.\n P.set(ctx, e, ctx.has(e, Tap) ? \"Recognized\" : \"Active\");\n } else if (ctx.hasTag(other, P.tags.Recognized) || ctx.hasTag(other, P.tags.Active)) {\n P.set(ctx, e, \"Failed\"); // `other` won → this loses\n } // else still waiting (other Possible/Pending)\n continue;\n }\n if (ctx.hasTag(e, HadSequence)) {\n const after = ctx.getRelation(e, Sequence);\n if (after === undefined) {\n P.set(ctx, e, \"Failed\");\n } else if (ctx.hasTag(after, P.tags.Active) || ctx.hasTag(after, P.tags.Recognized)) {\n // Hand off: rebase Down to the current pointer, enter, and RETIRE the\n // source — else it keeps its pointer claimed and arbitration would\n // fail this freshly-handed-off recognizer (v2 rule).\n const p = ctx.getRelations(e, Watches)[0];\n if (p !== undefined) {\n const screen = ctx.read(p, PointerScreen);\n ctx.edit(e).set(Down, { x: screen.x, y: screen.y, ms: now });\n }\n P.set(ctx, e, \"Possible\");\n // v2 retired an ACTIVE source; v3 must retire any still-live one —\n // LongPress claims at Recognized and keeps a continuous tail, and\n // arbitration's claim is first-wins (a live source would hold the\n // pointer against the handed-off recognizer forever).\n if (!isTerminal(ctx, after)) P.set(ctx, after, \"Ended\");\n } else if (ctx.hasTag(after, P.tags.Failed) || ctx.hasTag(after, P.tags.Cancelled)) {\n P.set(ctx, e, \"Failed\");\n } // else still waiting\n }\n }\n },\n { name: \"dependencySystem\", access: { write: [Down], orderIndependent: [Down] } },\n );\n\n return {\n cancelSweep,\n recognizerSpawn,\n wheelSpawn,\n recognizerIntegrity,\n tapSystem,\n longPressSystem,\n dragSystem,\n pinchSystem,\n wheelSystem,\n dependencySystem,\n };\n}\n","/**\n * Selection ops — bulk `Selected` tag flips from app handlers (design-003 §5.1).\n *\n * `Selected` is a runtime rider; toggling it via `world.addTag/removeTag` is a\n * legal free write from an app handler (design-001 §2 rule 4 — riders are not\n * doc cells). The engine bumps the `SelectionVersion` stamp (helpers/version-stamps.ts)\n * on every actual change, in addition to firing the optional `onChange` hook the\n * app wires for its own bookkeeping. Selection is committed ONCE per interaction,\n * never per frame (the v1 marquee lesson) — so change-only firing matters for both.\n */\nimport { defineQuery } from \"@vibecook/strata-ecs\";\nimport type { Entity, World } from \"@vibecook/strata-ecs\";\nimport { Selected } from \"../catalog/selection-presence\";\nimport { bumpVersion, SelectionVersion } from \"../helpers/version-stamps\";\n\nexport type SelectionMode = \"replace\" | \"toggle\" | \"add\";\n\nconst selectedQuery = defineQuery([Selected]);\n\n/** All entities currently carrying the `Selected` rider. */\nexport function selectedEntities(world: World): Entity[] {\n const out: Entity[] = [];\n world.query(selectedQuery).each((batch) => {\n for (const row of batch) out.push(batch.entity(row));\n });\n return out;\n}\n\n/**\n * Apply a selection.\n * - `replace`: exactly `entities` end up selected (others cleared).\n * - `toggle`: flip each of `entities`.\n * - `add`: union `entities` into the current selection.\n * `onChange` fires once, only if a tag actually flipped.\n */\nexport function setSelection(\n world: World,\n entities: Iterable<Entity>,\n mode: SelectionMode,\n onChange?: () => void,\n): void {\n const next = new Set(entities);\n let changed = false;\n\n if (mode === \"replace\") {\n for (const e of selectedEntities(world)) {\n if (!next.has(e)) {\n world.removeTag(e, Selected);\n changed = true;\n }\n }\n for (const e of next) {\n if (!world.hasTag(e, Selected)) {\n world.addTag(e, Selected);\n changed = true;\n }\n }\n } else if (mode === \"toggle\") {\n for (const e of next) {\n if (world.hasTag(e, Selected)) world.removeTag(e, Selected);\n else world.addTag(e, Selected);\n changed = true;\n }\n } else {\n for (const e of next) {\n if (!world.hasTag(e, Selected)) {\n world.addTag(e, Selected);\n changed = true;\n }\n }\n }\n\n if (changed) {\n bumpVersion(world, SelectionVersion);\n onChange?.();\n }\n}\n\n/** Clear the whole selection. `onChange` fires once, only if something was selected. */\nexport function clearSelection(world: World, onChange?: () => void): void {\n let changed = false;\n for (const e of selectedEntities(world)) {\n world.removeTag(e, Selected);\n changed = true;\n }\n if (changed) {\n bumpVersion(world, SelectionVersion);\n onChange?.();\n }\n}\n","/**\n * L3 — connect behavior (design-003 §5 item 8, §4.5 connectClaim; design-004 §6;\n * `ctl:claim` + `ctl:behave`). The node-editor core gesture: drag from a source\n * port to a compatible target port, commit ONE wire.\n *\n * `connectClaim` (JustActive × RoutedConnect): latch the source port — the\n * recognizer's `Captures` target must be a Port entity (dragRoute guarantees it,\n * or the connect tool started the drag). Recognizer field-sets are per-kind\n * (Drag), so per-gesture claim state lives in a closure Map keyed by recognizer\n * (the `tweenStart`/camera-sim precedent), holding the source WIDGET + port id +\n * world anchor + accepts-keys. The preview buffer arms here.\n *\n * `connectBehavior` (a TICK system, like marquee, so it can CLEAR the preview the\n * frame after the gesture ends): per Active frame it writes the out-of-ECS\n * `WirePreviewBuffer` (source anchor → pointer world, snapped to a COMPATIBLE\n * port anchor when the watched pointer `Targets` one; type check via the widgets'\n * port decls; self-wire never compatible). On `JustEnded` over a compatible port\n * it commits `{kind:\"connect\", wires:[{from,to,fromPort,toPort}]}` (the doc sink\n * spawns the wire); elsewhere it commits nothing.\n *\n * PREVIEW CONTINUITY — SIMPLIFICATION ACCEPTED (design-003 §5.8 / design-002 §8):\n * the preview clears on JustEnded+1 (one linger frame) rather than persisting\n * until the projected wire entity places (the promote-sweep analog). Full\n * continuity — hand the preview off to the freshly-synced wire with no blink —\n * is polish deferred; the one-frame gap is invisible in practice.\n */\nimport type { Entity, System, SystemCtx, TickSystem, World } from \"@vibecook/strata-ecs\";\nimport { defineQuery, defineSystem, defineTickSystem } from \"@vibecook/strata-ecs\";\nimport { type CameraState, type SpatialIndex, portAnchor, screenToWorld } from \"@ice/kernel\";\nimport {\n Camera,\n Captures,\n Drag,\n GesturePhases,\n Port,\n PortOf,\n PointerScreen,\n Position,\n RoutedConnect,\n Size,\n Targets,\n Watches,\n} from \"../catalog\";\nimport type { CommitSink } from \"../engine/commit-sink\";\nimport { portSlots } from \"../ops/port-geometry\";\nimport type { WirePickSource } from \"../ops/point-pick\";\nimport { PrefabId } from \"../schema/prefab\";\nimport { widgets } from \"../widget/define-widget\";\n\nconst P = GesturePhases;\n\n/**\n * The out-of-ECS connect preview (design-004 §6; the marquee-buffer precedent).\n * `sx,sy` = source port world anchor; `tx,ty` = the projected endpoint (pointer\n * world, or a snapped compatible-port anchor); `compatible` gates the landing.\n */\nexport interface WirePreviewBuffer {\n active: boolean;\n compatible: boolean;\n sx: number;\n sy: number;\n tx: number;\n ty: number;\n}\n\n/** Latched at claim: the source port, by value (survives a reaped source port). */\ninterface SourceLatch {\n widget: Entity;\n portId: string;\n ax: number;\n ay: number;\n accepts: readonly string[];\n}\n\nexport interface ConnectSystems {\n connectClaim: System;\n connectBehavior: TickSystem;\n previewBuffer: WirePreviewBuffer;\n}\n\nconst connectClaimQ = defineQuery([Drag, P.justTags.Active, RoutedConnect]);\nconst connectDragQ = defineQuery([Drag, RoutedConnect]);\n\n/** Port declarations of a ported widget, or undefined (not a widget / no ports). */\nfunction declsOf(ctx: SystemCtx, e: Entity) {\n const type = ctx.get(e, PrefabId)?.id;\n if (typeof type !== \"string\") return undefined;\n const decls = widgets.get(type)?.ports;\n return decls !== undefined && decls.length > 0 ? decls : undefined;\n}\n\n/** World anchor of one port on a widget, or undefined if unresolvable. */\nfunction anchorOf(ctx: SystemCtx, widget: Entity, portId: string): { x: number; y: number } | undefined {\n const decls = declsOf(ctx, widget);\n if (decls === undefined) return undefined;\n const slot = portSlots(decls).get(portId);\n const pos = ctx.get(widget, Position);\n const size = ctx.get(widget, Size);\n if (slot === undefined || pos === undefined || size === undefined) return undefined;\n return portAnchor({ x: pos.x, y: pos.y, width: size.w, height: size.h }, slot);\n}\n\n/** Empty accepts on either side = wildcard; otherwise the key lists must intersect. */\nfunction compatible(source: readonly string[], candidate: readonly string[]): boolean {\n if (source.length === 0 || candidate.length === 0) return true;\n return source.some((k) => candidate.includes(k));\n}\n\n/**\n * Signature carries the full graph-slice wiring (design brief) though connect\n * reads only `Targets` today:\n * @param _world reserved (systems reach world state via `ctx`).\n * @param _index reserved (future: a fresh event-time port pick to drop the\n * one-frame `Targets` staleness on snapping — the router's pattern).\n * @param _wires reserved (the wire narrow-phase source; connect reads `Targets`).\n */\nexport function createConnectSystems(\n _world: World,\n sink: CommitSink,\n _index: SpatialIndex<Entity>,\n _wires: WirePickSource,\n): ConnectSystems {\n const sourceOf = new Map<Entity, SourceLatch>();\n const previewBuffer: WirePreviewBuffer = { active: false, compatible: false, sx: 0, sy: 0, tx: 0, ty: 0 };\n let linger = false;\n\n const clearPreview = (): void => {\n previewBuffer.active = false;\n previewBuffer.compatible = false;\n };\n\n const connectClaim = defineSystem(\n connectClaimQ,\n (b, ctx) => {\n for (const r of b) {\n const rec = b.entity(r);\n const srcPort = ctx.getRelation(rec, Captures);\n if (srcPort === undefined || !ctx.isAlive(srcPort) || !ctx.has(srcPort, Port)) continue;\n const portId = ctx.get(srcPort, Port)?.id;\n const widget = ctx.getRelation(srcPort, PortOf);\n if (typeof portId !== \"string\" || widget === undefined) continue;\n const anchor = anchorOf(ctx, widget, portId);\n if (anchor === undefined) continue;\n const decls = declsOf(ctx, widget);\n const accepts = decls?.find((d) => d.id === portId)?.accepts ?? [];\n sourceOf.set(rec, { widget, portId, ax: anchor.x, ay: anchor.y, accepts });\n previewBuffer.active = true;\n previewBuffer.sx = anchor.x;\n previewBuffer.sy = anchor.y;\n previewBuffer.tx = anchor.x;\n previewBuffer.ty = anchor.y;\n previewBuffer.compatible = false;\n }\n },\n { name: \"connectClaim\" },\n );\n\n /** Resolve the drag's current endpoint: pointer world, snapped to a compatible port. */\n const resolveTarget = (\n ctx: SystemCtx,\n rec: Entity,\n src: SourceLatch,\n cam: CameraState,\n ): { tx: number; ty: number; compatible: boolean; targetWidget?: Entity; targetPortId?: string } => {\n const pointer = ctx.getRelations(rec, Watches)[0];\n if (pointer === undefined) return { tx: src.ax, ty: src.ay, compatible: false };\n const ps = ctx.get(pointer, PointerScreen);\n const pw = ps !== undefined ? screenToWorld(ps.x, ps.y, cam) : { x: src.ax, y: src.ay };\n\n const t = ctx.getRelation(pointer, Targets);\n if (t !== undefined && ctx.isAlive(t) && ctx.has(t, Port)) {\n const targetWidget = ctx.getRelation(t, PortOf);\n const targetPortId = ctx.get(t, Port)?.id;\n if (\n targetWidget !== undefined &&\n targetWidget !== src.widget && // self-wire is never compatible\n typeof targetPortId === \"string\"\n ) {\n const decls = declsOf(ctx, targetWidget);\n const accepts = decls?.find((d) => d.id === targetPortId)?.accepts ?? [];\n if (compatible(src.accepts, accepts)) {\n const a = anchorOf(ctx, targetWidget, targetPortId);\n if (a !== undefined) {\n return { tx: a.x, ty: a.y, compatible: true, targetWidget, targetPortId };\n }\n }\n }\n }\n return { tx: pw.x, ty: pw.y, compatible: false };\n };\n\n // TICK system (strata 0.5.0): runs every frame so the preview CLEARS the frame\n // after the gesture ends (JustEnded+1), the way marquee clears its buffer.\n const connectBehavior = defineTickSystem(\n (ctx) => {\n const cam0 = ctx.getResource(Camera);\n const cam: CameraState = { x: cam0?.x ?? 0, y: cam0?.y ?? 0, zoom: cam0?.zoom ?? 1 };\n let active = false;\n\n ctx.query(connectDragQ).each((b) => {\n for (const r of b) {\n const rec = b.entity(r);\n const src = sourceOf.get(rec);\n if (src === undefined) continue;\n\n if (ctx.hasTag(rec, P.tags.Active)) {\n const res = resolveTarget(ctx, rec, src, cam);\n previewBuffer.active = true;\n previewBuffer.sx = src.ax;\n previewBuffer.sy = src.ay;\n previewBuffer.tx = res.tx;\n previewBuffer.ty = res.ty;\n previewBuffer.compatible = res.compatible;\n active = true;\n continue;\n }\n\n if (ctx.hasTag(rec, P.justTags.Ended)) {\n const res = resolveTarget(ctx, rec, src, cam);\n // Keep the preview shown at the end pose for this frame (linger).\n previewBuffer.active = true;\n previewBuffer.sx = src.ax;\n previewBuffer.sy = src.ay;\n previewBuffer.tx = res.tx;\n previewBuffer.ty = res.ty;\n previewBuffer.compatible = res.compatible;\n active = true;\n linger = true;\n if (res.compatible && res.targetWidget !== undefined && res.targetPortId !== undefined) {\n sink.commit({\n kind: \"connect\",\n gesture: rec,\n writes: [],\n wires: [\n { from: src.widget, to: res.targetWidget, fromPort: src.portId, toPort: res.targetPortId },\n ],\n });\n }\n sourceOf.delete(rec);\n } else if (\n ctx.hasTag(rec, P.justTags.Cancelled) ||\n ctx.hasTag(rec, P.justTags.Failed)\n ) {\n sourceOf.delete(rec); // dropped — nothing commits, preview clears below\n }\n }\n });\n\n if (active) {\n previewBuffer.active = true;\n } else if (linger) {\n linger = false; // JustEnded+1 — the promised cleanup tick\n clearPreview();\n } else if (previewBuffer.active) {\n clearPreview();\n }\n },\n { name: \"connectBehavior\" },\n );\n\n return { connectClaim, connectBehavior, previewBuffer };\n}\n","/**\n * L3 — port materialization (design-004 §6 ports & wires runtime; `derive`\n * phase, BEFORE `selectionChrome`). The LOCKED gating from design-004 §6 /\n * design-001 §5.3: port ENTITIES are runtime and on-demand, so steady-state\n * pan/zoom with the select tool spawns ZERO ports.\n *\n * Three triggers materialize a widget's declared ports (registry decl → kernel\n * `portAnchor`; a port carries Port + PortAnchor + PortOf → widget, and NO\n * Position/Size — `spatialSync` must never see it; design-004 §6, the\n * SelectionBox precedent). Because ports carry no Position/Size, this system\n * gives them their OWN tiny world AABB in the shared spatial index so they are\n * pickable (design-003 §3 port tier):\n * (a) connect tool → widgets in viewport+overscan (`200/zoom`); materialize at\n * the overscan band, keep across a ×1.5 hysteresis band;\n * (b) any local pointer `Targets` a ported widget → that widget's ports;\n * (c) an Active `RoutedConnect` drag → COMPATIBLE ports (accepts-key\n * intersection with the source port; empty accepts = wildcard) light up\n * STAGED by distance-to-pointer, capped to the nearest 256 within the\n * `portLightUpRadiusPx` screen radius (rev 2: \"all visible\" at a 10k\n * zoomed-out view meant multi-second fills + sustained pick churn).\n *\n * Spawn budget ≤ `portSpawnPerFrame` (64) per frame — staging spreads a big\n * light-up across frames. A widget's ports reap when every trigger lapsed for\n * `portReapGraceMs`, or immediately if the widget died. Anchors recompute each\n * frame and rewrite Port entities + index entries CHANGE-ONLY (a still widget\n * churns nothing). `SpatialVersion` bumps only on a real index change.\n */\nimport type { Entity, SystemCtx, TickSystem, World } from \"@vibecook/strata-ecs\";\nimport { defineQuery, defineTickSystem } from \"@vibecook/strata-ecs\";\nimport {\n type AABB,\n type CameraState,\n type SpatialIndex,\n intersectsAABB,\n portAnchor,\n screenToWorld,\n} from \"@ice/kernel\";\nimport {\n Camera,\n Captures,\n Drag,\n GestureActive,\n LocalPointer,\n Pointer,\n PointerScreen,\n Port,\n PortAnchor,\n PortOf,\n Position,\n RoutedConnect,\n Size,\n Targets,\n Viewport,\n Watches,\n} from \"../catalog\";\nimport { ActiveTool } from \"../catalog/camera-derived\";\nimport { FrameInfo } from \"../engine/frame-info\";\nimport { SpatialVersion, bumpVersion } from \"../helpers/version-stamps\";\nimport { portSlots } from \"../ops/port-geometry\";\nimport { PrefabId } from \"../schema/prefab\";\nimport { GRAPH_PICK_DEFAULTS, RUNTIME_BUDGETS } from \"../settings/defaults\";\nimport type { WidgetPortDecl } from \"../widget/define-widget\";\nimport { widgets } from \"../widget/define-widget\";\n\n/** A materialized port: its entity + last-written anchor (change-only bookkeeping). */\ninterface PortRec {\n entity: Entity;\n ax: number;\n ay: number;\n}\n\n/** Per-widget materialization state (a derived cache, not world state). */\ninterface WidgetPorts {\n ports: Map<string, PortRec>;\n lastTriggerMs: number;\n}\n\n/** A pending spawn, ordered by distance-to-pointer so staging fills nearest-first. */\ninterface SpawnReq {\n widget: Entity;\n portId: string;\n ax: number;\n ay: number;\n dist: number;\n}\n\nconst H = GRAPH_PICK_DEFAULTS.portIndexHalfWorld;\n\nconst portedQ = defineQuery([Pointer, LocalPointer]);\nconst connectDragQ = defineQuery([Drag, RoutedConnect, GestureActive]);\n\n/** The port declarations of a ported widget, or undefined (not a widget / no ports). */\nfunction portedDeclsOf(ctx: SystemCtx, e: Entity): readonly WidgetPortDecl[] | undefined {\n const type = ctx.get(e, PrefabId)?.id;\n if (typeof type !== \"string\") return undefined;\n const decls = widgets.get(type)?.ports;\n return decls !== undefined && decls.length > 0 ? decls : undefined;\n}\n\n/** Empty accepts on either side = wildcard; otherwise the key lists must intersect. */\nfunction compatible(source: readonly string[], candidate: readonly string[]): boolean {\n if (source.length === 0 || candidate.length === 0) return true;\n return source.some((k) => candidate.includes(k));\n}\n\nconst portAabb = (ax: number, ay: number): AABB => ({\n minX: ax - H,\n minY: ay - H,\n maxX: ax + H,\n maxY: ay + H,\n});\n\nexport function createPortMaterialize(world: World, index: SpatialIndex<Entity>): TickSystem {\n // Derived cache (not world state): widget → its materialized ports + last trigger.\n const byWidget = new Map<Entity, WidgetPorts>();\n\n const getWP = (widget: Entity): WidgetPorts => {\n let wp = byWidget.get(widget);\n if (wp === undefined) {\n wp = { ports: new Map(), lastTriggerMs: 0 };\n byWidget.set(widget, wp);\n }\n return wp;\n };\n\n return defineTickSystem(\n (ctx) => {\n const cam0 = ctx.getResource(Camera);\n const cam: CameraState = { x: cam0?.x ?? 0, y: cam0?.y ?? 0, zoom: cam0?.zoom ?? 1 };\n const zoom = cam.zoom || 1;\n const now = ctx.getResource(FrameInfo)?.now ?? 0;\n const tool = ctx.getResource(ActiveTool)?.id ?? \"select\";\n\n const requests: SpawnReq[] = [];\n const keepAlive = new Set<Entity>();\n\n // Rect of a widget (world) or undefined if it lost its geometry.\n const rectOf = (w: Entity): { x: number; y: number; width: number; height: number } | undefined => {\n const p = ctx.get(w, Position);\n const s = ctx.get(w, Size);\n if (p === undefined || s === undefined) return undefined;\n return { x: p.x, y: p.y, width: s.w, height: s.h };\n };\n\n // --- trigger (a): connect tool × viewport+overscan, ×1.5 keep hysteresis ---\n if (tool === \"connect\") {\n const vp = ctx.getResource(Viewport);\n const tl = screenToWorld(0, 0, cam);\n const br = screenToWorld(vp?.w ?? 0, vp?.h ?? 0, cam);\n const over = RUNTIME_BUDGETS.cullOverscanWorldPerZoom / zoom;\n const spawnBand: AABB = { minX: tl.x - over, minY: tl.y - over, maxX: br.x + over, maxY: br.y + over };\n const keep = over * 1.5;\n const keepBand: AABB = { minX: tl.x - keep, minY: tl.y - keep, maxX: br.x + keep, maxY: br.y + keep };\n for (const entry of index.search(keepBand)) {\n const w = entry.id;\n const decls = portedDeclsOf(ctx, w);\n if (decls === undefined) continue;\n keepAlive.add(w); // in the keep band → hysteresis holds it\n if (!intersectsAABB(entry, spawnBand)) continue;\n const rect = rectOf(w);\n if (rect === undefined) continue;\n for (const [portId, slot] of portSlots(decls)) {\n const a = portAnchor(rect, slot);\n requests.push({ widget: w, portId, ax: a.x, ay: a.y, dist: 0 });\n }\n }\n }\n\n // --- trigger (b): a local pointer Targets a ported widget ---\n ctx.query(portedQ).each((b) => {\n for (const r of b) {\n const p = b.entity(r);\n const t = ctx.getRelation(p, Targets);\n if (t === undefined) continue;\n const decls = portedDeclsOf(ctx, t);\n if (decls === undefined) continue;\n const rect = rectOf(t);\n if (rect === undefined) continue;\n keepAlive.add(t);\n for (const [portId, slot] of portSlots(decls)) {\n const a = portAnchor(rect, slot);\n requests.push({ widget: t, portId, ax: a.x, ay: a.y, dist: 0 });\n }\n }\n });\n\n // --- trigger (c): Active RoutedConnect drag → compatible nearby ports ---\n const R = RUNTIME_BUDGETS.portLightUpRadiusPx / zoom;\n ctx.query(connectDragQ).each((b) => {\n for (const r of b) {\n const rec = b.entity(r);\n const srcPort = ctx.getRelation(rec, Captures);\n if (srcPort === undefined || !ctx.isAlive(srcPort) || !ctx.has(srcPort, Port)) continue;\n const srcWidget = ctx.getRelation(srcPort, PortOf);\n if (srcWidget === undefined) continue;\n const srcId = ctx.get(srcPort, Port)?.id;\n const srcDecls = portedDeclsOf(ctx, srcWidget);\n const srcAccepts =\n srcDecls?.find((d) => d.id === srcId)?.accepts ?? ([] as readonly string[]);\n keepAlive.add(srcWidget); // keep the source's ports so Captures never dangles\n\n const pointer = ctx.getRelations(rec, Watches)[0];\n if (pointer === undefined) continue;\n const ps = ctx.get(pointer, PointerScreen);\n if (ps === undefined) continue;\n const pw = screenToWorld(ps.x, ps.y, cam);\n\n const candidates: SpawnReq[] = [];\n for (const entry of index.search({ minX: pw.x - R, minY: pw.y - R, maxX: pw.x + R, maxY: pw.y + R })) {\n const w = entry.id;\n if (w === srcWidget) continue;\n const decls = portedDeclsOf(ctx, w);\n if (decls === undefined) continue;\n const rect = rectOf(w);\n if (rect === undefined) continue;\n for (const [portId, slot] of portSlots(decls)) {\n const accepts = decls.find((d) => d.id === portId)?.accepts ?? [];\n if (!compatible(srcAccepts, accepts)) continue;\n const a = portAnchor(rect, slot);\n const dist = Math.hypot(a.x - pw.x, a.y - pw.y);\n if (dist > R) continue;\n candidates.push({ widget: w, portId, ax: a.x, ay: a.y, dist });\n }\n }\n // Nearest-256 within the radius (design-004 §6 cap).\n candidates.sort((x, y) => x.dist - y.dist);\n for (let i = 0; i < candidates.length && i < 256; i++) {\n const c = candidates[i];\n if (c === undefined) continue;\n keepAlive.add(c.widget);\n requests.push(c);\n }\n }\n });\n\n let changed = false;\n\n // Refresh the trigger clock for every kept-alive widget (grace timer reset).\n for (const w of keepAlive) getWP(w).lastTriggerMs = now;\n\n // Spawn missing ports nearest-first, within the per-frame budget (staging).\n requests.sort((a, b) => a.dist - b.dist);\n let budget = RUNTIME_BUDGETS.portSpawnPerFrame;\n for (const req of requests) {\n if (budget <= 0) break;\n const wp = getWP(req.widget);\n if (wp.ports.has(req.portId)) continue; // already materialized\n const decls = portedDeclsOf(ctx, req.widget);\n const slot = decls !== undefined ? portSlots(decls).get(req.portId) : undefined;\n if (slot === undefined) continue;\n const port = ctx.spawn({\n components: [\n [Port, { id: req.portId, side: slot.side, index: slot.index }],\n [PortAnchor, { x: req.ax, y: req.ay }],\n ],\n });\n ctx.setRelation(port, PortOf, req.widget); // PortOf is arity \"one\"\n index.upsert(port, portAabb(req.ax, req.ay));\n wp.ports.set(req.portId, { entity: port, ax: req.ax, ay: req.ay });\n budget -= 1;\n changed = true;\n }\n\n // Anchor upkeep (change-only) + reap on lapse/grace or widget death.\n const reap: Entity[] = [];\n for (const [widget, wp] of byWidget) {\n const rect = rectOf(widget);\n const dead = !ctx.isAlive(widget) || rect === undefined;\n if (dead || now - wp.lastTriggerMs > RUNTIME_BUDGETS.portReapGraceMs) {\n for (const rec of wp.ports.values()) {\n if (ctx.isAlive(rec.entity)) ctx.destroy(rec.entity);\n index.remove(rec.entity);\n changed = true;\n }\n reap.push(widget);\n continue;\n }\n const slots = portSlots(portedDeclsOf(ctx, widget) ?? []);\n for (const [portId, rec] of wp.ports) {\n const slot = slots.get(portId);\n if (slot === undefined || !ctx.isAlive(rec.entity)) continue;\n const a = portAnchor(rect, slot);\n if (a.x !== rec.ax || a.y !== rec.ay) {\n ctx.edit(rec.entity).set(PortAnchor, { x: a.x, y: a.y });\n index.upsert(rec.entity, portAabb(a.x, a.y));\n rec.ax = a.x;\n rec.ay = a.y;\n changed = true;\n }\n }\n }\n for (const w of reap) byWidget.delete(w);\n\n if (changed) bumpVersion(world, SpatialVersion);\n },\n { name: \"portMaterialize\", access: { write: [PortAnchor] } },\n );\n}\n","/**\n * Churn guard — the `runIf` half of the petition-7 gating pattern\n * (design-002 §4 \"guards live in runIf, never the body\" × strata 0.7.0\n * `world.changes`).\n *\n * `activeMembership` gates by draining a collector INSIDE its tick body\n * (legal there: it declares no writes, so an early-out stamps nothing).\n * Systems that DECLARE `access.write` cannot use that shape — strata\n * blanket-stamps declared writes for any system that RUNS, even one that\n * early-outs (see helpers/version-stamps.ts) — so their gate must be a real\n * `runIf`. But a naive collector-in-runIf would LOSE the drained delta when\n * the body runs: this guard drains in `runIf`, stashes the delta, and hands\n * it to the body via `take()` in the same frame.\n *\n * Contract:\n * - `runIf` drains the collector every frame (collector creation is lazy —\n * a guard whose system is never installed never journals) and evaluates\n * the optional `extra` trigger (a value-compare closure, e.g. \"camera\n * zoom changed\"; it is called every frame so it can keep its own cache\n * current). Returns true iff there is work.\n * - `take()` (body, same frame) returns the work: `full` means rebuild\n * everything (first run, `world.reset`, coarse writes, or `extra` fired);\n * otherwise `changed`/`removed` are the journaled entities. The arrays\n * alias the collector's internal buffers — valid until the next drain,\n * i.e. for the body that runs this frame; do not retain them.\n */\nimport type { CollectOptions, Entity, World } from \"@vibecook/strata-ecs\";\nimport type { ChangeCollector } from \"@vibecook/strata-ecs\";\n\nexport interface ChurnWork {\n /** Rebuild everything: first run, reset, coarse writes, or `extra` fired. */\n readonly full: boolean;\n readonly changed: readonly Entity[];\n readonly removed: readonly Entity[];\n}\n\nexport interface ChurnGuard {\n /** Drop into a system's `runIf`. */\n readonly runIf: () => boolean;\n /** The work stashed by this frame's `runIf` (undefined if it returned false). */\n take(): ChurnWork | undefined;\n}\n\nconst NO_ENTITIES: readonly Entity[] = [];\n\nexport function makeChurnGuard(\n world: World,\n collect: CollectOptions,\n extra?: () => boolean,\n): ChurnGuard {\n let collector: ChangeCollector | undefined;\n let seeded = false;\n let stash: ChurnWork | undefined;\n\n return {\n runIf: () => {\n if (collector === undefined) collector = world.changes.collect(collect);\n const delta = collector.drain();\n const extraFired = extra?.() ?? false;\n const full = !seeded || delta.reset || delta.coarse.length > 0 || extraFired;\n seeded = true;\n if (!full && delta.changed.length === 0 && delta.removed.length === 0) {\n stash = undefined;\n return false;\n }\n stash = full\n ? { full: true, changed: NO_ENTITIES, removed: delta.removed }\n : { full: false, changed: delta.changed, removed: delta.removed };\n return true;\n },\n take: () => {\n const s = stash;\n stash = undefined;\n return s;\n },\n };\n}\n","/**\n * Chrome derive systems (design-004 §5 chrome plane, §8 LOD; `derive` phase).\n *\n * Two systems, both derive-scheduled, both write change-only:\n *\n * `selectionChrome` — maintains POOLED chrome entities mirroring the current\n * `Selected` set: ONE selection-box entity + 8 resize-handle entities. The box\n * entity carries ONLY the `SelectionBox` value (x,y,w,h = the union bbox); the\n * handles carry Position + Size + `HandleSpec{anchor}` + `VisualOf → box`.\n * Box policy (amended 2026-07-17): all-resizable selections get box + grips\n * (v1 parity); a MULTI-selection gets the box (group bbox) even when\n * non-resizable; a single non-resizable widget gets no engine chrome (the\n * app owns its selection look).\n *\n * HANDLE PICKING (the point of the design): handles carry a world AABB, so the\n * `react`-phase `spatialSync` indexes them automatically and `picking` resolves\n * a corner grab to the handle (HandleSpec has pick priority) → `dragRoute`\n * routes `RoutedResize` → `resizeBehavior` runs. Nothing here touches the index.\n *\n * HANDLES ARE SCREEN-CONSTANT: a handle's world size is `HANDLE_PICK_PX / zoom`\n * so its on-screen hit target stays ~constant across zoom. The tradeoff: the\n * handles must be recomputed whenever the camera zoom changes, so this system\n * runs every frame a selection exists and rewrites the 8 handles' Position/Size\n * change-only (a zoom change restamps 8 entities — small, bounded N; §5's\n * \"screen-space, recomputed on camera dirt, small N\").\n *\n * THE BOX IS DELIBERATELY NOT PICKABLE. It stores its rect in the `SelectionBox`\n * value, NOT in Position/Size, so `spatialSync` (which indexes [Position,Size])\n * never sees it. design-003 §3's pick priority lists ONLY HandleSpec chrome as\n * pickable; indexing the box would make it a widget-class pick (it has Position)\n * and let a center-of-selection click be grabbed by `moveClaim`. (This diverges\n * from a literal reading of the M6 brief's \"Position+Size+SelectionBox\" — the\n * box's geometry lives on the `SelectionBox` value instead; the chrome reflector\n * reads it from there.)\n *\n * POOL LIFECYCLE: entities spawn once via `ctx` (runtime prefab class) when a\n * selection appears and are reaped via `ctx.destroy` when it empties. On the\n * spawn frame the handles are still identity-only (placement defers to the\n * phase boundary), so their initial geometry rides the `ctx.spawn` payload and\n * the change-only `edit().set` updates begin the next frame.\n *\n * `breakpoint` — `WidgetBreakpoint{tier,w,h}` from a widget's EFFECTIVE size\n * (`MeasuredSize` where auto-sized and >0, else `Size`), width-thresholded into\n * 5 tiers with ±10% boundary hysteresis. Added lazily (on `WidgetEquipped`\n * widgets, once measured) and thereafter written ONLY when the tier changes —\n * the LOD signal must be stable within a tier so the measure→tier→content→\n * measure loop converges (§2). The stored w,h are the effective size at the\n * tier transition (what the tier \"was computed from\").\n */\nimport type { Entity, System, SystemCtx, TickSystem, World } from \"@vibecook/strata-ecs\";\nimport { defineQuery, defineSystem, defineTickSystem } from \"@vibecook/strata-ecs\";\nimport {\n Camera,\n ChromeSettings,\n Culled,\n Grab,\n HandleSpec,\n MeasuredSize,\n Position,\n Resizable,\n SelectionBox,\n Selected,\n Size,\n VisualOf,\n WidgetBreakpoint,\n} from \"../catalog\";\nimport { selectedEntities } from \"../ops/selection\";\nimport { WidgetEquipped } from \"../widget/define-widget\";\nimport { Active } from \"../catalog/camera-derived\";\nimport { makeChurnGuard } from \"../helpers/churn-guard\";\nimport { navFlightActive } from \"./nav-flight\";\n\n// --- selection chrome ---------------------------------------------------------\n\n/** Handle world size = this / zoom → ~constant on-screen hit target across zoom. */\nconst HANDLE_PICK_PX = 10;\n\n/** The 8 handle anchors, in a fixed order the pool aligns to. */\nconst HANDLE_ANCHORS = [\"nw\", \"n\", \"ne\", \"e\", \"se\", \"s\", \"sw\", \"w\"] as const;\ntype HandleAnchor = (typeof HANDLE_ANCHORS)[number];\n\ninterface Rect {\n x: number;\n y: number;\n w: number;\n h: number;\n}\n\n/** The center point (world) of a handle for one anchor over the bbox. */\nfunction anchorPoint(anchor: HandleAnchor, b: Rect): { x: number; y: number } {\n const cx = b.x + b.w / 2;\n const cy = b.y + b.h / 2;\n const l = b.x;\n const r = b.x + b.w;\n const t = b.y;\n const bot = b.y + b.h;\n switch (anchor) {\n case \"nw\":\n return { x: l, y: t };\n case \"n\":\n return { x: cx, y: t };\n case \"ne\":\n return { x: r, y: t };\n case \"e\":\n return { x: r, y: cy };\n case \"se\":\n return { x: r, y: bot };\n case \"s\":\n return { x: cx, y: bot };\n case \"sw\":\n return { x: l, y: bot };\n default:\n return { x: l, y: cy }; // \"w\"\n }\n}\n\n/** A handle's world AABB (top-left + size), centered on its anchor point. */\nfunction handleRect(anchor: HandleAnchor, b: Rect, worldSize: number): Rect {\n const p = anchorPoint(anchor, b);\n return { x: p.x - worldSize / 2, y: p.y - worldSize / 2, w: worldSize, h: worldSize };\n}\n\nconst selectedQ = defineQuery([Selected]);\n\nexport function createSelectionChromeSystem(world: World): TickSystem {\n // Pool state (a derived cache, not world state): the box + 8 handles, aligned\n // to HANDLE_ANCHORS, plus the last-written geometry for change-only writes.\n let boxEntity: Entity | undefined;\n let handleEntities: Entity[] = [];\n let boxCache: Rect | undefined;\n const handleCache = new Map<Entity, Rect>();\n\n const reapHandles = (ctx: SystemCtx): void => {\n for (const h of handleEntities) ctx.destroy(h);\n handleEntities = [];\n handleCache.clear();\n };\n\n const reap = (ctx: SystemCtx): void => {\n if (boxEntity !== undefined) {\n ctx.destroy(boxEntity);\n boxEntity = undefined;\n boxCache = undefined;\n }\n reapHandles(ctx);\n };\n\n const spawnHandles = (ctx: SystemCtx, bbox: Rect, worldSize: number, box: Entity): void => {\n for (const anchor of HANDLE_ANCHORS) {\n const hr = handleRect(anchor, bbox, worldSize);\n const he = ctx.spawn({\n components: [\n [Position, { x: hr.x, y: hr.y }],\n [Size, { w: hr.w, h: hr.h }],\n [HandleSpec, { anchor }],\n ],\n });\n ctx.setRelation(he, VisualOf, box); // VisualOf is arity \"one\"\n handleEntities.push(he);\n handleCache.set(he, hr);\n }\n };\n\n // Tick system (strata 0.5.0): exactly one pass per frame by construction\n // (spawn/destroy are NOT idempotent — cardinality is the scheduler's now).\n const sys = defineTickSystem(\n (ctx) => {\n // Union bbox over the selection's positioned entities.\n let minX = Number.POSITIVE_INFINITY;\n let minY = Number.POSITIVE_INFINITY;\n let maxX = Number.NEGATIVE_INFINITY;\n let maxY = Number.NEGATIVE_INFINITY;\n let count = 0;\n // Resize affordance gate (field report 2026-07-12, v1 parity): handles\n // exist only when EVERY selected entity is Resizable — a non-resizable\n // card gets the outline box, never the 8 grips (mixed multi-select is\n // conservatively grip-less too).\n let allResizable = true;\n // Visual drag-lift factor (2026-07-17): a Grab-bed member's card is\n // CSS-scaled about its center by the app (widgetlab 1.05); inflate its\n // rect by the mirrored setting so the box keeps WRAPPING what the user\n // sees. 1 (default) ⇒ pure ECS union.\n const liftScale = ctx.getResource(ChromeSettings)?.liftScale ?? 1;\n for (const e of selectedEntities(world)) {\n if (!ctx.has(e, Position)) continue;\n // Scope filter (field bug 2026-07-17, the wires-collect rule): a\n // selection that rode a nav transition must not draw chrome for\n // OTHER frames' widgets — their coords are frame-local nonsense\n // here. Non-member signature: Culled ∧ ¬Active (viewport-culled\n // members stay Culled ∧ Active and keep their chrome; bare\n // membership-less worlds carry neither tag).\n if (ctx.hasTag(e, Culled) && !ctx.hasTag(e, Active)) continue;\n if (!ctx.hasTag(e, Resizable)) allResizable = false;\n const p = ctx.read(e, Position);\n // Effective size (review finding): the outline must wrap what the user\n // SEES — MeasuredSize where auto-sized and measured, else Size.\n const m = ctx.get(e, MeasuredSize);\n const s = ctx.get(e, Size);\n let w = m !== undefined && m.w > 0 ? m.w : (s?.w ?? 0);\n let h = m !== undefined && m.h > 0 ? m.h : (s?.h ?? 0);\n let x = p.x;\n let y = p.y;\n if (liftScale !== 1 && ctx.has(e, Grab)) {\n x -= (w * (liftScale - 1)) / 2;\n y -= (h * (liftScale - 1)) / 2;\n w *= liftScale;\n h *= liftScale;\n }\n minX = Math.min(minX, x);\n minY = Math.min(minY, y);\n maxX = Math.max(maxX, x + w);\n maxY = Math.max(maxY, y + h);\n count++;\n }\n\n // Box policy (amended 2026-07-17, James: a multi-selection shares ONE\n // bounding chrome regardless of resizability):\n // - box for any ALL-RESIZABLE selection (the grips' anchor, v1 parity)\n // OR any selection of TWO OR MORE (the group bbox);\n // - a single non-resizable card still shows NO engine chrome — its\n // selection look is the app's (e.g. widgetlab's CardShell ring);\n // - grips stay gated to all-resizable selections (2026-07-12 rule).\n const wantBox = count > 0 && (allResizable || count >= 2);\n const wantHandles = count > 0 && allResizable;\n\n if (!wantBox) {\n if (boxEntity !== undefined) reap(ctx);\n return;\n }\n\n const bbox: Rect = { x: minX, y: minY, w: maxX - minX, h: maxY - minY };\n const zoom = ctx.getResource(Camera)?.zoom ?? 1;\n const worldSize = HANDLE_PICK_PX / zoom;\n\n if (boxEntity === undefined) {\n // Spawn the pool with its initial geometry on the payload — the entities\n // are identity-only until the phase boundary, so no edit() until next frame.\n boxEntity = ctx.spawn({ components: [[SelectionBox, { ...bbox }]] });\n boxCache = { ...bbox };\n if (wantHandles) spawnHandles(ctx, bbox, worldSize, boxEntity);\n return;\n }\n\n // Pool exists (placed) — change-only value writes.\n if (\n boxCache === undefined ||\n boxCache.x !== bbox.x ||\n boxCache.y !== bbox.y ||\n boxCache.w !== bbox.w ||\n boxCache.h !== bbox.h\n ) {\n ctx.edit(boxEntity).set(SelectionBox, { ...bbox });\n boxCache = { ...bbox };\n }\n if (!wantHandles) {\n // Mixed/non-resizable multi: group box only. Reap grips left over from\n // an all-resizable selection this replaced.\n if (handleEntities.length > 0) reapHandles(ctx);\n return;\n }\n if (handleEntities.length === 0) {\n // Turned all-resizable with the box already placed — grips spawn now\n // (geometry on the payload; change-only edits begin next frame).\n spawnHandles(ctx, bbox, worldSize, boxEntity);\n return;\n }\n for (let i = 0; i < HANDLE_ANCHORS.length; i++) {\n const he = handleEntities[i];\n const anchor = HANDLE_ANCHORS[i];\n if (he === undefined || anchor === undefined) continue;\n const hr = handleRect(anchor, bbox, worldSize);\n const prev = handleCache.get(he);\n if (prev === undefined || prev.x !== hr.x || prev.y !== hr.y || prev.w !== hr.w || prev.h !== hr.h) {\n ctx.edit(he).set(Position, { x: hr.x, y: hr.y });\n ctx.edit(he).set(Size, { w: hr.w, h: hr.h });\n handleCache.set(he, hr);\n }\n }\n },\n {\n name: \"selectionChrome\",\n access: { write: [SelectionBox, Position, Size] },\n // Run while there is a selection to mirror OR a pool still to reap.\n runIf: () => world.firstOf(selectedQ) !== undefined || boxEntity !== undefined,\n },\n );\n\n return sys;\n}\n\n// --- breakpoints --------------------------------------------------------------\n\n/** Tier width thresholds (px). Engine defaults pending design-005 facade config. */\nconst TIER_THRESHOLDS = [80, 160, 320, 560] as const;\nconst TIER_NAMES = [\"micro\", \"compact\", \"normal\", \"expanded\", \"detailed\"] as const;\ntype Tier = (typeof TIER_NAMES)[number];\n/** Boundary hysteresis: cross up at +10%, down at -10%, before the tier flips. */\nconst TIER_HYSTERESIS = 0.1;\n\n/** Raw tier index (no hysteresis) — the seed for a widget's first computation. */\nfunction rawTierIndex(w: number): number {\n let i = 0;\n while (i < TIER_THRESHOLDS.length) {\n const t = TIER_THRESHOLDS[i];\n if (t === undefined || w < t) break;\n i++;\n }\n return i;\n}\n\n/** Tier index from width, holding `cur` unless the ±10% band is crossed. */\nfunction hysteresisTierIndex(w: number, cur: number): number {\n let i = cur;\n while (i < TIER_THRESHOLDS.length) {\n const t = TIER_THRESHOLDS[i]; // upper boundary of tier i\n if (t === undefined || w < t * (1 + TIER_HYSTERESIS)) break;\n i++;\n }\n while (i > 0) {\n const t = TIER_THRESHOLDS[i - 1]; // lower boundary of tier i\n if (t === undefined || w >= t * (1 - TIER_HYSTERESIS)) break;\n i--;\n }\n return i;\n}\n\nfunction clampU16(v: number): number {\n return Math.max(0, Math.min(65535, Math.round(v)));\n}\n\n// ACTIVE-scoped (2026-07-15 gate): tiers drive RENDERED content; non-active\n// widgets (closed-container content) are frozen-while-hidden by design and\n// recompute on re-activation via the Active-tag journal below. This is what\n// bounds a zoom gesture's cost to the current frame's content.\nconst equippedWidgetQ = defineQuery([Size, WidgetEquipped, Active]);\n\n/** One entity's tier pass (shared by the full walk and the delta path). */\nfunction retier(ctx: SystemCtx, e: Entity, w: number, h: number, zoom: number): void {\n const m = ctx.get(e, MeasuredSize);\n // Effective size: MeasuredSize where auto-sized and measured, else Size.\n const ew = m !== undefined && m.w > 0 ? m.w : w;\n const eh = m !== undefined && m.h > 0 ? m.h : h;\n const cw = clampU16(ew);\n const ch = clampU16(eh);\n // Tier input is the ON-SCREEN width: effective size × zoom (design-004\n // §8 — a zoomed-out large card shows micro content). Stored w,h remain\n // the world-effective size the tier was computed from.\n const screenW = ew * zoom;\n\n const existing = ctx.get(e, WidgetBreakpoint);\n if (existing === undefined) {\n const idx = rawTierIndex(screenW);\n ctx.addComponent(e, WidgetBreakpoint, { tier: TIER_NAMES[idx] as Tier, w: cw, h: ch });\n return;\n }\n const curIdx = TIER_NAMES.indexOf(existing.tier as Tier);\n const idx = hysteresisTierIndex(screenW, curIdx < 0 ? rawTierIndex(screenW) : curIdx);\n // Write only on a tier change — the tier must be stable within a band so\n // the measure→tier→content→measure loop converges (w,h ride the change).\n if (idx !== curIdx) {\n ctx.edit(e).set(WidgetBreakpoint, { tier: TIER_NAMES[idx] as Tier, w: cw, h: ch });\n }\n}\n\nexport function createBreakpointSystem(world: World): TickSystem {\n // The gate (2026-07-15; the activeMembership playbook, but through a REAL\n // runIf — this system declares access.write, and a run-but-early-out would\n // blanket-stamp WidgetBreakpoint every frame). Zoom is the `extra` trigger:\n // its change re-tiers everything Active; Size/MeasuredSize churn and\n // Active flips re-tier only the journaled entities. Pan frames (zoom\n // unchanged) skip entirely — pre-gate they paid the full O(N) scan.\n // A TICK system (one body per frame — the batch form would re-run the\n // guard logic per chunk), so the full walk goes through ctx.query and the\n // column reads are declared explicitly (the spatialSync precedent).\n let lastZoom: number | undefined;\n const guard = makeChurnGuard(\n world,\n { components: [Size, MeasuredSize], tags: [Active], coarse: false },\n () => {\n // A nav flight sweeps the zoom across EVERY tier threshold in ~400 ms —\n // retier-ing per flight frame swaps widget CONTENT mid-flight (React\n // commits at the worst possible moment; James's field report,\n // 2026-07-16). Defer: lastZoom stays FROZEN at the pre-flight value\n // while flying, so the first post-flight frame compares arrival vs\n // pre-flight zoom and fires exactly ONE full retier at rest. The delta\n // path below still runs mid-flight — freshly mounted content gets its\n // first tier immediately (corrected at settle if the zoom moved on).\n if (navFlightActive(world)) return false;\n const zoom = world.getResource(Camera)?.zoom;\n const changed = zoom !== lastZoom;\n lastZoom = zoom;\n return changed;\n },\n );\n\n return defineTickSystem(\n (ctx) => {\n const work = guard.take();\n if (work === undefined) return; // runIf false — never happens with the guard wired\n const zoom = ctx.getResource(Camera)?.zoom ?? 1;\n if (work.full) {\n ctx.query(equippedWidgetQ).each((b) => {\n const sw = b.col(Size).w;\n const sh = b.col(Size).h;\n for (const r of b) {\n retier(ctx, b.entity(r), sw[r] as number, sh[r] as number, zoom);\n }\n });\n return;\n }\n // Delta path: only the journaled entities, re-read entity-wise.\n for (const e of work.changed) {\n if (!ctx.isAlive(e) || !ctx.has(e, Size) || !ctx.hasTag(e, Active)) continue;\n if (!world.hasTag(e, WidgetEquipped)) continue;\n const s = ctx.read(e, Size);\n retier(ctx, e, s.w, s.h, zoom);\n }\n },\n { name: \"breakpoint\", access: { read: [Size], write: [WidgetBreakpoint] }, runIf: guard.runIf },\n );\n}\n","/**\n * L3 — draw behavior (design-005 §3 `draw(widgetType)` tool; `ctl:behave`,\n * after connect, before camera — design-003 §5 order).\n *\n * A `RoutedDraw` drag creates ONE widget from the release rect: at\n * `JustEnded`, screen start+total → world rect (Camera at release), floored\n * at the widget's `minSize`; a sub-slop release (a click) places the\n * widget's DEFAULT size centered on the point. Commit is one `create`\n * intent through the sink — the doc sink spawns via the same override\n * builder as `ops.spawnWidget`, so the two paths can never diverge.\n * Cancel/fail commit nothing. The widget type comes from the ACTIVE tool's\n * `draw` config (latched per drag at claim would be stricter; tools switch\n * via `ops.setTool` which cancels active gestures first, so the active\n * tool is stable for a live drag by construction).\n *\n * Mid-drag rect preview is recorded polish (design-001 §3's full\n * draft→promote protocol is the vNext shape); v1 draws nothing until release.\n */\nimport type { System, World } from \"@vibecook/strata-ecs\";\nimport { defineQuery, defineSystem } from \"@vibecook/strata-ecs\";\nimport { screenToWorld, type CameraState } from \"@ice/kernel\";\nimport { Camera, Drag, GesturePhases, RoutedDraw } from \"../catalog\";\nimport { ActiveTool } from \"../catalog/camera-derived\";\nimport type { CommitSink } from \"../engine/commit-sink\";\nimport { tools } from \"../tools/define-tool\";\nimport { widgets } from \"../widget/define-widget\";\n\nconst P = GesturePhases;\nconst IDENTITY_CAM: CameraState = { x: 0, y: 0, zoom: 1 };\n\n/** Below this screen travel a draw release is a CLICK (default-size place). */\nconst DRAW_CLICK_SLOP_PX = 4;\n\nexport function createDrawBehavior(world: World, sink: CommitSink): System {\n const drawDragQ = defineQuery([Drag, RoutedDraw]);\n\n return defineSystem(\n drawDragQ,\n (b, ctx) => {\n for (const r of b) {\n const rec = b.entity(r);\n if (!ctx.hasTag(rec, P.justTags.Ended)) continue;\n\n const tool = tools.resolve(ctx.getResource(ActiveTool)?.id ?? \"select\");\n const type = tool.draw?.widgetType;\n const widget = type !== undefined ? widgets.get(type) : undefined;\n if (type === undefined || widget === undefined) continue; // route without a draw tool: no-op\n\n const d = ctx.read(rec, Drag);\n const cam = ctx.getResource(Camera) ?? IDENTITY_CAM;\n const w0 = screenToWorld(d.startX, d.startY, cam);\n const w1 = screenToWorld(d.startX + d.totalX, d.startY + d.totalY, cam);\n\n let x: number;\n let y: number;\n let w: number;\n let h: number;\n if (Math.hypot(d.totalX, d.totalY) < DRAW_CLICK_SLOP_PX) {\n // Click: default size centered on the point.\n w = widget.defaultSize.w;\n h = widget.defaultSize.h;\n x = w0.x - w / 2;\n y = w0.y - h / 2;\n } else {\n x = Math.min(w0.x, w1.x);\n y = Math.min(w0.y, w1.y);\n w = Math.max(widget.minSize.w, Math.abs(w1.x - w0.x));\n h = Math.max(widget.minSize.h, Math.abs(w1.y - w0.y));\n }\n\n sink.commit({\n kind: \"create\",\n gesture: rec,\n writes: [],\n creates: [{ type, x, y, w, h }],\n });\n }\n },\n { name: \"drawBehavior\" },\n );\n}\n","/**\n * spawnWidget — the paved-road widget creation op (app handler, design-005 §2).\n *\n * One guardedTransaction: spawnPrefab with Position (+Size) overrides and any\n * prop overrides folded into their group components (whole-group values —\n * design-001 §5.2's conflict-group granularity). Validation runs through each\n * prop's Standard Schema before the write.\n */\nimport type { Component, Entity, OrderPlace, Relation, World } from \"@vibecook/strata-ecs\";\nimport type { DurableStore } from \"@vibecook/strata-ecs/durable\";\nimport { ChildOf, Position, Size } from \"../catalog\";\nimport { guardedTransaction, type GuardedTx } from \"../guards/guarded-tx\";\nimport type { AnyBehaviorDef } from \"../behavior/types\";\nimport { frameParent } from \"../ops/sibling-order\";\nimport { init, type ComponentInit } from \"../schema/prefab\";\nimport { widgets, type WidgetType } from \"./define-widget\";\nimport { defaultValueOf } from \"./props\";\n\nexport interface SpawnWidgetOpts {\n readonly x: number;\n readonly y: number;\n readonly w?: number;\n readonly h?: number;\n /**\n * Sibling placement in the spawn parent's `ChildOf` sequence (petition 8);\n * default \"last\" = painted last = on top. \"first\" spawns UNDER everything in\n * the frame (e.g. a comment box spawning behind its members).\n */\n readonly order?: OrderPlace;\n /** Explicit `ChildOf` parent; default = the frame parent (nav frame ?? board root). */\n readonly parent?: Entity;\n readonly props?: Readonly<Record<string, unknown>>;\n /** false ⇒ the spawn never enters the local undo stack (batch seeds). */\n readonly undoable?: boolean;\n}\n\n/**\n * Hang the spawn's `ChildOf` edge (petition 8) — shared by `spawnWidget` and\n * the doc sink's create-intent execution so frame placement can never diverge\n * between the two spawn paths. A legacy world (no BoardRoot, no nav frame,\n * no explicit parent) gets NO edge: the entity stays legacy-fallback-ordered.\n */\nexport function attachSpawnParent(\n tx: { setRelation(e: Entity, r: Relation, target: Entity, place?: OrderPlace): void },\n world: World,\n spawned: Entity,\n opts?: { readonly parent?: Entity; readonly order?: OrderPlace },\n): void {\n const parent = opts?.parent ?? frameParent(world);\n if (parent === undefined) return;\n tx.setRelation(spawned, ChildOf, parent, opts?.order ?? \"last\");\n}\n\n/**\n * The prefab-override list for a widget spawn (Position/Size + validated\n * whole-group prop values). Shared by `spawnWidget` and the doc sink's\n * create-intent execution (draw tool) so the two can never diverge.\n */\nexport function widgetSpawnInits(type: string, opts: SpawnWidgetOpts): { prefab: import(\"../schema/prefab\").Prefab; overrides: ComponentInit[] } {\n const widget = widgets.get(type);\n if (widget === undefined) throw new Error(`ice: spawnWidget — unknown widget type \"${type}\".`);\n\n // Fold prop overrides into whole-group values (defaults + overrides).\n const overrides: ComponentInit[] = [\n init(Position, { x: opts.x, y: opts.y }),\n init(Size, {\n w: opts.w ?? widget.defaultSize.w,\n h: opts.h ?? widget.defaultSize.h,\n }),\n ];\n const givenProps = opts.props ?? {};\n for (const [name, value] of Object.entries(givenProps)) {\n const group = widget.propToGroup[name];\n if (group === undefined) throw new Error(`ice: spawnWidget(\"${type}\") — unknown prop \"${name}\".`);\n }\n for (const g of widget.groups) {\n const touched = Object.keys(givenProps).some((name) => widget.propToGroup[name] === g.name);\n if (!touched) continue;\n const value: Record<string, string | number | boolean> = {};\n for (const [name, spec] of Object.entries(g.fields)) {\n const given = givenProps[name];\n if (given !== undefined) {\n const result = spec[\"~standard\"].validate(spec.kind === \"json\" ? given : given);\n if (\"issues\" in result) {\n throw new Error(\n `ice: spawnWidget(\"${type}\") prop \"${name}\" invalid — ${result.issues[0]?.message}`,\n );\n }\n value[name] = spec.kind === \"json\" ? JSON.stringify(given) : (given as string | number | boolean);\n } else {\n // group values are whole-component writes: fill from defaults\n value[name] = defaultValueOf(spec);\n }\n }\n overrides.push([g.component, value] as ComponentInit);\n }\n\n return { prefab: widget.prefab, overrides };\n}\n\n/**\n * Attach a widget type's DURABLE pre-attached behaviors (design-009 §6), as\n * post-spawn `addComponent` calls inside the spawn transaction.\n *\n * Post-spawn rather than spawn-init overrides: `instantiate` checks every\n * override against the prefab's eligible set, and a behavior is eligible on\n * every entity by definition (BF-D6) — it is not in any prefab's set and never\n * will be. Runtime pre-attachments are NOT here: they ride projection (the\n * equip system), which is the only path that also equips a widget arriving\n * from a peer or a restored file.\n */\nexport function attachSpawnBehaviors(tx: GuardedTx, widget: WidgetType, e: Entity): void {\n for (const entry of widget.behaviors) {\n if (entry.behavior.store !== \"durable\") continue;\n tx.addComponent(\n e,\n entry.behavior.component as Component<Record<string, unknown>>,\n behaviorCell(entry.behavior, entry.data),\n );\n }\n}\n\n/** Defaults ∪ the declared pre-attach data, serialized for the cell. */\nfunction behaviorCell(b: AnyBehaviorDef, data: Readonly<Record<string, unknown>>): Record<string, unknown> {\n const out: Record<string, unknown> = { ...(b.defaults as Record<string, unknown>) };\n for (const [k, v] of Object.entries(data)) {\n if (v === undefined) continue;\n const spec = b.schema[k];\n out[k] = spec?.kind === \"json\" ? JSON.stringify(v) : v;\n }\n return out;\n}\n\nexport function spawnWidget(\n store: DurableStore,\n world: World,\n type: string,\n opts: SpawnWidgetOpts,\n): Entity {\n const { prefab, overrides } = widgetSpawnInits(type, opts);\n let spawned: Entity | undefined;\n guardedTransaction(\n store,\n world,\n (tx) => {\n spawned = tx.spawnPrefab(prefab, overrides);\n attachSpawnParent(tx, world, spawned, opts);\n attachSpawnBehaviors(tx, widgets.get(type) as WidgetType, spawned);\n },\n opts.undoable === false ? { undoable: false } : undefined,\n );\n if (spawned === undefined) throw new Error(\"ice: spawnWidget — transaction did not spawn.\");\n return spawned;\n}\n","/**\n * The doc-backed CommitSink — the M5 half of the commit seam (design-001 §3\n * step 3a; design-002 decision 4).\n *\n * One intent = ONE `guardedTransaction` = one undo step. Behaviors already\n * filtered their write sets to live `Drags` edges; the sink re-guards anyway —\n * the doc is the authority (design-001 §3: `keyOf(w) === undefined ⇒ skip` —\n * one dead widget must not roll back the gesture). Value writes go through\n * `tx.edit().set` on PRE-EXISTING cells (the synchronous agreement point);\n * consume's reparent is a relation write in the SAME transaction.\n *\n * Read-only sessions (version gate) swap in `createReadOnlyCommitSink`: the\n * gesture still runs (runtime feels live) but nothing commits — the runtime\n * cells reconverge with the baseline at the next remote sweep, exactly like a\n * cancel, and a DEV warn says why.\n */\nimport type { DurableStore } from \"@vibecook/strata-ecs/durable\";\nimport type { Entity, World } from \"@vibecook/strata-ecs\";\nimport { ChildOf } from \"../catalog\";\nimport type { CommitIntent, CommitSink } from \"../engine/commit-sink\";\nimport { init } from \"../schema/prefab\";\nimport { WireFrom, WirePorts, WirePrefab, WireTo } from \"../catalog/graph\";\nimport { attachSpawnParent, widgetSpawnInits } from \"../widget/spawn\";\nimport { widgets } from \"../widget/define-widget\";\nimport { guardedTransaction } from \"../guards/guarded-tx\";\n\n/**\n * Out-of-ECS hand-off for `CommitCreate.select` (the marquee-buffer precedent:\n * plain JS state written mid-tick, consumed by a system in a later phase —\n * never observed, never ECS). The sink appends the spawned twin here; the\n * insert-ghost reap system drains it and applies the selection ONE tick later,\n * when the twin's projection is alive. Keyed per world so parallel test\n * engines never cross-talk.\n */\nconst pendingSelects = new WeakMap<World, Entity[]>();\n\nexport function drainCreatedSelections(world: World): Entity[] {\n const list = pendingSelects.get(world);\n if (list === undefined || list.length === 0) return [];\n pendingSelects.set(world, []);\n return list;\n}\n\nexport function createDocCommitSink(store: DurableStore, world: World): CommitSink {\n return {\n commit(intent: CommitIntent): void {\n const liveWrites = intent.writes.filter((w) => store.keyOf(w.entity) !== undefined);\n const liveReparents = (intent.reparents ?? []).filter(\n (r) => store.keyOf(r.entity) !== undefined && store.keyOf(r.container) !== undefined,\n );\n // Wires bind widgets + port ids (design-001 §5.3): both ENDPOINT widgets\n // must still be durable-live at commit (the same divergence-is-the-signal\n // re-guard as writes — a remote delete mid-gesture drops the spawn).\n const liveWires = (intent.wires ?? []).filter(\n (w) => store.keyOf(w.from) !== undefined && store.keyOf(w.to) !== undefined,\n );\n // Order ops (petition 8): both ends re-guarded — a dead parent must not\n // roll back the gesture any more than a dead widget does.\n const liveOrders = (intent.orders ?? []).filter(\n (o) => store.keyOf(o.entity) !== undefined && store.keyOf(o.parent) !== undefined,\n );\n // Creates re-guard their PARENT (a consume-insert whose folder a remote\n // deleted mid-gesture): the container-local x/y are meaningless without\n // the container, so the create is dropped whole — the same\n // divergence-is-the-signal posture as a dead reparent target. Unknown\n // types are dropped too (never a throw inside the gesture's tx).\n const creates = (intent.creates ?? []).filter(\n (c) =>\n widgets.get(c.type) !== undefined &&\n (c.parent === undefined || store.keyOf(c.parent) !== undefined),\n );\n if (\n liveWrites.length === 0 &&\n liveReparents.length === 0 &&\n liveOrders.length === 0 &&\n liveWires.length === 0 &&\n creates.length === 0\n ) {\n return;\n }\n\n guardedTransaction(store, world, (tx) => {\n for (const w of liveWrites) {\n tx.edit(w.entity).set(w.component, w.value);\n }\n for (const r of liveReparents) {\n // Placeless set on the ordered ChildOf appends \"last\" — a consumed\n // widget lands on top of the container's sequence (petition 8).\n tx.setRelation(r.entity, ChildOf, r.container);\n }\n // Sibling placements land in the SAME transaction as the gesture's\n // value writes — one gesture, one undo step (petition 8).\n for (const o of liveOrders) {\n tx.setRelation(o.entity, ChildOf, o.parent, o.place);\n }\n // Draw-tool / tray-insert creations: one prefab spawn per entry,\n // through the SAME override builder as ops.spawnWidget — and the same\n // frame-parent edge attach, so the spawn paths cannot diverge. An\n // explicit `parent` (consume-insert) hangs the edge on the container\n // instead — x/y are container-local by that convention.\n for (const c of creates) {\n const { prefab, overrides } = widgetSpawnInits(c.type, {\n x: c.x,\n y: c.y,\n w: c.w,\n h: c.h,\n ...(c.props !== undefined ? { props: c.props } : {}),\n });\n const spawned = tx.spawnPrefab(prefab, overrides);\n attachSpawnParent(tx, world, spawned, c.parent !== undefined ? { parent: c.parent } : undefined);\n if (c.select === true) {\n let list = pendingSelects.get(world);\n if (list === undefined) {\n list = [];\n pendingSelects.set(world, list);\n }\n list.push(spawned);\n }\n }\n for (const w of liveWires) {\n // The paved prefab path: PrefabId + Wire tag ride the prefab, and\n // WireFrom/WireTo pass its eligibility contract (raw spawn skipped\n // those checks entirely — 2026-07-13 review).\n const wire = tx.spawnPrefab(WirePrefab, [init(WirePorts, { from: w.fromPort, to: w.toPort })]);\n tx.setRelation(wire, WireFrom, w.from);\n tx.setRelation(wire, WireTo, w.to);\n }\n });\n },\n };\n}\n\n/** The version-gate's read-only posture: gestures run, nothing commits. */\nexport function createReadOnlyCommitSink(): CommitSink {\n return {\n commit(intent) {\n console.warn(\n `ice: read-only document — dropped a \"${intent.kind}\" commit (${intent.writes.length} writes); runtime cells reconverge with the baseline.`,\n );\n },\n };\n}\n","/**\n * L4 — cursor projection (design-003 §7; `derive` phase).\n *\n * Memoryless: resolved fresh every run from live world state, priority order\n * (1) any LOCAL pointer with a live `ClaimedBy` — Drag+RoutedMove or a\n * LongPress in Recognized → \"grabbing\"; RoutedResize → directional resize by\n * the captured handle's `HandleSpec.anchor`; RoutedPan → \"grabbing\";\n * (2) `ActiveTool` override — pan tool → \"grab\"; (3) else the mouse pointer's\n * `Targets` kind — a `HandleSpec` → directional resize, an entity with\n * `Position` (widget) → \"default\", `CanvasSurface`/none → \"default\".\n *\n * Scheduled on the `CanvasSurface` anchor query (exactly one such entity,\n * guaranteed by install — the same idiom `pointerIngest` uses in l0-input.ts)\n * so the body runs every frame even on tool switches with no pointer motion;\n * `world.query(...)` inside then does the actual local-pointer scan (mirrors\n * `oneTickClear`'s marker sweep in cleanup.ts).\n *\n * The resolved string is closure state; `readCursor()` exposes it — the DOM\n * cursor reflector is the only consumer (core never touches DOM).\n */\nimport type { Entity, System, World } from \"@vibecook/strata-ecs\";\nimport { defineQuery, defineSystem } from \"@vibecook/strata-ecs\";\nimport { tools } from \"../tools/define-tool\";\nimport {\n ActiveTool,\n CanvasSurface,\n Captures,\n ClaimedBy,\n Drag,\n GesturePhases,\n HandleSpec,\n LocalPointer,\n LongPress,\n Pointer,\n Position,\n RoutedMove,\n RoutedPan,\n RoutedResize,\n Targets,\n} from \"../catalog\";\n\nconst P = GesturePhases;\n\nconst anchorQ = defineQuery([CanvasSurface]);\nconst localPointerQ = defineQuery([Pointer, LocalPointer]);\n\n/** `HandleSpec.anchor` → CSS directional-resize cursor (design-003 §7). */\nfunction resizeCursorForAnchor(anchor: string): string {\n switch (anchor) {\n case \"nw\":\n case \"se\":\n return \"nwse-resize\";\n case \"ne\":\n case \"sw\":\n return \"nesw-resize\";\n case \"n\":\n case \"s\":\n return \"ns-resize\";\n default: // \"e\" | \"w\"\n return \"ew-resize\";\n }\n}\n\nexport function createCursorSync(world: World): System & { readCursor(): string } {\n let cursor = \"default\";\n\n const system = defineSystem(\n anchorQ,\n (_b, ctx) => {\n let resolved: string | undefined;\n let mouseTargets: Entity | undefined;\n\n world.query(localPointerQ).each((b) => {\n for (const r of b) {\n const p = b.entity(r);\n if (ctx.read(p, Pointer).device === \"mouse\") {\n mouseTargets = ctx.getRelation(p, Targets);\n }\n if (resolved !== undefined) continue;\n const rec = ctx.getRelation(p, ClaimedBy);\n if (rec === undefined) continue;\n\n if (ctx.has(rec, Drag) && ctx.hasTag(rec, RoutedMove)) {\n resolved = \"grabbing\";\n } else if (ctx.has(rec, LongPress) && ctx.hasTag(rec, P.tags.Recognized)) {\n resolved = \"grabbing\";\n } else if (ctx.hasTag(rec, RoutedResize)) {\n const handle = ctx.getRelation(rec, Captures);\n if (handle !== undefined && ctx.has(handle, HandleSpec)) {\n resolved = resizeCursorForAnchor(ctx.read(handle, HandleSpec).anchor);\n }\n } else if (ctx.hasTag(rec, RoutedPan)) {\n resolved = \"grabbing\";\n }\n }\n });\n\n if (resolved === undefined) {\n // Tool cursor override from the registry (design-005 §3) — the pan\n // tool's \"grab\" now lives on its ToolDef; unknown ids have none.\n const toolCursor = tools.resolve(ctx.getResource(ActiveTool)?.id ?? \"select\").cursor;\n if (toolCursor !== undefined) resolved = toolCursor;\n }\n\n if (resolved === undefined && mouseTargets !== undefined) {\n if (ctx.has(mouseTargets, HandleSpec)) {\n resolved = resizeCursorForAnchor(ctx.read(mouseTargets, HandleSpec).anchor);\n } else if (ctx.has(mouseTargets, Position)) {\n resolved = \"default\";\n }\n }\n\n cursor = resolved ?? \"default\";\n },\n { name: \"cursorSync\" },\n );\n\n return Object.assign(system, { readCursor: () => cursor });\n}\n","/**\n * Interaction-stack installation (design-002 §2 phase layout × design-003).\n *\n * Composable: `installInteractionCore` wires the M4 spine (L0 ingest, L2\n * lifecycle + kinds + arbitration, ctl:claim, select/move behaviors, cleanup).\n * Later slices (picking, snap, drop, resize, marquee, camera) install through\n * their own module functions into the same phase groups — group order is the\n * only ordering contract between them; within-group order is the design-003 §5\n * in-phase order, so later installers pass explicit `before`-free appends in\n * the documented sequence.\n *\n * The canvas-surface anchor entity is guaranteed here (design-001 §4: picking\n * always resolves to SOMETHING; L0 ingest schedules on it).\n */\nimport type { Entity, World } from \"@vibecook/strata-ecs\";\nimport { defineQuery } from \"@vibecook/strata-ecs\";\nimport { SpatialIndex } from \"@ice/kernel\";\nimport { CanvasSurface } from \"../catalog\";\nimport { createRecordingCommitSink, type CommitSink } from \"../engine/commit-sink\";\nimport type { Engine } from \"../engine/engine\";\nimport type { InputQueue } from \"../input/queue\";\nimport { createInputQueue } from \"../input/queue\";\nimport { createCameraSystems } from \"../systems/camera-sim\";\nimport { createCleanupSystems } from \"../systems/cleanup\";\nimport { createL0Systems } from \"../systems/l0-input\";\nimport { createNavFlight } from \"../systems/nav-flight\";\nimport { createPickingSystems } from \"../systems/l1-pick\";\nimport { createWireSync } from \"../systems/l1-wires\";\nimport { createArbitrationSystems } from \"../systems/l2-arbitrate\";\nimport { createL2Systems, type SpawnProfiles } from \"../systems/l2-recognize\";\nimport { createSelectMoveBehaviors } from \"../systems/l3-behave\";\nimport { createClaimSystems } from \"../systems/l3-claim\";\nimport { createConnectSystems, type WirePreviewBuffer } from \"../systems/l3-connect\";\nimport { createDropSystem } from \"../systems/l3-drop\";\nimport { createMarqueeBehavior, type MarqueeBuffer } from \"../systems/l3-marquee\";\nimport { createPortMaterialize } from \"../systems/l3-ports\";\nimport { createResizeBehavior } from \"../systems/l3-resize\";\nimport { createSnapSystem } from \"../systems/l3-snap\";\nimport { createSelectionChromeSystem } from \"../systems/chrome\";\nimport { createDrawBehavior } from \"../systems/l3-draw\";\nimport { createInsertGhostReap } from \"../systems/insert-ghost\";\nimport { createCursorSync } from \"../systems/l4-cursor\";\n\nconst canvasSurfaceQ = defineQuery([CanvasSurface]);\n\n/** Ensure the guaranteed pick-fallback entity exists (idempotent; outside tick). */\nexport function ensureCanvasSurface(world: World): Entity {\n const existing = world.firstOf(canvasSurfaceQ);\n if (existing !== undefined) return existing;\n return world.spawn({ tags: [CanvasSurface] });\n}\n\nexport interface InteractionCoreOpts {\n readonly queue?: InputQueue;\n readonly sink?: CommitSink;\n readonly profiles?: SpawnProfiles;\n}\n\nexport interface InteractionCore {\n readonly queue: InputQueue;\n readonly sink: CommitSink;\n readonly canvasSurface: Entity;\n /** Remove every installed system (HMR / doc switch). */\n uninstall(): void;\n}\n\nexport function installInteractionCore(engine: Engine, opts: InteractionCoreOpts = {}): InteractionCore {\n const world = engine.world;\n const queue = opts.queue ?? createInputQueue();\n const sink = opts.sink ?? createRecordingCommitSink();\n const canvasSurface = ensureCanvasSurface(world);\n\n const l0 = createL0Systems(world, queue);\n const l2 = createL2Systems({ world, ...(opts.profiles ? { profiles: opts.profiles } : {}) });\n const arb = createArbitrationSystems();\n const claims = createClaimSystems(world);\n const behaviors = createSelectMoveBehaviors(world, sink);\n const cleanup = createCleanupSystems(world);\n\n const removers = [\n // input: lifecycle BEFORE ingest (value-based up+1 destroy; see l0-input.ts).\n engine.addSystems(\"input\", l0.pointerLifecycle, l0.pointerIngest, l0.pointerWorldSync),\n engine.addSystems(\"ctl:spawn\", l2.cancelSweep, l2.recognizerSpawn, l2.wheelSpawn, l2.recognizerIntegrity),\n // dependency LAST in ctl:recognize: its Pending resolutions flush at the\n // group boundary, so arbitration sees their Just* markers this frame.\n engine.addSystems(\n \"ctl:recognize\",\n l2.tapSystem,\n l2.longPressSystem,\n l2.dragSystem,\n l2.pinchSystem,\n l2.wheelSystem,\n l2.dependencySystem,\n ),\n engine.addSystems(\"ctl:arbitrate\", arb.arbitration, arb.dragRoute),\n engine.addSystems(\"ctl:claim\", claims.moveClaim, claims.resizeClaim),\n // design-003 §5 in-phase order: select → (snap) → move → (drop) → … later\n // installers splice their systems by installing in the documented sequence.\n engine.addSystems(\"ctl:behave\", behaviors.selectBehavior, behaviors.moveBehavior),\n engine.addSystems(\"cleanup\", cleanup.recognizerReap, cleanup.oneTickClear),\n ];\n\n return {\n queue,\n sink,\n canvasSurface,\n uninstall() {\n for (const remove of removers) remove();\n },\n };\n}\n\nexport interface InteractionStack extends InteractionCore {\n /** The one spatial index (picking/snap/drop/marquee/wires/ports share it). */\n readonly index: SpatialIndex<Entity>;\n /** Marquee preview render buffer (out-of-ECS by design — design-003 §5.7). */\n readonly marqueeBuffer: MarqueeBuffer;\n /** Connect preview render buffer (out-of-ECS — design-004 §6; M8). */\n readonly wirePreview: WirePreviewBuffer;\n /** Nav-op seam (design-004 §7): forget spatialSync's last-known AABBs. */\n clearCaches(): void;\n /** L4 cursor readout for the DOM cursor reflector. */\n readCursor(): string;\n}\n\n/**\n * The FULL M4 stack. Not a wrapper over `installInteractionCore`: within-group\n * order is registration order and design-003 §5's in-phase sequence\n * (select → snap → move → drop → resize → marquee → camera) interleaves spine\n * and non-spine systems, so the full installer registers everything itself in\n * the documented order. `installInteractionCore` remains the spine-only slice\n * (what the spine traces run against).\n */\nexport function installInteractionStack(engine: Engine, opts: InteractionCoreOpts = {}): InteractionStack {\n const world = engine.world;\n const queue = opts.queue ?? createInputQueue();\n const sink = opts.sink ?? createRecordingCommitSink();\n const canvasSurface = ensureCanvasSurface(world);\n\n const l0 = createL0Systems(world, queue);\n // The shared index is built HERE so wireSync (its source) and picking (its\n // consumer of that source) can both bind it before either installs.\n const index = new SpatialIndex<Entity>();\n const { wireSync, wires } = createWireSync(world, index);\n const pick = createPickingSystems(world, index, wires);\n const l2 = createL2Systems({ world, ...(opts.profiles ? { profiles: opts.profiles } : {}) });\n const arb = createArbitrationSystems();\n const claims = createClaimSystems(world);\n const behaviors = createSelectMoveBehaviors(world, sink);\n const snap = createSnapSystem(world, index);\n const drop = createDropSystem(world, index);\n const resize = createResizeBehavior(world, sink);\n const marquee = createMarqueeBehavior(world, index);\n const connect = createConnectSystems(world, sink, index, wires);\n const ports = createPortMaterialize(world, index);\n const camera = createCameraSystems(world);\n const cursor = createCursorSync(world);\n const cleanup = createCleanupSystems(world);\n\n const removers = [\n engine.addSystems(\"input\", l0.pointerLifecycle, l0.pointerIngest, l0.pointerWorldSync),\n // wireSync AFTER spatialSync (both SpatialVersion writers), BEFORE picking —\n // which now narrow-phases wire entries against wireSync's cached cubics.\n engine.addSystems(\"react\", pick.spatialSync, wireSync, pick.picking),\n engine.addSystems(\"ctl:spawn\", l2.cancelSweep, l2.recognizerSpawn, l2.wheelSpawn, l2.recognizerIntegrity),\n engine.addSystems(\n \"ctl:recognize\",\n l2.tapSystem,\n l2.longPressSystem,\n l2.dragSystem,\n l2.pinchSystem,\n l2.wheelSystem,\n l2.dependencySystem,\n ),\n engine.addSystems(\"ctl:arbitrate\", arb.arbitration, arb.dragRoute),\n engine.addSystems(\"ctl:claim\", claims.moveClaim, claims.resizeClaim, connect.connectClaim),\n // design-003 §5 in-phase order (value writes are immediately visible; the\n // order IS the contract): select → snap → move → drop → resize → marquee →\n // connect → camera.\n engine.addSystems(\n \"ctl:behave\",\n behaviors.selectBehavior,\n snap,\n behaviors.moveBehavior,\n drop,\n resize,\n marquee,\n connect.connectBehavior,\n createDrawBehavior(world, sink),\n camera.cameraControl,\n ),\n // navFlight AFTER cameraControl's group (ctl:behave): a gesture going\n // Active stamps Camera.gesturing THIS frame, so the flight yields\n // same-frame (design-006 §4 \"touch always wins\").\n engine.addSystems(\"simulate\", camera.cameraInertia, camera.tweenSystem, createNavFlight(world)),\n // derive order: portMaterialize BEFORE selectionChrome (both touch the index\n // in derive; ports must be indexed before chrome/next-frame picking read it),\n // selectionChrome BEFORE cursor (handles spawn at the derive flush so cursor\n // + next frame's spatialSync see them).\n engine.addSystems(\"derive\", ports, createSelectionChromeSystem(world), cursor),\n // insertGhostReap AFTER recognizerReap: it reads terminal phase tags on\n // capturing recognizers pre-flush (deferred destroys land at the group\n // boundary), and its own despawns must not race the marker sweep.\n engine.addSystems(\"cleanup\", cleanup.recognizerReap, cleanup.oneTickClear, createInsertGhostReap(world)),\n ];\n\n return {\n queue,\n sink,\n canvasSurface,\n index,\n marqueeBuffer: marquee.buffer,\n wirePreview: connect.previewBuffer,\n clearCaches: () => pick.clearCaches(),\n readCursor: cursor.readCursor,\n uninstall() {\n for (const remove of removers) remove();\n },\n };\n}\n","/**\n * cleanup phase — nothing transient crosses frames (design-002 §2; design-003\n * §4.1 reap, §8 CancelRequest one-tick rule).\n *\n * `recognizerReap` destroys terminal recognizers at terminal +1 frame: a Just*\n * marker means the transition happened THIS tick (markers clear later this\n * phase, but ctx reads are pre-flush) — no marker means the tag has lingered a\n * full frame and every edge-triggered consumer has run. `ClaimedBy`/`Watches`/\n * `Captures`/`Drags` edges auto-clear with the despawn.\n *\n * `oneTickClear` then clears pointer transition tags, zeroes wheel deltas,\n * clears all Just* markers, and consumes CancelRequest (a latched cancel would\n * kill every future gesture forever).\n */\nimport { Any, defineQuery, defineSystem, type System, type World } from \"@vibecook/strata-ecs\";\nimport {\n CancelRequest,\n Drag,\n GesturePhases,\n HandledByWidget,\n LongPress,\n Pinch,\n Pointer,\n PointerWheel,\n Tap,\n WentCancelled,\n WentDown,\n WentUp,\n WheelHandled,\n WheelPan,\n WheelZoom,\n} from \"../catalog\";\n\nconst P = GesturePhases;\n\nconst anyKindQ = defineQuery([Any(Tap, LongPress, Drag, Pinch, WheelPan, WheelZoom)]);\nconst pointerQ = defineQuery([Pointer, PointerWheel]);\n\nexport function createCleanupSystems(world: World): { recognizerReap: System; oneTickClear: System } {\n const recognizerReap = defineSystem(\n anyKindQ,\n (b, ctx) => {\n for (const r of b) {\n const e = b.entity(r);\n const terminal =\n ctx.hasTag(e, P.tags.Failed) ||\n ctx.hasTag(e, P.tags.Cancelled) ||\n ctx.hasTag(e, P.tags.Ended) ||\n (ctx.hasTag(e, P.tags.Recognized) && ctx.has(e, Tap)); // Recognized is terminal for Tap only\n if (!terminal) continue;\n const transitionedThisTick =\n ctx.hasTag(e, P.justTags.Failed) ||\n ctx.hasTag(e, P.justTags.Cancelled) ||\n ctx.hasTag(e, P.justTags.Ended) ||\n ctx.hasTag(e, P.justTags.Recognized);\n if (!transitionedThisTick) ctx.destroy(e); // terminal + 1 frame\n }\n },\n { name: \"recognizerReap\" },\n );\n\n const oneTickClear = defineSystem(\n pointerQ,\n (b, ctx) => {\n for (const r of b) {\n const e = b.entity(r);\n if (ctx.hasTag(e, WentDown)) ctx.removeTag(e, WentDown);\n if (ctx.hasTag(e, WentUp)) ctx.removeTag(e, WentUp);\n if (ctx.hasTag(e, WentCancelled)) ctx.removeTag(e, WentCancelled);\n if (ctx.hasTag(e, HandledByWidget)) ctx.removeTag(e, HandledByWidget);\n if (ctx.hasTag(e, WheelHandled)) ctx.removeTag(e, WheelHandled);\n const w = ctx.read(e, PointerWheel);\n if (w.dx !== 0 || w.dy !== 0 || w.pinch !== 0) {\n ctx.edit(e).set(PointerWheel, { dx: 0, dy: 0, pinch: 0 });\n }\n }\n // Recognizer markers (reap above already consumed them pre-flush).\n world.query(anyKindQ).each((rb) => {\n for (const rr of rb) P.clearMarkers(ctx, rb.entity(rr));\n });\n // Consume the one-tick cancel request.\n if (ctx.getResource(CancelRequest)?.active === true) {\n world.setResource(CancelRequest, { active: false });\n }\n },\n { name: \"oneTickClear\", access: { write: [PointerWheel] } },\n );\n\n return { recognizerReap, oneTickClear };\n}\n","/**\n * L0 — pointers & ingest (design-003 §2; `input` phase).\n *\n * Order inside the phase is load-bearing:\n *\n * `pointerLifecycle` runs BEFORE `pointerIngest` and reads only immediate\n * values: a touch pointer whose buttons are still 0 at the top of a frame has\n * been idle-up for a full frame (ingest zeroed buttons on the up frame), so its\n * `ctx.destroy` lands at the input flush of frame up+1 — recognizers saw the up\n * frame's `WentUp` in full. Tag-based detection cannot work in-phase (ingest's\n * one-tick tags are deferred to the flush), hence values.\n *\n * `pointerIngest` is scheduled on the CANVAS-SURFACE anchor query (exactly one\n * such entity, guaranteed by install) because a system body only runs when its\n * query matches — and ingest must run on frames where no pointer entity exists\n * yet (the first down CREATES the pointer). It drains the queue once per tick\n * in two passes: fold events into per-pointer samples, then apply — existing\n * pointers get immediate value writes + deferred one-tick tags; NEW pointers\n * spawn once with their folded final state (an identity-only `ctx.spawn` handle\n * cannot take `edit().set`). Facts are always true: `surfaceHandled` events\n * still land, but carry the one-tick `HandledByWidget` tag L1/L2 read (the\n * pinned widget-event contract, design-002 §8).\n */\nimport type { Entity, System, TickSystem, World } from \"@vibecook/strata-ecs\";\nimport { defineQuery, defineSystem, defineTickSystem } from \"@vibecook/strata-ecs\";\nimport { screenToWorld } from \"@ice/kernel\";\nimport {\n Camera,\n HandledByWidget,\n Keyboard,\n LocalPointer,\n OverInteractive,\n Pointer,\n PointerButtons,\n PointerMods,\n PointerRadius,\n PointerScreen,\n PointerWheel,\n PointerWorld,\n WentCancelled,\n WentDown,\n WentUp,\n WheelHandled,\n} from \"../catalog\";\nimport { PointerVersion, bumpVersion } from \"../helpers/version-stamps\";\nimport type { InputEvent, InputQueue } from \"../input/queue\";\nimport { PointerSettings } from \"../catalog/settings-resources\";\nimport { POINTER_DEFAULTS } from \"../settings/defaults\";\n\nconst pointerQ = defineQuery([Pointer, PointerScreen]);\nconst touchLifecycleQ = defineQuery([Pointer, PointerButtons]);\n\nfunction radiusFor(device: InputEvent[\"device\"], ps?: { radiusTouchPx: number; radiusPenPx: number; radiusMousePx: number }): number {\n if (device === \"touch\") return (ps ?? POINTER_DEFAULTS).radiusTouchPx;\n if (device === \"pen\") return (ps ?? POINTER_DEFAULTS).radiusPenPx;\n return (ps ?? POINTER_DEFAULTS).radiusMousePx;\n}\n\n/** Per-pointer fold of one tick's drained events. */\ninterface Sample {\n device: InputEvent[\"device\"];\n x: number;\n y: number;\n buttons: number;\n downX: number;\n downY: number;\n downMs: number;\n wentDown: boolean;\n wentUp: boolean;\n wentCancelled: boolean;\n handled: boolean;\n /** Last hover-bearing fact's verdict; undefined = no hover info this tick (tag holds). */\n overInteractive: boolean | undefined;\n mods: { shift: boolean; ctrl: boolean; alt: boolean; meta: boolean };\n wheelDx: number;\n wheelDy: number;\n wheelPinch: number;\n hasWheel: boolean;\n /** Any wheel fact this tick was ceded to widget scroll (design-007 §3.5). */\n wheelHandled: boolean;\n}\n\nexport interface L0Systems {\n pointerLifecycle: System;\n pointerIngest: TickSystem;\n pointerWorldSync: System;\n}\n\nexport function createL0Systems(world: World, queue: InputQueue): L0Systems {\n // pointerId → entity lookup. Derived index only (the fact is Pointer.id in\n // the world); entries validate with isAlive and rebuild on miss.\n const byId = new Map<string, Entity>();\n\n const resolve = (id: string): Entity | undefined => {\n const cached = byId.get(id);\n if (cached !== undefined && world.isAlive(cached)) return cached;\n byId.delete(id);\n let found: Entity | undefined;\n world.query(pointerQ).each((b) => {\n for (const r of b) {\n const e = b.entity(r);\n if (world.read(e, Pointer).id === id) {\n found = e;\n return;\n }\n }\n });\n if (found !== undefined) byId.set(id, found);\n return found;\n };\n\n const pointerLifecycle = defineSystem(\n touchLifecycleQ,\n (b, ctx) => {\n for (const r of b) {\n const e = b.entity(r);\n if (ctx.read(e, Pointer).device !== \"touch\") continue;\n if (ctx.read(e, PointerButtons).buttons === 0) ctx.destroy(e); // idle-up a full frame\n }\n },\n {\n name: \"pointerLifecycle\",\n // The STALE read is the mechanism: last frame's buttons==0 ⇒ up+1 destroy\n // (module doc). Declare no reads so strata's advisory \"reads before\n // ingest writes\" ordering hint doesn't flag the intentional dependency.\n access: { read: [] },\n },\n );\n\n // Tick system (strata 0.5.0): the drain runs exactly once per frame by\n // construction — the scheduler owns cardinality, no anchor query needed.\n const pointerIngest = defineTickSystem(\n (ctx) => {\n const events = queue.drain();\n if (events.length === 0) return;\n // Live-tunable pick radii (design-005 §4): resource first, const fallback.\n const pointerSettings = ctx.getResource(PointerSettings);\n\n // --- pass 1: fold ---\n const samples = new Map<string, Sample>();\n let keyboard: { shift: boolean; ctrl: boolean; alt: boolean; meta: boolean; space: boolean } | null =\n null;\n for (const ev of events) {\n if (ev.kind === \"key\") {\n keyboard = { ...ev.mods };\n continue;\n }\n let s = samples.get(ev.pointerId);\n if (s === undefined) {\n s = {\n device: ev.device,\n x: ev.screenX,\n y: ev.screenY,\n buttons: ev.buttons,\n downX: 0,\n downY: 0,\n downMs: 0,\n wentDown: false,\n wentUp: false,\n wentCancelled: false,\n handled: false,\n overInteractive: undefined,\n mods: { shift: ev.mods.shift, ctrl: ev.mods.ctrl, alt: ev.mods.alt, meta: ev.mods.meta },\n wheelDx: 0,\n wheelDy: 0,\n wheelPinch: 0,\n hasWheel: false,\n wheelHandled: false,\n };\n samples.set(ev.pointerId, s);\n }\n s.x = ev.screenX;\n s.y = ev.screenY;\n s.buttons = ev.buttons;\n s.mods = { shift: ev.mods.shift, ctrl: ev.mods.ctrl, alt: ev.mods.alt, meta: ev.mods.meta };\n if (ev.kind === \"down\") {\n s.wentDown = true;\n s.downX = ev.screenX;\n s.downY = ev.screenY;\n s.downMs = ev.tMs ?? 0; // event-time anchor (0 ⇒ consumers use frame now)\n } else if (ev.kind === \"up\") {\n s.wentUp = true;\n } else if (ev.kind === \"cancel\") {\n s.wentCancelled = true;\n } else if (ev.kind === \"wheel\" && ev.wheel !== undefined) {\n s.wheelDx += ev.wheel.dx;\n s.wheelDy += ev.wheel.dy;\n s.wheelPinch += ev.wheel.pinch;\n s.hasWheel = true;\n if (ev.wheelHandled === true) s.wheelHandled = true;\n }\n if (ev.surfaceHandled === true) s.handled = true;\n // Hover truth: last stamped fact wins; unstamped facts (wheel, blur\n // cancel, test drivers that don't track hover) leave it undefined.\n if (ev.overInteractive !== undefined) s.overInteractive = ev.overInteractive;\n }\n\n // --- pass 2: apply ---\n if (keyboard !== null) world.setResource(Keyboard, keyboard);\n\n for (const [id, s] of samples) {\n const existing = resolve(id);\n if (existing === undefined) {\n const spawned = ctx.spawn({\n components: [\n [Pointer, { id, device: s.device, owner: \"\" }],\n [PointerScreen, { x: s.x, y: s.y }],\n [PointerButtons, { buttons: s.buttons, downX: s.downX, downY: s.downY, downMs: s.downMs }],\n [PointerMods, s.mods],\n [PointerWheel, { dx: s.wheelDx, dy: s.wheelDy, pinch: s.wheelPinch }],\n [PointerRadius, { r: radiusFor(s.device, pointerSettings) }],\n [PointerWorld, { x: 0, y: 0 }],\n ],\n tags: [LocalPointer],\n });\n if (s.wentDown) ctx.addTag(spawned, WentDown);\n if (s.wentUp) ctx.addTag(spawned, WentUp);\n if (s.wentCancelled) ctx.addTag(spawned, WentCancelled);\n if (s.handled) ctx.addTag(spawned, HandledByWidget);\n if (s.wheelHandled) ctx.addTag(spawned, WheelHandled);\n if (s.overInteractive === true) ctx.addTag(spawned, OverInteractive);\n byId.set(id, spawned);\n continue;\n }\n\n ctx.edit(existing).set(PointerScreen, { x: s.x, y: s.y });\n const prev = ctx.read(existing, PointerButtons);\n ctx.edit(existing).set(PointerButtons, {\n buttons: s.buttons,\n downX: s.wentDown ? s.downX : prev.downX,\n downY: s.wentDown ? s.downY : prev.downY,\n downMs: s.wentDown ? s.downMs : prev.downMs,\n });\n ctx.edit(existing).set(PointerMods, s.mods);\n if (s.hasWheel) {\n const w = ctx.read(existing, PointerWheel);\n ctx.edit(existing).set(PointerWheel, {\n dx: w.dx + s.wheelDx,\n dy: w.dy + s.wheelDy,\n pinch: w.pinch + s.wheelPinch,\n });\n }\n if (s.wentDown) ctx.addTag(existing, WentDown);\n if (s.wentUp) ctx.addTag(existing, WentUp);\n if (s.wentCancelled) ctx.addTag(existing, WentCancelled);\n if (s.handled) ctx.addTag(existing, HandledByWidget);\n if (s.wheelHandled) ctx.addTag(existing, WheelHandled);\n // Persistent hover-boundary tag, change-only (interaction-rate law):\n // written only when a hover-bearing fact arrived AND the state flipped.\n if (s.overInteractive !== undefined && s.overInteractive !== ctx.hasTag(existing, OverInteractive)) {\n if (s.overInteractive) ctx.addTag(existing, OverInteractive);\n else ctx.removeTag(existing, OverInteractive);\n }\n }\n\n bumpVersion(world, PointerVersion);\n },\n {\n name: \"pointerIngest\",\n // Design-003 §10 table. Runs only when input arrived (runIf on the queue),\n // so idle frames stamp nothing.\n access: { write: [Pointer, PointerScreen, PointerButtons, PointerMods, PointerWheel] },\n runIf: () => queue.size() > 0,\n },\n );\n\n const pointerWorldSync = defineSystem(\n defineQuery([Pointer, PointerScreen, PointerWorld]),\n (b, ctx) => {\n const cam = ctx.getResource(Camera);\n if (cam === undefined) return;\n for (const r of b) {\n const e = b.entity(r);\n const s = ctx.read(e, PointerScreen);\n const w = screenToWorld(s.x, s.y, cam);\n ctx.edit(e).set(PointerWorld, { x: w.x, y: w.y });\n }\n },\n { name: \"pointerWorldSync\", access: { write: [PointerWorld] } },\n );\n\n return { pointerLifecycle, pointerIngest, pointerWorldSync };\n}\n","/**\n * L1 — spatial sync + targeting (design-003 §3; `react` phase).\n *\n * Two systems, run in this order:\n *\n * `spatialSync` maintains the kernel `SpatialIndex` over every Position+Size\n * entity (widgets AND HandleSpec chrome — both carry a world AABB). It is a\n * TICK system so the body runs every frame — it is the writer that bumps\n * `SpatialVersion` — but as of strata 0.7.0 (petition 7 LANDED) the body is\n * O(delta), not O(N): a `world.changes` collector journals exactly which\n * entities were touched (Position/Size writes, Active/WidgetEquipped flips,\n * spawns, destroys — same-frame, drained INSIDE the pipeline), and each is\n * re-checked against `isIndexable` → upsert or remove. The 2026-07-13 walk\n * machinery (last-known AABB cache, compare-and-skip, generation sweep) is\n * RETIRED — the collector knows; the system no longer has to discover.\n *\n * The FULL WALK survives as exactly what petition 7 said it should be:\n * - the SEED (a collector only journals writes made after its creation);\n * - the `reset` route (world.reset / replace import / nav `clearCaches`);\n * - the `coarse` fallback (some declared-raw-write system touched\n * Position/Size rows the journal cannot attribute — rescan, never miss).\n * Nav gating rides the walk QUERIES at archetype level: widgets match\n * `[Position, Size, WidgetEquipped, Active]`, chrome matches\n * `[Position, Size, Not(WidgetEquipped)]` — the union is exactly\n * `Position+Size ∧ (¬WidgetEquipped ∨ Active)`, and `isIndexable` is the\n * same predicate entity-wise for the delta path. Materialized ports are M8 —\n * skipped.\n *\n * `picking` runs the dual pick (design-003 §3), gated by a version guard over\n * `PointerVersion ∨ SpatialVersion`. `CameraVersion` does not exist — camera\n * motion alone does not re-pick, an accepted staleness (design-002 §2). Pointer\n * world position is derived from PointerScreen × Camera rather than the\n * PointerWorld cell: PointerWorld lags a frame on the pointer's spawn (the\n * pointerWorldSync writer cannot see a pointer spawned in the same input phase),\n * which would mis-capture on the down frame — screen×camera is exact here.\n * - `Targets` = radiused disc-vs-box pick with a screen-px release\n * dead-band (hover is forgiving; hold the current target\n * while the pointer stays within its expanded bounds).\n * - `TouchesExact` = r=0 point pick (grab is precise; no dead-band).\n * Pick priority is plane priority: HandleSpec chrome first, then widgets\n * topmost by sibling order (petition 8 — the shared SiblingOrderIndex feeds\n * pickTopAt, so pick can never diverge from paint), then the CanvasSurface\n * entity as the guaranteed fallback (design-001 §4). Relations are written\n * change-only (design-002 §4 hygiene). Wires/ports are M8 — skipped.\n */\nimport type { Batch, Entity, System, SystemCtx, TickSystem, World } from \"@vibecook/strata-ecs\";\nimport { defineQuery, defineSystem, defineTickSystem, Not } from \"@vibecook/strata-ecs\";\nimport { SpatialIndex, screenToWorld, type CameraState } from \"@ice/kernel\";\nimport {\n Camera,\n CanvasSurface,\n HandledByWidget,\n LocalPointer,\n Pointer,\n PointerRadius,\n PointerScreen,\n Position,\n Size,\n Targets,\n TouchesExact,\n} from \"../catalog\";\nimport { Active } from \"../catalog/camera-derived\";\nimport { WidgetEquipped } from \"../widget/define-widget\";\nimport { PointerVersion, SpatialVersion, bumpVersion, makeVersionGuard } from \"../helpers/version-stamps\";\nimport { distPointToBox, pickTopAt, type WirePickSource } from \"../ops/point-pick\";\nimport { createSiblingOrderIndex } from \"../ops/sibling-order\";\nimport { PointerSettings } from \"../catalog/settings-resources\";\nimport { POINTER_DEFAULTS } from \"../settings/defaults\";\n\nconst IDENTITY_CAM: CameraState = { x: 0, y: 0, zoom: 1 };\n\nconst canvasSurfaceQ = defineQuery([CanvasSurface]);\n// Nav gating at ARCHETYPE level (design-004 §7): the union of these two is\n// exactly `Position+Size ∧ (¬WidgetEquipped ∨ Active)` — equipped widgets are\n// hittable only while Active (in-frame); chrome/pre-equip entities always.\n// Tags in the query beat per-row `hasTag` calls (2026-07-13 perf audit).\nconst widgetAabbQ = defineQuery([Position, Size, WidgetEquipped, Active]);\nconst chromeAabbQ = defineQuery([Position, Size, Not(WidgetEquipped)]);\nconst pointerQ = defineQuery([Pointer, PointerScreen, PointerRadius, LocalPointer, Not(HandledByWidget)]);\n\nexport interface PickingSystems {\n spatialSync: TickSystem;\n picking: System;\n /** The shared spatial index — snap/drop/marquee consume the SAME instance. */\n index: SpatialIndex<Entity>;\n /** Nav-op seam (design-004 §7): forget every last-known AABB so the next\n * spatialSync pass repopulates the cleared index from the new Active set. */\n clearCaches(): void;\n}\n\nexport function createPickingSystems(\n world: World,\n index: SpatialIndex<Entity> = new SpatialIndex<Entity>(),\n wires?: WirePickSource,\n): PickingSystems {\n // The change journal (petition 7 / strata 0.7.0). Subscribing here is the\n // whole trick: Position/Size writes, Active/WidgetEquipped flips, spawns\n // and destroys journal the ENTITY at the write chokepoints — no walk needed\n // to discover them. `seeded` gates the initial full walk (pre-collector\n // entities) and is re-armed by nav `clearCaches` (design-004 §7).\n //\n // `coarse: false` is the engine's ATTESTATION (the strata option's exact\n // contract): every Position/Size writer here uses store-visible writes —\n // absolute writes via `ctx.*`/`world.edit`/doc projection are engine LAW.\n // Without it, the declared-`access.write` blanket from exact-path systems\n // (move/resize/snap declare for enforcement) would mark coarse every\n // gesture frame and force the full rescan collectors exist to retire.\n const collector = world.changes.collect({\n components: [Position, Size],\n tags: [Active, WidgetEquipped],\n coarse: false,\n });\n let seeded = false;\n // Entities THIS system put in the index. The index is SHARED and\n // multi-writer (ports + wires maintain their own entries) — rebuilds must\n // remove only our own stale entries, never `index.clear()`.\n let known = new Set<Entity>();\n\n /**\n * The delta path's entity-wise twin of the walk queries' union: upserts and\n * reports true when `e` belongs in the index, false (no write) otherwise.\n */\n const upsertIfIndexable = (e: Entity): boolean => {\n if (!world.isAlive(e)) return false;\n const p = world.get(e, Position);\n const s = world.get(e, Size);\n if (p === undefined || s === undefined) return false;\n if (world.hasTag(e, WidgetEquipped) && !world.hasTag(e, Active)) return false;\n index.upsert(e, { minX: p.x, minY: p.y, maxX: p.x + s.w, maxY: p.y + s.h });\n return true;\n };\n\n const spatialSync = defineTickSystem(\n (ctx) => {\n const delta = collector.drain();\n // Full-walk routes: seed, reset (world.reset / nav), coarse raw writes.\n if (!seeded || delta.reset || delta.coarse.length > 0) {\n seeded = true;\n const next = new Set<Entity>();\n const visit = (batch: Batch): void => {\n const px = batch.col(Position).x;\n const py = batch.col(Position).y;\n const sw = batch.col(Size).w;\n const sh = batch.col(Size).h;\n for (const row of batch) {\n const x = px[row] as number;\n const y = py[row] as number;\n const e = batch.entity(row);\n index.upsert(e, {\n minX: x,\n minY: y,\n maxX: x + (sw[row] as number),\n maxY: y + (sh[row] as number),\n });\n next.add(e);\n }\n };\n ctx.query(widgetAabbQ).each(visit);\n ctx.query(chromeAabbQ).each(visit);\n for (const e of known) {\n if (!next.has(e)) index.remove(e); // only OUR stale entries — never index.clear()\n }\n known = next;\n bumpVersion(world, SpatialVersion);\n return;\n }\n // Delta path — O(changed), ~0 on still frames.\n if (delta.changed.length === 0 && delta.removed.length === 0) return;\n for (const e of delta.removed) {\n if (known.delete(e)) index.remove(e); // destroyed — drop by our cached key\n }\n for (const e of delta.changed) {\n if (upsertIfIndexable(e)) {\n known.add(e);\n } else if (known.delete(e)) {\n index.remove(e);\n }\n }\n bumpVersion(world, SpatialVersion);\n },\n {\n name: \"spatialSync\",\n // The inner ctx.query col() reads are charged to THIS system by access\n // enforcement — a tick system has no query, so the default read set is\n // empty and the columns must be declared explicitly.\n access: { read: [Position, Size] },\n },\n );\n\n // The pull-based frame ordinal map (petition 8): pickTopAt's widget tier\n // takes the compareStackOrder max over it — the same map every renderer\n // sorts by. Stamp-checked per read; ~free while order is quiet.\n const order = createSiblingOrderIndex(world);\n\n /** THE narrow-phase, shared with the router's event-time pick (ops/point-pick).\n * `wires` (M8) narrow-phases wire entries against their cached cubic; undefined\n * before the wire slice installs ⇒ wire index entries are skipped by pickTopAt. */\n const pickTop = (ctx: SystemCtx, wx: number, wy: number, rWorld: number): Entity | undefined =>\n pickTopAt(ctx, index, wx, wy, rWorld, wires, order.ordinals());\n\n const picking = defineSystem(\n pointerQ,\n (b, ctx) => {\n const cam = ctx.getResource(Camera);\n const zoom = cam?.zoom ?? 1;\n const canvas = ctx.firstOf(canvasSurfaceQ);\n const deadBandWorld =\n (ctx.getResource(PointerSettings) ?? POINTER_DEFAULTS).hoverReleaseDeadBandPx / zoom;\n\n for (const r of b) {\n const p = b.entity(r);\n const s = ctx.read(p, PointerScreen);\n const w = screenToWorld(s.x, s.y, cam ?? IDENTITY_CAM);\n const rWorld = (ctx.get(p, PointerRadius)?.r ?? 0) / zoom;\n\n // TouchesExact — precise point pick, no dead-band (\"grab is precise\").\n const exact = pickTop(ctx, w.x, w.y, 0) ?? canvas;\n if (exact !== undefined && ctx.getRelation(p, TouchesExact) !== exact) {\n ctx.setRelation(p, TouchesExact, exact);\n }\n\n // Targets — radiused pick with a dead-band hysteresis (\"hover is forgiving\").\n let target = pickTop(ctx, w.x, w.y, rWorld);\n const cur = ctx.getRelation(p, Targets);\n if (\n cur !== undefined &&\n cur !== canvas &&\n ctx.isAlive(cur) &&\n ctx.has(cur, Position) &&\n ctx.has(cur, Size)\n ) {\n const cp = ctx.read(cur, Position);\n const cs = ctx.read(cur, Size);\n const d = distPointToBox(w.x, w.y, cp.x, cp.y, cp.x + cs.w, cp.y + cs.h);\n if (d <= rWorld + deadBandWorld) target = cur; // hold current within its expanded bounds\n }\n const finalTarget = target ?? canvas;\n if (finalTarget !== undefined && ctx.getRelation(p, Targets) !== finalTarget) {\n ctx.setRelation(p, Targets, finalTarget);\n }\n }\n },\n { name: \"picking\", runIf: makeVersionGuard(world, [PointerVersion, SpatialVersion]) },\n );\n\n // clearCaches (nav seam, design-004 §7): re-arm the seed — the next tick\n // rebuilds the cleared index from the new Active set via the full walk.\n return {\n spatialSync,\n picking,\n index,\n clearCaches: () => {\n seeded = false;\n },\n };\n}\n","/**\n * L2 — arbitration + routing (design-003 §4.3–§4.4; `ctl:arbitrate`).\n *\n * Arbitration rule (v2-proven, generalized): the first recognizer to enter a\n * claiming phase (`Active` for continuous, `Recognized` for discrete) claims\n * every pointer it watches; same-frame ties resolve by priority\n * Pinch > Drag > LongPress > Tap; every other non-terminal, non-`Simultaneous`,\n * non-suspended recognizer watching a claimed pointer → `Failed`. The claim is\n * world state: `ClaimedBy(pointer → recognizer)` (Law 4). DEV asserts at most\n * one ClaimedBy write per pointer per pass (`setRelation` is silent last-wins —\n * a mis-ordered arbitration would otherwise be undetectable).\n *\n * `dragRoute` — the ONE pan/marquee/move decision, latched at Drag activation\n * via route tags; the route never changes mid-gesture (design-003 §4.4).\n */\nimport type { Entity, System, SystemCtx, Tag } from \"@vibecook/strata-ecs\";\nimport { Any, Not, defineQuery, defineSystem } from \"@vibecook/strata-ecs\";\nimport {\n CanvasSurface,\n Captures,\n ClaimedBy,\n Drag,\n GesturePhases,\n GestureSuspended,\n HadRequiresFail,\n HadSequence,\n HandleSpec,\n Keyboard,\n LongPress,\n Movable,\n Pinch,\n Pointer,\n PointerButtons,\n Port,\n Position,\n RoutedConnect,\n RoutedDraw,\n RoutedMarquee,\n RoutedMove,\n RoutedPan,\n RoutedResize,\n Simultaneous,\n Tap,\n Watches,\n WheelPan,\n WheelZoom,\n} from \"../catalog\";\nimport { ActiveTool } from \"../catalog/camera-derived\";\nimport { devGuardsEnabled } from \"../guards/dev\";\nimport { tools } from \"../tools/define-tool\";\n\nconst P = GesturePhases;\n\nconst claimCandidateQ = defineQuery([\n Any(Tap, LongPress, Drag, Pinch),\n Not(Simultaneous),\n Not(GestureSuspended),\n]);\n\nconst justActiveDragQ = defineQuery([Drag, P.justTags.Active]);\n\nfunction isTerminal(ctx: SystemCtx, e: Entity): boolean {\n if (ctx.hasTag(e, P.tags.Failed) || ctx.hasTag(e, P.tags.Cancelled) || ctx.hasTag(e, P.tags.Ended)) {\n return true;\n }\n return ctx.hasTag(e, P.tags.Recognized) && ctx.has(e, Tap);\n}\n\n/** Same-frame tie priority (design-003 §4.3). Higher wins. */\nfunction priorityOf(ctx: SystemCtx, e: Entity): number {\n if (ctx.has(e, Pinch)) return 4;\n if (ctx.has(e, Drag)) return 3;\n if (ctx.has(e, LongPress)) return 2;\n return 1; // Tap\n}\n\nexport function createArbitrationSystems(): { arbitration: System; dragRoute: System } {\n const arbitration = defineSystem(\n claimCandidateQ,\n (b, ctx) => {\n // Collect this frame's claimants: recognizers that JUST entered a claiming phase.\n const bestByPointer = new Map<Entity, Entity>();\n for (const r of b) {\n const e = b.entity(r);\n const claiming =\n ctx.hasTag(e, P.justTags.Active) || ctx.hasTag(e, P.justTags.Recognized);\n if (!claiming) continue;\n for (const pointer of ctx.getRelations(e, Watches)) {\n // First-wins across frames: an existing live claim stands.\n const existing = ctx.getRelation(pointer, ClaimedBy);\n if (existing !== undefined && !isTerminal(ctx, existing)) continue;\n const incumbent = bestByPointer.get(pointer);\n if (incumbent === undefined || priorityOf(ctx, e) > priorityOf(ctx, incumbent)) {\n bestByPointer.set(pointer, e);\n }\n }\n }\n\n const written = devGuardsEnabled() ? new Set<Entity>() : null;\n for (const [pointer, winner] of bestByPointer) {\n if (written !== null) {\n if (written.has(pointer)) {\n throw new Error(\"ice: arbitration wrote ClaimedBy twice for one pointer in one pass.\");\n }\n written.add(pointer);\n }\n ctx.setRelation(pointer, ClaimedBy, winner);\n // Fail every other live competitor watching this pointer.\n for (const rec of ctx.getReverse(pointer, Watches)) {\n if (rec === winner) continue;\n if (isTerminal(ctx, rec)) continue;\n if (ctx.hasTag(rec, Simultaneous) || ctx.hasTag(rec, GestureSuspended)) continue;\n // Edge-parked Pending recognizers are the dependency system's to\n // resolve. v2 resolved them same-tick BEFORE arbitration (immediate\n // writes); v3's flush model runs dependency a frame behind the\n // source's claim, so arbitration must not race it — the dependency\n // verdict lands next frame either way. (Multi-tap Pendings carry no\n // edge and stay killable — tap-then-drag fails the pending tap.)\n if (\n ctx.hasTag(rec, P.tags.Pending) &&\n (ctx.hasTag(rec, HadSequence) || ctx.hasTag(rec, HadRequiresFail))\n ) {\n continue;\n }\n P.set(ctx, rec, \"Failed\");\n }\n }\n },\n { name: \"arbitration\" },\n );\n\n const dragRoute = defineSystem(\n justActiveDragQ,\n (b, ctx) => {\n // Tool ROUTE POLICY (design-005 §3, mechanized at M10): the active\n // tool's config decides canvas/widget/port drag routes; unknown ids\n // resolve to select semantics (tools.resolve). Device conventions\n // (space / middle / one-finger touch → pan) sit ABOVE tool policy.\n const tool = tools.resolve(ctx.getResource(ActiveTool)?.id ?? \"select\");\n const spaceHeld = ctx.getResource(Keyboard)?.space === true;\n const routeTag = (route: string): Tag | undefined => {\n switch (route) {\n case \"marquee\":\n return RoutedMarquee;\n case \"pan\":\n return RoutedPan;\n case \"connect\":\n return RoutedConnect;\n case \"move\":\n return RoutedMove;\n case \"draw\":\n return RoutedDraw;\n default:\n return undefined; // \"none\": claim the pointer, drive no behavior\n }\n };\n for (const r of b) {\n const e = b.entity(r);\n const captured = ctx.getRelation(e, Captures);\n\n if (captured !== undefined && ctx.has(captured, HandleSpec)) {\n // Resize gate (design-005 §3): a gating tool suppresses the handle\n // grab entirely — the claim still holds the pointer.\n if (tool.gates.resizable) ctx.addTag(e, RoutedResize);\n continue;\n }\n // Port captures route BEFORE the Movable gate (design-003 §4.4, M8):\n // a port-down on a movable widget starts a connect, not a move — and\n // pickTopAt's port tier returns the port even when the pointer sat on\n // the widget body.\n if (captured !== undefined && ctx.has(captured, Port)) {\n const t = routeTag(tool.route.portDrag);\n if (t !== undefined) ctx.addTag(e, t);\n continue;\n }\n const onCanvas = captured === undefined || ctx.hasTag(captured, CanvasSurface);\n if (!onCanvas && ctx.has(captured, Position)) {\n // Widget capture. \"move\" additionally requires the Movable\n // capability AND the tool's movable gate (review finding: a\n // non-movable widget's drag claims the pointer — no pan-through —\n // but drives no behavior).\n const route = tool.route.widgetDrag;\n if (route === \"move\") {\n if (tool.gates.movable && ctx.hasTag(captured, Movable)) ctx.addTag(e, RoutedMove);\n } else {\n const t = routeTag(route);\n if (t !== undefined) ctx.addTag(e, t);\n }\n continue;\n }\n\n // Canvas capture: device pan conventions first, then tool policy.\n const pointer = ctx.getRelations(e, Watches)[0];\n const middleButton =\n pointer !== undefined && (ctx.read(pointer, PointerButtons).buttons & 4) !== 0;\n const touch = pointer !== undefined && ctx.read(pointer, Pointer).device === \"touch\";\n if (spaceHeld || middleButton || touch) {\n ctx.addTag(e, RoutedPan); // one-finger touch pans (Freeform default)\n } else {\n const t = routeTag(tool.route.canvasDrag);\n if (t !== undefined) ctx.addTag(e, t);\n }\n }\n },\n { name: \"dragRoute\" },\n );\n\n return { arbitration, dragRoute };\n}\n\n/** Wheel recognizers never claim; exported so tests can assert the invariant set. */\nexport const NEVER_CLAIMS = [WheelPan, WheelZoom] as const;\n","/**\n * L3 — select + move behaviors (design-003 §5 items 1, 3, 5; `ctl:behave`).\n *\n * The behavior contract (design-003 §5): read riders/edges attached at\n * ctl:claim; per frame (persistent `Active`) apply ABSOLUTE live writes from\n * rider origins + gesture totals; on `JustEnded` emit ONE commit (through the\n * CommitSink seam — M5 swaps in the doc transaction); on `JustCancelled`\n * restore from riders — Position AND sibling order (petition 8: a forgotten\n * order restore leaves the sequence diverged forever, the old StackZ law);\n * remove riders and gesture-scoped edges on every terminal path. Discrete\n * actions edge-trigger on `Just*` markers only.\n *\n * Move outcome tree (design-003 §5.5, three-way via dropSystem's signals):\n * DropTarget + OverlapCandidate on the container → CONSUME (reparent intent);\n * DropTarget without OverlapCandidate → FLY-BACK (no commit; TransformTween\n * rider per widget — the tween HOLDS the claim, design-001 §3 amended);\n * no DropTarget → COMMIT (final Position per live Drags edge + the sibling\n * placement as ORDER ops, so one gesture stays one transaction).\n * Without dropSystem installed no DropTarget ever exists ⇒ plain commits.\n */\nimport type { Entity, OrderPlace, System, SystemCtx, World } from \"@vibecook/strata-ecs\";\nimport { defineQuery, defineSystem } from \"@vibecook/strata-ecs\";\nimport { insertSlot, screenToWorld, type CameraState, type LayoutRect } from \"@ice/kernel\";\nimport {\n Camera,\n Captures,\n ChildOf,\n Drag,\n Drags,\n DropTarget,\n GesturePhases,\n GhostCommitted,\n GhostRetiring,\n Grab,\n InsertGhost,\n MeasuredSize,\n NO_ENTITY,\n OverlapCandidate,\n OverlapRejected,\n PointerMods,\n Position,\n RoutedMove,\n Selectable,\n Size,\n Selected,\n SnapState,\n Tap,\n TransformTween,\n Watches,\n Wire,\n} from \"../catalog\";\nimport type { CommitCreate, CommitOrder, CommitSink, CommitWrite } from \"../engine/commit-sink\";\nimport { SelectionVersion, bumpVersion } from \"../helpers/version-stamps\";\nimport { selectedEntities } from \"../ops/selection\";\n\nconst P = GesturePhases;\n\nconst tapRecognizedQ = defineQuery([Tap, P.justTags.Recognized]);\nconst moveDragQ = defineQuery([Drag, RoutedMove]);\n\nconst FLY_BACK_MS = 200;\n\n/** Min separation for consume free-slot placement (kernel insertSlot). */\nconst CONSUME_GUTTER = 16;\n\nconst IDENTITY_CAM: CameraState = { x: 0, y: 0, zoom: 1 };\n\n/** InsertGhost.props (JSON) → CommitCreate.props; empty/malformed ⇒ absent. */\nfunction parseGhostProps(raw: string): Record<string, unknown> | undefined {\n if (raw === \"\" || raw === \"{}\") return undefined;\n try {\n const v: unknown = JSON.parse(raw);\n return typeof v === \"object\" && v !== null && Object.keys(v).length > 0\n ? (v as Record<string, unknown>)\n : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Fly a tray-insert ghost HOME (cancel / rejected drop): the tween target is\n * the tray press point re-projected through the CURRENT camera — the ghost\n * returns to the tray ON SCREEN even after a mid-drag zoom (wheel gestures are\n * Simultaneous). `GhostRetiring` hands it to the reap system, which despawns\n * it when the tween lands. No Position restore, no commit — the ghost never\n * had a document row to diverge from.\n */\nfunction ghostFlyBack(ctx: SystemCtx, ghost: Entity): void {\n const gh = ctx.read(ghost, InsertGhost);\n const cam = ctx.getResource(Camera) ?? IDENTITY_CAM;\n const home = screenToWorld(gh.screenX, gh.screenY, cam);\n const size = ctx.get(ghost, Size) ?? { w: 0, h: 0 };\n ctx.addComponent(ghost, TransformTween, {\n toX: home.x - size.w / 2,\n toY: home.y - size.h / 2,\n durationMs: FLY_BACK_MS,\n elapsedMs: 0,\n });\n ctx.addTag(ghost, GhostRetiring);\n}\n\n/** ctx-side selection flip (setSelection is the app-handler/world variant). */\nfunction applySelection(\n world: World,\n ctx: SystemCtx,\n target: Entity | undefined,\n toggle: boolean,\n): void {\n const current = selectedEntities(world);\n if (target === undefined) {\n if (current.length === 0) return;\n for (const s of current) ctx.removeTag(s, Selected);\n bumpVersion(world, SelectionVersion);\n return;\n }\n if (toggle) {\n if (ctx.hasTag(target, Selected)) ctx.removeTag(target, Selected);\n else ctx.addTag(target, Selected);\n bumpVersion(world, SelectionVersion);\n return;\n }\n const alreadySole = current.length === 1 && current[0] === target;\n if (alreadySole) return;\n for (const s of current) if (s !== target) ctx.removeTag(s, Selected);\n if (!ctx.hasTag(target, Selected)) ctx.addTag(target, Selected);\n bumpVersion(world, SelectionVersion);\n}\n\n/**\n * Reinsert the dragged set at its remembered sibling positions (petition 8 —\n * the cancel/fly-back twin of the claim elevate). Members walk in ORIGINAL\n * relative order (`Grab.ord`), each `{after: resolved anchor}`:\n * - same-`prev` run → ride the previously-reinserted member (a contiguous\n * block re-forms in claim order);\n * - the original `prev` anchor, when it survived UNDER THE SAME PARENT;\n * - else the nearest surviving earlier sibling we know — the last member\n * already reinserted into this parent;\n * - else \"first\" — NEVER \"last\": a mid-stack cancel must not jump to top.\n * Edge-less members (memo parent NO_ENTITY) were never elevated — skipped; a\n * parent that died mid-gesture took the whole sequence with it — skipped.\n * ctx placements apply at the flush IN ORDER, so each anchor is already\n * placed when consulted.\n */\nfunction restoreOrder(ctx: SystemCtx, dragged: readonly Entity[]): void {\n const members: { e: Entity; parent: Entity; prev: Entity; ord: number }[] = [];\n for (const w of dragged) {\n if (!ctx.isAlive(w) || !ctx.has(w, Grab)) continue;\n const g = ctx.read(w, Grab);\n if (g.parent === NO_ENTITY || !ctx.isAlive(g.parent)) continue;\n // FOREIGN-REPARENT GUARD (rev-ice-flip finding 2): the gesture itself never changes a\n // member's parent mid-flight (elevate is same-parent; consume runs only at end), so a\n // current parent that differs from the memo means a REMOTE edit won that edge. Restoring\n // the memo parent would revert the foreign reparent in the runtime only — cancel commits\n // nothing, so runtime structure forks from the doc until some later remote op happens to\n // rewrite the row. Skip: order restore is a courtesy; membership truth is the doc's.\n if (ctx.getRelation(w, ChildOf) !== g.parent) continue;\n members.push({ e: w, parent: g.parent, prev: g.prev, ord: g.ord });\n }\n members.sort((a, b) => a.ord - b.ord);\n const lastByParent = new Map<Entity, { e: Entity; prev: Entity }>();\n for (const m of members) {\n const last = lastByParent.get(m.parent);\n let place: OrderPlace;\n if (last !== undefined && last.prev === m.prev) {\n place = { after: last.e };\n } else if (m.prev !== NO_ENTITY && ctx.isAlive(m.prev) && ctx.getRelation(m.prev, ChildOf) === m.parent) {\n place = { after: m.prev };\n } else if (last !== undefined) {\n place = { after: last.e };\n } else {\n place = \"first\";\n }\n ctx.setRelation(m.e, ChildOf, m.parent, place);\n lastByParent.set(m.parent, { e: m.e, prev: m.prev });\n }\n}\n\n/**\n * The plain-move commit's ORDER ops (petition 8): re-assert each member's\n * elevated placement — `{parent, \"last\"}` in CURRENT sibling order, so the\n * doc transaction lands exactly the runtime sequence the elevate built.\n * Edge-less members carry no placement.\n */\nfunction commitOrders(ctx: SystemCtx, dragged: readonly Entity[]): CommitOrder[] {\n const byParent = new Map<Entity, Set<Entity>>();\n for (const w of dragged) {\n if (!ctx.isAlive(w) || !ctx.has(w, Grab)) continue;\n const parent = ctx.getRelation(w, ChildOf);\n if (parent === undefined) continue;\n let set = byParent.get(parent);\n if (set === undefined) {\n set = new Set();\n byParent.set(parent, set);\n }\n set.add(w);\n }\n const orders: CommitOrder[] = [];\n for (const [parent, set] of byParent) {\n for (const sib of ctx.getReverse(parent, ChildOf)) {\n if (set.has(sib)) orders.push({ entity: sib, parent, place: \"last\" });\n }\n }\n return orders;\n}\n\nexport function createSelectMoveBehaviors(\n world: World,\n sink: CommitSink,\n): { selectBehavior: System; moveBehavior: System } {\n const selectBehavior = defineSystem(\n tapRecognizedQ,\n (b, ctx) => {\n for (const r of b) {\n const rec = b.entity(r);\n // Modifiers come from the POINTER's latched sample (PointerMods rides\n // every event) — the Keyboard resource only carries key-event state.\n const pointer = ctx.getRelations(rec, Watches)[0];\n const shift = pointer !== undefined && ctx.get(pointer, PointerMods)?.shift === true;\n const captured = ctx.getRelation(rec, Captures);\n const selectable =\n captured !== undefined &&\n (ctx.hasTag(captured, Selectable) || ctx.hasTag(captured, Wire));\n // Tap on canvas/none/unselectable clears; on a selectable, replace (shift = toggle).\n applySelection(world, ctx, selectable ? captured : undefined, shift && selectable);\n }\n },\n { name: \"selectBehavior\" },\n );\n\n /** Remove this gesture's riders + edges (every terminal path, design-003 §5). */\n const clearGestureState = (ctx: SystemCtx, rec: Entity, dragged: readonly Entity[]): void => {\n for (const w of dragged) {\n if (ctx.isAlive(w) && ctx.has(w, Grab)) ctx.removeComponent(w, Grab);\n }\n ctx.removeRelation(rec, Drags);\n const container = ctx.getRelation(rec, DropTarget);\n if (container !== undefined) {\n if (ctx.hasTag(container, OverlapCandidate)) ctx.removeTag(container, OverlapCandidate);\n if (ctx.hasTag(container, OverlapRejected)) ctx.removeTag(container, OverlapRejected);\n ctx.removeRelation(rec, DropTarget);\n }\n };\n\n const moveBehavior = defineSystem(\n moveDragQ,\n (b, ctx) => {\n for (const r of b) {\n const rec = b.entity(r);\n const dragged = ctx.getRelations(rec, Drags); // live edges — remote despawns already gone\n\n if (ctx.hasTag(rec, P.tags.Active)) {\n // Per-frame absolute writes: Grab origin + screen totals / zoom-at-claim + snap.\n const d = ctx.read(rec, Drag);\n const snap = ctx.get(rec, SnapState) ?? { dx: 0, dy: 0 };\n const wx = d.totalX / d.zoomAtClaim + snap.dx;\n const wy = d.totalY / d.zoomAtClaim + snap.dy;\n for (const w of dragged) {\n if (!ctx.isAlive(w) || !ctx.has(w, Grab)) continue; // survivor-safe (design-003 §8)\n const g = ctx.read(w, Grab);\n ctx.edit(w).set(Position, { x: g.x + wx, y: g.y + wy });\n }\n continue;\n }\n\n if (ctx.hasTag(rec, P.justTags.Ended)) {\n const d = ctx.read(rec, Drag);\n const snap = ctx.get(rec, SnapState) ?? { dx: 0, dy: 0 };\n const wx = d.totalX / d.zoomAtClaim + snap.dx;\n const wy = d.totalY / d.zoomAtClaim + snap.dy;\n let container = ctx.getRelation(rec, DropTarget);\n\n // Re-validate at RELEASE: the drop system's candidate is one frame\n // behind, and a coalesced final-move+up frame can leave a STALE\n // target the widget no longer overlaps (2026-07-12: a mid-path card\n // triggered a spurious fly-back). The FINAL bounds are the truth.\n if (container !== undefined && ctx.isAlive(container)) {\n const cp = ctx.get(container, Position);\n const cs = ctx.get(container, Size);\n let overlaps = false;\n if (cp !== undefined && cs !== undefined) {\n for (const w of dragged) {\n if (!ctx.isAlive(w) || !ctx.has(w, Grab) || !ctx.has(w, Size)) continue;\n const g = ctx.read(w, Grab);\n const ws = ctx.read(w, Size);\n const x = g.x + wx;\n const y = g.y + wy;\n if (x < cp.x + cs.w && x + ws.w > cp.x && y < cp.y + cs.h && y + ws.h > cp.y) {\n overlaps = true;\n break;\n }\n }\n }\n if (!overlaps) container = undefined; // stale → plain commit\n }\n\n if (container !== undefined && !ctx.hasTag(container, OverlapCandidate)) {\n // Rejected drop → fly-back, NO commit. The tween holds the claim\n // (design-001 §3 amended); cells reconverge when it lands. A\n // tray-insert ghost flies HOME (the tray press point) instead of\n // to a Grab origin it only ever had under the tray — and retires.\n for (const w of dragged) {\n if (!ctx.isAlive(w) || !ctx.has(w, Grab)) continue;\n if (ctx.has(w, InsertGhost)) {\n ghostFlyBack(ctx, w);\n continue;\n }\n const g = ctx.read(w, Grab);\n ctx.addComponent(w, TransformTween, {\n toX: g.x,\n toY: g.y,\n durationMs: FLY_BACK_MS,\n elapsedMs: 0,\n });\n }\n // Restore sibling ORDER now (it is not animated): fly-back commits\n // nothing, so an elevated sequence left in place would keep the\n // runtime diverged forever and hold remote reorders indefinitely —\n // the same law as the cancel path (design-003 §5.3).\n restoreOrder(ctx, dragged);\n } else if (container !== undefined) {\n // Consume: reparent + final position, one intent (one tx at M5).\n // A tray-insert ghost becomes a CREATE-inside-container instead of\n // a reparent (it has no document row to reparent): same free-slot\n // placement, container-local coords, promoted in the same single\n // transaction. `GhostCommitted` hands it to the reap swap.\n const writes: CommitWrite[] = [];\n const reparents: { entity: Entity; container: Entity }[] = [];\n const creates: CommitCreate[] = [];\n const containerPos = ctx.get(container, Position) ?? { x: 0, y: 0 };\n // Free-slot placement (2026-07-17, James: folder drops \"pile up on\n // each other\"): the raw drop point maps everyone who aimed at the\n // folder's center onto the same container-local spot. Newcomers\n // get the nearest free slot instead; incumbents NEVER move (the\n // kernel insertSlot contract). Sizes mirror the folder preview's\n // rule: measured when real, else declared.\n const incumbents: LayoutRect[] = [];\n for (const c of ctx.getReverse(container, ChildOf)) {\n const cp = ctx.get(c, Position);\n const cm = ctx.get(c, MeasuredSize);\n const cs = cm !== undefined && cm.w > 0 ? cm : ctx.get(c, Size);\n if (cp === undefined || cs === undefined) continue;\n incumbents.push({ x: cp.x, y: cp.y, w: cs.w, h: cs.h });\n }\n for (const w of dragged) {\n if (!ctx.isAlive(w) || !ctx.has(w, Grab)) continue;\n const g = ctx.read(w, Grab);\n // Container-frame conversion: world → container-local (M8 refines\n // to the kernel container-frame path once nested canvas lands).\n const hint = { x: g.x + wx - containerPos.x, y: g.y + wy - containerPos.y };\n const wm = ctx.get(w, MeasuredSize);\n const ws = wm !== undefined && wm.w > 0 ? wm : (ctx.get(w, Size) ?? { w: 0, h: 0 });\n const slot = insertSlot(incumbents, ws, hint, CONSUME_GUTTER);\n // Later cards in a multi-drop see the earlier ones as occupied.\n incumbents.push({ x: slot.x, y: slot.y, w: ws.w, h: ws.h });\n if (ctx.has(w, InsertGhost)) {\n const gh = ctx.read(w, InsertGhost);\n const props = parseGhostProps(gh.props ?? \"\");\n creates.push({\n type: gh.type ?? \"\",\n x: slot.x,\n y: slot.y,\n w: ws.w,\n h: ws.h,\n ...(props !== undefined ? { props } : {}),\n parent: container,\n select: true,\n });\n ctx.addTag(w, GhostCommitted);\n continue;\n }\n writes.push({ entity: w, component: Position, value: slot });\n reparents.push({ entity: w, container });\n }\n if (writes.length > 0 || creates.length > 0) {\n sink.commit({\n kind: \"consume\",\n gesture: rec,\n writes,\n reparents,\n ...(creates.length > 0 ? { creates } : {}),\n });\n }\n } else {\n // Plain move commit: final Position per live edge + the elevated\n // sibling placement as ORDER ops — one gesture, one transaction,\n // one undo step (petition 8). A tray-insert ghost becomes the\n // gesture's CREATE at its final position (the promote — design-001\n // §3): same single transaction, selected at projection.\n const writes: CommitWrite[] = [];\n const creates: CommitCreate[] = [];\n for (const w of dragged) {\n if (!ctx.isAlive(w) || !ctx.has(w, Grab)) continue;\n const g = ctx.read(w, Grab);\n if (ctx.has(w, InsertGhost)) {\n const gh = ctx.read(w, InsertGhost);\n const props = parseGhostProps(gh.props ?? \"\");\n const ws = ctx.get(w, Size) ?? { w: 0, h: 0 };\n creates.push({\n type: gh.type ?? \"\",\n x: g.x + wx,\n y: g.y + wy,\n w: ws.w,\n h: ws.h,\n ...(props !== undefined ? { props } : {}),\n select: true,\n });\n ctx.addTag(w, GhostCommitted);\n continue;\n }\n writes.push({ entity: w, component: Position, value: { x: g.x + wx, y: g.y + wy } });\n }\n if (writes.length > 0 || creates.length > 0) {\n sink.commit({\n kind: creates.length > 0 && writes.length === 0 ? \"create\" : \"move\",\n gesture: rec,\n writes,\n orders: commitOrders(ctx, dragged),\n ...(creates.length > 0 ? { creates } : {}),\n });\n }\n }\n clearGestureState(ctx, rec, dragged);\n continue;\n }\n\n if (ctx.hasTag(rec, P.justTags.Cancelled) || ctx.hasTag(rec, P.justTags.Failed)) {\n // Restore Position AND sibling order from Grab (design-003 §5.3),\n // then clean up. A tray-insert ghost has nothing to restore TO —\n // it flies home to the tray and retires (Escape / blur / integrity).\n for (const w of dragged) {\n if (!ctx.isAlive(w) || !ctx.has(w, Grab)) continue;\n if (ctx.has(w, InsertGhost)) {\n ghostFlyBack(ctx, w);\n continue;\n }\n const g = ctx.read(w, Grab);\n ctx.edit(w).set(Position, { x: g.x, y: g.y });\n }\n restoreOrder(ctx, dragged);\n clearGestureState(ctx, rec, dragged);\n }\n }\n },\n {\n name: \"moveBehavior\",\n // Position is co-written with resizeBehavior in ctl:behave BY DESIGN\n // (design-003 §5 in-phase order) and row-disjoint by construction\n // (dragRoute: RoutedMove xor RoutedResize) — attested (strata 0.4.0,\n // petition 3a), so the writer-pair advisory stays quiet here and loud\n // for real mistakes.\n access: { write: [Position], orderIndependent: [Position] },\n },\n );\n\n return { selectBehavior, moveBehavior };\n}\n","/**\n * ctl:claim — the rider settle point (design-003 §4.5).\n *\n * This sub-phase exists for exactly one reason: riders (`Grab`) and edges\n * (`Drags`) attached via `ctx` must be readable by the behaviors that consume\n * them ON THE CLAIM FRAME — without it, the first mutation lags a frame and a\n * claim-frame `read(w, Grab)` throws (design-003 review C1).\n *\n * `moveClaim` (JustActive × RoutedMove): select-on-grab, `Drags` edges over the\n * dragged set, `Grab` per widget with the CURRENT Position/Size + the ORDER\n * MEMO embedded (petition 8: ChildOf parent, nearest non-dragged predecessor\n * sibling, original sibling index), and the sibling elevate — `moveRelation(w,\n * ChildOf, \"last\")`, frame-scoped, equivalent to the old global-top within the\n * frame; part of the gesture divergence, restored from the memo on cancel.\n * Edge-less widgets (legacy/runtime world) skip both memo and elevate — the\n * move would be a strata no-op and there is no sequence to restore.\n *\n * `resizeClaim` (JustActive × RoutedResize): `Drags` + `Grab` over the Selected\n * ∧ Resizable set; the anchor lives on the captured handle's `HandleSpec` — no\n * extra state.\n *\n * Same-widget double-grab guard: a widget already in another recognizer's\n * `Drags` set is skipped (first gesture owns it) — two `ctx.addComponent(Grab)`\n * for one widget in one frame would hit strata's flush-time duplicate policy.\n */\nimport type { Entity, System, SystemCtx, World } from \"@vibecook/strata-ecs\";\nimport { defineQuery, defineSystem } from \"@vibecook/strata-ecs\";\nimport {\n Active,\n Captures,\n ChildOf,\n Culled,\n Drag,\n Drags,\n GesturePhases,\n Grab,\n InsertGhost,\n MeasuredSize,\n Movable,\n NO_ENTITY,\n PointerMods,\n Position,\n Resizable,\n RoutedMove,\n RoutedResize,\n Selected,\n Size,\n SweepsContained,\n Watches,\n} from \"../catalog\";\nimport { SelectionVersion, bumpVersion } from \"../helpers/version-stamps\";\nimport { selectedEntities } from \"../ops/selection\";\n\nconst P = GesturePhases;\n\nconst moveClaimQ = defineQuery([Drag, P.justTags.Active, RoutedMove]);\nconst resizeClaimQ = defineQuery([Drag, P.justTags.Active, RoutedResize]);\nconst sweepCandidatesQ = defineQuery([Position, Size, Movable]);\n\n/**\n * Comment-box sweep (2026-07-18, James: the UE-Blueprint comment): expand the\n * dragged set with every widget FULLY INSIDE each SweepsContained member's\n * bounds at claim time. Spatial membership only — no reparenting, so dragging\n * a member out later is nothing at all. Frame-scoped via the canonical\n * non-member signature (Culled ∧ ¬Active — bare test worlds have no tags, so\n * requiring Active would break them; the wires-scope lesson 2026-07-17):\n * folder innards live in frame-local coords that can NUMERICALLY overlap a\n * root comment's rect and must never be swept across frames. Nested comments\n * need no recursion: inner ⊆ outer ⇒ the inner's members are inside the\n * outer's bounds already.\n */\nfunction expandSweep(world: World, ctx: SystemCtx, dragged: Entity[]): void {\n const roots = dragged.filter((w) => ctx.isAlive(w) && ctx.hasTag(w, SweepsContained));\n if (roots.length === 0) return;\n const inSet = new Set(dragged);\n for (const root of roots) {\n const rp = ctx.get(root, Position);\n const rs = ctx.get(root, Size);\n if (rp === undefined || rs === undefined) continue;\n world.query(sweepCandidatesQ).each((b) => {\n for (const r of b) {\n const w = b.entity(r);\n if (inSet.has(w)) continue;\n if (world.hasTag(w, Culled) && !world.hasTag(w, Active)) continue; // other frame\n const p = world.get(w, Position);\n const m = world.get(w, MeasuredSize);\n const s = m !== undefined && m.w > 0 ? m : world.get(w, Size);\n if (p === undefined || s === undefined) continue;\n if (p.x >= rp.x && p.y >= rp.y && p.x + s.w <= rp.x + rs.w && p.y + s.h <= rp.y + rs.h) {\n inSet.add(w);\n dragged.push(w);\n }\n }\n });\n }\n}\n\n/**\n * Attach the drag riders for one widget; returns false if another gesture owns\n * it. `Grab` embeds the ORDER MEMO (petition 8): the widget's ChildOf parent,\n * its nearest predecessor sibling that is NOT itself mid-drag (`taken` covers\n * this pass's claims, a live `Grab` covers earlier frames' — both sit at \"last\"\n * and are unstable anchors; a predecessor dragged by THIS gesture is fine, the\n * restore walk reinserts in `ord` order so it is back in place when consulted),\n * and the original sibling index. The memo reads the PRE-FLUSH sequence — ctx\n * structure is deferred, so capture and the enqueued elevates never interleave.\n */\nfunction attachRiders(ctx: SystemCtx, recognizer: Entity, widget: Entity, taken: Set<Entity>): boolean {\n if (taken.has(widget)) return false;\n const otherOwner = ctx\n .getReverse(widget, Drags)\n .some((rec) => rec !== recognizer);\n if (otherOwner) return false;\n taken.add(widget);\n const pos = ctx.read(widget, Position);\n const size = ctx.get(widget, Size);\n const parent = ctx.getRelation(widget, ChildOf);\n let prev: Entity = NO_ENTITY;\n let ord = 0;\n if (parent !== undefined) {\n const siblings = ctx.getReverse(parent, ChildOf);\n const at = siblings.indexOf(widget);\n ord = at >= 0 ? at : 0;\n for (let i = at - 1; i >= 0; i--) {\n const sib = siblings[i] as Entity;\n if (!taken.has(sib) && !ctx.has(sib, Grab)) {\n prev = sib;\n break;\n }\n }\n }\n ctx.addRelation(recognizer, Drags, widget);\n ctx.addComponent(widget, Grab, {\n x: pos.x,\n y: pos.y,\n w: size?.w ?? 0,\n h: size?.h ?? 0,\n parent: parent ?? NO_ENTITY,\n prev,\n ord,\n });\n return true;\n}\n\nexport function createClaimSystems(world: World): { moveClaim: System; resizeClaim: System } {\n const moveClaim = defineSystem(\n moveClaimQ,\n (b, ctx) => {\n // Shared across recognizers in this pass — first gesture owns a widget.\n const taken = new Set<Entity>();\n for (const r of b) {\n const rec = b.entity(r);\n const grabbed = ctx.getRelation(rec, Captures);\n if (grabbed === undefined || !ctx.has(grabbed, Position)) continue;\n\n // Select-on-grab (design-003 §4.5). Selection tags flip via ctx (deferred),\n // so the dragged set is computed HERE, not re-queried. Modifiers come\n // from the pointer's latched sample (Keyboard only carries key events).\n const pointer = ctx.getRelations(rec, Watches)[0];\n const shift = pointer !== undefined && ctx.get(pointer, PointerMods)?.shift === true;\n const current = selectedEntities(world);\n let dragged: Entity[];\n if (ctx.has(grabbed, InsertGhost)) {\n // Tray-insert ghosts drag SOLO (2026-07-19): the shift branch below\n // would sweep the standing selection into the insert, and a\n // selected-set join makes no sense for a widget that does not exist\n // yet. Replace-select the ghost (select-on-grab's plain posture) —\n // the reap system hands the selection to the projected twin at drop.\n for (const s of current) if (s !== grabbed) ctx.removeTag(s, Selected);\n if (!ctx.hasTag(grabbed, Selected)) ctx.addTag(grabbed, Selected);\n bumpVersion(world, SelectionVersion);\n dragged = [grabbed];\n } else if (ctx.hasTag(grabbed, Selected)) {\n dragged = current;\n } else if (shift) {\n ctx.addTag(grabbed, Selected);\n bumpVersion(world, SelectionVersion);\n dragged = [...current, grabbed];\n } else {\n for (const s of current) ctx.removeTag(s, Selected);\n ctx.addTag(grabbed, Selected);\n bumpVersion(world, SelectionVersion);\n dragged = [grabbed];\n }\n\n // Comment-box sweep BEFORE riders: swept members ride the same\n // recognizer; rider order keeps the comment BELOW its members in the\n // elevate (comment first, members after — each successive \"last\"\n // lands ABOVE the previous one).\n expandSweep(world, ctx, dragged);\n\n for (const w of dragged) {\n if (!ctx.isAlive(w) || !ctx.has(w, Position)) continue;\n if (w !== grabbed && !ctx.hasTag(w, Movable)) continue;\n if (!attachRiders(ctx, rec, w, taken)) continue;\n // Sibling elevate (petition 8): an immediate structural move —\n // gesture divergence; the Grab memo restores on cancel/fly-back.\n // Frame-scoped \"last\" = the old global-top within the frame. No\n // edge (legacy/runtime world) ⇒ strata no-op, skipped.\n if (ctx.getRelation(w, ChildOf) !== undefined) {\n ctx.moveRelation(w, ChildOf, \"last\");\n }\n }\n }\n },\n { name: \"moveClaim\" },\n );\n\n const resizeClaim = defineSystem(\n resizeClaimQ,\n (b, ctx) => {\n const taken = new Set<Entity>();\n for (const r of b) {\n const rec = b.entity(r);\n // Anchor = the captured handle's HandleSpec (read by resizeBehavior).\n for (const w of selectedEntities(world)) {\n if (!ctx.isAlive(w) || !ctx.hasTag(w, Resizable) || !ctx.has(w, Position)) continue;\n attachRiders(ctx, rec, w, taken);\n }\n }\n },\n { name: \"resizeClaim\" },\n );\n\n return { moveClaim, resizeClaim };\n}\n","/**\n * L3 — drop candidate detection (design-003 §5 item 4; `ctl:behave`, ordered\n * AFTER moveBehavior so it tests POST-move bounds).\n *\n * For Active `RoutedMove` drags: spatial-query the dragged union bounds for\n * `Container` widgets (∉dragged), pick the topmost by sibling order (petition\n * 8 — compareStackOrder, the SAME comparator pick/paint use, so the drop\n * candidate can never diverge from what the user sees on top), and publish two\n * signals the move-outcome tree consumes (l3-behave §5.5):\n * - `DropTarget(recognizer → container)` — set for the container under the\n * bounds REGARDLESS of an accepts-match (so the outcome tree can distinguish\n * a rejected drop from a plain move).\n * - `OverlapCandidate` on the container — ONLY when the container's `Accepts`\n * intersects the dragged set's `Provides` (a widget with no `Provides` never\n * matches; RFC-004 contracts).\n * BOTH are strictly change-only: `setRelation`/`addTag` bump the GLOBAL tag/\n * relation version, and any churn wakes every row-filtered observer world-wide\n * (design-002 §4). Both clear when no container is under the bounds; the move\n * behavior clears them on every terminal path.\n */\nimport type { Entity, System, SystemCtx, World } from \"@vibecook/strata-ecs\";\nimport { defineQuery, defineSystem } from \"@vibecook/strata-ecs\";\nimport type { SpatialIndex } from \"@ice/kernel\";\nimport {\n Accepts,\n Container,\n Drag,\n Drags,\n DropTarget,\n GestureActive,\n OverlapCandidate,\n OverlapRejected,\n Position,\n Provides,\n RoutedMove,\n Size,\n Solid,\n SweepsContained,\n} from \"../catalog\";\nimport { compareStackOrder, createSiblingOrderIndex } from \"../ops/sibling-order\";\n\nconst dropDragQ = defineQuery([Drag, GestureActive, RoutedMove]);\n\n/** Parse a JSON string-array field; malformed ⇒ empty (never throw inside the tick). */\nfunction parseList(raw: string | null | undefined): string[] {\n if (raw === null || raw === undefined || raw === \"\") return [];\n try {\n const v = JSON.parse(raw);\n return Array.isArray(v) ? v.filter((k): k is string => typeof k === \"string\") : [];\n } catch {\n return [];\n }\n}\n\nexport function createDropSystem(world: World, index: SpatialIndex<Entity>): System {\n // Frame ordinal map for the topmost-container compare (petition 8) — the\n // same pull-based source the pick systems read; candidates are same-frame\n // by construction (the spatial index is Active-gated).\n const order = createSiblingOrderIndex(world);\n return defineSystem(\n dropDragQ,\n (b, ctx) => {\n for (const r of b) {\n const rec = b.entity(r);\n const dragged = ctx.getRelations(rec, Drags);\n\n // A comment-box group (any dragged SweepsContained widget) is\n // LANDSCAPE, not cargo — with ONE exception (2026-07-18, James: \"i\n // do want that\"): it CAN file into an ACCEPTING container. So for\n // sweeper sets, Solid widgets never reject (the group's union bounds\n // overlap half the board by construction — that's what a comment is\n // FOR), and a NON-matching container is scenery (plain move), never\n // a fly-back: DropTarget only lands together with OverlapCandidate.\n const sweeper = dragged.some((w) => ctx.isAlive(w) && ctx.hasTag(w, SweepsContained));\n const draggedSet = new Set<Entity>(dragged);\n\n // Post-move union bounds from the dragged widgets' CURRENT transform.\n let minX = Number.POSITIVE_INFINITY;\n let minY = Number.POSITIVE_INFINITY;\n let maxX = Number.NEGATIVE_INFINITY;\n let maxY = Number.NEGATIVE_INFINITY;\n let any = false;\n for (const w of dragged) {\n if (!ctx.isAlive(w) || !ctx.has(w, Position) || !ctx.has(w, Size)) continue;\n const p = ctx.read(w, Position);\n const s = ctx.read(w, Size);\n minX = Math.min(minX, p.x);\n minY = Math.min(minY, p.y);\n maxX = Math.max(maxX, p.x + s.w);\n maxY = Math.max(maxY, p.y + s.h);\n any = true;\n }\n\n const prev = ctx.getRelation(rec, DropTarget);\n\n // Topmost drop-evaluating widget under the union bounds (∉dragged):\n // a Container (accept/reject by contracts) OR a Solid widget (always\n // rejects — v1's iOS-card overlap contract, 2026-07-12 field report).\n let container: Entity | undefined;\n if (any) {\n const ordinals = order.ordinals();\n for (const entry of index.search({ minX, minY, maxX, maxY })) {\n const e = entry.id;\n if (draggedSet.has(e) || !ctx.isAlive(e)) continue;\n if (!ctx.hasTag(e, Container) && !(!sweeper && ctx.hasTag(e, Solid))) continue;\n if (container === undefined || compareStackOrder(ctx, ordinals, e, container) > 0) {\n container = e;\n }\n }\n }\n\n const clearSignals = (e: Entity): void => {\n if (!ctx.isAlive(e)) return;\n if (ctx.hasTag(e, OverlapCandidate)) ctx.removeTag(e, OverlapCandidate);\n if (ctx.hasTag(e, OverlapRejected)) ctx.removeTag(e, OverlapRejected);\n };\n\n if (container === undefined) {\n if (prev !== undefined) {\n clearSignals(prev);\n ctx.removeRelation(rec, DropTarget);\n }\n continue;\n }\n\n // accepts ∩ (union of dragged provides) — a widget with no Provides never\n // matches; a Solid non-container has no Accepts and always rejects.\n const provided = new Set<string>();\n for (const w of dragged) {\n if (!ctx.isAlive(w)) continue;\n for (const k of parseList(ctx.get(w, Provides)?.list)) provided.add(k);\n }\n const accepts = parseList(ctx.get(container, Accepts)?.list);\n const matches = accepts.some((k) => provided.has(k));\n\n // Sweeper sets never fly back: a non-matching container is treated\n // like no container at all (release = plain move).\n if (sweeper && !matches) {\n if (prev !== undefined) {\n clearSignals(prev);\n ctx.removeRelation(rec, DropTarget);\n }\n continue;\n }\n\n // A moved-off previous target loses its signal tags.\n if (prev !== undefined && prev !== container) clearSignals(prev);\n if (prev !== container) ctx.setRelation(rec, DropTarget, container);\n\n if (matches) {\n if (!ctx.hasTag(container, OverlapCandidate)) ctx.addTag(container, OverlapCandidate);\n if (ctx.hasTag(container, OverlapRejected)) ctx.removeTag(container, OverlapRejected);\n } else {\n if (ctx.hasTag(container, OverlapCandidate)) ctx.removeTag(container, OverlapCandidate);\n if (!ctx.hasTag(container, OverlapRejected)) ctx.addTag(container, OverlapRejected);\n }\n }\n },\n { name: \"dropSystem\" },\n );\n}\n","/**\n * L3 — marquee behavior (design-003 §5 item 7, §5.7; `ctl:behave`). Rider-free.\n *\n * Two entry paths, one system (anchored on the CanvasSurface entity so the body\n * runs EVERY frame — the preview must clear the frame the gesture ends):\n * - desktop: an Active `RoutedMarquee` Drag — rect from `Drag.start + total`\n * (screen), both corners converted to world via the kernel seam.\n * - touch: a Recognized `LongPress` capturing the canvas, riding its\n * continuous tail — rect from `start → cur` (§4.2, v2's proven path; no\n * `Sequence` machinery).\n * Per frame the hit ENTITY SET goes into an out-of-ECS render buffer\n * (`MarqueeBuffer`, recomputed each frame — preview-as-tags would churn the\n * global tag version, design-003 §5.7). Selection commits ONCE at terminal\n * (`JustEnded`): replace with the hits, or union when the watched pointer holds\n * shift; `SelectionVersion` bumps once (the v1 marquee lesson). No `access.write`\n * — reads + the buffer + ctx selection tags only.\n *\n * Camera staleness: both corners convert with the CURRENT camera, so a mid-\n * marquee camera move re-projects the rect (accepted — design-002 §2).\n */\nimport type { Entity, System, SystemCtx, TickSystem, World } from \"@vibecook/strata-ecs\";\nimport { defineQuery, defineSystem, defineTickSystem } from \"@vibecook/strata-ecs\";\nimport { type CameraState, type SpatialIndex, screenToWorld } from \"@ice/kernel\";\nimport {\n Camera,\n CanvasSurface,\n Captures,\n Drag,\n GesturePhases,\n LongPress,\n PointerMods,\n RoutedMarquee,\n Selectable,\n Selected,\n Watches,\n} from \"../catalog\";\nimport { SelectionVersion, bumpVersion } from \"../helpers/version-stamps\";\nimport { selectedEntities } from \"../ops/selection\";\n\nconst P = GesturePhases;\nconst IDENTITY_CAM: CameraState = { x: 0, y: 0, zoom: 1 };\n\nconst canvasSurfaceQ = defineQuery([CanvasSurface]);\nconst dragMarqueeQ = defineQuery([Drag, RoutedMarquee]);\nconst longPressQ = defineQuery([LongPress]);\n\n/** The out-of-ECS marquee preview (design-003 §5.7): rect + hit set, recomputed each frame. */\nexport interface MarqueeBuffer {\n rect: { x: number; y: number; w: number; h: number } | null;\n hits: Entity[];\n}\n\nexport function createMarqueeBehavior(\n world: World,\n index: SpatialIndex<Entity>,\n): TickSystem & { buffer: MarqueeBuffer } {\n const buffer: MarqueeBuffer = { rect: null, hits: [] };\n\n const queryHits = (ctx: SystemCtx, rx: number, ry: number, rw: number, rh: number): Entity[] => {\n const out: Entity[] = [];\n for (const entry of index.search({ minX: rx, minY: ry, maxX: rx + rw, maxY: ry + rh })) {\n const e = entry.id;\n if (ctx.isAlive(e) && ctx.hasTag(e, Selectable)) out.push(e);\n }\n return out;\n };\n\n /** ctx-side selection flip — replace with hits (shift = union), one SelectionVersion bump. */\n const commitSelection = (ctx: SystemCtx, hits: Entity[], shift: boolean): void => {\n const current = selectedEntities(world);\n const next = new Set(hits);\n if (shift) for (const e of current) next.add(e);\n let changed = false;\n for (const e of current) {\n if (!next.has(e)) {\n ctx.removeTag(e, Selected);\n changed = true;\n }\n }\n for (const e of next) {\n if (!ctx.hasTag(e, Selected)) {\n ctx.addTag(e, Selected);\n changed = true;\n }\n }\n if (changed) bumpVersion(world, SelectionVersion);\n };\n\n // Tick system (strata 0.5.0): exactly once per frame by construction\n // (commitSelection is NOT idempotent within a tick: its tags defer, so a\n // re-run would re-bump SelectionVersion).\n const sys = defineTickSystem(\n (ctx) => {\n const cam = ctx.getResource(Camera) ?? IDENTITY_CAM;\n const canvas = ctx.firstOf(canvasSurfaceQ);\n let active = false;\n\n const process = (\n rec: Entity,\n sx0: number,\n sy0: number,\n sx1: number,\n sy1: number,\n isActive: boolean,\n justEnded: boolean,\n ): void => {\n const w0 = screenToWorld(sx0, sy0, cam);\n const w1 = screenToWorld(sx1, sy1, cam);\n const rx = Math.min(w0.x, w1.x);\n const ry = Math.min(w0.y, w1.y);\n const rw = Math.abs(w1.x - w0.x);\n const rh = Math.abs(w1.y - w0.y);\n const hits = queryHits(ctx, rx, ry, rw, rh);\n if (justEnded) {\n const pointer = ctx.getRelations(rec, Watches)[0];\n const shift = pointer !== undefined && ctx.get(pointer, PointerMods)?.shift === true;\n commitSelection(ctx, hits, shift);\n return;\n }\n if (isActive) {\n buffer.rect = { x: rx, y: ry, w: rw, h: rh };\n buffer.hits = hits;\n active = true;\n }\n };\n\n // Desktop: RoutedMarquee drag (start + total, screen space).\n world.query(dragMarqueeQ).each((bb) => {\n for (const r of bb) {\n const rec = bb.entity(r);\n const d = ctx.read(rec, Drag);\n process(\n rec,\n d.startX,\n d.startY,\n d.startX + d.totalX,\n d.startY + d.totalY,\n ctx.hasTag(rec, P.tags.Active),\n ctx.hasTag(rec, P.justTags.Ended),\n );\n }\n });\n\n // Touch: LongPress on the canvas, riding its continuous tail (start → cur).\n world.query(longPressQ).each((bb) => {\n for (const r of bb) {\n const rec = bb.entity(r);\n if (canvas === undefined || ctx.getRelation(rec, Captures) !== canvas) continue;\n const lp = ctx.read(rec, LongPress);\n process(\n rec,\n lp.startX,\n lp.startY,\n lp.curX,\n lp.curY,\n ctx.hasTag(rec, P.tags.Recognized),\n ctx.hasTag(rec, P.justTags.Ended),\n );\n }\n });\n\n if (!active) {\n buffer.rect = null;\n buffer.hits = [];\n }\n },\n { name: \"marqueeBehavior\" },\n );\n\n return Object.assign(sys, { buffer });\n}\n","/**\n * L3 — resize behavior (design-003 §5 item 6; `ctl:behave`).\n *\n * A drag captured on a `HandleSpec` chrome entity (route `RoutedResize`, riders\n * attached by `resizeClaim` §4.5). Per Active frame it writes ABSOLUTE Position+\n * Size for every live `Drags` target from its `Grab` origin + `Drag.total /\n * zoomAtClaim`, resized about the FIXED opposite edge/corner of the grabbed\n * handle (`n`/`s` height-only, `e`/`w` width-only, corners both). Modifiers ride\n * the watched pointer's `PointerMods`: `alt` = resize about center, `shift` =\n * preserve aspect (corner handles). Min size clamps to the target widget's\n * `defineWidget` `minSize` (via `PrefabId`), or 1×1 for non-widget resizables.\n * `JustEnded` emits ONE\n * `resize` commit (Position+Size per live target); `JustCancelled`/`JustFailed`\n * restore from `Grab`. Every terminal path removes `Grab` and the `Drags` edges\n * (mirrors l3-behave's clearGestureState; resize has no DropTarget).\n */\nimport type { Entity, System, SystemCtx, World } from \"@vibecook/strata-ecs\";\nimport { defineQuery, defineSystem } from \"@vibecook/strata-ecs\";\nimport {\n Captures,\n Drag,\n Drags,\n GesturePhases,\n Grab,\n HandleSpec,\n PointerMods,\n Position,\n RoutedResize,\n Size,\n Watches,\n} from \"../catalog\";\nimport type { CommitSink, CommitWrite } from \"../engine/commit-sink\";\nimport { PrefabId } from \"../schema/prefab\";\nimport { widgets } from \"../widget/define-widget\";\n\nconst P = GesturePhases;\nconst resizeDragQ = defineQuery([Drag, RoutedResize]);\n\ninterface RectVals {\n x: number;\n y: number;\n w: number;\n h: number;\n}\n\n/**\n * Resize a `Grab` rect by world deltas about the anchor handle's fixed opposite\n * edge/corner. `alt` pins the center instead; `shift` preserves aspect on corners.\n */\nfunction computeResize(\n g: { x: number; y: number; w: number; h: number },\n anchor: string,\n dx: number,\n dy: number,\n alt: boolean,\n shift: boolean,\n minW: number,\n minH: number,\n): RectVals {\n const affectsLeft = anchor === \"w\" || anchor === \"nw\" || anchor === \"sw\";\n const affectsRight = anchor === \"e\" || anchor === \"ne\" || anchor === \"se\";\n const affectsTop = anchor === \"n\" || anchor === \"nw\" || anchor === \"ne\";\n const affectsBottom = anchor === \"s\" || anchor === \"se\" || anchor === \"sw\";\n const lDelta = affectsLeft ? dx : 0;\n const rDelta = affectsRight ? dx : 0;\n const tDelta = affectsTop ? dy : 0;\n const bDelta = affectsBottom ? dy : 0;\n\n let left: number;\n let right: number;\n let top: number;\n let bottom: number;\n if (alt) {\n // About center: the opposite edge mirrors the grabbed edge's motion.\n left = g.x + lDelta - rDelta;\n right = g.x + g.w + rDelta - lDelta;\n top = g.y + tDelta - bDelta;\n bottom = g.y + g.h + bDelta - tDelta;\n } else {\n left = g.x + lDelta;\n right = g.x + g.w + rDelta;\n top = g.y + tDelta;\n bottom = g.y + g.h + bDelta;\n }\n\n const isCorner = (affectsLeft || affectsRight) && (affectsTop || affectsBottom);\n if (shift && isCorner && g.w > 0 && g.h > 0) {\n // Uniform-scale to the dominant relative change, re-anchored for the mode.\n const kW = Math.abs((right - left) / g.w);\n const kH = Math.abs((bottom - top) / g.h);\n const k = Math.max(kW, kH);\n const nw = g.w * k;\n const nh = g.h * k;\n if (alt) {\n const cx = g.x + g.w / 2;\n const cy = g.y + g.h / 2;\n left = cx - nw / 2;\n right = cx + nw / 2;\n top = cy - nh / 2;\n bottom = cy + nh / 2;\n } else {\n if (affectsRight) right = left + nw;\n else left = right - nw;\n if (affectsBottom) bottom = top + nh;\n else top = bottom - nh;\n }\n }\n\n // Min size — adjust the moving edge so the fixed (anchor) edge stays put.\n if (right - left < minW) {\n if (affectsLeft && !affectsRight) left = right - minW;\n else right = left + minW;\n }\n if (bottom - top < minH) {\n if (affectsTop && !affectsBottom) top = bottom - minH;\n else bottom = top + minH;\n }\n\n return { x: left, y: top, w: right - left, h: bottom - top };\n}\n\nexport function createResizeBehavior(world: World, sink: CommitSink): System {\n const clearResizeState = (ctx: SystemCtx, rec: Entity): void => {\n for (const w of ctx.getRelations(rec, Drags)) {\n if (ctx.isAlive(w) && ctx.has(w, Grab)) ctx.removeComponent(w, Grab);\n }\n ctx.removeRelation(rec, Drags);\n };\n\n // A resizable widget's declared floor (defineWidget `minSize`); non-widget\n // resizables (no `PrefabId`) keep the historical 1×1.\n const minSizeOf = (ctx: SystemCtx, w: Entity): { w: number; h: number } => {\n const type = ctx.get(w, PrefabId)?.id;\n const widget = typeof type === \"string\" ? widgets.get(type) : undefined;\n return widget?.minSize ?? { w: 1, h: 1 };\n };\n\n return defineSystem(\n resizeDragQ,\n (b, ctx) => {\n for (const r of b) {\n const rec = b.entity(r);\n const handle = ctx.getRelation(rec, Captures);\n const anchor = handle !== undefined ? ctx.get(handle, HandleSpec)?.anchor : undefined;\n const pointer = ctx.getRelations(rec, Watches)[0];\n const mods = pointer !== undefined ? ctx.get(pointer, PointerMods) : undefined;\n const alt = mods?.alt === true;\n const shift = mods?.shift === true;\n\n if (ctx.hasTag(rec, P.tags.Active)) {\n if (anchor === undefined) continue; // handle died — integrity cancels next frame\n const d = ctx.read(rec, Drag);\n const zoom = d.zoomAtClaim || 1;\n const dx = d.totalX / zoom;\n const dy = d.totalY / zoom;\n for (const w of ctx.getRelations(rec, Drags)) {\n if (!ctx.isAlive(w) || !ctx.has(w, Grab)) continue;\n const g = ctx.read(w, Grab);\n const min = minSizeOf(ctx, w);\n const rz = computeResize(g, anchor, dx, dy, alt, shift, min.w, min.h);\n ctx.edit(w).set(Position, { x: rz.x, y: rz.y });\n ctx.edit(w).set(Size, { w: rz.w, h: rz.h });\n }\n continue;\n }\n\n if (ctx.hasTag(rec, P.justTags.Ended)) {\n const writes: CommitWrite[] = [];\n if (anchor !== undefined) {\n const d = ctx.read(rec, Drag);\n const zoom = d.zoomAtClaim || 1;\n const dx = d.totalX / zoom;\n const dy = d.totalY / zoom;\n for (const w of ctx.getRelations(rec, Drags)) {\n if (!ctx.isAlive(w) || !ctx.has(w, Grab)) continue;\n const g = ctx.read(w, Grab);\n const min = minSizeOf(ctx, w);\n const rz = computeResize(g, anchor, dx, dy, alt, shift, min.w, min.h);\n writes.push({ entity: w, component: Position, value: { x: rz.x, y: rz.y } });\n writes.push({ entity: w, component: Size, value: { w: rz.w, h: rz.h } });\n }\n }\n if (writes.length > 0) sink.commit({ kind: \"resize\", gesture: rec, writes });\n clearResizeState(ctx, rec);\n continue;\n }\n\n if (ctx.hasTag(rec, P.justTags.Cancelled) || ctx.hasTag(rec, P.justTags.Failed)) {\n for (const w of ctx.getRelations(rec, Drags)) {\n if (!ctx.isAlive(w) || !ctx.has(w, Grab)) continue;\n const g = ctx.read(w, Grab);\n ctx.edit(w).set(Position, { x: g.x, y: g.y });\n ctx.edit(w).set(Size, { w: g.w, h: g.h });\n }\n clearResizeState(ctx, rec);\n }\n }\n },\n {\n name: \"resizeBehavior\",\n // Position co-write attested — see moveBehavior (row-disjoint routes).\n access: { write: [Position, Size], orderIndependent: [Position] },\n },\n );\n}\n","/**\n * L3 — snap (design-003 §5 item 2, §6; `ctl:behave`, ordered BEFORE moveBehavior).\n *\n * For Active `RoutedMove` drags whose dragged set is a `SnapSource`: compute the\n * intended PRE-SNAP rect as `Grab.origin + Drag.total / zoomAtClaim`, unioned\n * over the dragged widgets — NEVER last-applied `Position` (one frame stale ⇒\n * guide-chasing oscillation, design-003 §5.2 red-team; `Grab` is readable here\n * thanks to the ctl:claim settle point, §4.5). Candidates come from the SHARED\n * spatial index (rect query = intended bounds ∪ VIEWPORT, expanded by\n * threshold — design-003 §5.2: a distant same-axis edge IN VIEW must\n * contribute a guide, the Figma behavior; the widgetlab field check 2026-07-16\n * caught the intended-rect-only query never seeing a card 115px above the\n * drag). Filtered to `SnapTarget ∧ ¬Culled ∧ ∉dragged` — ¬Culled is the\n * design's \"Visible\" scoping in cull-less rigs too (no cull system ⇒ nothing\n * is Culled ⇒ all candidates pass). Threshold is\n * `thresholdPx / zoomAtClaim` (screen-constant). The kernel `computeSnapGuides`\n * does the Figma math; we write `SnapState{dx,dy}` on the recognizer (moveBehavior\n * adds it to the absolute write). SnapState clears to 0,0 when snap is off / no\n * source / no candidate.\n *\n * GUIDE CHROME (design-003 §6, as-built 2026-07-16 — the once-deferred half):\n * the kernel result's `guides`/`spacings` become pooled runtime `GuideLine` /\n * `SpacingBar` entities the P0 snap-guides reflector draws (design-004 §1\n * amendment: ground stratum, under content — James's call). Pool mechanics\n * mirror selectionChrome: a TICK system (exactly one pass per frame — spawn/\n * destroy are not idempotent, and the pool must reap on the frame the last\n * snapping drag ENDS, when the recognizer query is empty), `ctx.spawn` on\n * grow, `ctx.destroy` on shrink, change-only `edit().set` in steady state\n * (same guide held across frames ⇒ zero writes). Alignment guides write\n * `from = to = 0` — the full-viewport sentinel (v1's full-canvas lines);\n * spacing indicators flatten one entity per segment (v1 `u_spacings` parity).\n * No silent caps: the pool grows to whatever the kernel returns (v1's\n * MAX_GUIDES=16 truncation is banned).\n */\nimport type { Entity, SystemCtx, TickSystem, World } from \"@vibecook/strata-ecs\";\nimport { defineQuery, defineTickSystem } from \"@vibecook/strata-ecs\";\nimport { type EntityBounds, type SpatialIndex, computeSnapGuides } from \"@ice/kernel\";\nimport {\n Camera,\n Captures,\n Culled,\n Drag,\n Drags,\n GestureActive,\n Grab,\n GuideLine,\n RoutedMove,\n SnapConfig,\n SnapSource,\n SnapState,\n SnapTarget,\n SpacingBar,\n Viewport,\n} from \"../catalog\";\nimport { SNAP_DEFAULTS } from \"../settings/defaults\";\n\nconst snapDragQ = defineQuery([Drag, GestureActive, RoutedMove]);\n\ninterface GuideWant {\n axis: \"x\" | \"y\";\n at: number;\n}\n\ninterface BarWant {\n axis: \"x\" | \"y\";\n from: number;\n to: number;\n perp: number;\n gap: number;\n}\n\nexport function createSnapSystem(world: World, index: SpatialIndex<Entity>): TickSystem {\n // Guide-chrome pools (derived caches, not world state — selectionChrome\n // pattern): live entities aligned to this frame's wanted visuals, plus the\n // last-written values for change-only writes.\n const guidePool: Entity[] = [];\n const guideCache = new Map<Entity, GuideWant>();\n const barPool: Entity[] = [];\n const barCache = new Map<Entity, BarWant>();\n\n const syncGuides = (ctx: SystemCtx, want: readonly GuideWant[]): void => {\n for (let i = 0; i < want.length; i++) {\n const w = want[i] as GuideWant;\n const existing = guidePool[i];\n if (existing === undefined) {\n const e = ctx.spawn({\n components: [[GuideLine, { axis: w.axis, at: w.at, from: 0, to: 0 }]],\n });\n guidePool.push(e);\n guideCache.set(e, w);\n continue;\n }\n const c = guideCache.get(existing);\n if (c === undefined || c.axis !== w.axis || c.at !== w.at) {\n ctx.edit(existing).set(GuideLine, { axis: w.axis, at: w.at, from: 0, to: 0 });\n guideCache.set(existing, w);\n }\n }\n while (guidePool.length > want.length) {\n const e = guidePool.pop() as Entity;\n ctx.destroy(e);\n guideCache.delete(e);\n }\n };\n\n const syncBars = (ctx: SystemCtx, want: readonly BarWant[]): void => {\n for (let i = 0; i < want.length; i++) {\n const w = want[i] as BarWant;\n const existing = barPool[i];\n if (existing === undefined) {\n const e = ctx.spawn({\n components: [[SpacingBar, { axis: w.axis, from: w.from, to: w.to, perp: w.perp, gap: w.gap }]],\n });\n barPool.push(e);\n barCache.set(e, w);\n continue;\n }\n const c = barCache.get(existing);\n if (\n c === undefined ||\n c.axis !== w.axis ||\n c.from !== w.from ||\n c.to !== w.to ||\n c.perp !== w.perp ||\n c.gap !== w.gap\n ) {\n ctx.edit(existing).set(SpacingBar, { axis: w.axis, from: w.from, to: w.to, perp: w.perp, gap: w.gap });\n barCache.set(existing, w);\n }\n }\n while (barPool.length > want.length) {\n const e = barPool.pop() as Entity;\n ctx.destroy(e);\n barCache.delete(e);\n }\n };\n\n return defineTickSystem(\n (ctx) => {\n const cfg = ctx.getResource(SnapConfig);\n const enabled = cfg?.enabled ?? SNAP_DEFAULTS.enabled;\n const thresholdPx = cfg?.thresholdPx ?? SNAP_DEFAULTS.thresholdPx;\n\n const setSnap = (rec: Entity, dx: number, dy: number): void => {\n const cur = ctx.get(rec, SnapState);\n if (cur === undefined || cur.dx !== dx || cur.dy !== dy) ctx.edit(rec).set(SnapState, { dx, dy });\n };\n\n // This frame's wanted visuals, accumulated across every snapping drag\n // (multi-pointer drags each contribute; usually one).\n const wantGuides: GuideWant[] = [];\n const wantBars: BarWant[] = [];\n\n ctx.query(snapDragQ).each((b) => {\n for (const r of b) {\n const rec = b.entity(r);\n const dragged = ctx.getRelations(rec, Drags);\n const captured = ctx.getRelation(rec, Captures);\n const hasSource =\n (captured !== undefined && ctx.hasTag(captured, SnapSource)) ||\n dragged.some((w) => ctx.hasTag(w, SnapSource));\n if (!enabled || !hasSource) {\n setSnap(rec, 0, 0);\n continue;\n }\n\n // Intended union rect from Grab + total/zoom (never last-applied Position).\n const d = ctx.read(rec, Drag);\n const zoom = d.zoomAtClaim || 1;\n const draggedSet = new Set<Entity>(dragged);\n let minX = Number.POSITIVE_INFINITY;\n let minY = Number.POSITIVE_INFINITY;\n let maxX = Number.NEGATIVE_INFINITY;\n let maxY = Number.NEGATIVE_INFINITY;\n let any = false;\n for (const w of dragged) {\n if (!ctx.isAlive(w) || !ctx.has(w, Grab)) continue;\n const g = ctx.read(w, Grab);\n const x = g.x + d.totalX / zoom;\n const y = g.y + d.totalY / zoom;\n minX = Math.min(minX, x);\n minY = Math.min(minY, y);\n maxX = Math.max(maxX, x + g.w);\n maxY = Math.max(maxY, y + g.h);\n any = true;\n }\n if (!any) {\n setSnap(rec, 0, 0);\n continue;\n }\n\n const threshold = thresholdPx / zoom;\n const intended: EntityBounds = { x: minX, y: minY, width: maxX - minX, height: maxY - minY };\n\n // Candidates: index rect query over intended ∪ viewport (± threshold),\n // SnapTarget ∧ ¬Culled ∧ ∉dragged (design-003 §5.2).\n let qMinX = minX - threshold;\n let qMinY = minY - threshold;\n let qMaxX = maxX + threshold;\n let qMaxY = maxY + threshold;\n const cam = ctx.getResource(Camera);\n const vp = ctx.getResource(Viewport);\n if (cam !== undefined && vp !== undefined && vp.w > 0) {\n const vz = cam.zoom || 1; // Camera.x/y = world top-left (grid contract)\n qMinX = Math.min(qMinX, cam.x);\n qMinY = Math.min(qMinY, cam.y);\n qMaxX = Math.max(qMaxX, cam.x + vp.w / vz);\n qMaxY = Math.max(qMaxY, cam.y + vp.h / vz);\n }\n const refs: EntityBounds[] = [];\n for (const entry of index.search({ minX: qMinX, minY: qMinY, maxX: qMaxX, maxY: qMaxY })) {\n const e = entry.id;\n if (draggedSet.has(e) || !ctx.isAlive(e) || !ctx.hasTag(e, SnapTarget) || ctx.hasTag(e, Culled)) continue;\n refs.push({\n x: entry.minX,\n y: entry.minY,\n width: entry.maxX - entry.minX,\n height: entry.maxY - entry.minY,\n });\n }\n if (refs.length === 0) {\n setSnap(rec, 0, 0);\n continue;\n }\n\n const res = computeSnapGuides(intended, refs, threshold);\n setSnap(rec, res.snapDx, res.snapDy);\n for (const g of res.guides) wantGuides.push({ axis: g.axis, at: g.position });\n for (const sp of res.spacings) {\n for (const seg of sp.segments) {\n wantBars.push({ axis: sp.axis, from: seg.from, to: seg.to, perp: sp.perpPosition, gap: sp.gap });\n }\n }\n }\n });\n\n // Pool reconcile runs EVERY frame — the drag-ended frame (empty query)\n // is exactly the one that must reap; steady state is zero ops.\n syncGuides(ctx, wantGuides);\n syncBars(ctx, wantBars);\n },\n { name: \"snapSystem\", access: { write: [SnapState, GuideLine, SpacingBar] } },\n );\n}\n","/**\n * The insert-ghost reap (cleanup phase; catalog/insert.ts, 2026-07-19).\n *\n * Three exits for a tray-insert ghost, all owned here so nothing transient\n * crosses frames unaccounted (design-002 §2 cleanup law):\n *\n * - PROMOTED (`GhostCommitted`, set by moveBehavior at the create commit):\n * despawned ONE tick after the commit — the projected twin lands at the\n * NEXT sync, so waiting one tick makes the swap happen inside a single\n * reflect flush (twin mounts, ghost unmounts, same frame — no blink).\n * Selection rides the same beat: the doc sink parked the twin ids in its\n * out-of-ECS hand-off (`drainCreatedSelections`); they are drained on the\n * commit tick and applied HERE one tick later, when the projection is\n * alive — the select-on-grab the ghost held transfers to the real widget.\n *\n * - RETIRING (`GhostRetiring`, cancel / rejected drop): despawned when the\n * fly-back `TransformTween` lands (camera-sim removes it on arrival).\n *\n * - STRANDED (no Grab, no tween, no live recognizer still capturing it): a\n * clean click on a tray tile (the drag never formed), or an integrity\n * cancel that raced the claim. Despawned silently — it never left the\n * press point under the tray.\n */\nimport type { Entity, System, SystemCtx, World } from \"@vibecook/strata-ecs\";\nimport { defineQuery, defineSystem } from \"@vibecook/strata-ecs\";\nimport {\n Captures,\n GesturePhases,\n GhostCommitted,\n GhostRetiring,\n Grab,\n InsertGhost,\n Selected,\n TransformTween,\n} from \"../catalog\";\nimport { drainCreatedSelections } from \"../doc/doc-commit-sink\";\nimport { SelectionVersion, bumpVersion } from \"../helpers/version-stamps\";\nimport { selectedEntities } from \"../ops/selection\";\n\nconst P = GesturePhases;\nconst ghostQ = defineQuery([InsertGhost]);\n\n/** Terminal recognizer phases — a capture from one no longer holds the ghost. */\nfunction isTerminal(ctx: SystemCtx, rec: Entity): boolean {\n return (\n ctx.hasTag(rec, P.tags.Ended) ||\n ctx.hasTag(rec, P.tags.Failed) ||\n ctx.hasTag(rec, P.tags.Cancelled) ||\n ctx.hasTag(rec, P.tags.Recognized)\n );\n}\n\nexport function createInsertGhostReap(world: World): System {\n // Commit-tick memory (both live exactly one tick, and only while the ghost\n // is still alive — the zero-match chunk skip can never starve them):\n // ghosts sighted GhostCommitted last tick → despawn now; twin ids drained\n // last tick → their projection is alive now, select them.\n const committedSeen = new Set<Entity>();\n let pendingSelect: Entity[] = [];\n\n return defineSystem(\n ghostQ,\n (b, ctx) => {\n if (pendingSelect.length > 0) {\n const live = pendingSelect.filter((e) => ctx.isAlive(e));\n pendingSelect = [];\n if (live.length > 0) {\n const keep = new Set(live);\n for (const s of selectedEntities(world)) {\n if (!keep.has(s)) ctx.removeTag(s, Selected);\n }\n for (const e of live) {\n if (!ctx.hasTag(e, Selected)) ctx.addTag(e, Selected);\n }\n bumpVersion(world, SelectionVersion);\n }\n }\n\n for (const r of b) {\n const ghost = b.entity(r);\n if (ctx.hasTag(ghost, GhostCommitted)) {\n if (committedSeen.has(ghost)) {\n committedSeen.delete(ghost);\n ctx.destroy(ghost); // twin projected THIS tick's sync — same-flush swap\n } else {\n committedSeen.add(ghost); // commit tick — twin lands next sync\n }\n continue;\n }\n if (ctx.hasTag(ghost, GhostRetiring)) {\n if (!ctx.has(ghost, TransformTween)) ctx.destroy(ghost); // tween landed\n continue;\n }\n if (ctx.has(ghost, Grab) || ctx.has(ghost, TransformTween)) continue;\n const held = ctx.getReverse(ghost, Captures).some((rec) => !isTerminal(ctx, rec));\n if (!held) ctx.destroy(ghost); // stranded — click-no-drag or a raced cancel\n }\n\n // Drained on the COMMIT tick (sink wrote it in ctl:behave, this phase is\n // cleanup — same tick); applied at the top of the NEXT pass, above.\n const created = drainCreatedSelections(world);\n if (created.length > 0) pendingSelect.push(...created);\n },\n { name: \"insertGhostReap\" },\n );\n}\n","/**\n * Gesture ops — app-handler write paths (design-003 §2/§8).\n *\n * `cancelActiveGestures` sets the ONE-TICK CancelRequest resource: escape, tool\n * switch, and doc detach all converge here; the ctl:spawn sweep transitions\n * every non-terminal recognizer → Cancelled next tick, behaviors restore from\n * riders, and cleanup clears the flag.\n */\nimport type { World } from \"@vibecook/strata-ecs\";\nimport { CancelRequest } from \"../catalog\";\n\nexport function cancelActiveGestures(world: World): void {\n world.setResource(CancelRequest, { active: true });\n}\n","/**\n * The file envelope — the engine-owned at-rest format (design-001 §6.5,\n * design-005 §6.2).\n *\n * A document at rest is NEVER raw Loro bytes: it is an engine-versioned frame\n * read BEFORE any import, so the version gate and the autosave quarantine have\n * a hook point that cannot brick boot. Layout (little-endian):\n *\n * bytes 0..3 magic \"ICE1\"\n * byte 4 envelope version (1)\n * bytes 5..8 u32 header length\n * ... header JSON: { engineSchema, prefabVersions, savedAt? }\n * ... payload: Loro snapshot bytes (opaque here)\n *\n * WHERE bytes go (fs/IndexedDB/cloud) is app-owned; WHAT they are is this file.\n */\n\nexport const ENVELOPE_MAGIC = \"ICE1\";\nexport const ENVELOPE_VERSION = 1;\nexport const MAX_ENVELOPE_HEADER_BYTES = 1024 * 1024;\n\n/** The document-format version this build writes (gate compares against it). */\nexport const ENGINE_SCHEMA_VERSION = 2; // 2 = ordered relations (petition 8): board-root + ChildOf sibling sequences\n\nexport interface EnvelopeHeader {\n readonly engineSchema: number;\n /** Per-prefab pack versions at save time ({ [prefabId]: version }). */\n readonly prefabVersions: Readonly<Record<string, number>>;\n /** App-supplied wall-clock ms (the engine never reads a clock). */\n readonly savedAt?: number;\n}\n\nexport class EnvelopeError extends Error {\n constructor(\n message: string,\n readonly reason: \"magic\" | \"version\" | \"truncated\" | \"header\",\n ) {\n super(`ice: envelope — ${message}`);\n this.name = \"EnvelopeError\";\n }\n}\n\nexport function encodeEnvelope(header: EnvelopeHeader, payload: Uint8Array): Uint8Array {\n const headerBytes = new TextEncoder().encode(JSON.stringify(header));\n const out = new Uint8Array(4 + 1 + 4 + headerBytes.length + payload.length);\n const view = new DataView(out.buffer);\n out.set(new TextEncoder().encode(ENVELOPE_MAGIC), 0);\n out[4] = ENVELOPE_VERSION;\n view.setUint32(5, headerBytes.length, true);\n out.set(headerBytes, 9);\n out.set(payload, 9 + headerBytes.length);\n return out;\n}\n\nexport function decodeEnvelope(bytes: Uint8Array): { header: EnvelopeHeader; payload: Uint8Array } {\n if (bytes.length < 9) throw new EnvelopeError(\"too short to hold a frame\", \"truncated\");\n const magic = new TextDecoder().decode(bytes.subarray(0, 4));\n if (magic !== ENVELOPE_MAGIC) throw new EnvelopeError(`bad magic \"${magic}\"`, \"magic\");\n const version = bytes[4];\n if (version !== ENVELOPE_VERSION) {\n throw new EnvelopeError(`unknown envelope version ${version}`, \"version\");\n }\n const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n const headerLen = view.getUint32(5, true);\n if (headerLen > MAX_ENVELOPE_HEADER_BYTES) {\n throw new EnvelopeError(`header exceeds ${MAX_ENVELOPE_HEADER_BYTES} bytes`, \"header\");\n }\n if (9 + headerLen > bytes.length) throw new EnvelopeError(\"header overruns the frame\", \"truncated\");\n let header: EnvelopeHeader;\n try {\n header = JSON.parse(new TextDecoder().decode(bytes.subarray(9, 9 + headerLen))) as EnvelopeHeader;\n } catch {\n throw new EnvelopeError(\"header is not valid JSON\", \"header\");\n }\n if (\n !Number.isSafeInteger(header.engineSchema) ||\n header.engineSchema < 1 ||\n header.prefabVersions === null ||\n Array.isArray(header.prefabVersions) ||\n typeof header.prefabVersions !== \"object\" ||\n (header.savedAt !== undefined &&\n (!Number.isSafeInteger(header.savedAt) || header.savedAt < 0))\n ) {\n throw new EnvelopeError(\"header is missing required fields\", \"header\");\n }\n for (const [id, version] of Object.entries(header.prefabVersions)) {\n if (id.length === 0 || !Number.isSafeInteger(version) || version < 1) {\n throw new EnvelopeError(\"header carries an invalid prefab version\", \"header\");\n }\n }\n return { header, payload: bytes.subarray(9 + headerLen) };\n}\n","/**\n * The M9 migration runner — read-repair at open (design-005 §6.4).\n *\n * A migration is NOT an offline byte transform: the document is already\n * attached, its old cells projected into the runtime, and we upgrade them in\n * place. For each durable type whose doc-side pack marker is OLDER than the\n * local registry (`report.olderInDoc`) and whose widget carries a `migrate`\n * chain covering the gap, `runMigrations`:\n * 1. reads each entity's current group values from the runtime (already\n * canonicalised to the LOCAL schema — see the field-tolerance note below),\n * 2. folds the chain `docV → docV+1 → … → localV-1` over a flat prop record,\n * 3. writes the absolute per-group result back in ONE\n * `store.transaction(fn, { undoable: false })` — the commit never enters\n * the user's undo stack, history hooks skip it, a pending redo survives,\n * 4. stamps the new `engine.pack.<id>.<localV>` write-once marker via\n * `store.metaTransaction` (excluded from undo, invisible to observers).\n *\n * WHY NO LEGACY-SCHEMA REGISTRATION (the as-built finding — design-005 §6.4 is\n * conservative here): design-005 says \"the compiler keeps legacy group\n * components registered for every version covered by the migrate chain\" because\n * \"strata skips unknown inbound components at projection.\" That is TRUE at the\n * COMPONENT-NAME granularity — an unknown component name is never projected\n * (strata-ecs binding.ts:390-392, 804; \"unknown component — never projected\").\n * But it is field-TOLERANT within a known name: `canon(C, v)` iterates the\n * LOCAL schema's `C.fields` (strata-ecs substrate/canon.ts:57-64), so a stored\n * cell that carries EXTRA fields (a v2 that dropped a field) has them dropped,\n * and one MISSING fields (a v2 that added a field) gets them default-filled by\n * `encodeComponentValue`. Because `defineWidget` gives EVERY generated field a\n * default (define-widget.ts strataFieldOf), a v1 cell projects cleanly into a\n * v2 group component of the SAME name with no legacy registration — the\n * transform reads the already-v2-shaped runtime value. Legacy registration\n * would only be needed to migrate data OUT of a group REMOVED wholesale in v2\n * (its component name unregistered → never projected); that coincides with the\n * cross-schema data movement design-005 §6.4 already defers to vNext, so the\n * `migrate` API stays the doc's `{ fromVersion: (prev) => next }` shape with no\n * parallel legacy field. The `migrate.test.ts` \"field tolerance\" case proves\n * the v1→v2 projection empirically (a v1 cell missing a v2-added field).\n *\n * Idempotence / convergence: writes are ABSOLUTE (whole-group values computed\n * from v1), so two peers that migrate the same v1 doc independently produce\n * identical cells that merge by last-writer-wins, and the marker is a\n * first-writer-wins ADD. Re-opening an already-migrated doc reads the v2 marker\n * → the type is no longer `olderInDoc` → the runner skips it. The runner must\n * therefore run once per open against the open-time report (the caller re-gates\n * after it, never re-invokes it against the same report).\n */\nimport type { Component, Entity, World } from \"@vibecook/strata-ecs\";\nimport { defineQuery } from \"@vibecook/strata-ecs\";\nimport type { DurableStore } from \"@vibecook/strata-ecs/durable\";\nimport { PrefabId } from \"../schema/prefab\";\nimport { widgets } from \"../widget/define-widget\";\nimport type { DocVersionReport } from \"./version-gate\";\n\n/** Same reserved prefix as version-gate's markers (that module owns the read side). */\nconst PACK_PREFIX = \"engine.pack.\";\n\n/** What the runner needs: the doc store to write through, the world to read from. */\nexport interface MigrationCtx {\n readonly store: DurableStore;\n readonly world: World;\n}\n\nexport interface MigrationOutcome {\n /** Type ids whose entities were upgraded and whose v-local marker was stamped. */\n readonly migrated: string[];\n /** Type ids left as-is (no widget, no/gappy chain) — they stay read-only per the re-gate. */\n readonly skipped: string[];\n}\n\n// One durable-identity query, reused across opens (defineQuery interns; a module\n// singleton avoids re-defining per call).\nconst allDurableQ = defineQuery([PrefabId]);\n\ninterface EntityPlan {\n readonly e: Entity;\n /** The transform's absolute output — a flat prop record spanning every group. */\n readonly next: Record<string, unknown>;\n /** Component ids present on the entity NOW (edit vs add decision at write time). */\n readonly present: ReadonlySet<number>;\n}\n\ninterface TypePlan {\n readonly id: string;\n readonly widget: NonNullable<ReturnType<typeof widgets.get>>;\n readonly localV: number;\n readonly plans: EntityPlan[];\n}\n\n/**\n * Run every applicable per-type migration against an ATTACHED doc. ALL types\n * are planned (read + transform-fold) BEFORE anything is written — a throwing\n * transform on the Nth type therefore aborts with the document untouched,\n * never with types 1..N-1 permanently migrated and the rest old (2026-07-13\n * review). Each type then writes one non-undoable transaction and stamps its\n * marker. Never throws for a merely-un-migratable type (missing widget /\n * gappy chain → skipped); a genuine fault (a throwing transform) propagates so\n * the caller can fall back read-only.\n */\nexport function runMigrations(ctx: MigrationCtx, report: DocVersionReport): MigrationOutcome {\n const { store, world } = ctx;\n const migrated: string[] = [];\n const skipped: string[] = [];\n\n // --- plan pass: every type's reads + chain folds, NO writes yet ---\n const typePlans: TypePlan[] = [];\n for (const id of report.olderInDoc) {\n const widget = widgets.get(id);\n const chain = widget?.migrate;\n if (widget === undefined || chain === undefined || Object.keys(chain).length === 0) {\n skipped.push(id); // no widget or no chain → cannot upgrade; the re-gate keeps it read-only\n continue;\n }\n\n const docV = report.docPacks[id] ?? 1;\n const localV = report.localPacks[id] ?? widget.version;\n\n // The chain must cover every step fromVersion docV..localV-1. A gap means we\n // cannot reach localV from docV safely — skip the whole type (stays read-only)\n // rather than half-apply. (defineWidget already warns at definition time.)\n let contiguous = true;\n for (let v = docV; v < localV; v++) {\n if (typeof chain[v] !== \"function\") {\n contiguous = false;\n break;\n }\n }\n if (!contiguous) {\n skipped.push(id);\n continue;\n }\n\n // Gather each entity's current props + fold the chain (transforms run HERE,\n // pre-write — their throws leave the doc byte-identical).\n const plans: EntityPlan[] = [];\n world.query(allDurableQ).each((batch) => {\n for (const row of batch) {\n const e = batch.entity(row);\n if (world.read(e, PrefabId).id !== id) continue;\n\n const prev: Record<string, unknown> = {};\n const present = new Set<number>();\n for (const g of widget.groups) {\n const val = world.get(e, g.component);\n if (val === undefined) continue; // an added-in-v2 group has no v1 cell — written fresh below\n present.add(g.component.id);\n Object.assign(prev, val as Record<string, unknown>);\n }\n\n let cur = prev;\n for (let v = docV; v < localV; v++) {\n const step = chain[v];\n if (typeof step === \"function\") cur = step(cur); // contiguity checked above\n }\n plans.push({ e, next: cur, present });\n }\n });\n typePlans.push({ id, widget, localV, plans });\n }\n\n // --- write pass: per type, ONE non-undoable transaction of absolute per-group\n // writes. `edit().set` / `addComponent` canon the value against the group\n // schema, so a flat `next` spanning all groups is picked apart per group\n // (extra keys ignored, missing declared-default keys default-filled).\n for (const { id, widget, localV, plans } of typePlans) {\n store.transaction(\n (tx) => {\n for (const { e, next, present } of plans) {\n for (const g of widget.groups) {\n if (present.has(g.component.id)) {\n tx.edit(e).set(g.component as Component, next);\n } else {\n // Added-in-v2 group: structure rides projection at the next sync().\n tx.addComponent(e, g.component as Component, next);\n }\n }\n }\n },\n { undoable: false },\n );\n\n // Stamp the reached version as a write-once marker (idempotent; first-writer-wins).\n store.metaTransaction((meta) => {\n const key = `${PACK_PREFIX}${id}.${localV}`;\n if (meta.get(key) === undefined) meta.set(key, true);\n });\n\n migrated.push(id);\n }\n\n return { migrated, skipped };\n}\n","/**\n * The per-cell gesture guard (design-001 §2 rule 4 + §3), as the engine's\n * live-write path. strata worlds can't intercept writes, so behaviors write\n * doc-SENSITIVE values through this facade:\n *\n * a world value-write to a cell that exists in the doc for that entity is\n * legal iff the entity is currently allowed to diverge — an Active\n * recognizer Captures/Drags it, or it carries a live TransformTween\n * (fly-back holds the claim; design-003 review M3).\n *\n * \"Cell in doc\" is approximated conservatively from public API: entity is\n * doc-bound (keyOf defined) AND the component is durable-eligible for its\n * prefab. Eligible-but-uncommitted optionals are guarded too (documented).\n * The divergence predicate is injected — M4 wires claims + tween; tests stub.\n */\nimport type { Component, Entity, World } from \"@vibecook/strata-ecs\";\nimport { prefabs, PrefabId } from \"../schema/prefab\";\nimport { devGuardsEnabled } from \"./dev\";\n\nexport interface LiveWriterOpts {\n /** `doc.keyOf` when a doc is attached; absent doc = nothing is doc-bound. */\n keyOf: (e: Entity) => unknown;\n /** May this entity's doc cells diverge right now? (claims ∪ tween) */\n mayDiverge: (e: Entity) => boolean;\n /**\n * Exact \"is this cell in the doc?\" (e.g. wired to `doc.getComponent`).\n * When absent, the guard falls back to the eligibility approximation —\n * stricter than design-001 §2 rule 4's letter: an eligible-but-uncommitted\n * optional is guarded too (fails safe; matrix finding #2).\n */\n cellInDoc?: (e: Entity, c: Component) => boolean;\n}\n\nexport interface LiveWriter {\n set<S>(e: Entity, component: Component<S>, value: S): void;\n}\n\nexport function createLiveWriter(world: World, opts: LiveWriterOpts): LiveWriter {\n return {\n set(e, component, value) {\n if (devGuardsEnabled() && opts.keyOf(e) !== undefined) {\n const prefabId = world.get(e, PrefabId)?.id;\n const prefab = typeof prefabId === \"string\" ? prefabs.get(prefabId) : undefined;\n if (!opts.cellInDoc && prefab === undefined) {\n // Fail CLOSED (review finding A5): a doc-bound entity whose prefab we\n // cannot resolve must not get free live writes — without eligibility\n // knowledge every write could be a doc cell. Wire `cellInDoc` (exact)\n // or ensure durable spawns stamp a registered PrefabId.\n throw new Error(\n `ice: live write to a doc-bound entity with no resolvable prefab (PrefabId=${String(prefabId)}) — the guard cannot determine cell sovereignty; wire cellInDoc or spawn via a registered prefab.`,\n );\n }\n const guardedCell = opts.cellInDoc\n ? opts.cellInDoc(e, component as Component)\n : (prefab?.eligible.has(component as Component) ?? false);\n if (guardedCell && !opts.mayDiverge(e)) {\n const name = String(prefabId);\n throw new Error(\n `ice: live write to a doc cell of \"${name}\" without a gesture claim — doc-sovereign values are written live only under an Active recognizer's Captures/Drags (or a TransformTween), then committed once at JustEnded (design-001 §3). Use a transaction for non-gesture edits.`,\n );\n }\n }\n world.edit(e).set(component, value);\n },\n };\n}\n","/**\n * The DEFAULT divergence predicate for the live-write guard (design-001 §3):\n * an entity's doc cells may diverge iff\n * - some recognizer in `GestureActive` currently `Captures` or `Drags` it, or\n * - it carries a live `TransformTween` (fly-back holds the claim after the\n * recognizer is reaped — design-003 review M3 / design-001 §3 amendment).\n *\n * This replaces the \"inject a stub\" posture (review finding A2): engines wire\n * `createLiveWriter(world, { keyOf, mayDiverge: makeDefaultMayDiverge(world), … })`\n * by default; tests and special hosts may still inject their own predicate.\n * Discrete claims (`GestureRecognized`) deliberately do NOT grant divergence —\n * design-001 §3 live-writes happen only under continuous Active gestures.\n */\nimport type { Entity, World } from \"@vibecook/strata-ecs\";\nimport { Captures, Drags, GestureActive, TransformTween } from \"../catalog/gesture\";\n\nexport function makeDefaultMayDiverge(world: World): (e: Entity) => boolean {\n return (e) => {\n if (world.has(e, TransformTween)) return true;\n for (const claimant of world.getReverse(e, Captures)) {\n if (world.hasTag(claimant, GestureActive)) return true;\n }\n for (const claimant of world.getReverse(e, Drags)) {\n if (world.hasTag(claimant, GestureActive)) return true;\n }\n return false;\n };\n}\n","/**\n * The document version gate (design-001 §6.1/§5.2, design-005 §6.3).\n *\n * Version state lives in the doc's reserved `meta` root map as WRITE-ONCE\n * MARKER KEYS — a monotone key SET, never a mutated cell (sidestepping\n * first-writer-wins): `engine.schema.<n>` and `engine.pack.<type>.<v>` are\n * presence markers. Reading needs no strata API: the gate reads\n * `doc.getMap(\"meta\")` on the RAW LoroDoc after import, BEFORE\n * `createDurableStore`/`attachDurable` — an incompatible doc never projects.\n *\n * Stamps go through `store.metaTransaction` (strata 0.4.0 — petition 3b\n * LANDED): the commit is properly tagged (peers no longer warn about an\n * untagged foreign writer), excluded from undo/redo, and invisible to\n * observers. Same underlying `meta` root map and raw keys as the pre-0.4.0\n * raw-doc stamps, so docs stamped by either path read identically here —\n * and importers also stopped warning about metadata-only commits from\n * before the API, so legacy docs are quiet too.\n *\n * M5 gate policy: exact schema + no doc-side pack NEWER than local ⇒ ok;\n * anything else ⇒ readOnly (or reject via policy). The migrate verdict (older\n * doc packs with a migrate chain) lands at M9 — the gate's verdict surface\n * already carries it so the facade policy hook is stable.\n */\nimport type { LoroDoc } from \"loro-crdt\";\nimport type { DurableStore } from \"@vibecook/strata-ecs/durable\";\nimport { prefabs } from \"../schema/prefab\";\nimport { renames } from \"../widget/define-widget\";\nimport { ENGINE_SCHEMA_VERSION, type EnvelopeHeader } from \"./envelope\";\n\nconst SCHEMA_PREFIX = \"engine.schema.\";\nconst PACK_PREFIX = \"engine.pack.\";\n/** `engine.renamed.<oldId>` = \"<newId>\" — the rename tombstone (design-008 §4). */\nconst RENAMED_PREFIX = \"engine.renamed.\";\n\nexport interface DocVersionReport {\n /** Highest engine.schema.<n> marker present (0 = unstamped/pre-engine doc). */\n readonly docSchema: number;\n readonly localSchema: number;\n /** Highest engine.pack.<id>.<v> per prefab id present in the doc. */\n readonly docPacks: Readonly<Record<string, number>>;\n /** Local registry versions for DURABLE prefabs. */\n readonly localPacks: Readonly<Record<string, number>>;\n /** Prefab ids whose doc marker is NEWER than local (built by a newer app). */\n readonly newerInDoc: readonly string[];\n /** Prefab ids whose doc marker is OLDER than local (M9 migration input). */\n readonly olderInDoc: readonly string[];\n /**\n * Old ids with a REGISTERED rename, present in the doc and not yet\n * tombstoned → the doc pack version their markers carry (design-008 §4).\n * The rename runner's exact input; non-empty forces at least \"migrate\".\n * Meta has no delete, so a stale old marker without this classification\n * would brick the doc `readOnly` via `newerInDoc` — the I5 failure mode.\n */\n readonly renamedInDoc: Readonly<Record<string, number>>;\n}\n\nexport type GateVerdict = \"ok\" | \"readOnly\" | \"migrate\" | \"reject\";\n\n/**\n * Stamp the engine markers through the store's sanctioned meta path (create\n * path; idempotent write-once; callable BEFORE attach — the order is\n * `createDurableStore(doc)` first, then stamp, then `attachDurable`).\n */\nexport function stampEngineMeta(store: DurableStore): void {\n store.metaTransaction((meta) => {\n const stamp = (key: string): void => {\n if (meta.get(key) === undefined) meta.set(key, true);\n };\n stamp(`${SCHEMA_PREFIX}${ENGINE_SCHEMA_VERSION}`);\n for (const p of prefabs.all()) {\n if (p.store !== \"durable\") continue;\n stamp(`${PACK_PREFIX}${p.id}.${p.version ?? 1}`);\n }\n });\n}\n\n/**\n * Fold raw doc-side pack versions through the rename layer (design-008 §4):\n * tombstoned old ids are DEAD HISTORY (meta cannot delete, so their markers\n * persist forever — skip them entirely); registered-rename old ids without a\n * tombstone alias their version onto the NEW id (`max` — the strongest\n * evidence wins) and land in `renamedInDoc` instead of `newerInDoc`.\n */\nfunction foldRenames(\n rawPacks: Readonly<Record<string, number>>,\n tombstoned: ReadonlySet<string>,\n): { docPacks: Record<string, number>; renamedInDoc: Record<string, number> } {\n const docPacks: Record<string, number> = {};\n const renamedInDoc: Record<string, number> = {};\n for (const [id, v] of Object.entries(rawPacks)) {\n if (tombstoned.has(id)) continue; // renamed away — the tombstone is doc-side truth\n const rename = renames.get(id);\n if (rename !== undefined) {\n renamedInDoc[id] = Math.max(renamedInDoc[id] ?? 0, v);\n const target = rename.widget.type;\n docPacks[target] = Math.max(docPacks[target] ?? 0, v);\n continue;\n }\n docPacks[id] = Math.max(docPacks[id] ?? 0, v);\n }\n return { docPacks, renamedInDoc };\n}\n\nfunction compare(\n docPacks: Readonly<Record<string, number>>,\n localPacks: Readonly<Record<string, number>>,\n): { newerInDoc: string[]; olderInDoc: string[] } {\n const newerInDoc: string[] = [];\n const olderInDoc: string[] = [];\n for (const [id, v] of Object.entries(docPacks)) {\n const local = localPacks[id];\n if (local === undefined || v > local) newerInDoc.push(id);\n else if (v < local) olderInDoc.push(id);\n }\n return { newerInDoc, olderInDoc };\n}\n\nfunction localPackVersions(): Record<string, number> {\n const localPacks: Record<string, number> = {};\n for (const p of prefabs.all()) {\n if (p.store === \"durable\") localPacks[p.id] = p.version ?? 1;\n }\n return localPacks;\n}\n\n/** Read the marker keys off a raw (imported, unattached) doc and compare. */\nexport function readDocVersionReport(doc: LoroDoc): DocVersionReport {\n const meta = doc.getMap(\"meta\");\n let docSchema = 0;\n const rawPacks: Record<string, number> = {};\n const tombstoned = new Set<string>();\n for (const key of meta.keys()) {\n if (key.startsWith(SCHEMA_PREFIX)) {\n const n = Number(key.slice(SCHEMA_PREFIX.length));\n if (Number.isInteger(n) && n > docSchema) docSchema = n;\n } else if (key.startsWith(RENAMED_PREFIX)) {\n tombstoned.add(key.slice(RENAMED_PREFIX.length));\n } else if (key.startsWith(PACK_PREFIX)) {\n const rest = key.slice(PACK_PREFIX.length);\n const dot = rest.lastIndexOf(\".\");\n if (dot <= 0) continue;\n const id = rest.slice(0, dot);\n const v = Number(rest.slice(dot + 1));\n if (!Number.isInteger(v)) continue;\n if ((rawPacks[id] ?? 0) < v) rawPacks[id] = v;\n }\n }\n\n const localPacks = localPackVersions();\n const { docPacks, renamedInDoc } = foldRenames(rawPacks, tombstoned);\n const { newerInDoc, olderInDoc } = compare(docPacks, localPacks);\n return { docSchema, localSchema: ENGINE_SCHEMA_VERSION, docPacks, localPacks, newerInDoc, olderInDoc, renamedInDoc };\n}\n\n/**\n * Build the same comparison report from an envelope header, before Loro\n * import. The header carries no meta, so no tombstone knowledge here —\n * registry aliasing only. This preflight is coarse by design; the\n * authoritative in-document gate re-runs right after import.\n */\nexport function readEnvelopeVersionReport(header: EnvelopeHeader): DocVersionReport {\n const localPacks = localPackVersions();\n const { docPacks, renamedInDoc } = foldRenames(header.prefabVersions, new Set());\n const { newerInDoc, olderInDoc } = compare(docPacks, localPacks);\n return {\n docSchema: header.engineSchema,\n localSchema: ENGINE_SCHEMA_VERSION,\n docPacks,\n localPacks,\n newerInDoc,\n olderInDoc,\n renamedInDoc,\n };\n}\n\n/** The default M5 policy. A facade policy hook may override (design-005 §6.3). */\nexport function gateVerdict(report: DocVersionReport): GateVerdict {\n if (report.docSchema === 0) return \"reject\"; // not an engine doc (or pre-stamp corruption)\n if (report.docSchema > report.localSchema) return \"readOnly\"; // newer app wrote it\n if (report.newerInDoc.length > 0) return \"readOnly\";\n if (\n report.docSchema < report.localSchema ||\n report.olderInDoc.length > 0 ||\n Object.keys(report.renamedInDoc).length > 0 // design-008: pending renames fold at open\n ) {\n return \"migrate\"; // M9 runs the chain; M5 treats as readOnly downstream\n }\n return \"ok\";\n}\n","/**\n * The doc kit core — create/open/close on ONE world (design-001 §6, design-005\n * §6.1–§6.3; the engine.docs.* facade sugar lands at M10).\n *\n * - create: new LoroDoc → engine.* meta stamps (write-once markers, meta\n * origin — excluded from undo like the docId) → createDurableStore →\n * attachDurable → selection history hooks → doc-backed CommitSink.\n * - open: decode envelope (BEFORE any import) → import into a raw doc → read\n * the marker keys pre-attach → gate verdict → attach read-write, attach\n * read-only (tx path swapped for the warn-and-drop sink), or reject.\n * Corrupt/incompatible bytes NEVER throw out of open — quarantine is a\n * return value (the autosave kit and boot paths must not brick).\n * - close: cancelActiveGestures → detach → in-place world.reset (observers\n * and systems survive — R3) → respawn the canvas-surface anchor. Undo\n * stack, baseline, and held-cell ledger die with the attachment by\n * construction. Switching docs = close() then create/open the next.\n *\n * Selection history hooks (design-001 §12 / M5 exit \"undo restores\n * selection\"): capture = the Selected set as durable EntityKeys (stable across\n * peers and restarts); restore = resolve keys → setSelection. Runtime-only\n * selections (never-committed drafts) are skipped by construction.\n */\nimport { LoroDoc } from \"loro-crdt\";\nimport type { Entity, World } from \"@vibecook/strata-ecs\";\nimport { attachDurable, createDurableStore } from \"@vibecook/strata-ecs/durable\";\nimport type { Attachment, DurableStore } from \"@vibecook/strata-ecs/durable\";\nimport { Selected } from \"../catalog\";\nimport type { CommitSink } from \"../engine/commit-sink\";\nimport { ensureCanvasSurface } from \"../interaction/install\";\nimport { cancelActiveGestures } from \"../ops/gestures\";\nimport { selectedEntities, setSelection } from \"../ops/selection\";\nimport {\n EnvelopeError,\n decodeEnvelope,\n encodeEnvelope,\n type EnvelopeHeader,\n} from \"./envelope\";\nimport { createDocCommitSink, createReadOnlyCommitSink } from \"./doc-commit-sink\";\nimport { runMigrations } from \"./migrate\";\nimport { runRenames } from \"./rename\";\nimport { armRenameSweep } from \"./rename-sweep\";\nimport { ensureBoardRoot, resolveBoardRoot, runSchemaMigrations } from \"./schema-migrate\";\nimport { BoardRoot } from \"../catalog/scene\";\nimport { writeRuntimeResource } from \"../guards/resource-writer\";\nimport { createLiveWriter, type LiveWriter } from \"../guards/live-writer\";\nimport { makeDefaultMayDiverge } from \"../ops/claims\";\nimport {\n gateVerdict,\n readEnvelopeVersionReport,\n readDocVersionReport,\n stampEngineMeta,\n type DocVersionReport,\n type GateVerdict,\n} from \"./version-gate\";\n\nexport interface DocSessionOpts {\n readonly maxUndoSteps?: number;\n /** Override the default gate policy (design-005 §6.3 facade hook). */\n readonly onGate?: (report: DocVersionReport, verdict: GateVerdict) => GateVerdict;\n /**\n * Run the M9 read-repair migrator on a \"migrate\" verdict (design-005 §6.4).\n * Default TRUE: the doc attaches writable, the migrator upgrades older packs\n * in place, and the session re-gates. Set false to keep M5 behavior (a\n * \"migrate\" verdict attaches read-only, no upgrade).\n */\n readonly migrate?: boolean;\n}\n\nexport interface DocSession {\n readonly store: DurableStore;\n readonly sink: CommitSink;\n /**\n * The strata attachment — a read-only INSPECTION seam: its `baseline` feeds\n * the observer devtools' durable tab (runtime-vs-baseline = the un-agreed\n * sync delta). Never a sync path; `close()` owns its lifecycle.\n */\n readonly attachment: Attachment;\n readonly readOnly: boolean;\n /**\n * The design-001 §3 step-2 DEV guard, wired to THIS doc: userland live\n * writes to doc cells go through it (throws without a claim/tween;\n * cellInDoc is exact via store.getComponent). Engine behaviors stay on\n * ctx — they hold claims by construction.\n */\n readonly liveWriter: LiveWriter;\n /** Present on the open path (the gate's evidence). */\n readonly report?: DocVersionReport;\n /** Envelope-framed snapshot for storage (autosave kit consumes this). */\n exportEnvelope(savedAt?: number): Uint8Array;\n /** Relay passthroughs (M5 dumb relay; M9 brings the bootstrap protocol). */\n exportSnapshot(): Uint8Array;\n applyRemote(bytes: Uint8Array): void;\n /**\n * Fires after each successful `applyRemote` on THIS session (strata's\n * `subscribeOutbound` is local-commits-only by design, so remote imports are\n * otherwise unobservable). Autosave rides this so a peer's local backup\n * reflects the last-seen document, not just what it authored (2026-07-13\n * review). A transport writing through `store.applyRemote` directly bypasses\n * it — engine paths (bootstrap, broadcast relay) all go through the session.\n */\n subscribeRemote(fn: (bytes: Uint8Array) => void): () => void;\n /** cancel gestures → detach → world reset in place → respawn the anchor. */\n close(): void;\n}\n\nexport type OpenDocResult =\n | { readonly ok: true; readonly session: DocSession }\n | { readonly ok: false; readonly reason: string; readonly report?: DocVersionReport };\n\nfunction makeSession(\n world: World,\n doc: LoroDoc,\n store: DurableStore,\n attachment: Attachment,\n readOnly: boolean,\n report?: DocVersionReport,\n): DocSession {\n // Selection history hooks — capture keys, restore via resolve (skip dead).\n store.setHistoryHooks({\n capture: () => {\n const keys: string[] = [];\n for (const e of selectedEntities(world)) {\n const key = store.keyOf(e);\n if (key !== undefined) keys.push(key as unknown as string);\n }\n return keys;\n },\n restore: (value) => {\n if (!Array.isArray(value)) return;\n const entities: Entity[] = [];\n for (const key of value) {\n const e = store.resolve(key);\n if (e !== undefined && world.isAlive(e)) entities.push(e);\n }\n setSelection(world, entities, \"replace\");\n },\n });\n\n const sink = readOnly ? createReadOnlyCommitSink() : createDocCommitSink(store, world);\n const liveWriter = createLiveWriter(world, {\n keyOf: (e) => store.keyOf(e),\n mayDiverge: makeDefaultMayDiverge(world),\n cellInDoc: (e, c) => store.getComponent(e, c) !== undefined,\n });\n // The rename zombie sweep (design-008 §6): writable sessions fold stale\n // pre-rename deliveries between frames; read-only sessions never write, so\n // their zombies stay visible-but-inert until a writable open folds them.\n const disarmRenameSweep = readOnly ? undefined : armRenameSweep(world, store);\n let closed = false;\n const remoteSubs = new Set<(bytes: Uint8Array) => void>();\n\n return {\n store,\n sink,\n attachment,\n readOnly,\n liveWriter,\n ...(report !== undefined ? { report } : {}),\n exportEnvelope(savedAt) {\n const current = readDocVersionReport(doc);\n const header: EnvelopeHeader = {\n engineSchema: current.docSchema,\n prefabVersions: current.docPacks,\n ...(savedAt !== undefined ? { savedAt } : {}),\n };\n return encodeEnvelope(header, store.exportSnapshot());\n },\n exportSnapshot: () => store.exportSnapshot(),\n applyRemote(bytes) {\n if (closed) throw new Error(\"ice: cannot apply a remote update to a closed document\");\n store.applyRemote(bytes); // a throw (PendingImportError et al.) skips notification\n for (const fn of [...remoteSubs]) fn(bytes);\n },\n subscribeRemote(fn) {\n remoteSubs.add(fn);\n return () => remoteSubs.delete(fn);\n },\n close() {\n if (closed) return;\n closed = true;\n disarmRenameSweep?.();\n cancelActiveGestures(world); // consumed by the next tick IF one runs pre-detach;\n // the reset below clears in-flight gesture state regardless — both paths safe.\n store.setHistoryHooks(null);\n remoteSubs.clear();\n attachment.detach();\n world.reset(); // in place: observers/systems survive (R3); entities die\n ensureCanvasSurface(world); // the interaction stack's anchor must exist again\n },\n };\n}\n\n/** Create + attach a fresh document (local-first by construction, design-001 §6.3). */\nexport function createDocSession(world: World, opts: DocSessionOpts = {}): DocSession {\n const doc = new LoroDoc();\n // Store FIRST, then stamp through its sanctioned meta path (strata 0.4.0),\n // then attach — metaTransaction is callable pre-attach by contract.\n const store = createDurableStore(\n doc,\n opts.maxUndoSteps !== undefined ? { maxUndoSteps: opts.maxUndoSteps } : undefined,\n );\n stampEngineMeta(store);\n const attachment = attachDurable(world, store);\n // Petition 8: every schema-2 doc carries a board root from birth — root-level widgets hang\n // their ordered ChildOf edges on it. Runtime resource names it for the ops/renderers.\n const root = ensureBoardRoot(world, store);\n writeRuntimeResource(world, BoardRoot, { root });\n return makeSession(world, doc, store, attachment, false);\n}\n\n/** Open an envelope: gate BEFORE attach; quarantine is a return value, never a throw. */\nexport function openDocSession(world: World, bytes: Uint8Array, opts: DocSessionOpts = {}): OpenDocResult {\n let payload: Uint8Array;\n let envelopeReport: DocVersionReport;\n try {\n const decoded = decodeEnvelope(bytes);\n payload = decoded.payload;\n envelopeReport = readEnvelopeVersionReport(decoded.header);\n } catch (err) {\n const reason = err instanceof EnvelopeError ? err.message : String(err);\n return { ok: false, reason };\n }\n\n // Coarse gate before the WASM import. The in-document markers are still\n // authoritative and are checked again below; this fast path prevents a\n // policy-rejected future envelope from reaching Loro at all.\n try {\n const preflight = (opts.onGate ?? ((_, v) => v))(envelopeReport, gateVerdict(envelopeReport));\n if (preflight === \"reject\") {\n return { ok: false, reason: \"ice: version gate rejected the envelope\", report: envelopeReport };\n }\n } catch (err) {\n return { ok: false, reason: `ice: onGate callback threw during envelope preflight — ${String(err)}`, report: envelopeReport };\n }\n\n const doc = new LoroDoc();\n let attachment: Attachment | undefined;\n try {\n doc.import(payload);\n } catch (err) {\n return { ok: false, reason: `ice: payload import failed — ${String(err)}` };\n }\n\n const report = readDocVersionReport(doc);\n let verdict: ReturnType<typeof gateVerdict>;\n try {\n verdict = (opts.onGate ?? ((_, v) => v))(report, gateVerdict(report));\n } catch (err) {\n // A throwing policy callback must not break open()'s no-throw contract —\n // during network bootstrap it would escape an inbound channel callback and\n // leave the join promise pending forever. Quarantine instead.\n return { ok: false, reason: `ice: onGate callback threw — ${String(err)}`, report };\n }\n if (verdict === \"reject\") {\n return { ok: false, reason: \"ice: version gate rejected the document\", report };\n }\n\n try {\n const store = createDurableStore(\n doc,\n opts.maxUndoSteps !== undefined ? { maxUndoSteps: opts.maxUndoSteps } : undefined,\n );\n attachment = attachDurable(world, store);\n\n // M9 (design-005 §6.4): the \"migrate\" verdict upgrades in place. Attach is\n // identical either way — readOnly is an engine concept (the commit sink), and\n // the migrator writes through store.transaction directly — so we run it on the\n // live attachment, then RE-GATE off the freshly stamped markers. A migrate that\n // catches the doc fully up flips the session writable; one that could not\n // upgrade every older pack (a type with no/gappy chain) stays read-only. Opt\n // out with opts.migrate=false (then \"migrate\" keeps M5's read-only behavior).\n let effectiveReport = report;\n let readOnly = verdict !== \"ok\";\n if (verdict === \"migrate\" && (opts.migrate ?? true)) {\n try {\n // Petition 8: STRUCTURAL schema steps run FIRST (they may spawn the board root and\n // rewrite relations the pack runner's entities already carry), then RENAMES\n // (design-008 §5 — type folds must precede the pack runner so version chains\n // operate on new-name cells; schema steps touch no pack markers, so the original\n // report's renamedInDoc is still exact), then the per-prefab pack runner, then ONE\n // re-gate off the freshly stamped markers. SINGLE-WRITER LAW: this branch is the\n // solo-open path only — a live-room joiner passes migrate:false (bootstrap) and\n // stays read-only on an old-schema doc.\n runSchemaMigrations({ store, world }, report);\n const renamed = runRenames({ store, world }, report);\n // A rename WRITES cells the pack runner READS through the world, and\n // local transactions project only at the next sync — without this\n // drain the chain would fold an empty record (the runners before it\n // never had a write→read dependency, so this is the first sync the\n // open path needs).\n if (renamed.renamed.length > 0) world.sync();\n runMigrations({ store, world }, readDocVersionReport(doc));\n effectiveReport = readDocVersionReport(doc);\n readOnly = gateVerdict(effectiveReport) !== \"ok\";\n } catch {\n // A faulting transform must never brick open(): keep the doc, fall back\n // read-only (the user still gets projection + presence). Re-read the\n // report — runMigrations plans all types before writing, so a transform\n // throw leaves the doc untouched, but a write-phase fault may have\n // stamped earlier types; session.report must describe the doc AS IS.\n effectiveReport = readDocVersionReport(doc);\n readOnly = true;\n }\n }\n // Petition 8: name the board root for ops/renderers when the doc has one (any schema-2\n // doc). Absent on a pre-schema-2 read-only doc — renderers fall back to the legacy\n // StackZ sort; never minted here on the read-only path (minting is a write).\n if (readOnly) {\n const root = resolveBoardRoot(world, store);\n if (root !== undefined) writeRuntimeResource(world, BoardRoot, { root });\n } else {\n writeRuntimeResource(world, BoardRoot, { root: ensureBoardRoot(world, store) });\n }\n return { ok: true, session: makeSession(world, doc, store, attachment, readOnly, effectiveReport) };\n } catch (err) {\n // Store/attach residuals (already-attached world, pending-import state,\n // mid-emit) quarantine like everything else on this path — open() NEVER\n // throws (review hardening; the corrupt-bytes exit bar extended to attach).\n try {\n attachment?.detach();\n world.reset();\n ensureCanvasSurface(world);\n } catch (rollbackErr) {\n return {\n ok: false,\n reason: `ice: attach failed — ${String(err)}; rollback failed — ${String(rollbackErr)}`,\n report,\n };\n }\n return { ok: false, reason: `ice: attach failed — ${String(err)}`, report };\n }\n}\n","/**\n * The prefab rename runner (design-008 §5, petition I5) — the open-path half.\n *\n * Runs in doc-kit's migrate branch AFTER the structural schema steps and\n * BEFORE the M9 pack runner, under the same SINGLE-WRITER LAW (solo-open\n * only; live joiners pass migrate:false and stay read-only). For each old id\n * the gate reported (`report.renamedInDoc` — old id → its doc pack version):\n *\n * 1. PLAN: every durable entity whose `PrefabId.id` is the old id; its\n * legacy `<old>:<group>` cells read through the world — they PROJECT\n * because `renamedFrom` registered same-shaped components under the old\n * names (design-008 §1.1: projection is name-registry-driven).\n * 2. WRITE, one non-undoable transaction per old id: PrefabId → new id;\n * each legacy value moved to the new-name group cell (absolute writes;\n * a defensively-present new cell wins — §6.2); legacy cells removed.\n * NO version-chain folding here — that is the pack runner's job, right\n * after, on the new names.\n * 3. STAMP (write-once): the tombstone `engine.renamed.<old>` = newId, and\n * the carried pack marker `engine.pack.<new>.<docOldV>`. The tombstone\n * makes the gate skip the undeletable old markers forever; the carried\n * marker preserves the doc's version evidence under the NEW id — without\n * it the fresh report would show no `olderInDoc` entry and the pack\n * runner would silently skip the migrate chain over v-old cells.\n *\n * Idempotence/convergence: absolute cell writes + write-once markers — two\n * solo peers folding the same doc produce identical cells that merge LWW\n * (the migrate.ts argument). A fault mid-plan writes nothing; a fault after\n * the fold but before the stamps re-runs cleanly (folded entities no longer\n * match the old id).\n */\nimport { defineQuery } from \"@vibecook/strata-ecs\";\nimport type { Component, Entity } from \"@vibecook/strata-ecs\";\nimport { PrefabId } from \"../schema/prefab\";\nimport { renames } from \"../widget/define-widget\";\nimport type { MigrationCtx } from \"./migrate\";\nimport type { DocVersionReport } from \"./version-gate\";\n\nconst PACK_PREFIX = \"engine.pack.\";\nconst RENAMED_PREFIX = \"engine.renamed.\";\n\nconst allDurableQ = defineQuery([PrefabId]);\n\nexport interface RenameOutcome {\n /** Old ids folded and tombstoned this open (marker-only docs still stamp). */\n readonly renamed: string[];\n}\n\ninterface EntityRenamePlan {\n readonly e: Entity;\n /** Legacy value per group index (undefined = cell absent on this entity). */\n readonly legacyValues: readonly (Record<string, unknown> | undefined)[];\n /** New-name cell already present per group index (defensive new-wins). */\n readonly newPresent: readonly boolean[];\n}\n\nexport function runRenames(ctx: MigrationCtx, report: DocVersionReport): RenameOutcome {\n const { store, world } = ctx;\n const renamed: string[] = [];\n\n for (const [oldId, docOldV] of Object.entries(report.renamedInDoc)) {\n const entry = renames.get(oldId);\n if (entry === undefined) continue; // registry changed mid-open — defensive\n const { widget, legacyGroups } = entry;\n\n // --- plan (reads only; a throw leaves the doc byte-identical) ---\n const plans: EntityRenamePlan[] = [];\n world.query(allDurableQ).each((batch) => {\n for (const row of batch) {\n const e = batch.entity(row);\n if (world.read(e, PrefabId).id !== oldId) continue;\n const legacyValues: (Record<string, unknown> | undefined)[] = [];\n const newPresent: boolean[] = [];\n for (let i = 0; i < widget.groups.length; i++) {\n const legacy = world.get(e, legacyGroups[i] as Component);\n legacyValues.push(legacy as Record<string, unknown> | undefined);\n newPresent.push(world.get(e, (widget.groups[i] as { component: Component }).component) !== undefined);\n }\n plans.push({ e, legacyValues, newPresent });\n }\n });\n\n // --- write: ONE non-undoable transaction per old id ---\n if (plans.length > 0) {\n store.transaction(\n (tx) => {\n for (const { e, legacyValues, newPresent } of plans) {\n tx.edit(e).set(PrefabId, { id: widget.type });\n for (let i = 0; i < widget.groups.length; i++) {\n const value = legacyValues[i];\n if (value === undefined) continue;\n if (!newPresent[i]) {\n tx.addComponent(e, (widget.groups[i] as { component: Component }).component, value);\n }\n tx.removeComponent(e, legacyGroups[i] as Component);\n }\n }\n },\n { undoable: false },\n );\n }\n\n // --- stamp: tombstone + carried pack version (write-once, after the fold) ---\n store.metaTransaction((meta) => {\n const tomb = `${RENAMED_PREFIX}${oldId}`;\n if (meta.get(tomb) === undefined) meta.set(tomb, widget.type);\n const pack = `${PACK_PREFIX}${widget.type}.${docOldV}`;\n if (meta.get(pack) === undefined) meta.set(pack, true);\n });\n renamed.push(oldId);\n }\n\n return { renamed };\n}\n","/**\n * The rename zombie sweep (design-008 §6, petition I5) — the live half.\n *\n * The open-path runner (rename.ts) folds a doc once, solo. The CRDT layer\n * then converges BYTES with any stale replica — but it cannot know that\n * `comp:old:props` and `comp:new:props` are the same cell, so three shapes of\n * pre-rename traffic can land post-rename as ordinary deliveries:\n *\n * - a value set on an old cell winning LWW over the fold's delete\n * (resurrection);\n * - a `PrefabId = old` set winning over the fold's rewrite;\n * - a whole LATE ENTITY spawned old-shape by an offline pre-rename peer.\n *\n * The sweep folds all three, deterministically, on EVERY writable current\n * peer — identical absolute writes converge (the migrate.ts argument), so\n * \"zero zombies\" is a sweep property the replicas share, not a CRDT freebie.\n *\n * MECHANISM (frame-contract-legal): `observeQuery` watchers on the legacy\n * components and on `PrefabId` fire at notify (in-frame) and only SCHEDULE —\n * `queueMicrotask` runs the fold after the rAF task, between frames, the same\n * slot ops occupy. Bursts coalesce on a pending flag; the fold's own writes\n * re-fire the watchers into one empty pass, then quiet. Steady state is free\n * (zero-match chunk skip), and the first-party observers arm strata's write\n * enforcement as a side effect. Why not fold inside `applyRemote`? The\n * delivery has not PROJECTED yet — world queries see it exactly when the\n * observer fires.\n *\n * CONFLICT RULE (design-008 §6.2, stated honestly): a legacy value moves into\n * an ABSENT new cell (chain-folded per §6.3); a legacy value beside a PRESENT\n * new cell is dropped — NEW WINS. The true LWW order between a stale edit and\n * post-rename edits lives in Loro's clocks, which the engine cannot consult\n * per cell; any fixed rule converges, and new-wins is the only one that never\n * clobbers post-rename work with pre-rename state. Late entities lose\n * nothing.\n *\n * VERSIONING (§6.3): legacy cells are only ever written by old builds, so a\n * moved value is shaped at `renamedFrom.atVersion`. When the widget's migrate\n * chain covers atVersion → current, the flat record chain-folds before the\n * per-group write (the migrate.ts fold, per entity); a gap leaves that\n * entity's legacy cells in place with a dev warning — the per-entity analogue\n * of the pack runner's skip-stays-read-only, because the sweep must not guess\n * a transform.\n */\nimport { Any, defineQuery } from \"@vibecook/strata-ecs\";\nimport type { Component, Entity, Query, World } from \"@vibecook/strata-ecs\";\nimport type { DurableStore } from \"@vibecook/strata-ecs/durable\";\nimport { PrefabId } from \"../schema/prefab\";\nimport { renames, type WidgetRenameEntry } from \"../widget/define-widget\";\n\nconst RENAMED_PREFIX = \"engine.renamed.\";\n\nconst prefabQ = defineQuery([PrefabId]);\n\n// Legacy queries cached per REGISTRY ENTRY, not per old-id string (2026-08-09\n// review): a re-registration of the same old id (tests, hot reload) mints a\n// new entry with possibly different legacy components — a string-keyed cache\n// would keep watching the previous registration's cells. WeakMap lets dead\n// entries and their queries go with the registry reset.\nconst legacyQByEntry = new WeakMap<WidgetRenameEntry, Query>();\nfunction legacyQueryOf(entry: WidgetRenameEntry): Query | undefined {\n if (entry.legacyGroups.length === 0) return undefined;\n let q = legacyQByEntry.get(entry);\n if (q === undefined) {\n q =\n entry.legacyGroups.length === 1\n ? defineQuery([entry.legacyGroups[0] as Component])\n : defineQuery([Any(...(entry.legacyGroups as Component[]))]);\n legacyQByEntry.set(entry, q);\n }\n return q;\n}\n\n/** Chain coverage atVersion..widget.version (the migrate.ts contiguity rule). */\nfunction chainCovered(entry: WidgetRenameEntry): boolean {\n for (let v = entry.atVersion; v < entry.widget.version; v++) {\n if (typeof entry.widget.migrate[v] !== \"function\") return false;\n }\n return true;\n}\n\ninterface FoldPlan {\n readonly e: Entity;\n readonly rewriteId: boolean;\n /** Chain-folded flat record spanning the entity's legacy groups (write source). */\n readonly folded: Record<string, unknown>;\n /** Group indices whose new cell is absent → written from `folded`. */\n readonly writeGroups: readonly number[];\n /** Legacy components present on the entity → removed. */\n readonly removeLegacy: readonly Component[];\n}\n\nexport function armRenameSweep(world: World, store: DurableStore): () => void {\n const entries = renames.all();\n if (entries.length === 0) return () => {};\n\n let pending = false;\n let disposed = false;\n const warnedGap = new Set<string>();\n\n const sweep = (): void => {\n for (const entry of entries) {\n const { widget, legacyGroups, oldType } = entry;\n const covered = chainCovered(entry);\n\n // --- plan: entities carrying the old id and/or any legacy cell ---\n const seen = new Set<Entity>();\n const plans: FoldPlan[] = [];\n const consider = (e: Entity): void => {\n if (seen.has(e)) return;\n seen.add(e);\n const id = world.get(e, PrefabId)?.id;\n const rewriteId = id === oldType;\n let anyLegacy = false;\n const flat: Record<string, unknown> = {};\n const removeLegacy: Component[] = [];\n for (let i = 0; i < widget.groups.length; i++) {\n const legacy = world.get(e, legacyGroups[i] as Component);\n if (legacy === undefined) continue;\n anyLegacy = true;\n Object.assign(flat, legacy as Record<string, unknown>);\n removeLegacy.push(legacyGroups[i] as Component);\n }\n if (!rewriteId && !anyLegacy) return;\n // A foreign-typed entity carrying legacy cells is unfoldable — leave it visible.\n if (!rewriteId && anyLegacy && id !== widget.type) return;\n if (anyLegacy && !covered) {\n if (!warnedGap.has(oldType)) {\n warnedGap.add(oldType);\n console.warn(\n `ice: rename sweep — \"${oldType}\" values are at pack v${entry.atVersion} but \"${widget.type}\"'s migrate chain has a gap; leaving legacy cells in place (design-008 §6.3).`,\n );\n }\n return;\n }\n let folded = flat;\n for (let v = entry.atVersion; v < widget.version; v++) {\n const step = widget.migrate[v];\n if (typeof step === \"function\") folded = step(folded);\n }\n const writeGroups: number[] = [];\n if (anyLegacy) {\n for (let i = 0; i < widget.groups.length; i++) {\n const present = world.get(e, (widget.groups[i] as { component: Component }).component) !== undefined;\n if (!present) writeGroups.push(i); // new-wins: present cells keep their value\n }\n }\n plans.push({ e, rewriteId, folded, writeGroups, removeLegacy });\n };\n\n // The full PrefabId walk runs ONLY for zero-prop renames (no legacy\n // components to observe). For prop-bearing renames every reachable\n // zombie shape carries a legacy cell — an old build writes PrefabId\n // exactly once, at spawn, alongside its group cells, and no op it can\n // emit rewrites the id afterward — so the legacy-component pass below\n // is complete on its own and the O(entities) scan would be pure waste\n // on every spawn (2026-08-09 review).\n if (legacyGroups.length === 0) {\n world.query(prefabQ).each((batch) => {\n for (const row of batch) {\n const e = batch.entity(row);\n if (world.read(e, PrefabId).id === oldType) consider(e);\n }\n });\n }\n const legacyQ = legacyQueryOf(entry);\n if (legacyQ !== undefined) {\n world.query(legacyQ).each((batch) => {\n for (const row of batch) consider(batch.entity(row));\n });\n }\n if (plans.length === 0) continue;\n\n // --- write: one non-undoable transaction per old id, then tombstone ---\n store.transaction(\n (tx) => {\n for (const plan of plans) {\n if (plan.rewriteId) tx.edit(plan.e).set(PrefabId, { id: widget.type });\n for (const i of plan.writeGroups) {\n tx.addComponent(plan.e, (widget.groups[i] as { component: Component }).component, plan.folded);\n }\n for (const legacy of plan.removeLegacy) tx.removeComponent(plan.e, legacy);\n }\n },\n { undoable: false },\n );\n store.metaTransaction((meta) => {\n const tomb = `${RENAMED_PREFIX}${oldType}`;\n if (meta.get(tomb) === undefined) meta.set(tomb, widget.type);\n });\n }\n };\n\n const schedule = (): void => {\n if (pending || disposed) return;\n pending = true;\n queueMicrotask(() => {\n pending = false;\n if (!disposed) sweep();\n });\n };\n\n const watchers: Array<() => void> = [];\n let anyZeroProp = false;\n for (const entry of entries) {\n const q = legacyQueryOf(entry);\n if (q !== undefined) {\n watchers.push(world.reactive.observeQuery(q, schedule, { cols: [...(entry.legacyGroups as Component[])] }));\n } else {\n anyZeroProp = true;\n }\n }\n // The wide PrefabId watcher arms ONLY when some rename has no legacy\n // components to observe (a zero-prop widget's late entity carries nothing\n // but PrefabId + geometry). For every prop-bearing rename the legacy\n // watchers above are complete (see the sweep's reachability note), and\n // arming this unconditionally made EVERY widget spawn schedule a full\n // O(entities × renames) scan for the session's lifetime.\n if (anyZeroProp) {\n watchers.push(world.reactive.observeQuery(prefabQ, schedule, { cols: [PrefabId] }));\n }\n\n return () => {\n disposed = true;\n for (const u of watchers) u();\n };\n}\n","/**\n * STRUCTURAL schema migrations (petition 8; engineSchema 1 → 2).\n *\n * The per-prefab runner (migrate.ts) folds per-entity group values — it cannot spawn entities,\n * see siblings, write relations, or stamp `engine.schema`, so a schema-version bump used to\n * leave old docs read-only FOREVER (the gate re-ran, saw docSchema < local, and nothing ever\n * advanced it). This module is the missing half: whole-document transforms keyed by the schema\n * version they migrate FROM, run at open on a \"migrate\" verdict BEFORE the pack runner, each\n * stamping `engine.schema.<n+1>` on success.\n *\n * SINGLE-WRITER LAW: a structural migration may only run when this peer is the document's sole\n * occupant — the local open path (autosave restore, file open). A LIVE-ROOM JOINER MUST NOT\n * migrate (bootstrap passes `migrate: false`): the room's peers are still writing the old\n * shape, sync never re-gates, and a mid-room migration split-brains the doc (old peers write\n * scalar z the new shape ignores, and vice versa). An old-schema doc joined live is read-only\n * until it is opened solo by a current build.\n *\n * Step 1→2 — ordered relations:\n * 1. BOARD ROOT: mint the componentless durable entity root-level widgets hang `ChildOf` on\n * ({@link ensureBoardRoot}); its key is recorded first-writer-wins in the meta map.\n * 2. StackZ → sibling order: every durable widget is grouped by parent scope (existing\n * `ChildOf` target, else the board root), each group sorted by `(z asc, entityKey asc)`,\n * and re-linked in that order with `tx.setRelation(e, ChildOf, parent, \"last\")` — a\n * same-target re-set WITH a place is a move, so applying in sorted order lands the sorted\n * sequence; root-level widgets gain their first edge the same way. ONE non-undoable\n * transaction; absolute, idempotent, convergent (same doc → same sort → same sequence).\n * 3. The legacy `StackZ` CELLS ARE KEPT: an old build opening the migrated doc read-only\n * (docSchema newer than local) still paints z-correct from them. New entities never write\n * StackZ; the cells are simply never read by current builds outside the legacy fallback.\n */\nimport type { Entity, EntityKey, World } from \"@vibecook/strata-ecs\";\nimport { defineQuery } from \"@vibecook/strata-ecs\";\nimport type { DurableStore } from \"@vibecook/strata-ecs/durable\";\nimport { ChildOf, StackZ } from \"../catalog/scene\";\nimport { PrefabId } from \"../schema/prefab\";\nimport type { MigrationCtx } from \"./migrate\";\nimport { ENGINE_SCHEMA_VERSION } from \"./envelope\";\nimport type { DocVersionReport } from \"./version-gate\";\n\nconst SCHEMA_PREFIX = \"engine.schema.\";\n/** Meta key holding the board-root's EntityKey (a VALUE key, unlike the presence markers). */\nconst BOARD_ROOT_META = \"engine.boardRoot\";\n\n// Durable-identity + legacy-z queries (module singletons; defineQuery interns).\nconst allDurableQ = defineQuery([PrefabId]);\n\n/**\n * Resolve the document's board root, minting it if absent (create path + step 1→2). The mint\n * is a componentless `tx.spawn()` in a non-undoable transaction; the key is recorded in meta\n * first-writer-wins and re-read after the write so a raced winner is honored (the single-writer\n * law makes a race unreachable in practice — belt and braces). Returns the LIVE handle.\n */\nexport function ensureBoardRoot(world: World, store: DurableStore): Entity {\n let recorded: string | undefined;\n store.metaTransaction((meta) => {\n const v = meta.get(BOARD_ROOT_META);\n if (typeof v === \"string\") recorded = v;\n });\n if (recorded !== undefined) {\n const e = store.resolve(recorded as EntityKey);\n if (e !== undefined && world.isAlive(e)) return e;\n }\n const minted = store.transaction((tx) => tx.spawn(), { undoable: false });\n const mintedKey = store.keyOf(minted);\n if (mintedKey === undefined) throw new Error(\"ice: board-root mint failed to bind a key.\");\n store.metaTransaction((meta) => {\n if (meta.get(BOARD_ROOT_META) === undefined) meta.set(BOARD_ROOT_META, mintedKey as unknown as string);\n });\n let winner: string = mintedKey as unknown as string;\n store.metaTransaction((meta) => {\n const v = meta.get(BOARD_ROOT_META);\n if (typeof v === \"string\") winner = v;\n });\n return store.resolve(winner as EntityKey) ?? minted;\n}\n\n/** Read the board-root handle WITHOUT minting — read-only opens and post-attach lookups. */\nexport function resolveBoardRoot(world: World, store: DurableStore): Entity | undefined {\n let recorded: string | undefined;\n store.metaTransaction((meta) => {\n const v = meta.get(BOARD_ROOT_META);\n if (typeof v === \"string\") recorded = v;\n });\n if (recorded === undefined) return undefined;\n const e = store.resolve(recorded as EntityKey);\n return e !== undefined && world.isAlive(e) ? e : undefined;\n}\n\n/** Step 1→2: board root + StackZ→sibling-order rewrite (header). */\nfunction migrateToOrderedRelations(ctx: MigrationCtx): void {\n const { store, world } = ctx;\n const root = ensureBoardRoot(world, store);\n\n // Group every durable widget by parent scope; sort each group (z asc, entityKey asc).\n const groups = new Map<Entity, { e: Entity; z: number; key: string }[]>();\n world.query(allDurableQ).each((batch) => {\n for (const row of batch) {\n const e = batch.entity(row);\n if (e === root) continue;\n const key = store.keyOf(e);\n if (key === undefined) continue;\n const parent = world.getRelation(e, ChildOf) ?? root;\n const z = world.get(e, StackZ)?.z ?? 0; // legacy cell; absent (post-flip spawns) sorts at 0\n let g = groups.get(parent);\n if (g === undefined) {\n g = [];\n groups.set(parent, g);\n }\n g.push({ e, z, key: key as unknown as string });\n }\n });\n for (const g of groups.values()) {\n g.sort((a, b) => (a.z !== b.z ? a.z - b.z : a.key < b.key ? -1 : a.key > b.key ? 1 : 0));\n }\n\n // ONE non-undoable transaction: re-link in sorted order. Same-target re-set WITH a place is\n // a move (never a duplicate), so this is exact for already-parented children and appends\n // root-level widgets in sorted order.\n store.transaction(\n (tx) => {\n for (const [parent, g] of groups) {\n for (const { e } of g) tx.setRelation(e, ChildOf, parent, \"last\");\n }\n },\n { undoable: false },\n );\n}\n\n/** Structural steps keyed by the schema version they migrate FROM. */\nconst STEPS: Record<number, (ctx: MigrationCtx) => void> = {\n 1: migrateToOrderedRelations,\n};\n\n/**\n * Run the structural chain `docSchema → … → localSchema`, stamping `engine.schema.<n+1>` after\n * each step. A gap (missing step) stops the walk — the caller's re-gate keeps the doc\n * read-only, exactly like a gappy pack chain. A docSchema of 0 is the gate's \"reject\" domain\n * and never reaches here. Returns true when the doc reached the local schema version.\n */\nexport function runSchemaMigrations(ctx: MigrationCtx, report: DocVersionReport): boolean {\n let v = report.docSchema;\n while (v < ENGINE_SCHEMA_VERSION) {\n const step = STEPS[v];\n if (step === undefined) return false;\n step(ctx);\n const reached = v + 1;\n ctx.store.metaTransaction((meta) => {\n const key = `${SCHEMA_PREFIX}${reached}`;\n if (meta.get(key) === undefined) meta.set(key, true);\n });\n v = reached;\n }\n return true;\n}\n","/**\n * `createBehaviorHarness` — the testing story, shipped WITH the framework\n * rather than after it (design-009 §7).\n *\n * A behavior is frame-cadence, collaboration-native, transaction-writing code.\n * Testing that without a rig means standing up an engine, a document, a\n * pipeline and a hand-driven clock — enough ceremony that most authors would\n * simply not test the interesting parts. The interesting parts are exactly the\n * ones they will get wrong:\n *\n * - `claim(e)` fakes a live gesture claim, so an author can see their derived\n * behavior go quiet during a drag and coalesce at the settle. Suppression\n * is the single most surprising rule in the framework.\n * - `pair()` gives a SECOND engine on the same document. Convergence bugs are\n * invisible on one peer by definition, and \"it works for me\" is what a\n * collaborative editor's bug reports look like.\n * - `commits` records what actually reached the store, which is how you tell\n * \"the differ dropped it\" from \"it never ran\".\n */\nimport { createWorld, defineQuery, type Entity, type Query, type World } from \"@vibecook/strata-ecs\";\nimport { Captures, ChildOf, GestureActive, Position, Size } from \"../catalog\";\nimport { createEngine, type Engine } from \"../engine/engine\";\nimport { createDocSession, openDocSession, type DocSession } from \"../doc/doc-kit\";\nimport { guardedTransaction } from \"../guards/guarded-tx\";\nimport { definePrefab, init, prefabs, type Prefab } from \"../schema/prefab\";\nimport { createBehaviorRuntime, type BehaviorRuntime, type BehaviorSession } from \"./runtime\";\nimport type { AnyBehaviorDef } from \"./types\";\n\n/** One commit the harness observed reaching the store. */\nexport interface HarnessCommit {\n readonly undoable: boolean;\n /** `{ behavior, label }` for a `ctx.commit`; undefined for anything else. */\n readonly meta: Record<string, unknown> | undefined;\n}\n\nexport interface BehaviorHarnessOpts {\n /**\n * Attach a document. Default TRUE — durable behaviors need one, and a\n * runtime behavior is unharmed by having it. `false` exercises the doc-less\n * path deliberately (where `ctx.commit` refuses, by design).\n */\n readonly docs?: boolean;\n /** Extra behaviors to register beside the one under test. */\n readonly also?: readonly AnyBehaviorDef[];\n}\n\nexport interface BehaviorHarness {\n readonly world: World;\n readonly engine: Engine;\n readonly runtime: BehaviorRuntime;\n doc(): DocSession | undefined;\n /** Drive `n` frames (default 1). The clock advances 16ms per frame. */\n step(n?: number): void;\n /** A bare durable node with Position + Size, for behaviors to ride. */\n spawn(x?: number, y?: number): Entity;\n /** Attach the behavior under test — durable through a transaction, else direct. */\n attach(e: Entity, data?: Record<string, unknown>): void;\n detach(e: Entity): void;\n /** The behavior's live instances, as the runtime sees them. */\n instances(): readonly Entity[];\n /** Every commit that reached the store since construction. */\n readonly commits: readonly HarnessCommit[];\n /** Simulate a live gesture claim on `e`. Returns the release. */\n claim(e: Entity): () => void;\n /** A SECOND engine on this document — the two-peer rig. */\n pair(): BehaviorHarness;\n /** Exchange updates with every paired harness, both ways. */\n sync(): void;\n dispose(): void;\n}\n\nconst HARNESS_PREFAB_ID = \"ice.harness.node\";\n\nfunction harnessPrefab(): Prefab {\n return (\n prefabs.get(HARNESS_PREFAB_ID) ??\n definePrefab(HARNESS_PREFAB_ID, {\n store: \"durable\",\n components: [init(Position, { x: 0, y: 0 }), init(Size, { w: 100, h: 100 })],\n relations: [ChildOf],\n })\n );\n}\n\nexport function createBehaviorHarness(b: AnyBehaviorDef, opts: BehaviorHarnessOpts = {}): BehaviorHarness {\n const peers: BehaviorHarness[] = [];\n const root = build(b, opts, peers, undefined);\n peers.push(root);\n return root;\n}\n\nfunction build(\n b: AnyBehaviorDef,\n opts: BehaviorHarnessOpts,\n peers: BehaviorHarness[],\n seed: Uint8Array | undefined,\n): BehaviorHarness {\n const world = createWorld();\n const engine = createEngine(world);\n const commits: HarnessCommit[] = [];\n let session: DocSession | undefined;\n\n if (opts.docs !== false) {\n if (seed === undefined) {\n session = createDocSession(world);\n } else {\n const opened = openDocSession(world, seed);\n if (!opened.ok) throw new Error(`ice: behavior harness pair() could not open the seed doc — ${opened.reason}`);\n session = opened.session;\n }\n }\n\n // The recording shim: `ctx.commit` is the only way a behavior reaches the\n // document, so wrapping the store's transaction is how the harness can say\n // \"nothing was committed\" — a claim the differ makes constantly and that no\n // amount of reading final values can confirm.\n const view: BehaviorSession | undefined =\n session === undefined\n ? undefined\n : ({\n get readOnly() {\n return session?.readOnly ?? true;\n },\n get liveWriter() {\n return session?.liveWriter;\n },\n store: {\n transaction: (fn: never, o?: { undoable?: boolean; meta?: Record<string, unknown> }) => {\n commits.push({ undoable: o?.undoable !== false, meta: o?.meta });\n return session?.store.transaction(fn as never, o as never);\n },\n keyOf: (e: Entity) => session?.store.keyOf(e),\n resolve: (k: never) => session?.store.resolve(k),\n getComponent: (e: Entity, c: never) => session?.store.getComponent(e, c),\n get snapshot() {\n // `snapshot` is on the store CLASS, not the published\n // `DurableStore` interface — the behavior marker family reads\n // through it (behavior/migrate.ts), so the harness forwards it.\n return (session?.store as unknown as { snapshot?: unknown } | undefined)?.snapshot;\n },\n metaTransaction: (fn: never) => session?.store.metaTransaction(fn as never),\n },\n } as unknown as BehaviorSession);\n\n const runtime = createBehaviorRuntime({\n world,\n engine,\n session: () => view,\n onLog: () => {},\n });\n for (const extra of opts.also ?? []) runtime.register(extra);\n runtime.register(b);\n\n let clock = 0;\n const prefab = harnessPrefab();\n\n const harness: BehaviorHarness = {\n world,\n engine,\n runtime,\n commits,\n doc: () => session,\n\n step(n = 1) {\n for (let i = 0; i < n; i++) {\n clock += 16;\n engine.step(clock);\n }\n },\n\n spawn(x = 0, y = 0) {\n if (session === undefined) {\n return world.spawn({ components: [[Position, { x, y }], [Size, { w: 100, h: 100 }]] });\n }\n let e: Entity | undefined;\n guardedTransaction(\n session.store,\n world,\n (tx) => {\n e = tx.spawnPrefab(prefab, [[Position, { x, y }]]);\n },\n { undoable: false },\n );\n world.sync(); // the spawn projects at the next sync\n return e as Entity;\n },\n\n attach(e, data) {\n if (b.store !== \"durable\") {\n runtime.attach(e, b, data);\n return;\n }\n if (session === undefined) throw new Error(\"ice: behavior harness — a durable behavior needs docs: true.\");\n session.store.transaction((tx) => {\n tx.addComponent(e, b.component, { ...(b.defaults as Record<string, unknown>), ...(data ?? {}) });\n });\n world.sync();\n },\n\n detach(e) {\n if (b.store !== \"durable\") {\n runtime.detach(e, b);\n return;\n }\n session?.store.transaction((tx) => tx.removeComponent(e, b.component));\n world.sync();\n },\n\n instances() {\n const out: Entity[] = [];\n // Read through the world rather than the runtime's private registry: a\n // test asserting on instances should see what the WORLD says, or it can\n // pass while the two have quietly disagreed.\n for (const e of allEntitiesWith(world, b)) out.push(e);\n return out;\n },\n\n claim(e) {\n // The engine's own claim shape: an ACTIVE recognizer that `Captures` the\n // target. Discrete claims deliberately do not count (design-001 §3).\n const recognizer = world.spawn({});\n world.setRelation(recognizer, Captures, e);\n world.addTag(recognizer, GestureActive);\n return () => {\n if (world.isAlive(recognizer)) world.destroy(recognizer);\n };\n },\n\n pair() {\n if (session === undefined) throw new Error(\"ice: behavior harness pair() needs a document (docs: true).\");\n const bytes = session.exportEnvelope();\n const peer = build(b, opts, peers, bytes);\n peers.push(peer);\n return peer;\n },\n\n sync() {\n // Full-snapshot exchange, both ways, until every peer has seen every\n // other. Crude next to a real transport and exactly right for a rig: the\n // property under test is convergence, not the wire.\n for (const from of peers) {\n const src = from.doc();\n if (src === undefined) continue;\n const bytes = src.exportSnapshot();\n for (const to of peers) {\n if (to === from) continue;\n to.doc()?.applyRemote(bytes);\n }\n }\n for (const peer of peers) peer.world.sync();\n },\n\n dispose() {\n runtime.dispose();\n session?.close();\n session = undefined;\n const i = peers.indexOf(harness);\n if (i !== -1) peers.splice(i, 1);\n },\n };\n\n return harness;\n}\n\nfunction allEntitiesWith(world: World, b: AnyBehaviorDef): Entity[] {\n const out: Entity[] = [];\n world.query(behaviorQuery(b)).each((batch) => {\n for (const row of batch) out.push(batch.entity(row));\n });\n return out;\n}\n\n// Cached on the handle: `defineQuery` identity is strata's own cache key for\n// the matched-archetype list, so re-compiling per call defeats two caches.\nconst queryCache = new WeakMap<object, Query>();\nfunction behaviorQuery(b: AnyBehaviorDef): Query {\n let q = queryCache.get(b as object);\n if (q === undefined) {\n q = defineQuery([b.component]);\n queryCache.set(b as object, q);\n }\n return q;\n}\n","/**\n * The behavior runtime (design-009 §4.3, §5.1, §5.2) — one delivery loop for\n * every behavior, compiled onto the guest breaker rather than beside it.\n *\n * Delivery order, per frame, at the behavior's phase:\n *\n * drain → init (appeared) → update → changed → tick → dispose (departed)\n *\n * The instance list is a SNAPSHOT taken at phase entry, so a hook that attaches\n * or detaches affects the NEXT frame — the live-array lesson from the publish\n * and reflector loops, applied before it could bite here.\n *\n * TWO COLLECTORS, not one. Own-component churn and reads churn mean different\n * things to an author — \"update is about you, changed is about the world\" — and\n * a single collector cannot tell them apart after the drain, because the delta\n * reports ENTITIES, not which component moved. Merging them would fire\n * `changed` on every own-data write, which is exactly the hook authors put\n * expensive whole-graph work in. The cost of honesty is one extra drain.\n *\n * Change delivery rides strata's REAL change detection, which is why every\n * behavior is collaboration-native with zero author code: `applyRemote`\n * journals into collectors exactly like a local write, so `update` fires for a\n * remote peer's edit and for a local undo through the same path.\n */\nimport { Local, Not, defineQuery, type Query } from \"@vibecook/strata-ecs\";\nimport { valueEquals } from \"@vibecook/strata-ecs\";\nimport type {\n Batch,\n ChangeCollector,\n Component,\n Entity,\n Relation,\n Resource,\n SystemCtx,\n Tag,\n World,\n} from \"@vibecook/strata-ecs\";\nimport type { DrivenGuest, GuestRegistry } from \"../engine/guests\";\nimport { Captures, Drags, GestureActive } from \"../catalog/gesture\";\nimport { FrameInfo } from \"../engine/frame-info\";\nimport type { PhaseGroup } from \"../engine/pipeline\";\nimport { devGuardsEnabled } from \"../guards/dev\";\nimport type { LiveWriter } from \"../guards/live-writer\";\nimport { guardedTransaction } from \"../guards/guarded-tx\";\nimport type { GuardedTx } from \"../guards/guarded-tx\";\nimport type { JsonSpec, PropSpec } from \"../widget/props\";\nimport { compileBehavior, type BehaviorSystemHooks, type CompiledBehavior } from \"./compile\";\nimport { diffOps, recordDerivedOps, replayOps } from \"./differ\";\nimport {\n classifyBehaviorVersion,\n docBehaviorVersion,\n runBehaviorMigration,\n stampBehaviorMarker,\n type BehaviorMeta,\n} from \"./migrate\";\nimport {\n allowedQueryTerms,\n createBehaviorWorld,\n createQueryScope,\n publishWalker,\n systemWalker,\n type BehaviorWalker,\n} from \"./world-view\";\nimport type {\n AnyBehaviorDef,\n BehaviorChanges,\n BehaviorCtxBase,\n BehaviorFrame,\n BehaviorTx,\n} from \"./types\";\n\n/** The slice of a doc session the runtime needs (structural: tests fake it). */\nexport interface BehaviorSession {\n readonly readOnly: boolean;\n readonly liveWriter: LiveWriter;\n readonly store: {\n transaction(fn: (tx: never) => void, opts?: { undoable?: boolean }): void;\n keyOf(e: Entity): unknown;\n resolve(key: never): Entity | undefined;\n getComponent<S>(e: Entity, c: Component<S>): S | undefined;\n /** The version-marker surface (behavior/migrate.ts). Absent = no markers. */\n readonly snapshot?: BehaviorMeta;\n metaTransaction?(fn: (meta: { get(key: string): unknown; set(key: string, value: string): void }) => void): void;\n };\n}\n\n/**\n * The slice of a presence session an ephemeral behavior needs. Structural so\n * tests can fake it, and a FUNCTION on the opts so it can swap with the doc —\n * presence attaches and detaches with `docs.join`, and a behavior installed\n * before either must simply lie dormant until one exists.\n */\nexport interface BehaviorPresence {\n /** The local peer entity. A GETTER upstream: a world reset re-mints it. */\n readonly localPeer: Entity;\n readonly eph: {\n addComponent(e: Entity, c: Component<unknown>, v: unknown): void;\n removeComponent(e: Entity, c: Component): void;\n edit(e: Entity): { set(c: Component<unknown>, v: unknown): unknown };\n };\n}\n\nexport interface BehaviorRuntimeOpts {\n readonly world: World;\n readonly engine: {\n addSystems(group: PhaseGroup, ...systems: readonly never[]): () => void;\n readonly guests: GuestRegistry;\n onPublish(hook: (world: World) => void): () => void;\n };\n /** The FORWARDING session seam — the target swaps per doc open/close. */\n readonly session?: () => BehaviorSession | undefined;\n /**\n * The presence seam. Absent (or returning undefined) leaves every ephemeral\n * behavior DORMANT — installed, costing nothing, publishing nothing. That is\n * honest state, not a failure: a presence-less engine has no peer to be.\n */\n readonly presence?: () => BehaviorPresence | undefined;\n readonly onLog?: (behavior: string, message: string, rest: readonly unknown[]) => void;\n /**\n * A contained hook fault. Defaults to `console.error`. Hosts route this: a\n * quarantined instance in a derived behavior means part of the document\n * silently stops updating, which reads to a user as a broken document.\n */\n readonly onFault?: (behavior: string, hook: string, entity: Entity | undefined, err: unknown) => void;\n}\n\nexport interface BehaviorStatus {\n readonly name: string;\n readonly store: string;\n readonly phase: string;\n readonly instances: number;\n /** Instances quarantined by repeated hook throws (BF-D18). */\n readonly failed: number;\n readonly ticking: number;\n readonly suspended: boolean;\n}\n\nexport interface BehaviorRuntime {\n /** Compile + install a behavior. Returns an uninstaller. */\n register(b: AnyBehaviorDef): () => void;\n registered(): readonly AnyBehaviorDef[];\n /** Runtime/ephemeral attach from OUTSIDE a hook (the facade surface). */\n attach(e: Entity, b: AnyBehaviorDef, data?: Record<string, unknown>): void;\n detach(e: Entity, b: AnyBehaviorDef): void;\n has(e: Entity, b: AnyBehaviorDef): boolean;\n read(e: Entity, b: AnyBehaviorDef): Record<string, unknown> | undefined;\n list(): readonly BehaviorStatus[];\n dispose(): void;\n}\n\n/** One entity's watched state at the moment a commit sealed (see `echo`). */\ninterface EchoSnapshot {\n readonly cells: readonly [Component, unknown][];\n readonly tags: readonly [Tag, boolean][];\n}\n\n/** How many consecutive throws quarantine ONE instance (BF-D18). */\nconst INSTANCE_THROW_LIMIT = 3;\n\n/** Suppressed frames before the dev-warn names the behavior and the claimant. */\nconst SUPPRESSION_WARN_FRAMES = 600;\n\n/**\n * Is `e` under a LIVE gesture claim right now?\n *\n * Deliberately NARROWER than `makeDefaultMayDiverge`: a `TransformTween` also\n * grants divergence, but a glide is not a gesture — suppressing derives for the\n * duration of every fly-back would stall exactly the reflow the fly-back is\n * waiting for.\n */\nfunction isClaimed(world: World, e: Entity): boolean {\n if (!world.isAlive(e)) return false;\n for (const claimant of world.getReverse(e, Captures)) {\n if (world.hasTag(claimant, GestureActive)) return true;\n }\n for (const claimant of world.getReverse(e, Drags)) {\n if (world.hasTag(claimant, GestureActive)) return true;\n }\n return false;\n}\n\n/**\n * A patch → the ABSOLUTE whole-cell value a write commits (Law 5). Fields the\n * patch omits are read back off the entity when it already carries the\n * behavior, and only fall to the declared defaults when it does not — which is\n * what makes attach-when-attached an idempotent no-op that PRESERVES existing\n * data rather than resetting it.\n *\n * Module-scope on purpose: `tx.attach(e, Other)` may name a behavior this\n * engine never registered, and the earlier node-bound version silently fell\n * back to bare defaults there — clobbering the very data the idempotence rule\n * exists to protect.\n */\nfunction cellForBehavior(\n world: World,\n b: AnyBehaviorDef,\n e: Entity | undefined,\n patch: Record<string, unknown>,\n): Record<string, unknown> {\n const c = b.component as unknown as Component<Record<string, unknown>>;\n const carries = e !== undefined && world.isAlive(e) && world.has(e, c as unknown as Component);\n const out: Record<string, unknown> = {};\n for (const [f, spec] of Object.entries(b.schema)) {\n const given = patch[f];\n if (given !== undefined) {\n out[f] = (spec as PropSpec).kind === \"json\" ? JSON.stringify(given) : given;\n continue;\n }\n out[f] = carries ? world.readField(e as Entity, c, f) : (b.defaults as Record<string, unknown>)[f];\n }\n return out;\n}\n\ninterface Instance {\n readonly e: Entity;\n /** The last DELIVERED cell (raw, retained) — `update`'s `prev`. */\n prevCell: Record<string, unknown>;\n inited: boolean;\n /** Quarantined: hooks stop until re-attach. Doctor-visible. */\n failed: boolean;\n consecutiveThrows: number;\n}\n\nexport function createBehaviorRuntime(opts: BehaviorRuntimeOpts): BehaviorRuntime {\n const { world } = opts;\n const nodes = new Map<string, Node>();\n const onFault =\n opts.onFault ??\n ((behavior: string, hook: string, entity: Entity | undefined, err: unknown) => {\n console.error(`[ice] behavior \"${behavior}\" ${hook}${entity === undefined ? \"\" : ` on entity ${entity}`} threw`, err);\n });\n const onLog =\n opts.onLog ??\n ((behavior: string, message: string, rest: readonly unknown[]) => {\n console.log(`[ice:${behavior}] ${message}`, ...rest);\n });\n\n // ONE reset watch for the whole runtime. Structural writes are illegal inside\n // an observer emit, so this only MARKS: every node rebuilds at the top of its\n // own delivery body, in its own phase, where writes are legal again.\n const stopResetWatch = world.observe({\n onReset: () => {\n for (const n of nodes.values()) n.markGeneration();\n },\n });\n\n class Node {\n readonly b: AnyBehaviorDef;\n readonly compiled: CompiledBehavior;\n readonly own: Component;\n /** The same handle, typed for `readField`'s keyof-based field parameter. */\n readonly ownFields: Component<Record<string, unknown>>;\n readonly guest: DrivenGuest;\n readonly ownQuery: Query;\n /** Ephemeral only: REMOTE peers' facets of this behavior (read-only). */\n readonly peersQuery: Query | undefined;\n /** Ephemeral only: the local peer this node last published a facet on. */\n private facetPeer: Entity | undefined;\n /** The session whose version state has already been checked (§5.6). */\n private checkedSession: unknown;\n /**\n * The doc holds NEWER data than this build understands. Projection is\n * version-blind — a known name at a newer version projects straight into\n * older hooks — so dormancy has to be ACTIVE, not free.\n */\n private dormant = false;\n readonly instances = new Map<Entity, Instance>();\n readonly fieldNames: readonly string[];\n readonly jsonFields: readonly string[];\n readonly schema: Readonly<Record<string, PropSpec>>;\n\n private ownCollector: ChangeCollector | undefined;\n private readsCollector: ChangeCollector | undefined;\n private generation = new AbortController();\n private generationDirty = false;\n private seeded = false;\n /** Collectors detached because the breaker suspended us (see `goCold`). */\n private cold = false;\n private removeSystems: (() => void) | undefined;\n\n /** Stashed by `shouldDeliver` for the body — the drain-and-stash idiom. */\n private stash:\n | { full: boolean; ownChanged: readonly Entity[]; ownRemoved: readonly Entity[]; readsFired: boolean; readsChanged: readonly Entity[]; readsRemoved: readonly Entity[] }\n | undefined;\n\n /**\n * The ECHO snapshot (§3 own-write subtraction): for every entity this\n * behavior's last commit wrote, the values of every component it watches,\n * captured immediately after the seal.\n *\n * Why it exists: a derived commit journals the entities it just wrote, the\n * next frame reads that as churn, recomputes, diffs everything away and\n * commits nothing. One wasted full recompute per change event. Subtracting\n * the echo makes a derived behavior quiesce in ONE frame.\n *\n * Why it stores VALUES and not just entity ids: the journal reports\n * ENTITIES, not components, so an id-only subtraction cannot tell our own\n * echo from a real write that landed on the same entity inside the same\n * drain window — and it would DROP that real write permanently, since\n * nothing will journal it again. Comparing the watched values answers the\n * question exactly: unchanged everywhere means the entry was ours.\n *\n * \"Watched\" means EVERY subscription, tags included. Snapshotting only the\n * components left a hole with the same shape as the one this whole memo\n * exists to avoid: a tag in the reads set flipping on an entity we had just\n * written looked identical to our own echo, and was swallowed.\n */\n private echo: Map<Entity, EchoSnapshot> = new Map();\n\n /** Poll state (relations and resources cannot journal — see §5.2). */\n private readonly resourceStamps = new Map<Resource, number>();\n private readonly parentStamps = new Map<Entity, number>();\n private parentsDirty = true;\n\n // Scratch — reused between hook calls by DEFAULT (at 10k instances fresh\n // objects are ~600k allocs/sec). The do-not-retain rule in the docs is what\n // pays for this; it applies to `data`, `prev`, `changes()` and\n // `changedEntities()` alike.\n private readonly scratchCell: Record<string, unknown> = {};\n private readonly scratchData: Record<string, unknown>;\n private readonly scratchPrevData: Record<string, unknown>;\n\n private snapshot: Entity[] = [];\n /** What `ctx.entities()` reports for the CURRENTLY RUNNING pass. */\n private visible: Entity[] = [];\n /** Instances held back by a live claim (§5.3) — instance-scoped, always. */\n private readonly suppressed = new Set<Entity>();\n /** Consecutive suppressed frames per instance (the dev-warn's counter). */\n private readonly suppressedFrames = new Map<Entity, number>();\n /** Churn seen while suppressed — replayed in the coalesced delivery. */\n private readonly carry = new Set<Entity>();\n private changesView: BehaviorChanges = { full: false, changed: [], removed: [] };\n private changedEntitiesCache: Entity[] | undefined;\n /** Set for the duration of a delivery/tick pass; see BehaviorWalker. */\n private walker: BehaviorWalker | undefined;\n private readonly ctx: BehaviorCtxBase<Record<string, unknown>> & Record<string, unknown>;\n\n constructor(b: AnyBehaviorDef) {\n this.b = b;\n this.own = b.component as Component;\n this.ownFields = b.component as unknown as Component<Record<string, unknown>>;\n this.schema = b.schema;\n this.fieldNames = Object.keys(b.schema);\n this.jsonFields = this.fieldNames.filter((f) => (b.schema[f] as PropSpec).kind === \"json\");\n // With no json fields the data view IS the raw cell — one object, no copy.\n this.scratchData = this.jsonFields.length === 0 ? this.scratchCell : {};\n this.scratchPrevData = {};\n // An ephemeral behavior is a SINGLETON on the local peer, so remote\n // peers' projected facets must never become instances — they are read\n // through `ctx.peers()` instead. `Local` is strata's own marker for\n // entities THIS peer minted, which is exactly the distinction.\n this.ownQuery =\n b.store === \"ephemeral\" ? defineQuery([this.own, Local]) : defineQuery([this.own]);\n this.peersQuery = b.store === \"ephemeral\" ? defineQuery([this.own, Not(Local)]) : undefined;\n\n const hooks: BehaviorSystemHooks = {\n shouldDeliver: () => this.shouldDeliver(),\n deliver: (ctx) => this.runDeliver(systemWalker(ctx)),\n shouldTick: () => this.instances.size > 0 && !this.generationDirty,\n tickChunk: (batch, ctx) => this.tickChunk(batch, ctx),\n charge: (body) => this.guest.run(body),\n suspended: () => this.guest.suspended(),\n onSuspendedFrame: () => this.goCold(),\n };\n this.compiled = compileBehavior(b, hooks);\n this.guest = opts.engine.guests.addDriven({\n id: `behavior:${b.name}`,\n ...(b.budgetMs !== undefined ? { budgetMs: b.budgetMs } : {}),\n busy: () => this.owed(),\n });\n this.ctx = this.buildCtx();\n }\n\n // --- installation ------------------------------------------------------\n\n /**\n * Attach this behavior's two collectors. Separate from `install` because\n * suspension DETACHES them and resume re-attaches (see `goCold`/`goWarm`).\n */\n private installCollectors(): void {\n this.ownCollector = world.changes.collect({ components: [this.own], coarse: false });\n // The reads collector subscribes to everything EXCEPT the own component,\n // which the own collector already covers — so a behavior whose only\n // declared read is itself gets no second collector at all, rather than\n // one subscribed to nothing.\n const readsComponents = this.compiled.readComponents.filter((c) => c !== this.own);\n if (readsComponents.length > 0 || this.compiled.readTags.length > 0) {\n this.readsCollector = world.changes.collect({\n components: readsComponents,\n ...(this.compiled.readTags.length > 0 ? { tags: this.compiled.readTags } : {}),\n coarse: false,\n });\n }\n }\n\n /**\n * The breaker suspended us. DETACH the collectors — a suspended behavior\n * that keeps them alive keeps costing: strata journals every subscribed\n * write into buffers we then throw away, every frame, for as long as the\n * suspension lasts. Suspension is supposed to stop the cost, not launder it.\n */\n private goCold(): void {\n if (this.cold) return;\n this.cold = true;\n this.ownCollector?.dispose();\n this.readsCollector?.dispose();\n this.ownCollector = undefined;\n this.readsCollector = undefined;\n }\n\n /**\n * Resumed. Fresh collectors journal from NOW, so everything that happened\n * during the suspension is invisible to them — which is exactly the state a\n * newly registered behavior is in, and `seeded` already means \"rebuild from\n * the world rather than trust a delta\". Without this, `guests.resume()` —\n * the doctor's own repair action — hands back a behavior whose instance\n * registry has silently lost everything attached while it was down.\n */\n private goWarm(): void {\n if (!this.cold) return;\n this.cold = false;\n this.installCollectors();\n this.seeded = false;\n }\n\n install(): void {\n this.installCollectors();\n // ARM THE POLLS AT REGISTRATION, not at first use. Both stamp families\n // are dormant until their FIRST READ: a poll armed late reports its first\n // compare as \"unchanged\" and silently misses every write before it. Both\n // arming flags are WORLD-WIDE — one read of any resource, or of any\n // ordered relation, starts collection for all of them — so the hazard\n // applies to the first registration and not to later ones. The\n // order-stamp read below is purely for its arming side effect, which is\n // why the parent it names does not matter.\n for (const res of this.compiled.readResources) this.resourceStamps.set(res, world.resourceStamp(res));\n if (this.compiled.readRelations.length > 0) {\n world.orderStamp(0 as Entity, this.compiled.readRelations[0] as Relation);\n }\n\n if (this.b.phase === \"publish\") {\n // The publish slot is not a pipeline phase: it is the post-tick step\n // where ephemeral mutation is legal and there is no iteration bracket.\n // So no systems are registered — the node runs itself from the publish\n // hook, with a walker that goes straight to the world.\n //\n // Accounting note: a driven guest's accrual is closed at the GUEST\n // SLOT, which runs before publish hooks, so a publish behavior's cost\n // lands in the NEXT frame's seam total. The ladder counts invocations,\n // not wall alignment, so every trip rule still fires on schedule — the\n // seam CAP is what sees this one frame late.\n this.removeSystems = opts.engine.onPublish(() => {\n if (this.guest.suspended()) {\n this.goCold();\n return;\n }\n this.guest.run(() => {\n if (this.b.store === \"ephemeral\") this.ensureFacet();\n if (this.shouldDeliver()) this.runDeliver(publishWalker(world));\n this.publishTick();\n });\n });\n } else {\n this.removeSystems = opts.engine.addSystems(\n this.b.phase as PhaseGroup,\n ...(this.compiled.systems as readonly never[]),\n );\n }\n }\n\n /** The version-marker surface for the current session, if it has one. */\n private metaOf(session: BehaviorSession | undefined): BehaviorMeta | undefined {\n const snapshot = session?.store.snapshot;\n if (snapshot === undefined || typeof snapshot.readMeta !== \"function\") return undefined;\n const metaTransaction = session?.store.metaTransaction;\n if (typeof metaTransaction !== \"function\") return undefined;\n return {\n readMeta: (key) => snapshot.readMeta(key),\n metaTransaction: (fn) => metaTransaction.call(session?.store, fn),\n };\n }\n\n /** Classify this doc's version for this behavior, and act on the verdict. */\n private syncVersion(session: BehaviorSession | undefined): void {\n this.dormant = false;\n if (this.b.store !== \"durable\" || session === undefined) return;\n const meta = this.metaOf(session);\n if (meta === undefined) return;\n const docVersion = docBehaviorVersion(meta, this.b.name, this.b.version);\n const verdict = classifyBehaviorVersion(this.b, docVersion);\n switch (verdict.kind) {\n case \"ok\":\n return;\n case \"dormant\":\n this.dormant = true;\n onLog(\n this.b.name,\n `the document holds v${verdict.docVersion} data and this build installs v${verdict.installed} — hook delivery is REFUSED for this behavior (its cells stay untouched). The document itself is unaffected and stays writable.`,\n [],\n );\n return;\n case \"unreachable\":\n onLog(\n this.b.name,\n `the document holds v${verdict.from} data and this build's migrate chain cannot reach v${verdict.installed} — its cells stay at v${verdict.from}.`,\n [],\n );\n return;\n case \"migrate\": {\n if (session.readOnly) return; // nothing to write to\n const carriers: Entity[] = [];\n world.query(this.ownQuery).each((b) => {\n for (const row of b) carriers.push(b.entity(row));\n });\n const n = runBehaviorMigration(this.b, verdict.from, {\n world,\n meta,\n store: session.store,\n liveWriter: session.liveWriter,\n carriers: () => carriers,\n });\n onLog(this.b.name, `migrated ${n} instance(s) from v${verdict.from} to v${verdict.installed}.`, []);\n return;\n }\n }\n }\n\n /** Stamp this build's marker the first time a cell of ours enters the doc. */\n private stampFirstAttach(): void {\n if (this.b.store !== \"durable\") return;\n const session = opts.session?.();\n if (session === undefined || session.readOnly) return;\n const meta = this.metaOf(session);\n if (meta === undefined) return;\n stampBehaviorMarker(meta, this.b.name, this.b.version);\n }\n\n /** Does `e` carry this behavior AS AN INSTANCE? (ephemeral: local peer only) */\n private carries(e: Entity): boolean {\n if (!world.isAlive(e) || !world.has(e, this.own)) return false;\n return this.b.store !== \"ephemeral\" || world.hasTag(e, Local);\n }\n\n /**\n * Mint (or re-mint) the local peer's facet. `localPeer` is a getter that a\n * world reset replaces — the fresh peer carries NO facets, so the identity\n * swap is what tells us to attach again rather than edit a dead entity.\n */\n private ensureFacet(): void {\n const presence = opts.presence?.();\n if (presence === undefined) {\n this.facetPeer = undefined;\n return; // dormant: no peer to be\n }\n const peer = presence.localPeer;\n // A world reset kills the minted peer, and presence re-mints it a\n // MICROTASK later (attaching an ephemeral store is illegal inside an\n // observer emit). Between the two there is a window where `localPeer` is\n // a dead handle — writing through it throws inside strata's projector,\n // which the breaker then charges to a behavior that did nothing wrong.\n // Skip the frame; the fresh peer arrives on the next one.\n if (!world.isAlive(peer)) {\n this.facetPeer = undefined;\n return;\n }\n if (peer === this.facetPeer && world.has(peer, this.own)) return;\n this.facetPeer = peer;\n if (!world.has(peer, this.own)) {\n presence.eph.addComponent(\n peer,\n this.own as Component<unknown>,\n { ...(this.b.defaults as Record<string, unknown>) },\n );\n }\n }\n\n /** The publish-slot twin of the tick SYSTEM (no query, no chunks). */\n private publishTick(): void {\n const on = this.b.on;\n if (on.tick === undefined || this.snapshot.length === 0) return;\n const info = world.getResource(FrameInfo);\n const frame: BehaviorFrame = { dtMs: info?.dt ?? 0, tick: info?.tick ?? 0, clock: info?.clock ?? 0 };\n const faulted = new Set<Entity>();\n this.walker = publishWalker(world);\n for (const e of this.snapshot) {\n const inst = this.instances.get(e);\n if (inst === undefined || inst.failed || !inst.inited) continue;\n const data = this.dataOf(e);\n this.callHook(\"tick\", inst, faulted, () => {\n on.tick?.(e, data as never, frame, this.ctx as never);\n });\n }\n this.walker = undefined;\n }\n\n uninstall(): void {\n this.endGeneration();\n this.removeSystems?.();\n this.removeSystems = undefined;\n this.ownCollector?.dispose();\n this.readsCollector?.dispose();\n this.ownCollector = undefined;\n this.readsCollector = undefined;\n this.guest.remove();\n }\n\n markGeneration(): void {\n this.generationDirty = true;\n }\n\n /** Owed work for the frame gate — a freeze must not park mid-reflow. */\n owed(): boolean {\n return this.generationDirty;\n }\n\n // --- the gate ----------------------------------------------------------\n\n private shouldDeliver(): boolean {\n // Reached only while NOT suspended, so this is the resume edge.\n if (this.cold) this.goWarm();\n // The drain is UNCONDITIONAL even when the answer is \"no work\": a\n // collector nobody drains grows without bound, and the next real drain\n // would hand the body a delta describing a world several frames old.\n const ownDelta = this.ownCollector?.drain();\n const readsDelta = this.readsCollector?.drain();\n const pollFired = this.pollResources() || this.pollOrder();\n\n const full =\n this.generationDirty ||\n !this.seeded ||\n (ownDelta?.reset ?? false) ||\n (ownDelta?.coarse.length ?? 0) > 0 ||\n (readsDelta?.reset ?? false) ||\n (readsDelta?.coarse.length ?? 0) > 0;\n\n // The echo memo is consumed by INVALIDATION, not by a frame count.\n // A one-drain window would in fact suffice for the ordinary case — a\n // durable write journals twice (write-through now, batch re-projection at\n // the following `world.sync()`) but both copies land inside one drain —\n // so this is a margin, not a fix: it costs nothing, it does not depend on\n // that timing holding, and the first genuine change on an entity fails\n // the compare, wakes the behavior, and drops the entry anyway.\n const echo = this.echo;\n const isEcho = (e: Entity): boolean => {\n const snap = echo.get(e);\n if (snap === undefined) return false;\n const alive = world.isAlive(e);\n for (const [c, v] of snap.cells) {\n const now = alive && world.has(e, c) ? world.get(e, c) : undefined;\n const same = now === undefined || v === undefined ? now === v : valueEquals(c, now, v);\n if (!same) {\n echo.delete(e);\n return false;\n }\n }\n for (const [t, had] of snap.tags) {\n if ((alive && world.hasTag(e, t)) !== had) {\n echo.delete(e);\n return false;\n }\n }\n return true;\n };\n const keep = (list: readonly Entity[]): readonly Entity[] =>\n echo.size === 0 || list.length === 0 ? list : list.filter((e) => !isEcho(e));\n\n const ownChanged = keep(ownDelta?.changed ?? []);\n const ownRemoved = ownDelta?.removed ?? [];\n const readsChanged = keep(readsDelta?.changed ?? []);\n const readsRemoved = readsDelta?.removed ?? [];\n const ownWork = ownChanged.length > 0 || ownRemoved.length > 0;\n const readsWork = pollFired || readsChanged.length > 0 || readsRemoved.length > 0;\n\n // `instances > 0` gates the READS path only. It cannot gate the own path:\n // the very first attach arrives as own-component churn on a behavior that\n // has no instances yet, and gating that is how an installed behavior\n // never wakes up.\n // A claim clearing is WORK even on an otherwise silent frame: the\n // gesture's own commit landed at `ctl:behave`, `derive` runs later the\n // same frame, and the coalesced delivery has to happen against that\n // settled truth or the reflow waits for unrelated churn to wake it.\n const lifted = this.suppressionLifted();\n if (!full && !ownWork && !lifted && !(readsWork && this.instances.size > 0)) {\n if (this.suppressed.size > 0) {\n for (const e of readsChanged) this.carry.add(e);\n for (const e of ownChanged) this.carry.add(e);\n }\n this.stash = undefined;\n return false;\n }\n this.stash = { full, ownChanged, ownRemoved, readsFired: readsWork, readsChanged, readsRemoved };\n return true;\n }\n\n /** Any suppressed instance whose claim has cleared since last frame. */\n private suppressionLifted(): boolean {\n if (this.suppressed.size === 0) return false;\n for (const e of this.suppressed) {\n if (!this.isSuppressible(e)) return true;\n }\n return false;\n }\n\n /**\n * Is this instance held by a live claim? Two ways, and the second is what\n * makes the flagship case work: the CARRIER of a mind map is never itself\n * grabbed — its member node is. So a claimed entity that reaches an\n * instance through one of the behavior's own DECLARED read relations\n * suppresses that instance, and only that instance.\n */\n private isSuppressible(e: Entity): boolean {\n if (isClaimed(world, e)) return true;\n for (const r of this.compiled.readRelations) {\n for (const child of world.getReverse(e, r)) {\n if (isClaimed(world, child)) return true;\n }\n }\n return false;\n }\n\n /** Recompute the suppressed set for this delivery (derived behaviors only). */\n private updateSuppression(): void {\n const gone: Entity[] = [];\n for (const e of this.suppressed) if (!this.instances.has(e)) gone.push(e);\n for (const e of gone) {\n this.suppressed.delete(e);\n this.suppressedFrames.delete(e);\n }\n for (const e of this.snapshot) {\n if (this.isSuppressible(e)) {\n this.suppressed.add(e);\n const n = (this.suppressedFrames.get(e) ?? 0) + 1;\n this.suppressedFrames.set(e, n);\n if (n === SUPPRESSION_WARN_FRAMES) {\n onLog(\n this.b.name,\n `derive suppressed for ${n} frames on entity ${e} — a gesture claim on it (or on one of its members) has not cleared. Derived state for that instance is frozen until it does.`,\n [],\n );\n }\n continue;\n }\n this.suppressed.delete(e);\n this.suppressedFrames.delete(e);\n }\n }\n\n private pollResources(): boolean {\n let fired = false;\n for (const [res, last] of this.resourceStamps) {\n // A per-WRITE counter, not a frame stamp: same-frame rewrites each bump\n // it, so a poller can never miss a value that was written and\n // overwritten inside one frame. It also never moves backward — a\n // `world.reset()` bumps every held resource, which presents to this\n // poll as an ordinary change to everything, correctly.\n const now = world.resourceStamp(res);\n if (now !== last) {\n this.resourceStamps.set(res, now);\n fired = true;\n }\n }\n return fired;\n }\n\n /**\n * Poll the watched sequences. Sibling order is the one thing `reads:` can\n * name that NEVER reaches a change collector, so this poll is not an\n * optimization — it is the only mechanism there is.\n *\n * The per-parent value SUMS the stamps of every declared relation, which is\n * sound only because the stamps come from one shared monotonic counter:\n * they never decrease, so two relations cannot move in opposite directions\n * and cancel to the same total.\n */\n private pollOrder(): boolean {\n const rels = this.compiled.readRelations;\n if (rels.length === 0) return false;\n if (this.parentsDirty) this.rebuildParents();\n let fired = false;\n for (const [parent, last] of this.parentStamps) {\n let now = 0;\n for (const r of rels) now += world.orderStamp(parent, r);\n if (now !== last) {\n this.parentStamps.set(parent, now);\n fired = true;\n }\n }\n // A fired stamp usually means membership under that parent moved, so the\n // watch SET itself may be stale. Rebuilding next frame (rather than now)\n // is safe: the stamp we just banked is current, so nothing is missed in\n // the gap.\n if (fired) this.parentsDirty = true;\n return fired;\n }\n\n /**\n * Rebuild the set of sequences this behavior watches.\n *\n * BOTH DIRECTIONS, and the second is the load-bearing one. An instance\n * participates in an ordered relation two ways: as a CHILD (its own\n * parent's sequence moved) or as the PARENT (its members were reordered\n * under it). Watching only the first misses the flagship shape entirely — a\n * mind map's carrier holds the behavior and its NODES are the children, so\n * a pure reorder of those nodes would wake nothing at all.\n *\n * A CHILDLESS instance is watched too, and deliberately: its stamp reads 0\n * until it gains a first child, and that transition is precisely what has\n * to be detectable. Skipping childless parents would reintroduce the same\n * blind spot one case down.\n *\n * COST, stated honestly because design-009 §5.2 says \"O(distinct parents)\"\n * and this is not that: the watch set is instances ∪ instances' parents, so\n * the poll is O(instances) map lookups per frame for a behavior that\n * declares an ordered relation. Two consequences worth knowing — declare a\n * relation only when you navigate it, and prefer the §10 carrier idiom,\n * where the instance count is small by construction.\n */\n private rebuildParents(): void {\n this.parentsDirty = false;\n this.parentStamps.clear();\n if (this.compiled.readRelations.length === 0) return;\n const watch = (parent: Entity): void => {\n let total = 0;\n for (const rr of this.compiled.readRelations) total += world.orderStamp(parent, rr);\n this.parentStamps.set(parent, total);\n };\n for (const e of this.instances.keys()) {\n if (!world.isAlive(e)) continue;\n watch(e); // as a PARENT: its members' sequence\n for (const r of this.compiled.readRelations) {\n const parent = world.getRelation(e, r);\n if (parent !== undefined) watch(parent); // as a CHILD: its own sequence\n }\n }\n }\n\n // --- delivery ----------------------------------------------------------\n\n private runDeliver(walker: BehaviorWalker): void {\n this.walker = walker;\n if (this.generationDirty) {\n this.generationDirty = false;\n this.endGeneration();\n this.generation = new AbortController();\n this.seeded = false;\n }\n // The version check is RE-ENTRANT by construction: it re-runs whenever\n // the session identity changes, which covers doc open, doc switch, and\n // (because a plugin host installs mid-session) a behavior registered long\n // after the document was opened. \"Migrate at open\" alone would miss that\n // last path entirely, which is the normal one for plugins.\n const session = opts.session?.();\n if (session !== this.checkedSession) {\n this.checkedSession = session;\n this.syncVersion(session);\n }\n\n const work = this.stash;\n this.stash = undefined;\n const full = work?.full ?? true;\n\n if (this.dormant) {\n // Refuse hook delivery, but keep draining: the moment a build that\n // understands this data opens the doc, its own runtime picks up where\n // this one honestly declined to guess.\n this.walker = undefined;\n return;\n }\n\n const appeared: Entity[] = [];\n const departed: Instance[] = [];\n\n if (full) {\n // Rebuild: every carrier is an instance, every non-carrier is not.\n const carriers = new Set<Entity>();\n walker.each(this.ownQuery, (e) => carriers.add(e));\n for (const e of carriers) if (!this.instances.has(e)) appeared.push(e);\n for (const [e, inst] of this.instances) if (!carriers.has(e)) departed.push(inst);\n this.seeded = true;\n } else {\n // O(changed), never O(instances): structural changes arrive as\n // over-reporting archetype records, so the exact question — \"does this\n // entity carry my component NOW?\" — is one `has` per journaled entity.\n for (const e of work?.ownChanged ?? []) {\n const carries = this.carries(e);\n const known = this.instances.get(e);\n if (carries && known === undefined) appeared.push(e);\n else if (!carries && known !== undefined) departed.push(known);\n }\n for (const e of work?.ownRemoved ?? []) {\n const known = this.instances.get(e);\n if (known !== undefined) departed.push(known);\n }\n }\n\n for (const inst of departed) this.instances.delete(inst.e);\n for (const e of appeared) {\n this.instances.set(e, {\n e,\n prevCell: this.readCell(e, {}),\n inited: false,\n failed: false,\n consecutiveThrows: 0,\n });\n }\n // Rebuild the order-poll's watch set NOW, not lazily on the next poll:\n // the stamps have to be banked in the same frame the instance set\n // changed, or a reorder landing in between is compared against a stamp\n // taken AFTER it — \"late arming misses changes\", at instance granularity.\n // (No-op when the behavior declares no ordered relation.)\n if (appeared.length > 0 || departed.length > 0) this.rebuildParents();\n // FIRST-ATTACH stamping (§5.6): not at doc create, where the behavior may\n // not exist yet — a plugin installs later, and a marker for something the\n // document has no cells of is a lie about what is in it.\n if (appeared.length > 0) this.stampFirstAttach();\n\n // The instance SNAPSHOT: hooks below may attach or detach, and those\n // land next frame. Nothing after this line re-reads `this.instances` for\n // iteration.\n this.snapshot = [...this.instances.keys()];\n\n // Claim-scoped delivery suppression (§5.3). It REPLACED a deferred-commit\n // queue that re-ran a stale closure after the gesture's own commit — two\n // commits, the first gliding to the pre-drag layout. Here the hook simply\n // does not run while a claim is live, so closure freshness is structural\n // and `ctx.commit` stays a plain write-now call.\n const suppressing = this.b.derived && !this.b.deriveDuringGesture;\n const wasSuppressed = suppressing ? new Set(this.suppressed) : undefined;\n if (suppressing) this.updateSuppression();\n this.visible =\n suppressing && this.suppressed.size > 0\n ? this.snapshot.filter((e) => !this.suppressed.has(e))\n : this.snapshot;\n // A claim CLEARING is itself the trigger for the coalesced delivery. On\n // that frame there is usually no fresh churn at all — the gesture's last\n // write landed frames ago — so without this the settle would sit waiting\n // for unrelated churn to wake it.\n const lifted =\n wasSuppressed !== undefined && [...wasSuppressed].some((e) => !this.suppressed.has(e));\n\n let changedList = work?.readsChanged ?? [];\n if (this.carry.size > 0) {\n // Churn that arrived while suppressed, replayed ONCE at the settle so\n // the coalesced delivery's `ctx.changes()` describes the whole gesture,\n // not just its final frame.\n const merged = new Set<Entity>(changedList);\n for (const e of this.carry) merged.add(e);\n this.carry.clear();\n changedList = [...merged];\n }\n if (this.suppressed.size > 0) for (const e of changedList) this.carry.add(e);\n this.changesView = { full, changed: changedList, removed: work?.readsRemoved ?? [] };\n this.changedEntitiesCache = undefined;\n\n const on = this.b.on;\n const faultedEntities = new Set<Entity>();\n\n // 1. init — appeared instances, before their first tick.\n if (on.init !== undefined) {\n for (const e of appeared) {\n const inst = this.instances.get(e);\n if (inst === undefined || inst.failed) continue;\n if (this.callHook(\"init\", inst, faultedEntities, () => {\n on.init?.(e, this.dataOf(e) as never, this.ctx as never);\n })) {\n inst.inited = true;\n }\n }\n } else {\n for (const e of appeared) {\n const inst = this.instances.get(e);\n if (inst !== undefined) inst.inited = true;\n }\n }\n\n // 2. update — own data changed since the last delivery, by ANY writer.\n if (on.update !== undefined) {\n const candidates = full ? this.snapshot : (work?.ownChanged ?? []);\n for (const e of candidates) {\n const inst = this.instances.get(e);\n if (inst === undefined || inst.failed || !inst.inited) continue;\n if (this.suppressed.has(e)) continue; // held by a live claim\n // Just-appeared instances got current data in `init`; `prev` would be\n // that same value, so there is nothing to report.\n if (appeared.includes(e)) continue;\n if (!world.isAlive(e)) continue;\n this.readCell(e, this.scratchCell);\n // The journal OVER-REPORTS (an archetype migration reports every\n // carried component), so a real value compare is what keeps `update`\n // meaning \"your data changed\". strata's own equality, never a\n // hand-rolled one: a local comparison drifts on exactly the cells\n // reconcile considers settled (f32 fround, enum labels, ±0).\n if (valueEquals(this.own, this.scratchCell, inst.prevCell)) continue;\n const data = this.viewOf(this.scratchCell, this.scratchData);\n const prev = this.viewOf(inst.prevCell, this.scratchPrevData);\n this.callHook(\"update\", inst, faultedEntities, () => {\n on.update?.(e, data as never, prev as never, this.ctx as never);\n });\n // Bank the delivered value even when the hook threw: re-delivering\n // the same change to an instance that failed on it is a loop.\n this.copyInto(this.scratchCell, inst.prevCell);\n }\n }\n\n // 3. changed — ONCE per behavior, not per instance. N instances × one tag\n // flip must not mean N journal scans.\n const anyVisible = this.visible.length > 0;\n if (on.changed !== undefined && (full || (work?.readsFired ?? false) || lifted) && anyVisible) {\n try {\n on.changed(this.ctx as never);\n } catch (err) {\n // No entity to quarantine — this one is the behavior's.\n onFault(this.b.name, \"changed\", undefined, err);\n this.guest.fault(err);\n }\n }\n\n // 4. dispose — departed instances. Runs before the tick SYSTEM in this\n // phase, which is unobservable: a departed instance no longer carries\n // the component the tick query matches on.\n if (on.dispose !== undefined) {\n for (const inst of departed) {\n try {\n on.dispose(inst.e, this.ctx as never);\n } catch (err) {\n // Swallowed by contract (§4.3): teardown must not stop teardown.\n onFault(this.b.name, \"dispose\", inst.e, err);\n }\n }\n }\n\n this.walker = undefined;\n }\n\n private tickChunk(batch: Batch, ctx: SystemCtx): void {\n const on = this.b.on;\n if (on.tick === undefined) return;\n this.walker = systemWalker(ctx);\n const info = world.getResource(FrameInfo);\n const frame: BehaviorFrame = {\n dtMs: info?.dt ?? 0,\n tick: info?.tick ?? 0,\n clock: info?.clock ?? 0,\n };\n const faulted = new Set<Entity>();\n this.visible = this.snapshot;\n for (const row of batch) {\n const e = batch.entity(row);\n const inst = this.instances.get(e);\n // A carrier the delivery pass has not adopted yet (attached this frame\n // after delivery ran) has had no `init`; ticking it would violate\n // \"init runs before that instance's first tick\".\n if (inst === undefined || inst.failed || !inst.inited) continue;\n const data = this.dataOf(e);\n this.callHook(\"tick\", inst, faulted, () => {\n on.tick?.(e, data as never, frame, this.ctx as never);\n });\n }\n this.walker = undefined;\n }\n\n /**\n * Per-(behavior, hook, entity) fault attribution (BF-D18): three\n * consecutive throws on ONE entity quarantine that INSTANCE; the behavior\n * itself is only struck when throws SPAN instances. One bad node must not\n * kill a 1000-node layout.\n */\n private callHook(hook: string, inst: Instance, faulted: Set<Entity>, body: () => void): boolean {\n try {\n body();\n inst.consecutiveThrows = 0;\n return true;\n } catch (err) {\n inst.consecutiveThrows++;\n onFault(this.b.name, hook, inst.e, err);\n if (inst.consecutiveThrows >= INSTANCE_THROW_LIMIT) inst.failed = true;\n faulted.add(inst.e);\n if (faulted.size > 1) this.guest.fault(err);\n return false;\n }\n }\n\n // --- generation --------------------------------------------------------\n\n private endGeneration(): void {\n const on = this.b.on;\n if (on.dispose !== undefined) {\n for (const inst of this.instances.values()) {\n try {\n on.dispose(inst.e, this.ctx as never);\n } catch (err) {\n onFault(this.b.name, \"dispose\", inst.e, err);\n }\n }\n }\n this.instances.clear();\n this.facetPeer = undefined;\n this.suppressed.clear();\n this.suppressedFrames.clear();\n this.carry.clear();\n this.parentStamps.clear();\n this.parentsDirty = true;\n // dispose FIRST, abort SECOND: a teardown that guards on\n // `signal.aborted` would otherwise skip its own cleanup.\n this.generation.abort();\n }\n\n // --- data views --------------------------------------------------------\n\n /** Fill `target` with `e`'s raw cell, field by field — no intermediate object. */\n private readCell(e: Entity, target: Record<string, unknown>): Record<string, unknown> {\n for (const f of this.fieldNames) target[f] = world.readField(e, this.ownFields, f);\n return target;\n }\n\n /** The hook-facing view of a raw cell (json fields parsed). */\n private viewOf(cell: Record<string, unknown>, target: Record<string, unknown>): Record<string, unknown> {\n if (this.jsonFields.length === 0) return cell;\n for (const f of this.fieldNames) target[f] = cell[f];\n for (const f of this.jsonFields) {\n const raw = cell[f];\n target[f] = typeof raw === \"string\" ? safeParse(raw) : raw;\n }\n return target;\n }\n\n private dataOf(e: Entity): Record<string, unknown> {\n this.readCell(e, this.scratchCell);\n return this.viewOf(this.scratchCell, this.scratchData);\n }\n\n private copyInto(src: Record<string, unknown>, dst: Record<string, unknown>): void {\n for (const f of this.fieldNames) dst[f] = src[f];\n }\n\n cellFor(e: Entity | undefined, patch: Record<string, unknown>): Record<string, unknown> {\n return cellForBehavior(world, this.b, e, patch);\n }\n\n // --- ctx ---------------------------------------------------------------\n\n private buildCtx(): BehaviorCtxBase<Record<string, unknown>> & Record<string, unknown> {\n const scopedQuery = createQueryScope(\n this.b,\n allowedQueryTerms(this.b, this.compiled.readComponents, this.compiled.readTags),\n );\n const behaviorWorld = createBehaviorWorld(world);\n const node = this;\n\n const requireWalker = (what: string): BehaviorWalker => {\n const w = node.walker;\n if (w === undefined) {\n throw new Error(\n `ice: behavior \"${node.b.name}\" called ctx.${what} outside a hook — the ctx is valid only for the duration of the hook call (its walks are attributed to the running system, and there is none here).`,\n );\n }\n return w;\n };\n\n const base: BehaviorCtxBase<Record<string, unknown>> = {\n world: behaviorWorld,\n query: (spec) => scopedQuery(requireWalker(\"query\"), spec),\n entities: () => node.visible,\n changes: () => node.changesView,\n changedEntities: () => {\n if (node.changedEntitiesCache === undefined) {\n const out: Entity[] = [];\n // Instances MINUS the suppressed ones — the same set `ctx.entities()`\n // reports, derived from the same two collections rather than from\n // `visible`, which is per-PASS state (the tick pass resets it) and\n // would make this answer depend on who asked. Reporting a suppressed\n // instance here would invite the hook to act on exactly the instance\n // suppression exists to leave alone.\n for (const e of node.changesView.changed) {\n if (node.instances.has(e) && !node.suppressed.has(e)) out.push(e);\n }\n node.changedEntitiesCache = out;\n }\n return node.changedEntitiesCache;\n },\n keyOf: (e) => {\n const key = opts.session?.()?.store.keyOf(e);\n return typeof key === \"string\" ? key : undefined;\n },\n entityFor: (key) => opts.session?.()?.store.resolve(key as never),\n get signal() {\n return node.generation.signal;\n },\n log: (message, ...rest) => onLog(node.b.name, message, rest),\n };\n\n // The store class routes the WRITE VOCABULARY. Assembling it here — one\n // object per behavior, built once — is what makes \"you cannot misuse the\n // two-worlds model\" a property of the object rather than a doc promise.\n const extra: Record<string, unknown> = {};\n if (this.b.store === \"runtime\") {\n extra.write = (e: Entity, patch: Record<string, unknown>) => node.writeOwn(e, patch);\n extra.set = (e: Entity, c: Component, v: unknown) => node.writeTarget(e, c, v);\n extra.attach = (e: Entity, data?: Record<string, unknown>) => {\n requireWalker(\"attach\").addComponent(e, node.own, node.cellFor(undefined, data ?? {}));\n };\n extra.detach = (e: Entity) => {\n requireWalker(\"detach\").removeComponent(e, node.own);\n };\n }\n if (this.b.store === \"ephemeral\") {\n // No entity argument: the instance IS the local peer, and there is\n // exactly one. Legal without a queue because ephemeral hooks run at the\n // publish slot — post-tick, where eph mutation is allowed.\n extra.write = (patch: Record<string, unknown>) => node.writeFacet(patch);\n extra.peers = () => node.readPeers();\n }\n if (this.b.store === \"durable\" || this.b.store === \"runtime\") {\n extra.commit = (label: string, fn: (tx: BehaviorTx<Record<string, unknown>>) => void, o?: { undoable?: boolean }) =>\n node.commit(label, fn, o);\n }\n return Object.assign(base, extra) as BehaviorCtxBase<Record<string, unknown>> & Record<string, unknown>;\n }\n\n /** `ctx.write(patch)` for the ephemeral class — publish THIS peer's facet. */\n private writeFacet(patch: Record<string, unknown>): void {\n const presence = opts.presence?.();\n if (presence === undefined) return; // dormant\n const peer = presence.localPeer;\n if (!world.isAlive(peer)) return; // mid re-mint (see ensureFacet)\n const cell = cellForBehavior(world, this.b, peer, patch);\n if (world.has(peer, this.own)) presence.eph.edit(peer).set(this.own as Component<unknown>, cell);\n else presence.eph.addComponent(peer, this.own as Component<unknown>, cell);\n }\n\n /** `ctx.peers()` — REMOTE peers' facets, read-only. The read side of presence. */\n private readPeers(): { entity: Entity; data: Record<string, unknown> }[] {\n const q = this.peersQuery;\n if (q === undefined) return [];\n const out: { entity: Entity; data: Record<string, unknown> }[] = [];\n world.query(q).each((b) => {\n for (const row of b) {\n const e = b.entity(row);\n const cell = this.readCell(e, {});\n out.push({ entity: e, data: this.viewOf(cell, {}) });\n }\n });\n return out;\n }\n\n /** `ctx.write` — own runtime data, immediate, through the armed guard. */\n private writeOwn(e: Entity, patch: Record<string, unknown>): void {\n if (!world.isAlive(e) || !world.has(e, this.own)) return;\n this.writeTarget(e, this.own, this.cellFor(e, patch));\n }\n\n /**\n * `ctx.set` — a declared `writes:` target, immediate. Routed through the\n * session's LiveWriter, which is what makes the divergence law ARMED rather\n * than aspirational: a per-frame write to a DURABLE-eligible cell without a\n * gesture claim or tween grant throws here, naming the law. Doc-less\n * engines write direct — nothing is doc-sovereign without a document.\n */\n private writeTarget(e: Entity, c: Component, v: unknown): void {\n if (devGuardsEnabled() && c !== this.own && !this.b.writes.includes(c)) {\n throw new Error(\n `ice: behavior \"${this.b.name}\" wrote a component it did not declare in writes: — declared writes are what the compiler derives access from (design-009 §7).`,\n );\n }\n const live = opts.session?.()?.liveWriter;\n if (live !== undefined) live.set(e, c as Component<unknown>, v);\n else world.edit(e).set(c as Component<unknown>, v);\n }\n\n /** `ctx.commit` — ONE labeled transaction, opened INSIDE the hook. */\n private commit(\n label: string,\n fn: (tx: BehaviorTx<Record<string, unknown>>) => void,\n o?: { undoable?: boolean },\n ): void {\n const session = opts.session?.();\n if (session === undefined) {\n throw new Error(\n `ice: behavior \"${this.b.name}\" called ctx.commit(\"${label}\") with no document attached — durable writes need a doc (engine.docs.create()/open()/join()).`,\n );\n }\n if (session.readOnly) {\n throw new Error(\n `ice: behavior \"${this.b.name}\" called ctx.commit(\"${label}\") on a READ-ONLY document (version gate) — writes are disabled.`,\n );\n }\n const store = session.store as unknown as Parameters<typeof guardedTransaction>[0];\n const keyOf = (e: Entity): string | undefined => {\n const key = session.store.keyOf(e);\n return typeof key === \"string\" ? key : undefined;\n };\n // `label` is a stable MACHINE id, never display text: it rides in-CRDT as\n // provenance (strata 0.12.0 petition 9) and a receiving peer reads it.\n const meta = { behavior: this.b.name, label };\n\n if (!this.b.derived) {\n guardedTransaction(store, world, (tx) => fn(this.wrapTx(tx)), {\n ...(o?.undoable !== undefined ? { undoable: o.undoable } : {}),\n live: session.liveWriter,\n keyOf,\n meta,\n });\n return;\n }\n\n // The derived path BUFFERS: `undoable` has to be decided before the\n // transaction opens, and whether this commit is derived output or an\n // authorial config edit is only knowable from its ops.\n const recorded = recordDerivedOps(this.b.name, (rec) => fn(this.wrapTx(rec)));\n const diff = diffOps(recorded, {\n world,\n docValue: (e, c) => session.store.getComponent(e, c),\n writeTargets: new Set(this.b.writes as readonly Component[]),\n });\n if (diff.ops.length === 0) return; // zero ops opens NO transaction\n guardedTransaction(store, world, (tx) => replayOps(diff.ops, tx), {\n // ⌘Z must never un-derive. Output rides non-undoable; a commit that\n // only touches the behavior's OWN data is authorial and keeps undo.\n undoable: diff.derivedOutput ? false : (o?.undoable ?? true),\n live: session.liveWriter,\n keyOf,\n meta,\n });\n this.captureEcho(diff.writtenEntities, diff.writtenValues);\n }\n\n /**\n * Snapshot what the world will look like once this commit projects.\n *\n * Committed components take the value the COMMIT wrote — a durable write\n * lands in the doc now and projects at the next `world.sync()`, so reading\n * the world here would snapshot the value being replaced and every echo\n * would then look like a real change. Everything else the behavior watches\n * is read from the world, where it is already current.\n */\n private captureEcho(\n entities: readonly Entity[],\n committed: ReadonlyMap<Entity, ReadonlyMap<Component, unknown>>,\n ): void {\n const watched: Component[] = [this.own, ...this.compiled.readComponents];\n this.echo = new Map();\n for (const e of entities) {\n const wrote = committed.get(e);\n const alive = world.isAlive(e);\n const cells: [Component, unknown][] = [];\n for (const c of watched) {\n const v = wrote?.get(c);\n cells.push([c, v !== undefined ? v : alive && world.has(e, c) ? world.get(e, c) : undefined]);\n }\n const tags: [Tag, boolean][] = [];\n for (const t of this.compiled.readTags) tags.push([t, alive && world.hasTag(e, t)]);\n this.echo.set(e, { cells, tags });\n }\n }\n\n /**\n * The door's transaction. `setResource` is MASKED — the §9 resource-write\n * fence made mechanical rather than doctrinal: `GuardedTx` structurally\n * carries it, so leaving it reachable would make the fence a comment.\n */\n private wrapTx(tx: GuardedTx): BehaviorTx<Record<string, unknown>> {\n const node = this;\n const wrapped = {\n ...tx,\n spawnPrefab: tx.spawnPrefab.bind(tx),\n spawn: tx.spawn.bind(tx),\n destroy: tx.destroy.bind(tx),\n addComponent: tx.addComponent.bind(tx),\n removeComponent: tx.removeComponent.bind(tx),\n edit: tx.edit.bind(tx),\n addTag: tx.addTag.bind(tx),\n removeTag: tx.removeTag.bind(tx),\n setRelation: tx.setRelation.bind(tx),\n addRelation: tx.addRelation.bind(tx),\n removeRelation: tx.removeRelation.bind(tx),\n moveRelation: tx.moveRelation.bind(tx),\n move: tx.move.bind(tx),\n setResource: () => {\n throw new Error(\n `ice: behavior \"${node.b.name}\" called tx.setResource — behaviors do not write resources (design-009 §4.4). A resource-backed behavior is the named \"singleton\" v1.1 shape.`,\n );\n },\n write(e: Entity, patch: Record<string, unknown>) {\n tx.edit(e).set(node.own as Component<unknown>, node.cellFor(e, patch));\n },\n attach(e: Entity, behavior: { component: unknown; defaults: unknown; name: string }, data?: Record<string, unknown>) {\n const other = behavior as unknown as AnyBehaviorDef;\n const cell = cellForBehavior(world, other, e, data ?? {});\n // Attach-when-attached is an IDEMPOTENT no-op that preserves existing\n // data (§6) — expressed as a value write, which the differ then sees\n // as an ordinary value diff rather than a structural op.\n if (world.has(e, other.component as Component)) {\n tx.edit(e).set(other.component as Component<unknown>, cell);\n } else {\n tx.addComponent(e, other.component as Component<unknown>, cell);\n }\n },\n detach(e: Entity, behavior: AnyBehaviorDef) {\n tx.removeComponent(e, behavior.component as Component);\n },\n };\n return wrapped as unknown as BehaviorTx<Record<string, unknown>>;\n }\n\n status(): BehaviorStatus {\n let failed = 0;\n for (const inst of this.instances.values()) if (inst.failed) failed++;\n return {\n name: this.b.name,\n store: this.b.store,\n phase: this.b.phase,\n instances: this.instances.size,\n failed,\n ticking: this.b.on.tick === undefined ? 0 : this.instances.size - failed,\n suspended: this.guest.suspended(),\n };\n }\n }\n\n function safeParse(raw: string): unknown {\n try {\n return JSON.parse(raw);\n } catch {\n return undefined;\n }\n }\n\n return {\n register(b) {\n if (nodes.has(b.name)) {\n throw new Error(`ice: behavior \"${b.name}\" is already registered with this engine.`);\n }\n const node = new Node(b);\n nodes.set(b.name, node);\n node.install();\n return () => {\n if (nodes.get(b.name) !== node) return;\n nodes.delete(b.name);\n node.uninstall();\n };\n },\n\n registered() {\n return [...nodes.values()].map((n) => n.b);\n },\n\n attach(e, b, data) {\n if (b.store === \"durable\") {\n throw new Error(\n `ice: engine.behaviors.attach(\"${b.name}\") — durable attachment is a DOCUMENT op: use tx.attach inside a transaction so it syncs and undoes.`,\n );\n }\n const cell = cellForBehavior(world, b, e, data ?? {});\n if (world.has(e, b.component as Component)) world.edit(e).set(b.component as Component<unknown>, cell);\n else world.addComponent(e, b.component as Component<unknown>, cell);\n },\n\n detach(e, b) {\n if (b.store === \"durable\") {\n throw new Error(\n `ice: engine.behaviors.detach(\"${b.name}\") — durable detachment is a DOCUMENT op: use tx.detach inside a transaction.`,\n );\n }\n if (world.has(e, b.component as Component)) world.removeComponent(e, b.component as Component);\n },\n\n has: (e, b) => world.isAlive(e) && world.has(e, b.component as Component),\n\n read(e, b) {\n if (!world.isAlive(e) || !world.has(e, b.component as Component)) return undefined;\n const cell = world.get(e, b.component as Component) as Record<string, unknown> | undefined;\n if (cell === undefined) return undefined;\n for (const [f, spec] of Object.entries(b.schema)) {\n if ((spec as JsonSpec).kind !== \"json\") continue;\n const raw = cell[f];\n if (typeof raw === \"string\") cell[f] = safeParse(raw);\n }\n return cell;\n },\n\n list() {\n return [...nodes.values()].map((n) => n.status());\n },\n\n dispose() {\n stopResetWatch();\n for (const n of nodes.values()) n.uninstall();\n nodes.clear();\n },\n };\n}\n","/**\n * The `derived` differ (design-009 §3, BF-D5) — M13c.\n *\n * A derived behavior recomputes from other state, so it re-writes the same\n * values constantly. Left alone that is a CRDT catastrophe: every frame of\n * churn becomes journal entries, undo steps, and wire bytes for values that did\n * not change. The differ makes a derived commit cost nothing when nothing moved.\n *\n * Three protections ride together, and they only make sense together:\n *\n * 1. **Value writes equal to the current projection are dropped.** Equality is\n * strata's OWN — `valueEquals`, the predicate reconcile itself judges\n * settlement by. A hand-rolled comparison WOULD drift on exactly the cells\n * reconcile considers settled (f32 fround, integer wrap, enum labels, ±0\n * collapse), which is the one place a differ must never disagree.\n * 2. **Structural ops are diffed too** — attach-when-attached falls through to\n * a value diff, detach-when-absent and destroy-when-dead are dropped, and\n * `spawn` under `derived` throws outright (a derived behavior that mints\n * entities has no convergent story; `tx.ensure` is the named seam).\n * Without this the differ was writable around: one structural op per frame\n * and the whole protection lapses.\n * 3. **Zero remaining ops opens NO transaction.** Not an empty one — none.\n *\n * The buffering this requires is not a cost, it is the enabler: `undoable` has\n * to be decided BEFORE the transaction opens, and whether a commit is derived\n * OUTPUT (never undoable — ⌘Z must not un-derive) or an authorial config edit\n * (ordinarily undoable) is only knowable once you have seen its ops.\n */\nimport { valueEquals } from \"@vibecook/strata-ecs\";\nimport type { Component, Entity, OrderPlace, Relation, Tag, World } from \"@vibecook/strata-ecs\";\nimport { Position } from \"../catalog\";\nimport type { GuardedTx } from \"../guards/guarded-tx\";\n\nexport type RecOp =\n | { readonly kind: \"set\"; readonly e: Entity; readonly c: Component; readonly v: unknown }\n | { readonly kind: \"add\"; readonly e: Entity; readonly c: Component; readonly v: unknown }\n | { readonly kind: \"removeComponent\"; readonly e: Entity; readonly c: Component }\n | { readonly kind: \"destroy\"; readonly e: Entity }\n | { readonly kind: \"addTag\"; readonly e: Entity; readonly t: Tag }\n | { readonly kind: \"removeTag\"; readonly e: Entity; readonly t: Tag }\n | { readonly kind: \"setRelation\"; readonly e: Entity; readonly r: Relation; readonly target: Entity; readonly place?: OrderPlace }\n | { readonly kind: \"addRelation\"; readonly e: Entity; readonly r: Relation; readonly target: Entity }\n | { readonly kind: \"removeRelation\"; readonly e: Entity; readonly r: Relation; readonly target?: Entity }\n | { readonly kind: \"moveRelation\"; readonly e: Entity; readonly r: Relation; readonly place: OrderPlace }\n | { readonly kind: \"move\"; readonly e: Entity; readonly to: { x: number; y: number }; readonly animateMs: number };\n\nexport interface DiffDeps {\n readonly world: World;\n /** The DOC's value for a cell — what a commit would actually be compared to. */\n docValue(e: Entity, c: Component): unknown;\n /** The behavior's declared `writes:` targets (the derived-output test). */\n readonly writeTargets: ReadonlySet<Component>;\n}\n\nexport interface DiffResult {\n readonly ops: readonly RecOp[];\n /**\n * The commit touches a declared `writes:` target — it is derived OUTPUT, so\n * it is forced non-undoable. A commit that only touches the behavior's OWN\n * data is an authorial config edit and keeps normal undo.\n */\n readonly derivedOutput: boolean;\n /** Entities this commit wrote — the next drain's subtraction set. */\n readonly writtenEntities: readonly Entity[];\n /**\n * The VALUES the surviving ops commit, per entity per component. The echo\n * snapshot needs these rather than a post-seal world read: a durable write\n * lands in the doc now but projects into the world at the NEXT `world.sync()`,\n * so reading the world here would capture the value the commit is replacing.\n */\n readonly writtenValues: ReadonlyMap<Entity, ReadonlyMap<Component, unknown>>;\n}\n\n/**\n * Record a DERIVED commit body's ops without performing any of them. Only the\n * derived path buffers: a plain durable behavior commits straight through, so\n * it keeps `tx.spawn` and pays no recording cost.\n */\nexport function recordDerivedOps(behaviorName: string, build: (rec: GuardedTx) => void): RecOp[] {\n const ops: RecOp[] = [];\n const refuseSpawn = (): never => {\n throw new Error(\n `ice: behavior \"${behaviorName}\" called tx.spawn under derived: true — a derived behavior may not spawn entities (design-009 §11). Its output must be a function of state that already exists; \\`tx.ensure(key, …)\\` is the named idempotent-spawn seam.`,\n );\n };\n const editor = (e: Entity) => {\n const chain = {\n set(c: Component, v: unknown) {\n ops.push({ kind: \"set\", e, c, v });\n return chain;\n },\n };\n return chain;\n };\n const rec = {\n spawnPrefab: refuseSpawn,\n spawn: refuseSpawn,\n destroy: (e: Entity) => ops.push({ kind: \"destroy\", e }),\n addComponent: (e: Entity, c: Component, v: unknown) => ops.push({ kind: \"add\", e, c, v }),\n removeComponent: (e: Entity, c: Component) => ops.push({ kind: \"removeComponent\", e, c }),\n edit: editor,\n addTag: (e: Entity, t: Tag) => ops.push({ kind: \"addTag\", e, t }),\n removeTag: (e: Entity, t: Tag) => ops.push({ kind: \"removeTag\", e, t }),\n setRelation: (e: Entity, r: Relation, target: Entity, place?: OrderPlace) =>\n ops.push({ kind: \"setRelation\", e, r, target, ...(place !== undefined ? { place } : {}) }),\n addRelation: (e: Entity, r: Relation, target: Entity) => ops.push({ kind: \"addRelation\", e, r, target }),\n removeRelation: (e: Entity, r: Relation, target?: Entity) =>\n ops.push({ kind: \"removeRelation\", e, r, ...(target !== undefined ? { target } : {}) }),\n moveRelation: (e: Entity, r: Relation, place: OrderPlace) => ops.push({ kind: \"moveRelation\", e, r, place }),\n setResource: () => {\n throw new Error(`ice: behavior \"${behaviorName}\" called tx.setResource — behaviors do not write resources.`);\n },\n move: (e: Entity, to: { x: number; y: number }, o?: { animateMs?: number }) =>\n ops.push({ kind: \"move\", e, to, animateMs: o?.animateMs ?? 0 }),\n };\n build(rec as unknown as GuardedTx);\n return ops;\n}\n\nexport function diffOps(ops: readonly RecOp[], deps: DiffDeps): DiffResult {\n const kept: RecOp[] = [];\n const written = new Set<Entity>();\n const values = new Map<Entity, Map<Component, unknown>>();\n const noteValue = (e: Entity, c: Component, v: unknown): void => {\n let byComponent = values.get(e);\n if (byComponent === undefined) {\n byComponent = new Map();\n values.set(e, byComponent);\n }\n byComponent.set(c, v);\n };\n let derivedOutput = false;\n\n for (const op of ops) {\n switch (op.kind) {\n case \"set\":\n case \"add\": {\n const current = deps.docValue(op.e, op.c);\n // `undefined` means CELL ABSENT — an add, never a no-op. Present and\n // canonically equal means the CRDT would stage nothing: drop it here so\n // no journal entry, no undo step and no wire bytes are produced either.\n if (current !== undefined && valueEquals(op.c, op.v, current)) continue;\n if (deps.writeTargets.has(op.c)) derivedOutput = true;\n written.add(op.e);\n noteValue(op.e, op.c, op.v);\n kept.push(op);\n break;\n }\n case \"removeComponent\": {\n if (!deps.world.isAlive(op.e) || !deps.world.has(op.e, op.c)) continue;\n if (deps.writeTargets.has(op.c)) derivedOutput = true;\n written.add(op.e);\n kept.push(op);\n break;\n }\n case \"destroy\": {\n if (!deps.world.isAlive(op.e)) continue;\n written.add(op.e);\n kept.push(op);\n break;\n }\n case \"addTag\": {\n if (deps.world.isAlive(op.e) && deps.world.hasTag(op.e, op.t)) continue;\n written.add(op.e);\n kept.push(op);\n break;\n }\n case \"removeTag\": {\n if (!deps.world.isAlive(op.e) || !deps.world.hasTag(op.e, op.t)) continue;\n written.add(op.e);\n kept.push(op);\n break;\n }\n case \"setRelation\": {\n // An edge already pointing at the same target with no reorder asked for\n // is the relation twin of a same-value write.\n if (op.place === undefined && deps.world.getRelation(op.e, op.r) === op.target) continue;\n written.add(op.e);\n kept.push(op);\n break;\n }\n case \"removeRelation\": {\n if (deps.world.getRelations(op.e, op.r).length === 0) continue;\n written.add(op.e);\n kept.push(op);\n break;\n }\n case \"move\": {\n // `move` IS diffed, and the reason it is safe to diff is petition I15's\n // two chokepoints. The worry was a glide in flight: drop the move and\n // the tween keeps easing toward a stale target. But every path that\n // moves the durable value — a post-seal write, an undo — already\n // retargets live tweens onto doc truth, so \"the doc already says `to`\"\n // means \"any live tween already aims at `to`\". There is nothing to\n // strand.\n //\n // Not diffing it was not a small conservatism: the flagship path\n // commits its whole layout through `move`, so an undiffed move meant\n // every peer that merely OPENED a laid-out document immediately wrote\n // the same layout back to it.\n const current = deps.docValue(op.e, Position as Component) as\n | { x: number; y: number }\n | undefined;\n if (current !== undefined && valueEquals(Position as Component, { x: op.to.x, y: op.to.y }, current)) {\n continue;\n }\n if (deps.writeTargets.has(Position as Component)) derivedOutput = true;\n noteValue(op.e, Position as Component, { x: op.to.x, y: op.to.y });\n written.add(op.e);\n kept.push(op);\n break;\n }\n default: {\n written.add(op.e);\n kept.push(op);\n break;\n }\n }\n }\n\n return { ops: kept, derivedOutput, writtenEntities: [...written], writtenValues: values };\n}\n\n/** Replay diffed ops onto the real transaction. */\nexport function replayOps(ops: readonly RecOp[], tx: GuardedTx): void {\n for (const op of ops) {\n switch (op.kind) {\n case \"set\":\n tx.edit(op.e).set(op.c as Component<unknown>, op.v);\n break;\n case \"add\":\n tx.addComponent(op.e, op.c as Component<unknown>, op.v);\n break;\n case \"removeComponent\":\n tx.removeComponent(op.e, op.c);\n break;\n case \"destroy\":\n tx.destroy(op.e);\n break;\n case \"addTag\":\n tx.addTag(op.e, op.t);\n break;\n case \"removeTag\":\n tx.removeTag(op.e, op.t);\n break;\n case \"setRelation\":\n tx.setRelation(op.e, op.r, op.target, op.place);\n break;\n case \"addRelation\":\n tx.addRelation(op.e, op.r, op.target);\n break;\n case \"removeRelation\":\n tx.removeRelation(op.e, op.r, op.target);\n break;\n case \"moveRelation\":\n tx.moveRelation(op.e, op.r, op.place);\n break;\n case \"move\":\n tx.move(op.e, op.to, { animateMs: op.animateMs });\n break;\n }\n }\n}\n","/**\n * `ctx.world` and `ctx.query` — the behavior read surface (design-009 §4.4,\n * BF-D19).\n *\n * `ctx.world` is a HOST-BUILT WRAPPER and that is a decision, not an\n * implementation shortcut. The obvious alternative — hand authors strata's\n * `ReadonlyWorld` — is not a sandbox: it is `Omit<World, WorldMutatorName>`,\n * which keeps `.runtime` (the full mutable store) and, being a type, erases at\n * runtime anyway. A wrapper object exposes exactly what it forwards.\n *\n * `ctx.query` closes the DISCOVERY hole. Without it a behavior could navigate\n * only outward from its own instances, and `changed` got abused as a discovery\n * channel — a journal is a terrible search index. Scoping the terms to the\n * declared `reads` keeps the access story honest, and walking through the\n * running system's `SystemCtx` means the walk is ATTRIBUTED: strata's only\n * ENFORCED read path and its only zero-allocation bulk path. Three arguments,\n * one mechanism.\n */\nimport { Not, defineQuery } from \"@vibecook/strata-ecs\";\nimport type { Component, Entity, Query, Relation, Resource, SystemCtx, Tag, World } from \"@vibecook/strata-ecs\";\nimport { devGuardsEnabled } from \"../guards/dev\";\nimport { schemaMeta } from \"../schema/meta\";\nimport type { AnyBehaviorDef, BehaviorQuery, BehaviorQuerySpec, BehaviorWorld } from \"./types\";\n\nexport function createBehaviorWorld(world: World): BehaviorWorld {\n return {\n read: (e, c) => world.read(e, c),\n get: (e, c) => world.get(e, c),\n readField: (e, c, f) => world.readField(e, c, f),\n has: (e, c) => world.has(e, c),\n hasTag: (e, t) => world.hasTag(e, t),\n getRelation: (e, r) => world.getRelation(e, r),\n getRelations: (e, r) => world.getRelations(e, r),\n getReverse: (e, r) => world.getReverse(e, r),\n orderStamp: (parent, r) => world.orderStamp(parent, r),\n getResource: (res) => world.getResource(res),\n componentsOf: (e) => world.componentsOf(e),\n tagsOf: (e) => world.tagsOf(e),\n isAlive: (e) => world.isAlive(e),\n };\n}\n\n/** Resolve a query term to its underlying handle (a behavior means its component). */\nfunction termOf(t: Component | Tag | AnyBehaviorDef): Component | Tag {\n if (typeof t === \"object\" && t !== null && (t as AnyBehaviorDef).__behavior === true) {\n return (t as AnyBehaviorDef).component as Component;\n }\n return t as Component | Tag;\n}\n\nfunction termName(t: Component | Tag): string {\n return schemaMeta.component(t as Component)?.name ?? schemaMeta.tagName(t as Tag) ?? \"<handle>\";\n}\n\n/**\n * The compiled-query cache for one behavior. Keyed on the term identity list,\n * so the common case (a behavior calling `ctx.query` with the same spec every\n * frame) compiles ONCE — `defineQuery` identity is strata's own cache key for\n * the matched-archetype list, so re-compiling per call would defeat two caches.\n */\nexport function createQueryScope(behavior: AnyBehaviorDef, allowed: ReadonlySet<Component | Tag>) {\n const cache = new Map<string, Query>();\n let nextId = 0;\n const ids = new Map<Component | Tag, number>();\n const idOf = (t: Component | Tag): number => {\n let id = ids.get(t);\n if (id === undefined) {\n id = nextId++;\n ids.set(t, id);\n }\n return id;\n };\n\n const check = (t: Component | Tag): void => {\n if (!devGuardsEnabled() || allowed.has(t)) return;\n throw new Error(\n `ice: behavior \"${behavior.name}\" queried \"${termName(t)}\", which is not in its reads: — a behavior may only query what it declared (design-009 §4.4). Add it to reads:, or navigate from ctx.entities() instead.`,\n );\n };\n\n const compile = (spec: BehaviorQuerySpec): Query => {\n const all = (spec.all ?? []).map(termOf);\n const none = (spec.none ?? []).map(termOf);\n for (const t of all) check(t);\n for (const t of none) check(t);\n const key = `${all.map(idOf).join(\",\")}|${none.map(idOf).join(\",\")}`;\n let q = cache.get(key);\n if (q === undefined) {\n q = defineQuery([...all, ...none.map((t) => Not(t))]);\n cache.set(key, q);\n }\n return q;\n };\n\n /** Build the per-call query handle bound to the current walker. */\n return function scopedQuery(walker: BehaviorWalker, spec: BehaviorQuerySpec): BehaviorQuery {\n const q = compile(spec);\n return {\n entities() {\n const out: Entity[] = [];\n walker.each(q, (e) => out.push(e));\n return out;\n },\n each(fn) {\n walker.each(q, fn);\n },\n first() {\n return walker.first(q);\n },\n };\n };\n}\n\n/**\n * Where a behavior's walks and structural ops go, which depends on WHERE it is\n * running — and the difference is not cosmetic.\n *\n * In a pipeline phase the behavior is inside a system: walks go through\n * `SystemCtx` (attributed — strata's enforced read path), and structural ops\n * are DEFERRED to the phase boundary because immediate `world.*` structural\n * mutation throws at iteration depth > 0.\n *\n * At the publish slot there is no running system and no iteration bracket:\n * walks are plain `world.query` (unattributed — nothing to attribute them to),\n * and structural ops are immediate and legal. Ephemeral behaviors live here,\n * which is exactly why eph structural writes are legal for them and illegal\n * for everyone else.\n */\nexport interface BehaviorWalker {\n each(q: Query, fn: (e: Entity) => void): void;\n first(q: Query): Entity | undefined;\n addComponent(e: Entity, c: Component, v: unknown): void;\n removeComponent(e: Entity, c: Component): void;\n}\n\nexport function systemWalker(ctx: SystemCtx): BehaviorWalker {\n return {\n each(q, fn) {\n ctx.query(q).each((b) => {\n for (const row of b) fn(b.entity(row));\n });\n },\n first: (q) => ctx.firstOf(q),\n addComponent: (e, c, v) => ctx.addComponent(e, c as Component<unknown>, v),\n removeComponent: (e, c) => ctx.removeComponent(e, c),\n };\n}\n\nexport function publishWalker(world: World): BehaviorWalker {\n return {\n each(q, fn) {\n world.query(q).each((b) => {\n for (const row of b) fn(b.entity(row));\n });\n },\n first: (q) => world.firstOf(q),\n addComponent: (e, c, v) => world.addComponent(e, c as Component<unknown>, v),\n removeComponent: (e, c) => world.removeComponent(e, c),\n };\n}\n\n/** The term set a behavior may query: its own component ∪ declared components/tags. */\nexport function allowedQueryTerms(\n behavior: AnyBehaviorDef,\n readComponents: readonly Component[],\n readTags: readonly Tag[],\n): ReadonlySet<Component | Tag> {\n const set = new Set<Component | Tag>([behavior.component as Component]);\n for (const c of readComponents) set.add(c);\n for (const t of readTags) set.add(t);\n return set;\n}\n\nexport type { Relation, Resource };\n","/**\n * ops.arrange — the explicit desktop-style \"Clean Up\" (2026-07-17, James:\n * \"if user click auto layout, it will try to organize the canvas nicely, bit\n * like desktop auto layout feature in windows and mac\").\n *\n * Scope: explicit `ids` > the current selection (when ≥2, Figma-tidy style) >\n * every widget of the CURRENT nav frame (the same Selectable ∧ Active ∧\n * WidgetEquipped set selectAll sees — works at any nav depth, coordinates are\n * frame-local for every member by construction).\n *\n * Placement (v2 2026-07-17, James: \"can this clean up be more smarter?\"):\n * - WIRED widgets arrange like Unreal Blueprint's auto-format: each\n * connected component (WireFrom/WireTo among the movers) is laid out by\n * kernel `layerGraph` — layered columns along wire direction — and moves\n * as one rigid block.\n * - Blocks + loose widgets then pack via kernel `packLayout` (bottom-left\n * candidates: dense with mixed sizes, anchored at the cluster's own bbox\n * top-left, idempotent — a second click is a no-op and commits nothing).\n * - Frame widgets OUTSIDE the moving set are passed as OBSTACLES: a scoped\n * Clean Up flows around bystanders instead of landing on top of them.\n *\n * Write protocol (design-001 §3, composed from existing primitives only):\n * 1. ONE guarded transaction sets every mover's final Position — a single\n * undo step restores the whole arrangement. The tx write-through snaps\n * runtime + baseline to the target synchronously (strata transaction.ts\n * §13.2 rule 2: pre-existing component value writes are committer-wins).\n * 2. Per mover: attach TransformTween(→ target), then write the runtime\n * cell BACK to the old position through the session LiveWriter — legal\n * divergence (a live tween IS the claim, design-001 §3 amendment), so\n * the card glides while the document already holds the truth. The tween\n * reconverges with the committed value on land; no commit-at-land\n * machinery exists or is needed.\n *\n * **[AMENDED 2026-08-15, petition I15]** Two corrections, both from the door\n * review:\n * - The parenthetical that used to sit here — \"undo DURING the glide is the\n * same accepted divergence window fly-back already has\" — was WRONG. It is\n * not a window: an undo mid-glide advanced the baseline alone (strata's\n * `(own, value)` branch banks nothing), the tween landed on the stale\n * target, and the cell stayed diverged FOREVER, poisoned against later\n * remote updates. The facade's history chokepoint now retargets live tweens\n * onto doc truth, so ⌘Z mid-glide converges by landing.\n * - Movers already tweening are RETARGETED, not skipped. Skipping them left a\n * second Clean Up gliding everyone else while the in-flight ones completed\n * at their previous, now-wrong targets.\n *\n * The user's hand still always wins: widgets under a live Grab are skipped.\n * Runtime-only widgets (no doc key) skip the tx and are tweened/written\n * directly — no doc cell, nothing to guard.\n */\nimport { layerGraph, packLayout, type LayoutRect } from \"@ice/kernel\";\nimport type { Entity, World } from \"@vibecook/strata-ecs\";\nimport { defineQuery } from \"@vibecook/strata-ecs\";\nimport type { DurableStore } from \"@vibecook/strata-ecs/durable\";\nimport {\n Active,\n Grab,\n MeasuredSize,\n Position,\n Selectable,\n Size,\n TransformTween,\n Wire,\n WireFrom,\n WireTo,\n} from \"../catalog\";\nimport { guardedTransaction } from \"../guards/guarded-tx\";\nimport type { LiveWriter } from \"../guards/live-writer\";\nimport { WidgetEquipped } from \"../widget/define-widget\";\nimport { selectedEntities } from \"./selection\";\n\nexport interface ArrangeOpts {\n /** Explicit scope; wins over selection/frame resolution. */\n readonly ids?: readonly Entity[];\n /** Min separation between packed widgets (default 24). */\n readonly gutter?: number;\n /** Row wrap width; default = packLayout's near-square derivation. */\n readonly maxWidth?: number;\n /** Glide duration; 0 snaps instantly (tests/headless). Default 240ms. */\n readonly durationMs?: number;\n}\n\nconst ARRANGE_MS = 240;\nconst ARRANGE_GUTTER = 24;\n\nconst frameWidgetsQ = defineQuery([Position, Size, Selectable, Active, WidgetEquipped]);\nconst wireQ = defineQuery([Wire]);\n\n/** Returns the entities that actually moved (empty = already tidy). */\nexport function arrangeWidgets(\n store: DurableStore,\n liveWriter: LiveWriter,\n world: World,\n opts: ArrangeOpts = {},\n): Entity[] {\n let targets: Entity[];\n if (opts.ids !== undefined && opts.ids.length > 0) {\n targets = [...opts.ids];\n } else {\n const sel = selectedEntities(world);\n if (sel.length >= 2) {\n targets = sel;\n } else {\n targets = [];\n world.query(frameWidgetsQ).each((b) => {\n for (const r of b) targets.push(b.entity(r));\n });\n }\n }\n\n const movable = targets.filter(\n (e) =>\n world.isAlive(e) &&\n // Grab-held only: an in-flight tween is RETARGETED below (I15), not\n // skipped — skipping stranded it at the previous run's target.\n !world.has(e, Grab) &&\n world.get(e, Position) !== undefined,\n );\n if (movable.length < 2) return [];\n\n const rectOf = (e: Entity): LayoutRect => {\n const p = world.get(e, Position) as { x: number; y: number };\n const m = world.get(e, MeasuredSize);\n const s = m !== undefined && m.w > 0 ? m : (world.get(e, Size) ?? { w: 0, h: 0 });\n return { x: p.x, y: p.y, w: s.w, h: s.h };\n };\n const rects: LayoutRect[] = movable.map(rectOf);\n const gutter = opts.gutter ?? ARRANGE_GUTTER;\n\n // One band width rules both layers: wired blocks WRAP into stacked bands\n // when a chain would outgrow it (2026-07-17 \"rigid blocks\" limit lifted),\n // and the packer wraps loose rows at the same width. Explicit maxWidth\n // wins; the default is packLayout's own near-square derivation, computed\n // over the individual movers.\n const bandWidth =\n opts.maxWidth ??\n (() => {\n let area = 0;\n let widest = 0;\n for (const r of rects) {\n area += (r.w + gutter) * (r.h + gutter);\n widest = Math.max(widest, r.w);\n }\n return Math.max(widest, Math.sqrt(area * 1.6));\n })();\n\n // Bystanders are obstacles: every frame widget outside the moving set\n // (unselected, live-claimed, in-flight) stays put and must not be crowded.\n const movableSet = new Set(movable);\n const obstacles: LayoutRect[] = [];\n world.query(frameWidgetsQ).each((b) => {\n for (const r of b) {\n const e = b.entity(r);\n if (!movableSet.has(e)) obstacles.push(rectOf(e));\n }\n });\n\n // Wire edges among the movers (WireFrom/WireTo point at widgets): each\n // connected component becomes a rigid layerGraph block.\n const indexOf = new Map<Entity, number>();\n movable.forEach((e, i) => indexOf.set(e, i));\n const edges: Array<[number, number]> = [];\n world.query(wireQ).each((b) => {\n for (const r of b) {\n const wire = b.entity(r);\n const from = world.getRelation(wire, WireFrom);\n const to = world.getRelation(wire, WireTo);\n if (from === undefined || to === undefined) continue;\n const fi = indexOf.get(from);\n const ti = indexOf.get(to);\n if (fi !== undefined && ti !== undefined && fi !== ti) edges.push([fi, ti]);\n }\n });\n const parent = movable.map((_, i) => i);\n const find = (i: number): number => {\n let root = i;\n while (parent[root] !== root) root = parent[root] as number;\n let cursor = i;\n while (parent[cursor] !== root) {\n const next = parent[cursor] as number;\n parent[cursor] = root;\n cursor = next;\n }\n return root;\n };\n for (const [u, v] of edges) {\n const a = find(u);\n const b = find(v);\n if (a !== b) parent[a] = b;\n }\n const comps = new Map<number, number[]>();\n for (let i = 0; i < movable.length; i++) {\n const root = find(i);\n const list = comps.get(root);\n if (list === undefined) comps.set(root, [i]);\n else list.push(i);\n }\n\n // Pack units: wired components as blocks (internal layerGraph placement),\n // everything else as itself.\n type Unit = { members: number[]; rel: Array<{ x: number; y: number }> };\n const units: Unit[] = [];\n const unitRects: LayoutRect[] = [];\n for (const members of comps.values()) {\n if (members.length < 2) {\n const i = members[0] as number;\n units.push({ members: [i], rel: [{ x: 0, y: 0 }] });\n unitRects.push(rects[i] as LayoutRect);\n continue;\n }\n const local = new Map<number, number>();\n members.forEach((gi, li) => local.set(gi, li));\n const localEdges: Array<[number, number]> = [];\n for (const [u, v] of edges) {\n const lu = local.get(u);\n const lv = local.get(v);\n if (lu !== undefined && lv !== undefined) localEdges.push([lu, lv]);\n }\n const sizes = members.map((gi) => ({ w: (rects[gi] as LayoutRect).w, h: (rects[gi] as LayoutRect).h }));\n const measure = (placements: Array<{ x: number; y: number }>): { w: number; h: number } => {\n let w = 0;\n let h = 0;\n placements.forEach((p, li) => {\n const r = rects[members[li] as number] as LayoutRect;\n w = Math.max(w, p.x + r.w);\n h = Math.max(h, p.y + r.h);\n });\n return { w, h };\n };\n // Short chains stay LINEAR (the Blueprint promise: follow the wires);\n // only a run clearly wider than the band (>1.5×) wraps into stacked\n // bands. The decision depends only on the graph, so re-runs repeat it —\n // idempotence holds.\n let rel = layerGraph(sizes, localEdges, { gapX: gutter * 2, gapY: gutter });\n let dims = measure(rel);\n if (dims.w > bandWidth * 1.5) {\n rel = layerGraph(sizes, localEdges, { gapX: gutter * 2, gapY: gutter, maxWidth: bandWidth });\n dims = measure(rel);\n }\n let bx = Number.POSITIVE_INFINITY;\n let by = Number.POSITIVE_INFINITY;\n for (const gi of members) {\n const r = rects[gi] as LayoutRect;\n bx = Math.min(bx, r.x); // the block's CURRENT anchor: members' bbox top-left\n by = Math.min(by, r.y);\n }\n units.push({ members, rel });\n unitRects.push({ x: bx, y: by, w: dims.w, h: dims.h });\n }\n\n const placedUnits = packLayout(unitRects, { gutter, obstacles, maxWidth: bandWidth });\n\n const finalPos = new Array<{ x: number; y: number }>(movable.length);\n units.forEach((u, k) => {\n const p = placedUnits[k] as { x: number; y: number };\n u.members.forEach((gi, li) => {\n const rel = u.rel[li] as { x: number; y: number };\n finalPos[gi] = { x: p.x + rel.x, y: p.y + rel.y };\n });\n });\n\n const moves: Array<{ e: Entity; from: { x: number; y: number }; to: { x: number; y: number } }> = [];\n for (let i = 0; i < movable.length; i++) {\n const from = rects[i] as LayoutRect;\n const to = finalPos[i] as { x: number; y: number };\n if (Math.abs(from.x - to.x) < 0.5 && Math.abs(from.y - to.y) < 0.5) continue;\n moves.push({ e: movable[i] as Entity, from: { x: from.x, y: from.y }, to });\n }\n if (moves.length === 0) return [];\n\n // ONE transaction owns capture, the durable finals, and the glide — the\n // write protocol above, now expressed in the primitive it seeded\n // (`tx.move`, petition I15). Runtime-only movers are recognised by `keyOf`\n // and skip the durable half without a second code path here.\n const dur = opts.durationMs ?? ARRANGE_MS;\n guardedTransaction(\n store,\n world,\n (tx) => {\n for (const m of moves) tx.move(m.e, m.to, { animateMs: dur });\n },\n { live: liveWriter, keyOf: (e) => store.keyOf(e) },\n );\n return moves.map((m) => m.e);\n}\n","/**\n * Engine-owned destroy cascade (design-001 §5.1, §5.3, design-003 §5).\n *\n * strata clears an entity's edges on `tx.destroy` but does NOT recurse, so the\n * engine walks containment itself: depth-first over `getReverse(e, ChildOf)`,\n * destroying descendants before their parent, then the root. Wires are reified\n * edge entities, so a wire whose `WireFrom`/`WireTo` endpoint dies is destroyed\n * with it (reverse-index lookup, same transaction).\n *\n * The walk reads runtime world state via `getReverse`; `tx.destroy` only RECORDS\n * (applied at seal / projection), so the reverse indices stay whole for the whole\n * walk. A `visited` set guards against cycles and double-destroying a wire that\n * touches two doomed endpoints.\n */\nimport type { Entity, World } from \"@vibecook/strata-ecs\";\nimport type { Mutator } from \"@vibecook/strata-ecs/durable\";\nimport { WireFrom, WireTo } from \"../catalog/graph\";\nimport { ChildOf } from \"../catalog/scene\";\n\n/** Depth-first destroy `root` and its `ChildOf` subtree + any wires bound to a destroyed entity. */\nexport function cascadeDestroy(tx: Mutator, world: World, root: Entity): void {\n const visited = new Set<Entity>();\n\n const walk = (e: Entity): void => {\n if (visited.has(e)) return;\n visited.add(e);\n\n // Children before their parent.\n for (const child of world.getReverse(e, ChildOf)) walk(child);\n\n // Wires whose endpoint dies here die with it.\n for (const wire of world.getReverse(e, WireFrom)) walk(wire);\n for (const wire of world.getReverse(e, WireTo)) walk(wire);\n\n tx.destroy(e);\n };\n\n walk(root);\n}\n","/**\n * \"Is a gesture in flight?\" — the one read, shared by every subsystem that\n * must not act mid-interaction (design-003 §8 terminal phases).\n *\n * Extracted from `doc/autosave.ts` on 2026-08-04 when the frame gate needed\n * the same question: autosave defers a save so it never captures a half-\n * applied interaction, and a freeze walks its settle until the gesture it\n * cancelled has reached its commit tick. One definition of \"in flight\", so the\n * two can never drift apart.\n */\nimport { Any, defineQuery } from \"@vibecook/strata-ecs\";\nimport type { World } from \"@vibecook/strata-ecs\";\nimport { Camera, Drag, GesturePhases, LongPress, Pinch, Tap, WheelPan, WheelZoom } from \"../catalog\";\n\nconst gestureQ = defineQuery([Any(Tap, LongPress, Drag, Pinch, WheelPan, WheelZoom)]);\nconst P = GesturePhases;\n\n/**\n * Any recognizer NOT in a terminal phase ⇒ a gesture is in flight (mirrors the\n * cleanup.ts terminal definition: Failed/Cancelled/Ended, plus Recognized-Tap).\n */\nexport function anyGestureNonTerminal(world: World): boolean {\n let active = false;\n world.query(gestureQ).each((b) => {\n for (const r of b) {\n const e = b.entity(r);\n const terminal =\n world.hasTag(e, P.tags.Failed) ||\n world.hasTag(e, P.tags.Cancelled) ||\n world.hasTag(e, P.tags.Ended) ||\n (world.hasTag(e, P.tags.Recognized) && world.has(e, Tap));\n if (!terminal) {\n active = true;\n return;\n }\n }\n });\n return active;\n}\n\n/**\n * The full mid-interaction read: a live camera gesture (pan/zoom, which writes\n * `Camera.gesturing` without a recognizer entity of its own) OR any recognizer\n * still walking its phases. Either means runtime edits are outstanding and the\n * durable transaction that will carry them has not been sealed yet.\n */\nexport function isMidGesture(world: World): boolean {\n return world.getResource(Camera)?.gesturing === true || anyGestureNonTerminal(world);\n}\n","/**\n * The widget equip system (design-005 §2 \"capability-tag stamping recipe\",\n * design-001 reconciled catalog).\n *\n * Capability tags are RUNTIME state — a restored/remote document carries only\n * durable cells, so every projected widget entity gets its type's tags stamped\n * here, once (`WidgetEquipped` makes the query zero-match at steady state:\n * row-filtered, nothing runs, nothing stamps). Runs in `derive`; new\n * projections from this frame's sync() are visible by then.\n *\n * This generalizes the graybox demo's equipSceneBoxes into the engine.\n */\nimport { Not, defineQuery, defineSystem, type Component, type System } from \"@vibecook/strata-ecs\";\nimport type { AnyBehaviorDef } from \"../behavior/types\";\nimport { PrefabId } from \"../schema/prefab\";\nimport { WidgetEquipped, widgets } from \"./define-widget\";\n\n/** Defaults ∪ the declared pre-attach data, serialized for the cell. */\nfunction runtimeBehaviorCell(b: AnyBehaviorDef, data: Readonly<Record<string, unknown>>): Record<string, unknown> {\n const out: Record<string, unknown> = { ...(b.defaults as Record<string, unknown>) };\n for (const [k, v] of Object.entries(data)) {\n if (v === undefined) continue;\n out[k] = b.schema[k]?.kind === \"json\" ? JSON.stringify(v) : v;\n }\n return out;\n}\n\nconst unequippedQ = defineQuery([PrefabId, Not(WidgetEquipped)]);\n\nexport function createWidgetEquipSystem(): System {\n return defineSystem(\n unequippedQ,\n (b, ctx) => {\n for (const r of b) {\n const e = b.entity(r);\n const type = ctx.read(e, PrefabId).id;\n const widget = typeof type === \"string\" ? widgets.get(type) : undefined;\n // Non-widget prefabs still get the Equipped mark so this row never\n // re-scans; widgets get their capability tags.\n if (widget !== undefined) {\n for (const tag of widget.capabilityTags) ctx.addTag(e, tag);\n // RUNTIME pre-attached behaviors (design-009 §6) are riders, exactly\n // like capability tags: session-local, and needed on every peer's\n // projection — including one that received this widget over the wire\n // or restored it from a file, neither of which ran its spawn path.\n for (const entry of widget.behaviors) {\n if (entry.behavior.store !== \"runtime\") continue;\n ctx.addComponent(\n e,\n entry.behavior.component as Component<Record<string, unknown>>,\n runtimeBehaviorCell(entry.behavior, entry.data),\n );\n }\n }\n ctx.addTag(e, WidgetEquipped);\n }\n },\n { name: \"widgetEquip\" },\n );\n}\n","/**\n * setWidgetProps — the paved-road widget prop UPDATE op (2026-07-13 review:\n * spawn validated through each prop's Standard Schema, but the update path —\n * raw `useCommit` writes — bypassed bounds/enum/json-shape checks entirely).\n *\n * Mirrors `widgetSpawnInits` semantics exactly: unknown prop names throw,\n * each given value runs `spec[\"~standard\"].validate` (an invalid value throws\n * BEFORE anything is written), `p.json` values are validated as parsed shapes\n * then serialized into their string cell. Writes are whole-group absolute\n * values (the current cell merged with the validated updates — design-001\n * §5.2 conflict-group granularity), one guardedTransaction = one undo step.\n */\nimport type { Component, Entity, World } from \"@vibecook/strata-ecs\";\nimport type { DurableStore } from \"@vibecook/strata-ecs/durable\";\nimport { guardedTransaction, type GuardedTxOpts } from \"../guards/guarded-tx\";\nimport { PrefabId } from \"../schema/prefab\";\nimport { widgets } from \"./define-widget\";\n\nexport function setWidgetProps(\n store: DurableStore,\n world: World,\n entity: Entity,\n props: Readonly<Record<string, unknown>>,\n opts?: GuardedTxOpts,\n): void {\n const type = world.get(entity, PrefabId)?.id;\n const widget = typeof type === \"string\" ? widgets.get(type) : undefined;\n if (widget === undefined) {\n throw new Error(`ice: setWidgetProps — entity ${String(entity)} is not a defined widget.`);\n }\n for (const name of Object.keys(props)) {\n if (widget.propToGroup[name] === undefined) {\n throw new Error(`ice: setWidgetProps(\"${widget.type}\") — unknown prop \"${name}\".`);\n }\n }\n\n // Validate + serialize every touched group BEFORE the transaction opens, so\n // an invalid value can never leave a partial multi-group update behind.\n const groupWrites: [Component, Record<string, string | number | boolean>][] = [];\n for (const g of widget.groups) {\n const touched = Object.keys(props).some((name) => widget.propToGroup[name] === g.name);\n if (!touched) continue;\n const current = (world.get(entity, g.component) ?? {}) as Record<string, string | number | boolean>;\n const value = { ...current };\n for (const [name, spec] of Object.entries(g.fields)) {\n const given = props[name];\n if (given === undefined) continue;\n const result = spec[\"~standard\"].validate(given);\n if (\"issues\" in result) {\n throw new Error(\n `ice: setWidgetProps(\"${widget.type}\") prop \"${name}\" invalid — ${result.issues[0]?.message}`,\n );\n }\n value[name] = spec.kind === \"json\" ? JSON.stringify(given) : (given as string | number | boolean);\n }\n groupWrites.push([g.component as Component, value]);\n }\n\n guardedTransaction(\n store,\n world,\n (tx) => {\n for (const [component, value] of groupWrites) {\n tx.edit(entity).set(component, value);\n }\n },\n opts,\n );\n}\n","/**\n * Measurement ingest (design-004 §2; `input` phase).\n *\n * Drains the {@link MeasureQueue} once per tick and folds each auto-sized\n * widget's latest content-box measurement into the `MeasuredSize` session rider\n * — the effective-size source cull/hit/breakpoint consume where a widget is\n * auto-sized (`MeasuredSize` where present and >0, else `Size`). Auto-sized\n * widgets never commit `Size`; the doc stores authorial intent only.\n *\n * Scheduled on the CANVAS-SURFACE anchor query (exactly one such entity,\n * guaranteed by install) — like `pointerIngest` — because the body must run on\n * frames where no measured widget exists yet, and a tag-only query matches every\n * archetype-independent (a tick system, strata 0.5.0): the drain runs exactly\n * once per frame BY CONSTRUCTION.\n *\n * Two guards keep a hidden widget's `display:none` collapse out of the rider\n * (the §2 double wall): the adapter never enqueues a `0×0` sample, and ingest\n * skips `w===0 && h===0` again here. Real changes clear a **±1 px dead-band**\n * against the current rider so sub-pixel RO jitter never restamps (which would\n * churn breakpoint/cull downstream). Within one drain, samples fold last-wins\n * per entity so a same-tick pair never double-`addComponent`s (strata's\n * flush-time duplicate policy).\n */\nimport type { Entity, System, TickSystem, World } from \"@vibecook/strata-ecs\";\nimport { defineQuery, defineSystem, defineTickSystem } from \"@vibecook/strata-ecs\";\nimport { MeasuredSize } from \"../catalog\";\nimport type { MeasureQueue } from \"../input/measure-queue\";\n\n/** Sub-pixel dead-band (px): a change must exceed this on either axis to restamp. */\nconst MEASURE_DEAD_BAND_PX = 1;\n\nexport function createMeasureIngest(world: World, queue: MeasureQueue): TickSystem {\n // Tick system (strata 0.5.0): the drain runs exactly once per frame by\n // construction (mirrors pointerIngest).\n return defineTickSystem(\n (ctx) => {\n const events = queue.drain();\n if (events.length === 0) return;\n\n // Fold last-wins per entity: one add/set per entity per tick (addComponent\n // defers, so a same-tick pair would otherwise duplicate at flush).\n const folded = new Map<Entity, { w: number; h: number }>();\n for (const ev of events) folded.set(ev.entity, { w: ev.w, h: ev.h });\n\n for (const [e, m] of folded) {\n if (m.w === 0 && m.h === 0) continue; // hidden-measure corruption guard (§2)\n if (!ctx.isAlive(e)) continue; // measured entity despawned between RO fire and ingest\n const cur = ctx.get(e, MeasuredSize);\n if (cur === undefined) {\n ctx.addComponent(e, MeasuredSize, { w: m.w, h: m.h });\n continue;\n }\n if (\n Math.abs(m.w - cur.w) > MEASURE_DEAD_BAND_PX ||\n Math.abs(m.h - cur.h) > MEASURE_DEAD_BAND_PX\n ) {\n ctx.edit(e).set(MeasuredSize, { w: m.w, h: m.h });\n }\n }\n },\n {\n name: \"measureIngest\",\n access: { write: [MeasuredSize] },\n runIf: () => queue.size() > 0,\n },\n );\n}\n","/**\n * Widget lifecycle: cull → keep-mounted LRU → the external mount store\n * (design-004 §2).\n *\n * - `cullSystem` (derive): viewport test over equipped widgets' EFFECTIVE size\n * (MeasuredSize where present, else Size), overscan scaled by zoom; flips\n * Visible/Culled CHANGE-ONLY. GATED (2026-07-15, the activeMembership\n * playbook): a real `runIf` — camera/viewport window compare as the `extra`\n * trigger (full pass; the window moved under everyone) ∨ a petition-7\n * collector on Position/Size/MeasuredSize + Active flips (delta pass —\n * drags/spawns/measures re-test only the journaled entities). Idle frames\n * skip; camera frames stay O(active) by the widgetQ Active scope.\n * - `mountSystem` (derive, after cull): maintains the mount list — every\n * Visible widget is mounted; Culled widgets stay mounted-but-hidden\n * (`display:none` at the host; React state preserved) within a count LRU\n * budget (default RUNTIME_BUDGETS.keepMountedWidgets); beyond it the\n * least-recently-visible unmount for real. Decisions are ENGINE-side; the\n * dom host reflector and the React portal hook both consume the snapshot.\n * GATED the same way on Visible/Culled flips (+ destroys of tagged\n * widgets); LRU recency is stamped at the flip (identical eviction order —\n * \"last tick seen visible\" = the tick it stopped being visible).\n * - The store implements the `useSyncExternalStore` contract: `subscribe` /\n * `getSnapshot` with snapshot identity changing IFF membership or a hidden\n * flag changed. Listener notification is deferred to post-notify (the\n * engine flush reflector) — never from inside the tick.\n */\nimport { Not, defineQuery, defineTickSystem, type Entity, type TickSystem, type World } from \"@vibecook/strata-ecs\";\nimport { screenToWorld } from \"@ice/kernel\";\nimport { Active, Camera, Culled, MeasuredSize, Position, Size, Viewport, Visible } from \"../catalog\";\nimport type { Engine } from \"../engine/engine\";\nimport { RUNTIME_BUDGETS } from \"../settings/defaults\";\nimport { WidgetEquipped } from \"./define-widget\";\nimport { createWidgetEquipSystem } from \"./equip\";\nimport { createBreakpointSystem } from \"../systems/chrome\";\nimport { createActiveMembership, currentNavFrame } from \"../nav/nested-canvas\";\nimport { createMeasureIngest } from \"../systems/measure-ingest\";\nimport type { MeasureQueue } from \"../input/measure-queue\";\nimport { makeChurnGuard } from \"../helpers/churn-guard\";\n\nconst widgetQ = defineQuery([Position, Size, WidgetEquipped, Active]);\n\nexport interface MountEntry {\n readonly entity: Entity;\n /** Culled-but-kept-mounted: host hides, React state survives. */\n readonly hidden: boolean;\n}\n\nexport interface WidgetMountStore {\n subscribe(listener: () => void): () => void;\n getSnapshot(): readonly MountEntry[];\n}\n\nexport interface WidgetRuntime {\n readonly store: WidgetMountStore;\n readonly cullSystem: TickSystem;\n readonly mountSystem: TickSystem;\n /** Post-notify listener flush — install registers it as a reflector. */\n flush(): void;\n}\n\nexport function createWidgetRuntime(\n world: World,\n opts: { keepMounted?: number } = {},\n): WidgetRuntime {\n const budget = opts.keepMounted ?? RUNTIME_BUDGETS.keepMountedWidgets;\n\n // Camera/viewport window compare — the cull gate's `extra` trigger. Kept\n // outside the guard so the closure caches the last-seen window verbatim\n // (undefined-ness included: the headless posture compares equal and never\n // fires; the first real camera write fires a full pass).\n let lastWin: { x: number; y: number; zoom: number; w: number; h: number } | undefined | null = null;\n // NAV DEFERRAL (field bug 2026-07-17, the folder-zombie): on the tick a nav\n // op lands, activeMembership strips Active from the departing frame's\n // widgets IN THE SAME TICK cull's full pass runs — and tag flips flush at\n // the group boundary, so cull classifies against STALE Active tags and the\n // FLIGHT-START window (which can span the old frame's coords). A widget\n // culled at root then re-tags Visible while ¬Active is a ZOMBIE: rendered,\n // unpickable, repaired by nobody (membership sees no input churn; cull only\n // touches Active). So: the nav tick SKIPS classification entirely and the\n // NEXT tick runs a forced full pass against the flushed membership.\n let lastNavFrame: Entity | undefined;\n let navPrimed = false;\n let navSkipTick = false;\n let navHoldFull = false;\n const cullGuard = makeChurnGuard(\n world,\n { components: [Position, Size, MeasuredSize], tags: [Active], coarse: false },\n () => {\n const frame = currentNavFrame(world);\n if (!navPrimed || frame !== lastNavFrame) {\n navPrimed = true;\n lastNavFrame = frame;\n navSkipTick = true;\n navHoldFull = true;\n }\n const cam = world.getResource(Camera);\n const vp = world.getResource(Viewport);\n const win =\n cam === undefined || vp === undefined\n ? undefined\n : { x: cam.x, y: cam.y, zoom: cam.zoom, w: vp.w, h: vp.h };\n const changed =\n lastWin === null ||\n (win === undefined) !== (lastWin === undefined) ||\n (win !== undefined &&\n lastWin !== undefined &&\n lastWin !== null &&\n (win.x !== lastWin.x || win.y !== lastWin.y || win.zoom !== lastWin.zoom || win.w !== lastWin.w || win.h !== lastWin.h));\n lastWin = win;\n // Nav ticks fire the gate regardless: the skip tick must consume the\n // guard (dropping its delta is safe — the held full pass covers it) and\n // the following tick must run even if camera/journal are quiet.\n if (navSkipTick || navHoldFull) return true;\n return changed;\n },\n );\n\n const cullSystem = defineTickSystem(\n (ctx) => {\n const work = cullGuard.take();\n if (work === undefined) return;\n if (navSkipTick) {\n // The nav tick: membership's Active flips flush at this group's\n // boundary — classify next tick (navHoldFull), never against stale tags.\n navSkipTick = false;\n return;\n }\n const forcedFull = navHoldFull;\n navHoldFull = false;\n const cam = ctx.getResource(Camera);\n const vp = ctx.getResource(Viewport);\n if (cam === undefined || vp === undefined || vp.w === 0) return; // headless: everything stays unculled\n const over = RUNTIME_BUDGETS.cullOverscanWorldPerZoom / cam.zoom;\n const tl = screenToWorld(0, 0, cam);\n const br = screenToWorld(vp.w, vp.h, cam);\n const minX = tl.x - over;\n const minY = tl.y - over;\n const maxX = br.x + over;\n const maxY = br.y + over;\n const classify = (e: Entity): void => {\n const p = ctx.read(e, Position);\n const m = ctx.get(e, MeasuredSize);\n const s = m !== undefined && m.w > 0 ? m : ctx.read(e, Size); // effective size\n const inView = p.x + s.w >= minX && p.x <= maxX && p.y + s.h >= minY && p.y <= maxY;\n // Change-only flips (hygiene, design-002 §4).\n if (inView) {\n if (!ctx.hasTag(e, Visible)) {\n ctx.addTag(e, Visible);\n if (ctx.hasTag(e, Culled)) ctx.removeTag(e, Culled);\n }\n } else if (!ctx.hasTag(e, Culled)) {\n ctx.addTag(e, Culled);\n if (ctx.hasTag(e, Visible)) ctx.removeTag(e, Visible);\n }\n };\n if (work.full || forcedFull) {\n ctx.query(widgetQ).each((b) => {\n for (const r of b) classify(b.entity(r));\n });\n return;\n }\n for (const e of work.changed) {\n // The delta twin of widgetQ: equipped ∧ Active (membership already\n // parks non-Active in the canonical Culled state — never touch them).\n if (!ctx.isAlive(e) || !ctx.hasTag(e, Active)) continue;\n if (!world.hasTag(e, WidgetEquipped) || !ctx.has(e, Position) || !ctx.has(e, Size)) continue;\n classify(e);\n }\n },\n { name: \"cull\", access: { read: [Position, Size, MeasuredSize] }, runIf: cullGuard.runIf },\n );\n\n // --- mount bookkeeping (engine-side LRU; closure state is derived cache) ---\n const mounted = new Map<Entity, { hidden: boolean }>();\n const lastVisibleTick = new Map<Entity, number>();\n let tickCounter = 0;\n let snapshot: readonly MountEntry[] = [];\n let dirty = false;\n const listeners = new Set<() => void>();\n\n const visibleWidgetsQ = defineQuery([Position, Size, WidgetEquipped, Active, Visible]);\n const culledWidgetsQ = defineQuery([Position, Size, WidgetEquipped, Not(Visible)]);\n\n // GATED tick system (2026-07-15): Visible/Culled flips journal the entity;\n // destroys of tagged widgets land in `removed` (every mounted widget carries\n // one of the two tags). Idle frames skip. LRU recency stamps at the flip —\n // \"last tick seen visible\" = the tick it stopped being visible, so the\n // eviction order matches the old refresh-every-frame bookkeeping.\n const mountGuard = makeChurnGuard(world, { tags: [Visible, Culled], coarse: false });\n\n const mountSystem = defineTickSystem(\n (ctx) => {\n const work = mountGuard.take();\n if (work === undefined) return;\n tickCounter += 1;\n let changed = false;\n\n const markVisible = (e: Entity): void => {\n lastVisibleTick.set(e, tickCounter);\n const entry = mounted.get(e);\n if (entry === undefined) {\n mounted.set(e, { hidden: false });\n changed = true;\n } else if (entry.hidden) {\n entry.hidden = false;\n changed = true;\n }\n };\n const markHidden = (e: Entity): void => {\n const entry = mounted.get(e);\n if (entry !== undefined && !entry.hidden) {\n entry.hidden = true;\n lastVisibleTick.set(e, tickCounter); // visible until THIS tick\n changed = true;\n }\n };\n\n if (work.full) {\n // Full reconcile: first run, reset (doc switch — every handle dead),\n // coarse. Queries + the isAlive sweep rebuild the map from scratch.\n ctx.query(visibleWidgetsQ).each((vb) => {\n for (const r of vb) markVisible(vb.entity(r));\n });\n ctx.query(culledWidgetsQ).each((cb) => {\n for (const r of cb) markHidden(cb.entity(r));\n });\n for (const e of [...mounted.keys()]) {\n if (!world.isAlive(e)) {\n mounted.delete(e);\n lastVisibleTick.delete(e);\n changed = true;\n }\n }\n } else {\n for (const e of work.removed) {\n if (mounted.delete(e)) changed = true;\n lastVisibleTick.delete(e);\n }\n for (const e of work.changed) {\n if (!world.isAlive(e)) continue; // removed handles it\n // Active required, matching visibleWidgetsQ (defense in depth vs the\n // nav-tick zombie: a stray Visible on a non-member must never mount).\n if (ctx.hasTag(e, Visible) && ctx.hasTag(e, Active)) markVisible(e);\n else markHidden(e);\n }\n }\n\n // Keep-mounted LRU budget (only reachable when something flipped).\n const hiddenEntries = [...mounted.entries()].filter(([, v]) => v.hidden);\n const visibleCount = mounted.size - hiddenEntries.length;\n const hiddenBudget = Math.max(0, budget - visibleCount);\n if (hiddenEntries.length > hiddenBudget) {\n hiddenEntries.sort((a, b2) => (lastVisibleTick.get(a[0]) ?? 0) - (lastVisibleTick.get(b2[0]) ?? 0));\n for (const [e] of hiddenEntries.slice(0, hiddenEntries.length - hiddenBudget)) {\n mounted.delete(e); // true unmount — session UI state is best-effort\n lastVisibleTick.delete(e);\n changed = true;\n }\n }\n\n if (changed) {\n snapshot = [...mounted.entries()].map(([entity, v]) => ({ entity, hidden: v.hidden }));\n dirty = true;\n }\n },\n { name: \"widgetMount\", runIf: mountGuard.runIf },\n );\n\n return {\n store: {\n subscribe(listener) {\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\n getSnapshot: () => snapshot,\n },\n cullSystem,\n mountSystem,\n flush() {\n if (!dirty) return;\n dirty = false;\n for (const l of listeners) l();\n },\n };\n}\n\n/** Install cull + mount + the post-notify listener flush on an engine. */\nexport function installWidgetRuntime(\n engine: Engine,\n opts: { keepMounted?: number; measureQueue?: MeasureQueue } = {},\n): WidgetRuntime & { uninstall(): void } {\n const runtime = createWidgetRuntime(engine.world, opts);\n // equip → cull → mount → breakpoint (equip's deferred tags land at the\n // derive flush, so a brand-new widget mounts one frame after projection —\n // accepted lag). Breakpoints ship installed (review: built but orphaned).\n const removeSystems = engine.addSystems(\n \"derive\",\n createActiveMembership(engine.world), // membership BEFORE cull (design-004 §7)\n createWidgetEquipSystem(),\n runtime.cullSystem,\n runtime.mountSystem,\n createBreakpointSystem(engine.world),\n );\n // Measurement ingest (input phase) when the app wires a measure queue\n // (the dom measure adapter feeds it; design-004 §2).\n const removeMeasure =\n opts.measureQueue !== undefined\n ? engine.addSystems(\"input\", createMeasureIngest(engine.world, opts.measureQueue))\n : undefined;\n const removeReflector = engine.registerReflector({\n name: \"widgetMountFlush\",\n always: true, // cheap: a dirty-flag check; listener fan-out only on change\n flush: () => runtime.flush(),\n });\n return {\n ...runtime,\n uninstall() {\n removeSystems();\n removeMeasure?.();\n removeReflector();\n },\n };\n}\n","/**\n * Ground-layer (P0) pass configs — CANONICAL home (2026-07-16, the @ice/ground\n * extraction): plain data shared by the ground renderer, the react facade's\n * `grid` prop, and apps. They live in core because core is the vocabulary\n * package every layer may import (ground cannot import react; react cannot\n * import ground — design-002 §6). Values are verbatim from the original\n * renderers: GridConfig from v1 GridRenderer.ts:5-35 (tuned to Apple\n * Freeform / FigJam), wires + snap-guides from their 2026 dom reflectors.\n */\n\nexport interface GridConfig {\n /** World-unit spacings for up to 3 grid levels [fine, medium, coarse]. */\n spacings: [number, number, number];\n /** Dot RGB color as [r, g, b] in 0-1 range. */\n dotColor: [number, number, number];\n /** Base dot opacity multiplier (0-1). */\n dotAlpha: number;\n /** CSS-pixel range where a grid level fades in: [start, end]. */\n fadeIn: [number, number];\n /** CSS-pixel range where a grid level fades out: [start, end]. */\n fadeOut: [number, number];\n /** Dot radius range in CSS pixels [min, max]. Scaled by DPR internally. */\n dotRadius: [number, number];\n /** Per-level opacity weight: level i gets (base + i * step). */\n levelWeight: [number, number];\n}\n\n/** Verbatim from v1 GridRenderer.ts:27-35 (Apple Freeform / FigJam feel). */\nexport const DEFAULT_GRID_CONFIG: GridConfig = {\n spacings: [20, 100, 500],\n dotColor: [0.75, 0.77, 0.8],\n dotAlpha: 1.0,\n fadeIn: [8, 16],\n fadeOut: [120, 200],\n dotRadius: [0.75, 0.75],\n levelWeight: [1.0, 0.0],\n};\n\n/** Minimal-neutral wire styling (design-004 §6: chrome is subdued; wires defer to content). */\nexport interface WiresConfig {\n /** Default wire stroke (CSS color). */\n wireColor: string;\n /** Accent stroke for a Selected wire. */\n selectedColor: string;\n wireWidth: number;\n selectedWidth: number;\n /** Materialized-port dot radius (CSS px) + colors (idle vs during a connect drag). */\n portRadius: number;\n portColor: string;\n portActiveColor: string;\n}\n\nexport const DEFAULT_WIRES_CONFIG: WiresConfig = {\n wireColor: \"rgba(120, 132, 145, 0.9)\",\n selectedColor: \"#4a90d9\",\n wireWidth: 1.5,\n selectedWidth: 2,\n portRadius: 4,\n portColor: \"rgba(120, 132, 145, 0.9)\",\n portActiveColor: \"#4a90d9\",\n};\n\n/** v1 `DEFAULT_SNAP_GUIDE_CONFIG` (SnapGuideRenderer.ts), field for field. */\nexport interface SnapGuidesConfig {\n /** Guide line + spacing bar color as [r, g, b] in 0-1 range. */\n color: [number, number, number];\n /** Stroke width in screen px (constant across zoom). */\n lineWidth: number;\n /** Alignment-line alpha. */\n guideAlpha: number;\n /** Equal-spacing bar alpha. */\n spacingAlpha: number;\n /** End-tick half-length in screen px (v1 shader barHeight). */\n tickPx: number;\n}\n\nexport const DEFAULT_SNAP_GUIDES_CONFIG: SnapGuidesConfig = {\n color: [1.0, 0.0, 0.55], // v1 magenta/pink\n lineWidth: 1,\n guideAlpha: 0.8,\n spacingAlpha: 0.7,\n tickPx: 4,\n};\n","/**\n * The autosave kit (design-005 §6.6; design-001 §6.5 envelope-at-rest).\n *\n * Persists a `DocSession` to app-owned storage on a debounce (default 800 ms)\n * with a max-wait ceiling (default 10 s), DEFERRED while the user is mid-gesture\n * so a save never captures a half-applied interaction. What it writes is an\n * ENVELOPE (`session.exportEnvelope(savedAt)`) — never raw Loro bytes — so the\n * restore path can read the header and gate/quarantine BEFORE any import.\n *\n * CHANGE-SUBSCRIPTION SURFACE: two triggers, plus an initial arm.\n * - `DurableStore.subscribeOutbound` (durable-store.ts) fires SYNCHRONOUSLY on\n * each sealed LOCAL commit and never on remote imports.\n * - `DocSession.subscribeRemote` (doc-kit) fires after each successful\n * `applyRemote`. The original design left remote changes to \"whichever peer\n * originated them\" — but that peer persists to ITS storage, not this one's:\n * a joiner that received edits and closed restored a STALE local backup\n * (2026-07-13 review). Local autosave must reflect the last-seen document.\n * - Autosave starts DIRTY: state that predates startAutosave() (a seeded or\n * freshly-joined doc) reaches storage after the first debounce, not only\n * after the next edit (same review — a seeded doc could close unsaved).\n * No polling — the design's `store.exportSnapshot()` length/frontier poll is\n * the last-resort fallback and is not needed here.\n *\n * Clock and scheduler are injectable so tests are deterministic with NO real\n * timers; the design's `requestIdleCallback` optimization is just an alternate\n * `schedule` an app can pass. `flush()` forces an awaited save; `close()`\n * captures and durably serializes the final revision; `stop()` explicitly\n * discards pending state.\n *\n * RESTORE (`restoreAutosave`): reads storage → `openDocSession`. Incompatible or\n * corrupt bytes NEVER throw and NEVER brick boot (the M5 exit criterion) —\n * they come back as `{ status: \"quarantined\", reason, bytes }` so the app can\n * stash the bytes aside and start fresh.\n */\nimport type { World } from \"@vibecook/strata-ecs\";\nimport { isMidGesture } from \"../interaction/gesture-status\";\nimport { openDocSession, type DocSession, type DocSessionOpts } from \"./doc-kit\";\nimport type { DocVersionReport } from \"./version-gate\";\n\n/** The app-owned write side of storage (localStorage, IndexedDB, fs, cloud — WHERE is app-owned). */\nexport interface AutosaveStorageWrite {\n put(bytes: Uint8Array): Promise<void> | void;\n /** Optional opaque Loro-update journal. `put` replaces the checkpoint and\n * clears its journal; `append` durably extends the current checkpoint. */\n append?(bytes: Uint8Array): Promise<void> | void;\n}\n\n/** The app-owned read side of storage (restore path). */\nexport interface AutosaveStorageRead {\n get(): Promise<Uint8Array | undefined> | Uint8Array | undefined;\n}\n\n/** Cancels a scheduled callback (the return of an injected `schedule`). */\nexport type CancelScheduled = () => void;\n\nexport interface AutosaveOpts {\n readonly storage: AutosaveStorageWrite;\n /** The session's world — read for the gesture-deferral gate (never written). */\n readonly world: World;\n /** Quiet-period before a save (default 800 ms). */\n readonly debounceMs?: number;\n /** Hard ceiling from the first unsaved change to a forced save (default 10 s). */\n readonly maxWaitMs?: number;\n /** Wall-clock source; the engine never reads a clock itself (default `Date.now`). */\n readonly now?: () => number;\n /** Timer factory; return a canceller (default `setTimeout`/`clearTimeout`). */\n readonly schedule?: (fn: () => void, ms: number) => CancelScheduled;\n /** Compact after this many journal records (default 64). */\n readonly checkpointEvery?: number;\n /** Compact before the journal exceeds this many bytes (default 4 MiB). */\n readonly maxJournalBytes?: number;\n}\n\nexport type AutosaveStatus = \"idle\" | \"pending\" | \"deferred\" | \"saving\" | \"saved\" | \"error\";\n\nexport interface AutosaveState {\n readonly status: AutosaveStatus;\n /** Wall-clock ms of the last successful save (via the injected `now`), or undefined. */\n readonly lastSavedAt: number | undefined;\n /** True while there are unsaved changes (a timer is armed or deferred). */\n readonly pending: boolean;\n}\n\nexport interface Autosave {\n /** Force a save of the current document now and await it. Rejects when persistence fails. */\n flush(): Promise<void>;\n /**\n * Capture the final document synchronously, serialize it behind any in-flight\n * write, and stop only after storage acknowledges it. Rejects on failure and\n * may be retried; no document mutation should occur after close begins.\n */\n close(): Promise<void>;\n /** Discard pending state immediately. Idempotent; never use for a normal close. */\n stop(): void;\n /** A pull-based status read for a per-frame HUD (design demo). */\n state(): AutosaveState;\n}\n\nfunction defaultSchedule(fn: () => void, ms: number): CancelScheduled {\n const id = setTimeout(fn, ms);\n return () => clearTimeout(id);\n}\n\n/**\n * Begin autosaving `session` to `opts.storage`. Debounced with a max-wait\n * ceiling, deferred while a gesture (or `Camera.gesturing`) is live. Returns the\n * control surface; call `stop()` at teardown.\n */\nexport function startAutosave(session: DocSession, opts: AutosaveOpts): Autosave {\n const { storage, world } = opts;\n const debounceMs = opts.debounceMs ?? 800;\n const maxWaitMs = opts.maxWaitMs ?? 10_000;\n const now = opts.now ?? (() => Date.now());\n const schedule = opts.schedule ?? defaultSchedule;\n const checkpointEvery = opts.checkpointEvery ?? 64;\n const maxJournalBytes = opts.maxJournalBytes ?? 4 * 1024 * 1024;\n\n let dirty = false;\n let firstDirtyAt = 0;\n let cancelTimer: CancelScheduled | undefined;\n let saving = false;\n let lastSavedAt: number | undefined;\n let errored = false;\n let lastWriteError: unknown;\n let stopped = false;\n let closing = false;\n let closeBytes: Uint8Array | undefined;\n let closeSavedAt = 0;\n let closeInFlight: Promise<void> | undefined;\n let forceCheckpoint = true;\n let journalEntries = 0;\n let journalBytes = 0;\n let pendingUpdates: Uint8Array[] = [];\n // The serialized writer: at most ONE storage.put is ever in flight. A save\n // requested while a put runs does NOT start a second put — the running loop\n // re-runs with FRESHLY exported bytes once the current put settles. So two\n // puts never interleave and never land out of order; the newest document\n // always wins (latest-wins), and a slow put can never be clobbered by a\n // faster one started later. `writing` (a flag, not the promise) is the gate:\n // a run that finishes synchronously — e.g. a put that throws before any await\n // — must clear it WITHOUT racing the `writeInFlight = runWrites()` assignment.\n let writing = false;\n let writeInFlight: Promise<void> = Promise.resolve();\n\n const deferred = (): boolean => isMidGesture(world);\n\n const clearTimer = (): void => {\n if (cancelTimer !== undefined) {\n cancelTimer();\n cancelTimer = undefined;\n }\n };\n\n const arm = (): void => {\n clearTimer();\n if (stopped || closing) return;\n const elapsed = now() - firstDirtyAt;\n // Debounce, but never later than the max-wait ceiling from the first change.\n const delay = Math.max(0, Math.min(debounceMs, maxWaitMs - elapsed));\n cancelTimer = schedule(onTimer, delay);\n };\n\n function onTimer(): void {\n cancelTimer = undefined;\n if (stopped || !dirty) return;\n if (deferred()) {\n // Can't persist mid-gesture; poll again a debounce later. The gesture's own\n // JustEnded commit also re-arms us the moment it lands (subscribeOutbound).\n cancelTimer = schedule(onTimer, debounceMs);\n return;\n }\n requestWrite();\n }\n\n /**\n * Persist the LATEST document until nothing is dirty. One loop owns the sole\n * `storage.put` call site, so writes are strictly serialized; each iteration\n * re-exports, so a change that arrives mid-put is written on the next pass\n * (latest-wins) rather than lost under a stale in-flight put. This never\n * rejects: a throwing/rejecting put is caught, recorded as status \"error\",\n * and left dirty for the next change/flush to retry — a persistent failure\n * breaks out instead of spinning.\n */\n async function runWrites(): Promise<void> {\n try {\n while (dirty && !stopped && !closing) {\n const at = now();\n const nextUpdate = pendingUpdates[0];\n // Read the optional appender once per pass, bound to its storage object:\n // a method-shorthand optional does not narrow through the `canAppend`\n // alias, and an unbound extraction would break a `this`-using storage.\n const append = storage.append?.bind(storage);\n const canAppend =\n append !== undefined &&\n !forceCheckpoint &&\n nextUpdate !== undefined &&\n journalEntries < checkpointEvery &&\n journalBytes + nextUpdate.byteLength <= maxJournalBytes;\n if (canAppend) {\n pendingUpdates.shift();\n dirty = pendingUpdates.length > 0;\n saving = true;\n try {\n await append(nextUpdate);\n journalEntries += 1;\n journalBytes += nextUpdate.byteLength;\n lastSavedAt = at;\n errored = false;\n lastWriteError = undefined;\n } catch (err) {\n // The full current snapshot includes this update. A checkpoint is\n // both the recovery path and compaction, including lost-ACK cases.\n forceCheckpoint = true;\n dirty = true;\n lastWriteError = err;\n } finally {\n saving = false;\n }\n continue;\n }\n\n const bytes = session.exportEnvelope(at);\n pendingUpdates = [];\n dirty = false; // optimistic: a change during the await re-sets it\n saving = true;\n try {\n await storage.put(bytes);\n forceCheckpoint = false;\n journalEntries = 0;\n journalBytes = 0;\n lastSavedAt = at;\n errored = false;\n lastWriteError = undefined;\n } catch (err) {\n errored = true;\n lastWriteError = err;\n forceCheckpoint = true;\n dirty = true; // keep marked so a later change/flush retries\n break; // do not spin on a persistent failure\n } finally {\n saving = false;\n }\n }\n } finally {\n writing = false;\n }\n }\n\n /** Kick (or join) the serialized writer; returns the in-flight write promise. */\n function requestWrite(): Promise<void> {\n if (stopped || closing) return writeInFlight;\n if (!writing) {\n writing = true;\n writeInFlight = runWrites();\n }\n return writeInFlight;\n }\n\n const markDirty = (): void => {\n if (stopped || closing) return;\n if (!dirty) firstDirtyAt = now();\n dirty = true;\n arm();\n };\n\n const journal = (bytes: Uint8Array): void => {\n pendingUpdates.push(bytes.slice());\n markDirty();\n };\n const unsubOutbound = session.store.subscribeOutbound(journal);\n const unsubRemote = session.subscribeRemote(journal);\n // Start dirty: the document AS HANDED IN (seeded, opened, joined) is unsaved\n // state — without this, a doc with no post-start edits never reaches storage.\n markDirty();\n\n return {\n async flush(): Promise<void> {\n if (stopped) {\n await writeInFlight; // stop() semantics: nothing new persists after stop\n return;\n }\n clearTimer();\n // Force-write the current document even mid-gesture: the doc holds only\n // committed state (the in-flight gesture commits at JustEnded), so every\n // frame is a consistent one to persist. Serialized like every other save —\n // if a put is already running this joins it, and the queued dirty state is\n // written when that put settles. ALWAYS exports — a flush must never be a\n // silent no-op (2026-07-13 review: the beforeunload path relied on it).\n forceCheckpoint = true;\n dirty = true;\n requestWrite();\n await writeInFlight;\n if (lastWriteError !== undefined) throw lastWriteError;\n },\n close(): Promise<void> {\n if (stopped) return writeInFlight;\n if (!closing) {\n closing = true;\n clearTimer();\n unsubOutbound();\n unsubRemote();\n // Capture before the caller can detach/reset the world. This exact\n // envelope is serialized behind the current background write below.\n closeSavedAt = now();\n closeBytes = session.exportEnvelope(closeSavedAt);\n dirty = false;\n }\n if (closeInFlight !== undefined) return closeInFlight;\n const finalBytes = closeBytes;\n if (finalBytes === undefined) return Promise.reject(new Error(\"ice: autosave close lost its final envelope\"));\n closeInFlight = (async () => {\n await writeInFlight;\n try {\n await storage.put(finalBytes);\n lastSavedAt = closeSavedAt;\n lastWriteError = undefined;\n errored = false;\n stopped = true;\n } catch (err) {\n lastWriteError = err;\n errored = true;\n throw err;\n }\n })();\n void closeInFlight.catch(() => {\n // A caller may retry close() after recovering the storage path.\n closeInFlight = undefined;\n });\n return closeInFlight;\n },\n stop(): void {\n if (stopped) return;\n stopped = true;\n clearTimer();\n if (!closing) {\n unsubOutbound();\n unsubRemote();\n }\n // Semantics: a put already in flight runs to completion (a promise cannot\n // be cancelled); the writer loop's `!stopped` guard then DROPS any queued\n // newer write — nothing is persisted after stop() beyond the put already\n // awaiting. Call flush() before stop() to force a final save.\n },\n state(): AutosaveState {\n const status: AutosaveStatus = saving\n ? \"saving\"\n : errored\n ? \"error\"\n : dirty\n ? deferred()\n ? \"deferred\"\n : \"pending\"\n : lastSavedAt !== undefined\n ? \"saved\"\n : \"idle\";\n return { status, lastSavedAt, pending: dirty };\n },\n };\n}\n\n/** The outcome of a restore attempt — a tagged union; nothing here ever throws. */\nexport type RestoreResult =\n | { readonly status: \"restored\"; readonly session: DocSession }\n | { readonly status: \"empty\" }\n | {\n readonly status: \"quarantined\";\n readonly reason: string;\n readonly bytes: Uint8Array;\n readonly report?: DocVersionReport;\n };\n\n/**\n * Load the autosaved document into `world`. Missing/empty storage ⇒\n * `{ status: \"empty\" }` (the app creates fresh). A successful open ⇒\n * `{ status: \"restored\", session }` (may be read-only per the version gate).\n * Corrupt or incompatible bytes ⇒ `{ status: \"quarantined\", reason, bytes }` —\n * NEVER a throw, NEVER a bricked boot (M5 exit criterion): the app stashes the\n * bytes aside and starts fresh.\n */\nexport async function restoreAutosave(\n world: World,\n storage: AutosaveStorageRead,\n opts?: DocSessionOpts,\n): Promise<RestoreResult> {\n const bytes = await storage.get();\n if (bytes === undefined || bytes.length === 0) return { status: \"empty\" };\n\n const result = openDocSession(world, bytes, opts ?? {});\n if (result.ok) return { status: \"restored\", session: result.session };\n return {\n status: \"quarantined\",\n reason: result.reason,\n bytes,\n ...(result.report !== undefined ? { report: result.report } : {}),\n };\n}\n","/**\n * The dumb snapshot relay (design-005 §6.5 M5 stopgap; §6, decision \"relay is\n * dumb — inventory §1.3).\n *\n * M5 ONLY: broadcasts the WHOLE converged document on every local change and\n * imports whole documents it receives. Loro imports dedupe, so a full snapshot\n * is a valid (if wasteful) relay — this is deliberately the simplest thing that\n * converges two tabs. M9 REPLACES it with the transport/bootstrap protocol\n * (hello → addressed-snapshot base → increment stream); do not grow this into\n * that — it is the throwaway.\n *\n * CHANGE-SUBSCRIPTION SURFACE + FEEDBACK GUARD: rides the same\n * `DurableStore.subscribeOutbound` as the autosave kit, which fires ONLY on\n * sealed LOCAL commits (durable-store.ts `onLocalBatch` early-returns on\n * `origin !== \"local\"`). That origin filter IS the feedback-loop guard: applying\n * a peer's snapshot via `applyRemote` produces remote-origin batches, which do\n * NOT re-fire `subscribeOutbound`, so an imported change is never rebroadcast.\n * No `applying` flag is needed — the subscription tells us the origin.\n *\n * LATE-JOINER SEED: on attach we post our snapshot (best-effort seed) AND a\n * `hello`; peers answer a `hello` with their snapshot, so a tab opened second\n * converges up to the first. BroadcastChannel never delivers a message to the\n * instance that posted it, so hello/answer never self-loops.\n */\nimport type { DocSession } from \"./doc-kit\";\n\n/**\n * The minimal channel surface the relay needs — structurally satisfied by the\n * global `BroadcastChannel` and by test fakes. Anything carrying a `Uint8Array`\n * through `postMessage` works (design-005 §6.5).\n */\nexport interface RelayChannel {\n postMessage(message: unknown): void;\n addEventListener(type: \"message\", listener: (ev: { data: unknown }) => void): void;\n removeEventListener(type: \"message\", listener: (ev: { data: unknown }) => void): void;\n close?(): void;\n}\n\nexport interface BroadcastRelayOpts {\n /** Channel name; used to construct a `BroadcastChannel` when `channel` is absent. */\n readonly channelName: string;\n /** Injected channel (tests). When omitted, a `new BroadcastChannel(channelName)` is created and owned. */\n readonly channel?: RelayChannel;\n}\n\nexport interface BroadcastRelay {\n /** Unsubscribe from the store, detach the listener, and close an owned channel. Idempotent. */\n stop(): void;\n}\n\ntype RelayMessage =\n | { readonly kind: \"snapshot\"; readonly bytes: Uint8Array }\n | { readonly kind: \"hello\" };\n\nfunction asRelayMessage(data: unknown): RelayMessage | undefined {\n if (typeof data !== \"object\" || data === null) return undefined;\n const kind = (data as { kind?: unknown }).kind;\n if (kind === \"hello\") return { kind: \"hello\" };\n if (kind === \"snapshot\") {\n const bytes = (data as { bytes?: unknown }).bytes;\n if (bytes instanceof Uint8Array) return { kind: \"snapshot\", bytes };\n }\n return undefined;\n}\n\n/** Attach a dumb snapshot relay to `session` over a `BroadcastChannel` (or injected channel). */\nexport function attachBroadcastRelay(session: DocSession, opts: BroadcastRelayOpts): BroadcastRelay {\n const ownsChannel = opts.channel === undefined;\n const channel: RelayChannel = opts.channel ?? new BroadcastChannel(opts.channelName);\n\n const broadcastSnapshot = (): void => {\n channel.postMessage({ kind: \"snapshot\", bytes: session.exportSnapshot() } satisfies RelayMessage);\n };\n\n const onMessage = (ev: { data: unknown }): void => {\n const msg = asRelayMessage(ev.data);\n if (msg === undefined) return;\n if (msg.kind === \"hello\") {\n broadcastSnapshot(); // answer a late joiner with our converged document\n } else {\n // Remote import: dedupes in loro and does NOT re-fire subscribeOutbound\n // (remote origin), so no rebroadcast — the feedback guard is the origin.\n session.applyRemote(msg.bytes);\n }\n };\n\n channel.addEventListener(\"message\", onMessage);\n const unsub = session.store.subscribeOutbound(() => broadcastSnapshot());\n\n // Seed peers with our current document, and ask them for theirs.\n broadcastSnapshot();\n channel.postMessage({ kind: \"hello\" } satisfies RelayMessage);\n\n let stopped = false;\n return {\n stop(): void {\n if (stopped) return;\n stopped = true;\n unsub();\n channel.removeEventListener(\"message\", onMessage);\n if (ownsChannel) channel.close?.();\n },\n };\n}\n","/**\n * The measurement queue — the ONE ingest path for auto-sized widget sizes\n * (design-004 §2 host pipeline). Mirrors {@link ../input/queue.ts} exactly:\n * pre-ingest TRANSPORT, not world state. A DOM `ResizeObserver` adapter (the\n * `measure-adapter` in @ice/dom) enqueues normalized `{ entity, w, h }` samples\n * as content boxes resize; `measureIngest` drains once per tick and folds them\n * into the `MeasuredSize` session rider. No system reads it, nothing observes\n * it, it holds nothing across a drain.\n *\n * Measurements are content-box sizes in CSS px (screen == world here — the\n * host's content plane carries the camera transform, so a widget's content is\n * laid out in world units). The adapter NEVER enqueues a `0×0` sample (from a\n * `display:none` host) and ingest skips it a second time — the §2 double wall\n * against a full→0 collapse corrupting bounds/cull on re-entry.\n */\nimport type { Entity } from \"@vibecook/strata-ecs\";\n\nexport interface MeasureEvent {\n /** The widget entity whose content element resized (a runtime handle). */\n readonly entity: Entity;\n readonly w: number;\n readonly h: number;\n}\n\nexport interface MeasureQueue {\n enqueue(event: MeasureEvent): void;\n /** Drain in arrival order. Called ONLY by `measureIngest`, once per tick. */\n drain(): readonly MeasureEvent[];\n /** Samples waiting (telemetry / the ingest `runIf` guard). */\n size(): number;\n}\n\nexport function createMeasureQueue(): MeasureQueue {\n let buffer: MeasureEvent[] = [];\n return {\n enqueue(event) {\n buffer.push(event);\n },\n drain() {\n const drained = buffer;\n buffer = [];\n return drained;\n },\n size() {\n return buffer.length;\n },\n };\n}\n","/**\n * The presence attach kit (design-005 §6.5; design-001 §5.6 presence prefab).\n *\n * `attachPresence(world, opts)` stands up ONE ephemeral presence layer per room:\n * a caller-owned Loro `EphemeralStore` → `LoroEphemeralSnapshot` (the one\n * Loro-aware adapter) → `createEphemeralStore` (writer-partitioned Mutator) →\n * `attachEphemeral` (projects every OTHER peer's blobs in as `Not(Local)`\n * entities that self-expire on TTL). The local peer is spawned once with its\n * identity (`PresenceInfo` + `PresencePeer`); `Local` is auto-applied by the\n * store (runtime-only, never transmitted). Its cursor + selection facets are\n * DYNAMIC — the publish hook (publish.ts) adds/updates/removes them per frame,\n * so a peer with no pointer carries no `PresenceCursor` and a peer with an empty\n * selection carries no `SelectionSummary` (facet presence IS the signal).\n *\n * TRANSPORT-FREE (mirrors the doc kit): the engine never owns a socket. The\n * binding's own throttle/keepalive timers hand outbound bytes to `send`, which\n * this kit fans out to `onOutbound` subscribers; inbound bytes arrive through\n * `wire.apply`. The bootstrap kit (doc/bootstrap.ts) binds both to a channel so\n * presence rides the same byte relay as the document.\n *\n * peerId MUST be session-unique (006 B5) — defaults to `crypto.randomUUID()`.\n * `detach()` is leave-then-teardown: it ships tombstones so peers despawn us\n * promptly, THEN tears the binding down (despawns projections, stops timers) and\n * destroys the Loro store we own.\n */\nimport { EphemeralStore as LoroEphemeralStore } from \"loro-crdt\";\nimport type { Entity, World } from \"@vibecook/strata-ecs\";\nimport {\n LoroEphemeralSnapshot,\n attachEphemeral,\n createEphemeralStore,\n type EphemeralSource,\n type EphemeralStore,\n} from \"@vibecook/strata-ecs/ephemeral\";\nimport { PresenceInfo, PresencePeer } from \"../catalog\";\n\n/** Default per-entry TTL — a presence entity self-expires this long after its last keepalive. */\nexport const DEFAULT_PRESENCE_TTL_MS = 5000;\n\nexport interface PresenceOpts {\n /** SESSION-unique peer id (006 B5). Defaults to `crypto.randomUUID()`. */\n readonly peerId?: string;\n /** Display name — must be real (bare, no default). */\n readonly name: string;\n /** Display color — must be real (bare, no default). */\n readonly color: string;\n /** Per-entry TTL (design §15.3), default {@link DEFAULT_PRESENCE_TTL_MS}. */\n readonly ttlMs?: number;\n}\n\nexport interface PresenceSession {\n /** This session's peer id (the ephemeral partition prefix). */\n readonly peerId: string;\n /** The writer-partitioned Mutator for this peer's own presence entities. */\n readonly eph: EphemeralStore;\n /** The local peer entity (facets: PresenceInfo + PresencePeer + Local; cursor/selection added by publish). */\n readonly localPeer: Entity;\n /**\n * The LoroEphemeralSnapshot surface. INBOUND presence bytes go through\n * `wire.apply(bytes)`; the encoders (`encodeChanged`/`encodeKeys`/…) are\n * driven by the binding's own timers — do not call them externally.\n */\n readonly wire: EphemeralSource;\n /** Subscribe to the binding's OUTBOUND presence bytes (its two timers). Returns an unsubscribe. */\n onOutbound(fn: (bytes: Uint8Array) => void): () => void;\n /** Leave (ship tombstones) then tear down the binding + destroy the owned Loro store. Idempotent. */\n detach(): void;\n}\n\n/**\n * Attach an ephemeral presence layer to `world`. The returned session owns the\n * Loro store; the app (or the bootstrap kit) wires `wire.apply` / `onOutbound`\n * to a byte channel and installs the publish hook + remote-cursor system via\n * {@link installPresence}.\n */\nexport function attachPresence(world: World, opts: PresenceOpts): PresenceSession {\n const peerId = opts.peerId ?? crypto.randomUUID();\n const ttlMs = opts.ttlMs ?? DEFAULT_PRESENCE_TTL_MS;\n\n const loro = new LoroEphemeralStore(ttlMs);\n const source = new LoroEphemeralSnapshot(loro);\n\n // The binding's timers call `send`; fan it out to `onOutbound` subscribers so\n // a transport can bind AFTER attach (the doc-kit precedent — transport-free core).\n const outbound = new Set<(bytes: Uint8Array) => void>();\n const eph = createEphemeralStore(source, {\n peerId,\n ttlMs,\n send: (bytes) => {\n for (const fn of [...outbound]) fn(bytes);\n },\n });\n let attachment = attachEphemeral(world, eph);\n\n // Identity now; PresenceCursor/SelectionSummary are dynamic facets the publish\n // hook owns. `Local` is auto-applied by eph.spawn (§15.4) — never transmitted.\n const spawnLocalPeer = (): Entity =>\n eph.spawn({\n components: [[PresenceInfo, { name: opts.name, color: opts.color }]],\n tags: [PresencePeer],\n });\n let localPeer = spawnLocalPeer();\n\n let detached = false;\n // world.reset() (doc close / joinDoc's internal re-bootstrap) kills every\n // projected presence entity AND our minted local peer, while the loro store,\n // wire, and outbound timers all survive — leaving the binding pointing at\n // dead handles and remote keepalives unable to re-project (blob-diff cache\n // says \"unchanged\"). Self-heal by REBINDING: tombstone the orphaned minted\n // keys (peers drop the stale identity now, not at TTL), detach the stale\n // binding, re-attach (fresh blob-diff cache → the next keepalive ≤ ttl/2\n // re-projects every remote peer), and re-mint the local identity. Deferred a\n // microtask: attachEphemeral is illegal inside an observer emit.\n let healQueued = false;\n const stopResetHeal = world.observe({\n onReset: () => {\n if (detached || healQueued) return;\n healQueued = true;\n queueMicrotask(() => {\n healQueued = false;\n if (detached) return;\n eph.leave(); // needs the live seam + minted set — must precede detach\n attachment.detach();\n attachment = attachEphemeral(world, eph);\n localPeer = spawnLocalPeer(); // fresh key (the mint counter only moves forward)\n });\n },\n });\n\n return {\n peerId,\n eph,\n // A getter: the local peer is RE-MINTED after a world reset (see the\n // self-heal above) — consumers must read through, never capture.\n get localPeer() {\n return localPeer;\n },\n wire: source,\n onOutbound(fn) {\n outbound.add(fn);\n return () => {\n outbound.delete(fn);\n };\n },\n detach() {\n if (detached) return;\n detached = true;\n stopResetHeal();\n // leave() needs the live seam + minted set, so it MUST precede detach:\n // it deletes our keys and flushes tombstones through `send` NOW (peers\n // despawn us immediately rather than waiting the TTL). detach() then\n // despawns projections + stops the timers; the minted set is already empty.\n eph.leave();\n attachment.detach();\n outbound.clear();\n loro.destroy(); // we own the Loro store — clear its wasm cleanup timer\n },\n };\n}\n","/**\n * The presence publish hook (design-002 §1 publish step; design-001 §5.6).\n *\n * Publish is the POST-TICK, PRE-NOTIFY presence I/O home: the tick is over, so\n * ephemeral structural mutation is legal here (and ONLY here), and `world.*`\n * reads are settled. This hook derives the local peer's outbound facets from the\n * frame's runtime state and stages them on the ephemeral store — CHANGE-ONLY, so\n * an idle frame writes nothing and the throttle sends nothing:\n *\n * - `PresenceCursor` from the local MOUSE pointer's `PointerWorld` (design-003\n * §2). No local mouse pointer ⇒ SKIP (the facet stays as last published).\n * - `SelectionSummary` from the `Selected` set: count + union bbox + a JSON key\n * list (durable keys via the injected `keyOf`, capped at 32 — design-001\n * §5.6). Present ONLY while the selection is non-empty; the facet is REMOVED\n * when the selection empties (facet presence is the signal).\n *\n * All ephemeral mutations run AFTER the query walks complete (collect-then-write),\n * so no structural `eph.*` fires mid-iteration.\n */\nimport { defineQuery } from \"@vibecook/strata-ecs\";\nimport type { Entity, World } from \"@vibecook/strata-ecs\";\nimport type { PublishHook } from \"../engine/engine\";\nimport {\n LocalPointer,\n MeasuredSize,\n Pointer,\n PointerWorld,\n Position,\n PresenceCursor,\n Selected,\n SelectionSummary,\n Size,\n} from \"../catalog\";\nimport { selectedEntities } from \"../ops/selection\";\nimport type { PresenceSession } from \"./presence-kit\";\n\n/** design-001 §5.6: peers outline the listed widgets; beyond the cap they draw the bbox only. */\nconst SELECTION_KEY_CAP = 32;\n/** u16 ceiling for `SelectionSummary.count`. */\nconst COUNT_MAX = 65535;\n\nconst localMouseQ = defineQuery([Pointer, LocalPointer, PointerWorld]);\n\nexport interface PresencePublishOpts {\n /** Durable key for a selected entity — the doc session's `store.keyOf`. Absent ⇒ no keys carried. */\n readonly keyOf?: (e: Entity) => string | undefined;\n /** Max selection keys carried (default {@link SELECTION_KEY_CAP}). */\n readonly maxKeys?: number;\n}\n\ninterface CursorFacet {\n x: number;\n y: number;\n device: \"mouse\" | \"touch\" | \"pen\";\n}\n\ninterface SummaryFacet {\n count: number;\n x: number;\n y: number;\n w: number;\n h: number;\n keys: string;\n}\n\n/**\n * Build the publish hook that maintains `session.localPeer`'s cursor + selection\n * facets. Register it with `engine.onPublish` (installPresence does this).\n */\nexport function createPresencePublish(\n world: World,\n session: PresenceSession,\n opts: PresencePublishOpts = {},\n): PublishHook {\n const { eph } = session;\n const keyOf = opts.keyOf;\n const cap = opts.maxKeys ?? SELECTION_KEY_CAP;\n\n let cursorPresent = false;\n let lastCursor: CursorFacet | undefined;\n let summaryPresent = false;\n let lastSummary: SummaryFacet | undefined;\n // `session.localPeer` is a GETTER — a world reset re-mints it (the\n // presence-kit self-heal). Read through per publish; when the identity\n // swaps, drop the change-suppression caches too: the fresh peer carries NO\n // facets, so an \"unchanged\" cursor must still be re-added.\n let localPeer = session.localPeer;\n\n // The engine hands the hook its world; it is `session`'s world by construction\n // (installPresence registers on the same engine), so we read the captured one.\n return () => {\n if (session.localPeer !== localPeer) {\n localPeer = session.localPeer;\n cursorPresent = false;\n lastCursor = undefined;\n summaryPresent = false;\n lastSummary = undefined;\n }\n publishCursor(world);\n publishSelection(world);\n };\n\n function publishCursor(w: World): void {\n // The local mouse pointer is the presence cursor. Collect during the walk,\n // mutate after (structural eph.* is illegal mid-iteration).\n let cursor: CursorFacet | undefined;\n w.query(localMouseQ).each((b) => {\n for (const r of b) {\n if (cursor !== undefined) break;\n const e = b.entity(r);\n if (w.read(e, Pointer).device !== \"mouse\") continue;\n const pw = w.read(e, PointerWorld);\n cursor = { x: pw.x, y: pw.y, device: \"mouse\" };\n }\n });\n\n if (cursor === undefined) return; // no local mouse ⇒ leave the facet as last published\n if (\n cursorPresent &&\n lastCursor !== undefined &&\n lastCursor.x === cursor.x &&\n lastCursor.y === cursor.y &&\n lastCursor.device === cursor.device\n ) {\n return; // unchanged ⇒ no write, no throttle traffic\n }\n if (cursorPresent) eph.edit(localPeer).set(PresenceCursor, cursor);\n else eph.addComponent(localPeer, PresenceCursor, cursor);\n cursorPresent = true;\n lastCursor = cursor;\n }\n\n function publishSelection(w: World): void {\n const selected = selectedEntities(w);\n if (selected.length === 0) {\n if (summaryPresent) {\n eph.removeComponent(localPeer, SelectionSummary); // present only while non-empty\n summaryPresent = false;\n lastSummary = undefined;\n }\n return;\n }\n\n let minX = Number.POSITIVE_INFINITY;\n let minY = Number.POSITIVE_INFINITY;\n let maxX = Number.NEGATIVE_INFINITY;\n let maxY = Number.NEGATIVE_INFINITY;\n let anyPositioned = false;\n const keys: string[] = [];\n for (const e of selected) {\n if (keyOf !== undefined && keys.length < cap) {\n const key = keyOf(e);\n if (key !== undefined) keys.push(key); // runtime-only (never-committed) entities have no key\n }\n if (!w.has(e, Position)) continue;\n const p = w.read(e, Position);\n // Effective size mirrors selectionChrome: MeasuredSize where auto-sized, else Size.\n const m = w.get(e, MeasuredSize);\n const s = w.get(e, Size);\n const width = m !== undefined && m.w > 0 ? m.w : (s?.w ?? 0);\n const height = m !== undefined && m.h > 0 ? m.h : (s?.h ?? 0);\n minX = Math.min(minX, p.x);\n minY = Math.min(minY, p.y);\n maxX = Math.max(maxX, p.x + width);\n maxY = Math.max(maxY, p.y + height);\n anyPositioned = true;\n }\n\n const summary: SummaryFacet = {\n count: Math.min(selected.length, COUNT_MAX),\n x: anyPositioned ? minX : 0,\n y: anyPositioned ? minY : 0,\n w: anyPositioned ? maxX - minX : 0,\n h: anyPositioned ? maxY - minY : 0,\n keys: JSON.stringify(keys),\n };\n\n if (summaryPresent && lastSummary !== undefined && summaryEquals(lastSummary, summary)) return;\n if (summaryPresent) eph.edit(localPeer).set(SelectionSummary, summary);\n else eph.addComponent(localPeer, SelectionSummary, summary);\n summaryPresent = true;\n lastSummary = summary;\n }\n}\n\nfunction summaryEquals(a: SummaryFacet, b: SummaryFacet): boolean {\n return a.count === b.count && a.x === b.x && a.y === b.y && a.w === b.w && a.h === b.h && a.keys === b.keys;\n}\n","/**\n * Remote-cursor projection (design-001 §5.6, design-003 §7; `derive` phase).\n *\n * A tick system that maintains one pooled cursor entity per REMOTE presence peer\n * carrying a `PresenceCursor` (`PresencePeer` + `Not(Local)`): `CursorVisual{kind:\n * \"remote\"}` + `Position` (from the peer's cursor) + `Follows → peer`. Pooled and\n * change-only (a peer's cursor motion restamps one Position); reaped when the peer\n * dies (TTL/leave despawns the projected peer, so it drops out of the query) or\n * drops its cursor facet. The pool is a derived cache keyed by the peer entity\n * handle — stable while the peer is alive, gone from the query when it despawns.\n *\n * Selection summaries are intentionally NOT drawn here — M9 core keeps the\n * `SelectionSummary` facet queryable and leaves chrome rendering to the demo.\n *\n * `installPresence` is the seam: it registers the publish hook (publish.ts) and\n * this derive system, returning one uninstall.\n */\nimport { Not, defineQuery, defineTickSystem } from \"@vibecook/strata-ecs\";\nimport { Local } from \"@vibecook/strata-ecs\";\nimport type { Entity, TickSystem, World } from \"@vibecook/strata-ecs\";\nimport { CursorVisual, Follows, Position, PresenceCursor, PresencePeer } from \"../catalog\";\nimport type { Engine } from \"../engine/engine\";\nimport { createPresencePublish, type PresencePublishOpts } from \"./publish\";\nimport type { PresenceSession } from \"./presence-kit\";\n\nconst remotePeerCursorsQ = defineQuery([PresenceCursor, PresencePeer, Not(Local)]);\n\ninterface PoolEntry {\n cursor: Entity;\n x: number;\n y: number;\n}\n\n/**\n * The derive tick system that pools + reaps remote cursor entities. `world` is\n * unused directly (iteration goes through `ctx`), kept for factory symmetry with\n * the other `create*System(world)` builders.\n */\nexport function createRemoteCursorsSystem(_world: World): TickSystem {\n const pool = new Map<Entity, PoolEntry>();\n\n return defineTickSystem(\n (ctx) => {\n const live = new Set<Entity>();\n ctx.query(remotePeerCursorsQ).each((b) => {\n for (const r of b) {\n const peer = b.entity(r);\n live.add(peer);\n const pc = ctx.read(peer, PresenceCursor);\n const entry = pool.get(peer);\n if (entry === undefined) {\n // Spawn with geometry on the payload — identity-only until the phase\n // boundary, so no edit() this frame (the selectionChrome pattern).\n const cursor = ctx.spawn({\n components: [\n [Position, { x: pc.x, y: pc.y }],\n [CursorVisual, { kind: \"remote\", pressed: false }],\n ],\n });\n ctx.setRelation(cursor, Follows, peer); // arity \"one\"\n pool.set(peer, { cursor, x: pc.x, y: pc.y });\n } else if (entry.x !== pc.x || entry.y !== pc.y) {\n ctx.edit(entry.cursor).set(Position, { x: pc.x, y: pc.y });\n entry.x = pc.x;\n entry.y = pc.y;\n }\n }\n });\n\n // Reap cursors whose peer despawned or dropped its PresenceCursor facet.\n for (const [peer, entry] of [...pool]) {\n if (!live.has(peer)) {\n ctx.destroy(entry.cursor);\n pool.delete(peer);\n }\n }\n },\n {\n name: \"remoteCursors\",\n access: { write: [Position, CursorVisual] },\n },\n );\n}\n\nexport type InstallPresenceOpts = PresencePublishOpts;\n\n/**\n * Wire a presence session into an engine: the publish hook (outbound facet\n * derivation) + the remote-cursor derive system. Returns an uninstall that\n * removes both. Does NOT own the session's lifecycle — call `session.detach()`\n * separately.\n */\nexport function installPresence(\n engine: Engine,\n session: PresenceSession,\n opts: InstallPresenceOpts = {},\n): () => void {\n const removePublish = engine.onPublish(createPresencePublish(engine.world, session, opts));\n const removeSystem = engine.addSystems(\"derive\", createRemoteCursorsSystem(engine.world));\n return () => {\n removePublish();\n removeSystem();\n };\n}\n","/**\n * The transport/bootstrap kit (design-005 §6.5) — the engine-provided join state\n * machine; the app provides the byte channel (channels.ts).\n *\n * `joinDoc` runs the LOCKED §6.5 protocol:\n * join = broadcast hello → buffer inbound → import addressed snapshot as causal\n * base → re-broadcast own base → drain buffer; ~800 ms silence ⇒ first peer ⇒\n * seed. Reconnect = the caller calls `joinDoc` again (streams are never\n * resumed). A strata `PendingImportError` on a live update ⇒ automatic internal\n * re-bootstrap (one retry, then surfaced via `onError`).\n *\n * ── THE FRAME PROTOCOL (1-byte kind + payload) ──\n * HELLO(1) payload = joinerId (UTF-8). \"I'm joining; send me a base.\"\n * SNAPSHOT_OFFER(2) payload = an ENVELOPE-framed doc snapshot (header + loro\n * bytes). An UNaddressed base broadcast — the post-import\n * \"re-broadcast own base\" step; a buffering peer OPENS it (the\n * gate runs), an active peer unwraps + merges it (dedupes).\n * SNAPSHOT(3) payload = idLen(u16 LE) ++ targetId(UTF-8) ++ ENVELOPE. An\n * addressed answer to a HELLO — only the peer whose id ==\n * targetId adopts it as its causal base (others unwrap/merge).\n * UPDATE(4) payload = a sealed local commit's incremental (raw) loro bytes.\n * PRESENCE(5) payload = ephemeral presence bytes — rides the same channel,\n * applied immediately (independent of the doc handshake).\n *\n * ── STATES ──\n * BUFFERING: helloed, no base yet. UPDATE frames are BUFFERED; the first snapshot\n * (offer, or addressed to us) triggers `becomeJoiner`; the hello-timeout triggers\n * `becomeSeeder`. PRESENCE flows immediately; HELLOs are ignored (nothing to offer).\n * ACTIVE: session live (either role). Answers HELLOs with an addressed snapshot,\n * merges snapshots/offers, applies updates, relays presence. Local commits ride\n * `store.subscribeOutbound` → UPDATE frames (remote-origin imports never re-fire it,\n * so an imported change is never rebroadcast — the origin IS the feedback guard).\n *\n * Two cold joiners with no existing doc BOTH time out and seed (split-brain) — the\n * design's \"first peer seeds\" assumes a joiner arrives after a seeder exists; a\n * simultaneous-cold-start tie-break is out of scope for M9 and noted here.\n */\nimport type { World } from \"@vibecook/strata-ecs\";\nimport { PendingImportError } from \"@vibecook/strata-ecs/durable\";\nimport type { ByteChannel } from \"./channels\";\nimport { createDocSession, openDocSession, type DocSession, type DocSessionOpts } from \"./doc-kit\";\nimport { decodeEnvelope } from \"./envelope\";\nimport type { PresenceSession } from \"../presence/presence-kit\";\n\nconst K_HELLO = 1;\nconst K_SNAPSHOT_OFFER = 2;\nconst K_SNAPSHOT = 3;\nconst K_UPDATE = 4;\nconst K_PRESENCE = 5;\n\nconst utf8 = new TextEncoder();\nconst fromUtf8 = new TextDecoder();\n\n/** Injectable timer surface (autosave's clock precedent) so the hello-timeout is deterministic in tests. */\nexport interface BootstrapClock {\n setTimeout(fn: () => void, ms: number): unknown;\n clearTimeout(handle: unknown): void;\n}\n\nconst defaultClock: BootstrapClock = {\n setTimeout: (fn, ms) => setTimeout(fn, ms),\n clearTimeout: (h) => clearTimeout(h as ReturnType<typeof setTimeout>),\n};\n\nexport interface JoinDocOpts {\n /** Passed to create/open (maxUndoSteps, etc.). */\n readonly docOpts?: DocSessionOpts;\n /** Version-gate override, forwarded to `openDocSession` (a non-\"ok\" verdict ⇒ a read-only joiner). */\n readonly onGate?: DocSessionOpts[\"onGate\"];\n /** Injected timer surface (tests). Default: global setTimeout/clearTimeout. */\n readonly clock?: BootstrapClock;\n /** Silence window before the lone/first peer seeds (design §6.5, default 800 ms). */\n readonly helloTimeoutMs?: number;\n /** Populate the fresh document — runs on the SEEDER path only, before it goes active. */\n readonly seed?: (session: DocSession) => void;\n /** Presence session to relay over the same channel (kind PRESENCE). Optional. */\n readonly presence?: PresenceSession;\n /** Surfaced when a re-bootstrap (after a PendingImportError) itself fails, or a base import fails post-join. */\n readonly onError?: (err: unknown) => void;\n /**\n * Abort the join: tears the room down (channel unsubscribed, session closed)\n * and rejects the promise if it hasn't resolved yet. The facade aborts its\n * pending join when another document supersedes it — a resolution-time check\n * alone cannot stop a mid-handshake join from attaching to the world.\n */\n readonly signal?: AbortSignal;\n /**\n * Live-session transitions: fired at every activation (including the first,\n * just before the promise resolves) and with `undefined` when an internal\n * re-bootstrap tears the quarantined session down. The facade re-targets its\n * forwarding sink here — without it, callers keep committing into a session\n * `rebootstrap()` already closed.\n */\n readonly onSession?: (session: DocSession | undefined) => void;\n}\n\nexport interface JoinResult {\n /** \"seeder\" = we created the doc (timed out); \"joiner\" = we imported a peer's base. */\n readonly role: \"seeder\" | \"joiner\";\n /** LIVE (a getter): after an internal re-bootstrap this is the replacement session. */\n readonly session: DocSession;\n /** Stop relaying, unsubscribe the channel, and close the session. Idempotent. */\n leave(): void;\n}\n\n/** Prefix `payload` with a 1-byte `kind`. */\nfunction frame(kind: number, payload?: Uint8Array): Uint8Array {\n const len = payload?.length ?? 0;\n const out = new Uint8Array(1 + len);\n out[0] = kind;\n if (payload !== undefined) out.set(payload, 1);\n return out;\n}\n\n/** Build an addressed SNAPSHOT frame: kind ++ idLen(u16 LE) ++ id ++ snapshot. */\nfunction frameSnapshot(targetId: string, snapshot: Uint8Array): Uint8Array {\n const id = utf8.encode(targetId);\n const out = new Uint8Array(1 + 2 + id.length + snapshot.length);\n out[0] = K_SNAPSHOT;\n out[1] = id.length & 0xff;\n out[2] = (id.length >> 8) & 0xff;\n out.set(id, 3);\n out.set(snapshot, 3 + id.length);\n return out;\n}\n\n/** Parse a SNAPSHOT payload (the bytes AFTER the kind byte) into its target id + snapshot. */\nfunction parseSnapshot(payload: Uint8Array): { targetId: string; snapshot: Uint8Array } {\n const idLen = (payload[0] ?? 0) | ((payload[1] ?? 0) << 8);\n const targetId = fromUtf8.decode(payload.subarray(2, 2 + idLen));\n const snapshot = payload.subarray(2 + idLen);\n return { targetId, snapshot };\n}\n\n/**\n * Re-offer this session's document to the room (design-005 §6.5 amendment,\n * 2026-07-20 — the lossy-transport repair). Broadcasts the base as an\n * UN-addressed SNAPSHOT_OFFER — exactly the frame a joiner broadcasts after\n * importing its base — so the protocol already defines every receiver's move:\n * an ACTIVE peer MERGES it (loro dedupes; increments the outage dropped are\n * subsumed by the full document), a BUFFERING peer OPENS it as its causal base.\n * Call it when a lossy transport BEHIND a still-live channel heals (an Electron\n * main's mesh link bounced; the IPC channel object never died). A channel that\n * itself died (a closed socket) needs a fresh `joinDoc` instead — offers ride\n * the channel, and a dead one drops them silently.\n */\nexport function offerBase(channel: ByteChannel, session: DocSession): void {\n channel.send(frame(K_SNAPSHOT_OFFER, session.exportEnvelope()));\n}\n\n/**\n * Join (or found) the room's document over `channel`. Resolves once we go active —\n * as a \"joiner\" (imported a peer's base) or a \"seeder\" (timed out and created one).\n */\nexport function joinDoc(world: World, channel: ByteChannel, opts: JoinDocOpts = {}): Promise<JoinResult> {\n const clock = opts.clock ?? defaultClock;\n const helloTimeoutMs = opts.helloTimeoutMs ?? 800;\n const joinerId = crypto.randomUUID();\n const docOpts: DocSessionOpts = {\n ...(opts.docOpts ?? {}),\n ...(opts.onGate !== undefined ? { onGate: opts.onGate } : {}),\n // SINGLE-WRITER LAW (petition 8, schema-migrate.ts): a live-room joiner is never the\n // document's sole occupant — structural/pack migration here would split-brain the room\n // (the peers keep writing the old shape; sync never re-gates). An old-schema doc joined\n // live attaches read-only; it migrates on its next SOLO open.\n migrate: false,\n };\n\n return new Promise<JoinResult>((resolve, reject) => {\n let session: DocSession | undefined;\n let active = false;\n let settled = false;\n let left = false;\n let timeoutHandle: unknown;\n let unsubOutbound: (() => void) | undefined;\n let rebootstrapAttempts = 0;\n\n // UPDATE frames that arrived while BUFFERING — drained after the base imports.\n const buffered: Uint8Array[] = [];\n // Channel + presence-relay unsubs (filled at wire-up; exists from the start\n // so teardown is safe on every path, including a pre-resolution abort).\n const roomSubs: (() => void)[] = [];\n\n // EVERY exit — leave(), abort, a failed base import, a throwing seed(), the\n // quarantine give-up — funnels through this one idempotent teardown, so no\n // path can leak the channel/presence/outbound subscriptions or the timer.\n const teardown = (): void => {\n if (left) return;\n left = true;\n clock.clearTimeout(timeoutHandle);\n opts.signal?.removeEventListener(\"abort\", onAbort);\n for (const unsub of roomSubs.splice(0)) unsub();\n unsubOutbound?.();\n unsubOutbound = undefined;\n session?.close();\n };\n\n /** Failure exit: teardown, then reject (pre-resolve) or surface via onError (post-resolve). */\n const fail = (err: unknown): void => {\n teardown();\n if (!settled) {\n settled = true;\n reject(err instanceof Error ? err : new Error(String(err)));\n } else {\n opts.onError?.(err);\n }\n };\n\n // EVERY channel write goes through this guard: a transport throw (a socket\n // flipping state between the readiness check and send) must fail the join,\n // not strand a half-attached session — and an outbound-subscription send\n // must never escape into the user's local transaction (2026-07-13 review).\n const send = (bytes: Uint8Array): void => {\n try {\n channel.send(bytes);\n } catch (err) {\n fail(err);\n }\n };\n\n // A post-resolve abort is the caller closing a live join — leave() semantics,\n // deliberately NOT routed to onError (fail() would report every normal close).\n const onAbort = (): void => {\n const wasSettled = settled;\n teardown();\n if (!wasSettled) {\n settled = true;\n const reason: unknown = opts.signal?.reason ?? new Error(\"ice: joinDoc aborted\");\n reject(reason instanceof Error ? reason : new Error(String(reason)));\n }\n };\n\n const armTimeout = (): void => {\n timeoutHandle = clock.setTimeout(() => {\n if (!active && !left) becomeSeeder();\n }, helloTimeoutMs);\n };\n\n const applyRemoteSafe = (bytes: Uint8Array): void => {\n if (session === undefined) return;\n try {\n session.applyRemote(bytes);\n } catch (err) {\n if (err instanceof PendingImportError) rebootstrap();\n else opts.onError?.(err); // corrupt bytes must not brick the channel\n }\n };\n\n // An active peer MERGES a snapshot/offer (envelope-framed) — unwrap to raw\n // loro bytes, then apply. A buffering peer instead OPENS it (openDocSession\n // decodes the envelope itself + runs the gate).\n const mergeSnapshotEnvelope = (envelope: Uint8Array): void => {\n let payload: Uint8Array;\n try {\n payload = decodeEnvelope(envelope).payload;\n } catch (err) {\n opts.onError?.(err); // a corrupt envelope must not brick the channel\n return;\n }\n applyRemoteSafe(payload);\n };\n\n const goActive = (s: DocSession, role: \"seeder\" | \"joiner\"): void => {\n session = s;\n active = true;\n // Local commits → UPDATE frames. Remote-origin imports never fire this\n // (durable's onLocalBatch origin filter), so an import is never rebroadcast.\n unsubOutbound = s.store.subscribeOutbound((bytes) => send(frame(K_UPDATE, bytes)));\n opts.onSession?.(s);\n if (!settled) {\n settled = true;\n resolve({\n role,\n // The getter tracks re-bootstrap: the resolved object never pins the\n // original session (callers would keep a quarantined one otherwise).\n get session() {\n return session as DocSession;\n },\n leave: teardown,\n });\n }\n };\n\n const becomeSeeder = (): void => {\n if (active || left) return;\n if (rebootstrapAttempts > 0) {\n // A re-bootstrap that finds no peer cannot recover the doc — re-seeding\n // here would present a fresh empty doc as if it were the recovered one.\n teardown();\n opts.onError?.(new Error(\"ice: re-bootstrap found no peer to rejoin from — document quarantined\"));\n return;\n }\n let s: DocSession | undefined;\n try {\n s = createDocSession(world, docOpts);\n opts.seed?.(s); // seed BEFORE going active — the state rides every future snapshot\n } catch (err) {\n // seed() runs inside the hello-timeout timer callback — uncaught, the\n // throw would escape the timer and the join promise would hang forever.\n s?.close();\n fail(err);\n return;\n }\n goActive(s, \"seeder\");\n };\n\n const becomeJoiner = (base: Uint8Array): void => {\n if (active || left) return;\n clock.clearTimeout(timeoutHandle);\n const result = openDocSession(world, base, docOpts);\n if (!result.ok) {\n // A corrupt/incompatible base — tear the room down and surface it\n // (reconnect = re-join; the channel must not stay subscribed).\n fail(new Error(`ice: bootstrap base import failed — ${result.reason}`));\n return;\n }\n const s = result.session;\n session = s; // BEFORE the send: a throwing transport must find it in teardown\n // §6.5: import base → re-broadcast own base → drain buffer. Go active before\n // draining so late live UPDATEs (post-drain) apply through the active path.\n send(frame(K_SNAPSHOT_OFFER, s.exportEnvelope())); // envelope-framed (a peer may OPEN it)\n if (left) return; // the offer send failed — teardown already closed s\n goActive(s, \"joiner\");\n const drained = buffered.splice(0);\n for (let i = 0; i < drained.length; i++) {\n const bytes = drained[i];\n if (bytes === undefined) continue;\n applyRemoteSafe(bytes);\n if (left || !active || session !== s) {\n // A PendingImportError mid-drain re-bootstrapped (or quarantined) the\n // session — the rest of these frames belong to the REPLACEMENT's\n // buffer (they may import cleanly once the fresh base lands), not to\n // the session that just closed under us.\n buffered.push(...drained.slice(i + 1));\n break;\n }\n }\n };\n\n const rebootstrap = (): void => {\n if (rebootstrapAttempts >= 1) {\n // Second quarantine: give up FOR REAL — leave the room (else every later\n // UPDATE re-fires this error against a session we know is dead) and tell\n // the session listener the doc is gone.\n teardown();\n opts.onSession?.(undefined);\n opts.onError?.(new Error(\"ice: re-bootstrap after PendingImportError failed — document quarantined\"));\n return;\n }\n rebootstrapAttempts++;\n // Tear the quarantined session down, return to BUFFERING, and re-hello. The\n // channel subscription + presence relay stay wired (presence is session-free).\n // `session` keeps pointing at the closed one so the result getter stays\n // non-undefined; `active=false` routes every frame to the buffering path.\n unsubOutbound?.();\n unsubOutbound = undefined;\n session?.close();\n active = false;\n buffered.length = 0;\n opts.onSession?.(undefined); // no live session until the re-join lands\n send(frame(K_HELLO, utf8.encode(joinerId)));\n armTimeout();\n };\n\n const onFrame = (bytes: Uint8Array): void => {\n if (bytes.length === 0) return;\n const kind = bytes[0];\n const payload = bytes.subarray(1);\n\n if (kind === K_PRESENCE) {\n try {\n opts.presence?.wire.apply(payload); // independent of the doc handshake\n } catch (err) {\n opts.onError?.(err);\n }\n return;\n }\n\n if (active) {\n if (kind === K_HELLO) {\n if (session !== undefined) {\n send(frameSnapshot(fromUtf8.decode(payload), session.exportEnvelope()));\n }\n } else if (kind === K_UPDATE) {\n applyRemoteSafe(payload); // raw loro increment\n } else if (kind === K_SNAPSHOT_OFFER) {\n mergeSnapshotEnvelope(payload);\n } else if (kind === K_SNAPSHOT) {\n mergeSnapshotEnvelope(parseSnapshot(payload).snapshot);\n }\n return;\n }\n\n // BUFFERING (joiner-in-progress / pre-seed).\n if (kind === K_SNAPSHOT_OFFER) {\n becomeJoiner(payload);\n } else if (kind === K_SNAPSHOT) {\n const { targetId, snapshot } = parseSnapshot(payload);\n if (targetId === joinerId) becomeJoiner(snapshot); // \"import ADDRESSED snapshot as causal base\"\n } else if (kind === K_UPDATE) {\n buffered.push(payload); // buffer then drain (order preserved)\n }\n // HELLO while buffering: ignore (we have nothing to offer yet).\n };\n\n // Abort wiring before anything opens: a pre-aborted signal never joins the room.\n if (opts.signal?.aborted === true) {\n onAbort();\n return;\n }\n opts.signal?.addEventListener(\"abort\", onAbort);\n\n roomSubs.push(channel.subscribe(onFrame));\n const unsubPresence = opts.presence?.onOutbound((b) => send(frame(K_PRESENCE, b)));\n if (unsubPresence !== undefined) roomSubs.push(unsubPresence);\n\n // Broadcast hello, buffer inbound, wait for a base (or the silence timeout).\n // A transport that reports readiness GATES both: arming the ~800 ms window\n // while a socket is still CONNECTING lets a slow connect elapse it and seed\n // a divergent second doc offline — whose seeded state (pre-outbound-\n // subscription) would never reach the existing room (2026-07-13 review).\n const begin = (): void => {\n if (left) return; // aborted while the transport was connecting\n send(frame(K_HELLO, utf8.encode(joinerId)));\n if (left) return; // the hello itself failed — already torn down\n armTimeout();\n };\n if (channel.ready !== undefined) {\n channel.ready().then(begin, (err: unknown) => fail(err));\n } else {\n begin();\n }\n });\n}\n","/**\n * Byte-channel adapters for the bootstrap kit (design-005 §6.5: \"provided\n * adapters for BroadcastChannel and WebSocket byte relays; anything carrying a\n * Uint8Array works\").\n *\n * A `ByteChannel` is the whole transport contract the bootstrap state machine\n * needs: `send(bytes)` out, `subscribe(fn)` in. The engine stays transport-free —\n * the app owns the socket lifecycle and hands the instance in.\n *\n * Both adapters interact through STRUCTURAL types (no DOM lib dependency beyond\n * what core already uses — the broadcast-relay precedent), so a test double or an\n * alternative runtime satisfies them without the platform's exact event types.\n */\n\n/** The transport contract: bytes out, bytes in. Structurally satisfied by both adapters + test fakes. */\nexport interface ByteChannel {\n send(bytes: Uint8Array): void;\n /** Deliver every inbound frame to `fn`. Returns an unsubscribe. */\n subscribe(fn: (bytes: Uint8Array) => void): () => void;\n /**\n * OPTIONAL readiness: resolves once the transport can actually transmit,\n * rejects if it never will. `joinDoc` gates its hello + the seed-silence\n * window on this — a queue-until-open transport otherwise lets a slow\n * connect elapse the window and seed a DIVERGENT second doc offline\n * (2026-07-13 review). Synchronous transports (BroadcastChannel, in-memory\n * buses) simply omit it.\n */\n ready?(): Promise<void>;\n}\n\n/** A `ByteChannel` that owns a resource (a BroadcastChannel) and can release it. */\nexport interface OwnedByteChannel extends ByteChannel {\n close(): void;\n}\n\n/** The slice of `BroadcastChannel` we use (structural — avoids the DOM event lib). */\ninterface BroadcastChannelLike {\n postMessage(message: unknown): void;\n addEventListener(type: \"message\", listener: (ev: { data: unknown }) => void): void;\n removeEventListener(type: \"message\", listener: (ev: { data: unknown }) => void): void;\n close(): void;\n}\n\n/** The slice of `WebSocket` we use (structural — the app supplies the instance). */\nexport interface WebSocketLike {\n binaryType: string;\n readyState: number;\n send(data: ArrayBufferLike | ArrayBufferView): void;\n addEventListener(type: string, listener: (ev: { data: unknown }) => void): void;\n removeEventListener(type: string, listener: (ev: { data: unknown }) => void): void;\n}\n\n/** WebSocket `readyState` OPEN. */\nconst WS_OPEN = 1;\n\n/** Coerce a received message payload to a `Uint8Array`, or undefined if it is neither bytes nor a buffer. */\nfunction toBytes(data: unknown): Uint8Array | undefined {\n if (data instanceof Uint8Array) return data;\n if (data instanceof ArrayBuffer) return new Uint8Array(data);\n return undefined;\n}\n\n/**\n * A `ByteChannel` over a `BroadcastChannel` (same-origin tab-to-tab). Uint8Array\n * is structured-cloneable, so it rides `postMessage` directly. A BroadcastChannel\n * never delivers a message to the instance that posted it, so a peer never hears\n * its own frames. `close()` releases the owned channel.\n */\nexport function broadcastChannelByteChannel(name: string): OwnedByteChannel {\n const bc: BroadcastChannelLike = new BroadcastChannel(name);\n const listeners = new Set<(bytes: Uint8Array) => void>();\n\n const onMessage = (ev: { data: unknown }): void => {\n const bytes = toBytes(ev.data);\n if (bytes === undefined) return;\n for (const fn of [...listeners]) fn(bytes);\n };\n bc.addEventListener(\"message\", onMessage);\n\n return {\n send(bytes) {\n bc.postMessage(bytes);\n },\n subscribe(fn) {\n listeners.add(fn);\n return () => {\n listeners.delete(fn);\n };\n },\n close() {\n bc.removeEventListener(\"message\", onMessage);\n bc.close();\n listeners.clear();\n },\n };\n}\n\n/**\n * A `ByteChannel` over a caller-supplied WebSocket. Sets `binaryType =\n * \"arraybuffer\"` (so inbound frames arrive as `ArrayBuffer`), and QUEUES outbound\n * frames until the socket is OPEN, flushing on the `open` event. The app owns the\n * socket (construction, reconnection, close).\n */\nexport function webSocketByteChannel(ws: WebSocketLike): ByteChannel {\n ws.binaryType = \"arraybuffer\";\n const listeners = new Set<(bytes: Uint8Array) => void>();\n const queue: Uint8Array[] = [];\n\n const flush = (): void => {\n if (ws.readyState !== WS_OPEN) return;\n for (const bytes of queue.splice(0)) ws.send(bytes);\n };\n ws.addEventListener(\"open\", flush);\n ws.addEventListener(\"message\", (ev) => {\n const bytes = toBytes(ev.data);\n if (bytes === undefined) return;\n for (const fn of [...listeners]) fn(bytes);\n });\n flush(); // already-open sockets flush immediately\n\n // Readiness (the ByteChannel.ready contract): a CONNECTING socket resolves on\n // \"open\" and rejects on \"close\"/\"error\" first — joinDoc must not start its\n // seed-silence window while frames are still queued behind the connect.\n const readyPromise = new Promise<void>((resolve, reject) => {\n if (ws.readyState === WS_OPEN) {\n resolve();\n return;\n }\n if (ws.readyState > WS_OPEN) {\n reject(new Error(\"ice: webSocketByteChannel — the socket is already closing/closed.\"));\n return;\n }\n ws.addEventListener(\"open\", () => resolve());\n ws.addEventListener(\"close\", () => reject(new Error(\"ice: webSocketByteChannel — the socket closed before opening.\")));\n ws.addEventListener(\"error\", () => reject(new Error(\"ice: webSocketByteChannel — the socket errored before opening.\")));\n });\n readyPromise.catch(() => {}); // pre-observed: no unhandled rejection when ready() is never called\n\n return {\n send(bytes) {\n if (ws.readyState === WS_OPEN) ws.send(bytes);\n else queue.push(bytes); // queue-until-open\n },\n subscribe(fn) {\n listeners.add(fn);\n return () => {\n listeners.delete(fn);\n };\n },\n ready: () => readyPromise,\n };\n}\n","/**\n * `createCanvasEngine` — THE published construction path (design-005 §4).\n *\n * Construction wires: world + engine + the FULL interaction stack + the\n * widget runtime + nested canvas + settings resources, doc-less. A document\n * attaches later through `engine.docs.*` (doc-attached remains the default\n * POSTURE: `docs.create()` is the first call of every editor app) — the\n * commit seam is a FORWARDING sink whose target swaps per session, so the\n * stack never rebuilds across doc open/close.\n *\n * `ops.*` is the catalog of engine-owned write paths (design-005 §4 table):\n * app handlers call ops between frames (design-002 §3); each op is one\n * transaction / one resource write / one tag sweep. Nothing here adds a\n * write path that didn't already exist — ops BIND existing primitives to\n * the current session.\n *\n * Budgets: `keepMounted` feeds the widget runtime; `fboBytes` is carried\n * for the GL layer (GLViews reads it via the react facade). Port budgets\n * remain reviewed constants (RUNTIME_BUDGETS) in v1 — recorded.\n */\nimport type { Entity, World } from \"@vibecook/strata-ecs\";\nimport { createWorld, defineQuery } from \"@vibecook/strata-ecs\";\nimport { fitCamera, zoomAtPoint } from \"@ice/kernel\";\nimport {\n ActiveTool,\n Camera,\n CameraLimits,\n ChildOf,\n ChromeSettings,\n GestureSettings,\n MeasuredSize,\n PointerSettings,\n Position,\n Selectable,\n Size,\n SnapConfig,\n StageMode,\n TransformTween,\n Viewport,\n} from \"../catalog\";\nimport { Active } from \"../catalog/camera-derived\";\nimport {\n createBehaviorRuntime,\n type BehaviorPresence,\n type BehaviorRuntime,\n type BehaviorSession,\n} from \"../behavior/runtime\";\nimport type { AnyBehaviorDef } from \"../behavior/types\";\nimport { createEngine, type Engine } from \"../engine/engine\";\nimport type { FrameControl } from \"../engine/frame-control\";\nimport { isMidGesture } from \"../interaction/gesture-status\";\nimport type { CommitIntent, CommitSink } from \"../engine/commit-sink\";\nimport { guardedTransaction, retargetTweensToDoc } from \"../guards/guarded-tx\";\nimport { writeRuntimeResource } from \"../guards/resource-writer\";\nimport { installInteractionStack, type InteractionStack } from \"../interaction/install\";\nimport { createNestedCanvas, type NavOpts, type NestedCanvas } from \"../nav/nested-canvas\";\nimport { cancelActiveGestures } from \"../ops/gestures\";\nimport { arrangeWidgets, type ArrangeOpts } from \"../ops/arrange\";\nimport { insertByDrag, type InsertByDragOpts } from \"../ops/insert\";\nimport { cascadeDestroy } from \"../ops/cascade\";\nimport { clearSelection, selectedEntities, setSelection } from \"../ops/selection\";\nimport { installWidgetRuntime, type WidgetRuntime } from \"../widget/mount-store\";\nimport { spawnWidget, type SpawnWidgetOpts } from \"../widget/spawn\";\nimport { setWidgetProps } from \"../widget/set-props\";\nimport { WidgetEquipped, widgets } from \"../widget/define-widget\";\nimport { registerBuiltinTools, tools, type Tool } from \"../tools/define-tool\";\nimport { PrefabId } from \"../schema/prefab\";\nimport { createDocSession, openDocSession, type DocSession, type DocSessionOpts, type OpenDocResult } from \"../doc/doc-kit\";\nimport { joinDoc, type JoinDocOpts, type JoinResult } from \"../doc/bootstrap\";\nimport type { ByteChannel } from \"../doc/channels\";\nimport { startAutosave, type Autosave, type AutosaveOpts, type AutosaveStorageWrite } from \"../doc/autosave\";\nimport { attachPresence, type PresenceSession } from \"../presence/presence-kit\";\nimport { installPresence } from \"../presence/remote-cursors\";\nimport type { MeasureQueue } from \"../input/measure-queue\";\nimport {\n CAMERA_DEFAULTS,\n CHROME_DEFAULTS,\n FIT_DEFAULTS,\n GESTURE_DEFAULTS,\n POINTER_DEFAULTS,\n RUNTIME_BUDGETS,\n SNAP_DEFAULTS,\n} from \"../settings/defaults\";\n\nexport interface CanvasEngineOpts {\n /** Registered widget types (definition happens at defineWidget; this list is validated). */\n readonly widgets?: readonly { readonly type: string }[];\n /** Registered tools (definition happens at defineTool; validated). */\n readonly tools?: readonly Tool[];\n /**\n * Behaviors this engine runs (design-009). Definition is the import\n * side-effect; listing them here COMPILES and installs them — a behavior that\n * is defined but never registered costs nothing and does nothing, which is\n * what makes \"a plugin declared it\" and \"this engine runs it\" separable.\n */\n readonly behaviors?: readonly AnyBehaviorDef[];\n readonly budgets?: {\n readonly keepMounted?: number;\n readonly fboBytes?: number;\n };\n readonly settings?: {\n readonly zoom?: { readonly min?: number; readonly max?: number };\n readonly gestures?: Partial<Record<keyof typeof GESTURE_DEFAULTS, number>>;\n readonly pointers?: Partial<Record<keyof typeof POINTER_DEFAULTS, number>>;\n readonly snap?: { readonly enabled?: boolean; readonly thresholdPx?: number };\n /** Selection-chrome knobs: liftScale = the app's visual drag-lift scale (union box wraps it). */\n readonly chrome?: { readonly liftScale?: number };\n };\n readonly policy?: {\n /** The gate verdict a \"migrate\"-classified doc downgrades to when migration is off/fails. */\n readonly versionGate?: \"reject\" | \"readOnly\" | \"migrate\";\n };\n /** The dom measure adapter's queue (wireMeasurement provides; optional headless). */\n readonly measureQueue?: MeasureQueue;\n}\n\nexport interface CanvasOps {\n /** cancel active gestures → switch (design-003 §8; the strata-example lesson). */\n setTool(id: string): void;\n spawnWidget(type: string, opts: SpawnWidgetOpts): Entity;\n /**\n * Tray adoption (2026-07-19): DRAFT-spawn a runtime ghost of `type` centered\n * under the pressing pointer and enqueue one synthetic down — the ordinary\n * drag stack takes over (lift, snap, drop targets, folder consume). Release\n * promotes it through ONE `create` tx (selected, one undo step); cancel or a\n * rejected drop flies it back to the tray press point and despawns it with\n * zero undo footprint. Call from the tray tile's `pointerdown` AFTER\n * `stopPropagation()` (the down must not double-land via the adapter).\n */\n insertByDrag(type: string, opts: InsertByDragOpts): Entity;\n /** Validated prop update: Standard-Schema-checked, json serialized, ONE tx (2026-07-13 review). */\n setWidgetProps(entity: Entity, props: Readonly<Record<string, unknown>>): void;\n deleteSelection(): void;\n /** Twin spawns offset +16/+16; the clones become the selection. */\n duplicateSelection(): Entity[];\n setSelection(ids: readonly Entity[], mode?: \"replace\" | \"add\" | \"toggle\"): void;\n clearSelection(): void;\n selectAll(): void;\n /** Sibling-sequence sweep, one tx: the ids to the frame top/bottom (petition 8). */\n reorder(ids: readonly Entity[], mode: \"top\" | \"bottom\"): void;\n /**\n * Desktop-style Clean Up (kernel packLayout): tidy reading-order rows, one\n * undo step, 240ms glide (durationMs: 0 snaps). Scope: ids > selection ≥2 >\n * current nav frame. Returns the movers (empty = already tidy).\n */\n arrange(opts?: ArrangeOpts): Entity[];\n zoomToFit(ids?: readonly Entity[]): void;\n /**\n * The natural DEFAULT framing (2026-07-18): zoom-to-fit the current\n * frame's widgets inside the FIT_DEFAULTS band (never past 100%, never\n * below 50%, ∩ settings.zoom) — same band as the folder arrival camera.\n * Returns false (camera untouched) until a real viewport AND content\n * exist, so boot code can retry. zoomToFit stays the uncapped explicit\n * \"show me everything\".\n */\n frameContent(): boolean;\n zoomTo(zoom: number, anchor?: { x: number; y: number }): void;\n panTo(x: number, y: number): void;\n enterContainer(container: Entity, opts?: NavOpts): void;\n exitContainer(opts?: NavOpts): void;\n /** Pop several levels in ONE transition (breadcrumb jumps; design-006 §5). */\n exitTo(targetDepth: number, opts?: NavOpts): void;\n cancelActiveGestures(): void;\n}\n\nexport interface CanvasDocs {\n create(opts?: DocSessionOpts): DocSession;\n open(bytes: Uint8Array, opts?: DocSessionOpts): OpenDocResult;\n /**\n * §6.5 bootstrap + optional presence sugar over the same channel. `signal`/\n * `onSession` are facade-owned (supersede + re-bootstrap wiring) — track the\n * live session through `docs.current()`. Rejects if another document is\n * opened while the join is in flight.\n */\n join(\n channel: ByteChannel,\n opts?: Omit<JoinDocOpts, \"presence\" | \"signal\" | \"onSession\"> & {\n readonly presence?: { name: string; color: string };\n },\n ): Promise<JoinResult>;\n current(): DocSession | undefined;\n /**\n * The live presence session (the `join({presence})` sugar's attachment), or\n * undefined when doc-less / presence-less. An INSPECTION seam — the devtools\n * dock's ephemeral tab reads `presence().eph` (DevtoolsOpts.presence) —\n * never a sync path; same contract as `DocSession.attachment`. Swaps with\n * the doc lifecycle exactly like `current()`: set by join, cleared by close.\n */\n presence(): PresenceSession | undefined;\n close(): void;\n undo(): boolean;\n redo(): boolean;\n autosave(storage: AutosaveStorageWrite, opts?: Omit<AutosaveOpts, \"storage\" | \"world\">): Autosave;\n}\n\n/**\n * Stage presentation control (StageMode resource, 2026-07-19): app chrome\n * that covers/recedes the canvas takes a refcounted, NAMED background hold —\n * the disposer pattern makes overlay lifecycles leak-proof (release on\n * unmount), the name makes \"why isn't the canvas animating?\" answerable.\n * Rendering policy only — input/interactability stays the overlay's concern.\n */\nexport interface StageControl {\n /** Take a named background hold. Returns an IDEMPOTENT release. */\n background(name: string): () => void;\n isBackgrounded(): boolean;\n /** Live hold names, in take order (debug/devtools). */\n holds(): readonly string[];\n}\n\nexport interface CanvasEngine {\n readonly world: World;\n readonly engine: Engine;\n /**\n * The behavior runtime (design-009 §6): attach/detach/has/read for\n * runtime-class behaviors, plus `list()` for devtools and the doctor.\n * DURABLE attachment is deliberately absent — it is a document op and goes\n * through `tx.attach` inside a transaction, so it syncs and undoes.\n */\n readonly behaviors: BehaviorRuntime;\n readonly stack: InteractionStack;\n readonly runtime: WidgetRuntime & { uninstall(): void };\n readonly nav: NestedCanvas;\n readonly ops: CanvasOps;\n readonly docs: CanvasDocs;\n readonly stage: StageControl;\n /**\n * The frame gate (2026-08-04) — `stage`'s stricter sibling. A background\n * hold is presentation policy over a LIVE world; a freeze stops the host\n * loop outright. Reach for `stage` when chrome RECEDES the canvas, `frame`\n * when chrome COVERS it. Passthrough of `engine.frame`, so there is one gate\n * whether you hold the facade or the raw engine.\n */\n readonly frame: FrameControl;\n readonly budgets: { readonly keepMounted: number; readonly fboBytes: number };\n /** step(now) passthrough — the app's rAF loop drives this. */\n step(now: number): void;\n dispose(): void;\n}\n\n/** Sink whose target swaps per doc session (records nothing when doc-less). */\nfunction createForwardingSink(): CommitSink & { target: CommitSink | undefined } {\n return {\n target: undefined,\n commit(intent: CommitIntent) {\n this.target?.commit(intent);\n },\n };\n}\n\n// Query singletons (module scope — defineQuery identity is the cache key).\nconst selectableWidgetsQ = defineQuery([Position, Size, Selectable, Active, WidgetEquipped]);\n/** Live glides — the history chokepoint's sweep set (petition I15). */\nconst tweenQ = defineQuery([Position, TransformTween]);\n\nexport function createCanvasEngine(opts: CanvasEngineOpts = {}): CanvasEngine {\n registerBuiltinTools();\n // Validate the declared lists against the registries (definition is the\n // import side-effect; the lists exist so a typo fails at construction).\n for (const w of opts.widgets ?? []) {\n if (widgets.get(w.type) === undefined) {\n throw new Error(`ice: createCanvasEngine — widget type \"${w.type}\" is not defined.`);\n }\n }\n for (const t of opts.tools ?? []) {\n if (tools.get(t.id) === undefined) {\n throw new Error(`ice: createCanvasEngine — tool \"${t.id}\" is not defined.`);\n }\n }\n\n const world = createWorld();\n const engine = createEngine(world);\n const sink = createForwardingSink();\n const stack = installInteractionStack(engine, { sink });\n const budgets = {\n keepMounted: opts.budgets?.keepMounted ?? RUNTIME_BUDGETS.keepMountedWidgets,\n fboBytes: opts.budgets?.fboBytes ?? RUNTIME_BUDGETS.fboBytes,\n };\n const runtime = installWidgetRuntime(engine, {\n keepMounted: budgets.keepMounted,\n ...(opts.measureQueue !== undefined ? { measureQueue: opts.measureQueue } : {}),\n });\n const nav = createNestedCanvas(world, {\n index: stack.index,\n clearSpatialCaches: () => stack.clearCaches(),\n });\n engine.addSystems(\"react\", nav.navIntegrity);\n\n // Settings resources (design-005 §4): construction seeds; live-tunable after.\n const st = opts.settings ?? {};\n world.setResource(Camera, { x: 0, y: 0, zoom: 1, gesturing: false });\n world.setResource(Viewport, { w: 0, h: 0, dpr: 1 });\n world.setResource(ActiveTool, { id: \"select\" });\n world.setResource(CameraLimits, {\n minZoom: st.zoom?.min ?? CAMERA_DEFAULTS.minZoom,\n maxZoom: st.zoom?.max ?? CAMERA_DEFAULTS.maxZoom,\n });\n world.setResource(GestureSettings, { ...GESTURE_DEFAULTS, ...st.gestures });\n world.setResource(PointerSettings, { ...POINTER_DEFAULTS, ...st.pointers });\n world.setResource(SnapConfig, {\n enabled: st.snap?.enabled ?? SNAP_DEFAULTS.enabled,\n thresholdPx: st.snap?.thresholdPx ?? SNAP_DEFAULTS.thresholdPx,\n });\n world.setResource(ChromeSettings, {\n liftScale: st.chrome?.liftScale ?? CHROME_DEFAULTS.liftScale,\n });\n\n // --- doc lifecycle ---------------------------------------------------------\n let session: DocSession | undefined;\n let presence: PresenceSession | undefined;\n let uninstallPresence: (() => void) | undefined;\n let joined: JoinResult | undefined; // the room handle — closeDoc must LEAVE, not just close\n let joinAbort: AbortController | undefined; // kills an in-flight join on supersede\n const liveAutosaves = new Set<Autosave>(); // facade-created; stopped at closeDoc\n\n const requireSession = (op: string): DocSession => {\n if (session === undefined) {\n throw new Error(`ice: ops.${op} needs a document — call engine.docs.create()/open()/join() first.`);\n }\n return session;\n };\n\n // Read-only is enforced at every SANCTIONED write surface, not only the\n // gesture sink (2026-07-13 review: the sink swap alone let facade ops and\n // undo/redo edit — and broadcast — a version-gated document).\n const requireWritable = (op: string): DocSession => {\n const s = requireSession(op);\n if (s.readOnly) {\n throw new Error(`ice: ops.${op} — the document is read-only (version gate); writes are disabled.`);\n }\n return s;\n };\n\n const adoptSession = (next: DocSession): DocSession => {\n session = next;\n sink.target = next.sink;\n return next;\n };\n\n const closeDoc = (): void => {\n // A pending join dies here — left to resolve, it would attach a stale\n // session over whatever the caller opens next.\n joinAbort?.abort(new Error(\"ice: docs.join superseded — another document was opened while joining.\"));\n joinAbort = undefined;\n for (const a of [...liveAutosaves]) a.stop(); // before close: no export of a detached session\n liveAutosaves.clear();\n uninstallPresence?.();\n uninstallPresence = undefined;\n presence?.detach();\n presence = undefined;\n joined?.leave(); // leaves the ROOM: channel + outbound unsubs, then closes the session\n joined = undefined;\n session?.close(); // idempotent — a no-op when leave() above already closed it\n session = undefined;\n sink.target = undefined;\n };\n\n /**\n * Undo/redo + THE HISTORY CHOKEPOINT (petition I15). Undo does not pass\n * through `guardedTransaction` — it is strata's own local batch — so a glide\n * in flight when ⌘Z lands would otherwise complete at the PRE-undo target and\n * strand the cell: runtime ≠ baseline with nothing banked, divergence that\n * never reconciles and poisons the cell against later remote updates. After\n * the history step, every live tween is retargeted onto its doc truth, so the\n * glide finishes on the undone value and the cell reconverges by landing.\n */\n const historyStep = (which: \"undo\" | \"redo\"): boolean => {\n const s = session;\n if (s === undefined) return false;\n const ok = which === \"undo\" ? s.store.undo() : s.store.redo();\n if (!ok) return false;\n const tweening: Entity[] = [];\n world.query(tweenQ).each((b) => {\n for (const r of b) tweening.push(b.entity(r));\n });\n if (tweening.length > 0) {\n retargetTweensToDoc(world, tweening, (e) => {\n const v = s.store.getComponent(e, Position);\n return v === undefined ? undefined : { x: v.x, y: v.y };\n });\n }\n return true;\n };\n\n const gatePolicy: DocSessionOpts[\"onGate\"] =\n opts.policy?.versionGate === undefined\n ? undefined\n : (_report, verdict) => (verdict === \"migrate\" ? (opts.policy?.versionGate ?? verdict) : verdict);\n\n const docs: CanvasDocs = {\n create(o) {\n closeDoc();\n return adoptSession(createDocSession(world, o));\n },\n open(bytes, o) {\n closeDoc();\n const result = openDocSession(world, bytes, {\n ...(gatePolicy !== undefined ? { onGate: gatePolicy } : {}),\n ...o,\n });\n if (result.ok) adoptSession(result.session);\n return result;\n },\n async join(channel, o = {}) {\n closeDoc();\n const ac = new AbortController();\n joinAbort = ac;\n const { presence: presenceOpts, ...joinOpts } = o;\n if (presenceOpts !== undefined) {\n presence = attachPresence(world, { name: presenceOpts.name, color: presenceOpts.color });\n uninstallPresence = installPresence(engine, presence, {\n keyOf: (e) => session?.store.keyOf(e),\n });\n }\n const result = await joinDoc(world, channel, {\n ...(gatePolicy !== undefined ? { docOpts: { onGate: gatePolicy } } : {}),\n ...(presence !== undefined ? { presence } : {}),\n ...joinOpts,\n signal: ac.signal,\n // Re-bootstrap swaps the session inside joinDoc (PendingImportError\n // recovery) — re-target the forwarding sink or ops keep committing\n // into the quarantined session.\n onSession: (s) => {\n if (joinAbort !== ac) return; // superseded — a newer doc owns the sink\n if (s !== undefined) {\n adoptSession(s);\n } else {\n session = undefined; // joinDoc already closed it\n sink.target = undefined;\n }\n },\n });\n // The await gap: user code in the same task may have opened another doc\n // after our resolve was queued — that newer doc owns the engine now.\n if (joinAbort !== ac) {\n result.leave();\n throw new Error(\"ice: docs.join superseded — another document was opened while joining.\");\n }\n joined = result;\n adoptSession(result.session);\n return result;\n },\n current: () => session,\n presence: () => presence,\n close: closeDoc,\n // Read-only documents must not mutate through history either — undo/redo\n // write the store exactly like an op does.\n undo: () => (session === undefined || session.readOnly ? false : historyStep(\"undo\")),\n redo: () => (session === undefined || session.readOnly ? false : historyStep(\"redo\")),\n autosave(storage, o) {\n const s = requireSession(\"autosave\");\n const inner = startAutosave(s, { storage, world, ...o });\n // Track facade-created autosaves: an untracked one outlives closeDoc and\n // its next timer exports the DETACHED old session over the new document's\n // storage (2026-07-13 review).\n const handle: Autosave = {\n flush: () => inner.flush(),\n close: async () => {\n await inner.close();\n liveAutosaves.delete(handle);\n },\n state: () => inner.state(),\n stop: () => {\n liveAutosaves.delete(handle);\n inner.stop();\n },\n };\n liveAutosaves.add(handle);\n return handle;\n },\n };\n\n // --- the behavior runtime ---------------------------------------------------\n // The session seam is FORWARDING, exactly like the commit sink above: a\n // behavior's `ctx.commit` and its divergence-guarding live writer both have\n // to follow the document across open/close, and the runtime itself must\n // survive that (its instances are per-generation, not per-engine).\n const behaviors = createBehaviorRuntime({\n world,\n engine,\n session: () => session as BehaviorSession | undefined,\n // Presence attaches with `docs.join({presence})` and detaches with the\n // document, so this reads through per publish: an ephemeral behavior\n // installed before anyone joins simply lies dormant until there is a peer\n // for it to be.\n presence: () => presence as BehaviorPresence | undefined,\n });\n for (const b of opts.behaviors ?? []) behaviors.register(b);\n\n // --- ops catalog -------------------------------------------------------------\n const widgetQuery = (): Entity[] => {\n const out: Entity[] = [];\n world.query(selectableWidgetsQ).each((b) => {\n for (const r of b) out.push(b.entity(r));\n });\n return out;\n };\n\n const ops: CanvasOps = {\n setTool(id) {\n cancelActiveGestures(world);\n writeRuntimeResource(world, ActiveTool, { id });\n },\n spawnWidget(type, o) {\n const s = requireWritable(\"spawnWidget\");\n return spawnWidget(s.store, world, type, o);\n },\n insertByDrag(type, o) {\n // Writable-session gate UP FRONT: the ghost drag would otherwise run\n // beautifully and silently drop its create at commit (read-only sink).\n requireWritable(\"insertByDrag\");\n return insertByDrag(world, stack.queue, type, o);\n },\n setWidgetProps(entity, props) {\n const s = requireWritable(\"setWidgetProps\");\n setWidgetProps(s.store, world, entity, props);\n },\n deleteSelection() {\n const s = requireWritable(\"deleteSelection\");\n const doomed = selectedEntities(world).filter((e) => s.store.keyOf(e) !== undefined);\n if (doomed.length === 0) return;\n s.store.transaction((tx) => {\n for (const e of doomed) cascadeDestroy(tx, world, e);\n });\n },\n duplicateSelection() {\n const s = requireWritable(\"duplicateSelection\");\n const sources = selectedEntities(world).filter((e) => s.store.keyOf(e) !== undefined);\n if (sources.length === 0) return [];\n const clones: Entity[] = [];\n guardedTransaction(s.store, world, (tx) => {\n for (const src of sources) {\n const type = world.get(src, PrefabId)?.id;\n const widget = typeof type === \"string\" ? widgets.get(type) : undefined;\n if (widget === undefined) continue;\n const pos = world.get(src, Position) ?? { x: 0, y: 0 };\n const size = world.get(src, Size);\n const overrides: [unknown, unknown][] = [\n [Position, { x: pos.x + 16, y: pos.y + 16 }],\n ...(size !== undefined ? [[Size, { ...size }] as [unknown, unknown]] : []),\n ];\n for (const g of widget.groups) {\n const v = world.get(src, g.component);\n if (v !== undefined) overrides.push([g.component, { ...(v as Record<string, unknown>) }]);\n }\n const clone = tx.spawnPrefab(widget.prefab, overrides as never);\n // The clone joins its source's sequence right above it (petition 8;\n // the +16/+16 twin reads as \"on top of\" its source — and an edge-less\n // clone would be unordered entirely, the pre-flip latent bug). A\n // source without an edge (legacy doc) has nothing to inherit.\n const parent = world.getRelation(src, ChildOf);\n if (parent !== undefined) tx.setRelation(clone, ChildOf, parent, { after: src });\n clones.push(clone);\n }\n });\n // The clones land at the next sync; select them once alive.\n setSelection(world, clones.filter((e) => world.isAlive(e)), \"replace\");\n return clones;\n },\n setSelection(ids, mode = \"replace\") {\n setSelection(world, [...ids], mode);\n },\n clearSelection() {\n clearSelection(world);\n },\n selectAll() {\n setSelection(world, widgetQuery(), \"replace\");\n },\n reorder(ids, mode) {\n const s = requireWritable(\"reorder\");\n // Sibling-sequence sweep, one tx (petition 8): \"top\" appends each id to\n // its sequence tail — painted last = topmost, so later ids finish higher;\n // \"bottom\" prepends, later ids finish lower. Exactly the legacy\n // fractional-z sweep's outcome, keyed on sequence position instead.\n // TODO(design-005): relative modes (\"above\"/\"below\" an anchor) are a\n // {before}/{after} moveRelation away — deferred until the public ops\n // table names them.\n guardedTransaction(s.store, world, (tx) => {\n for (const e of ids) {\n if (s.store.keyOf(e) === undefined) continue;\n // No ChildOf edge (legacy doc) — no sequence to move within.\n if (world.getRelation(e, ChildOf) === undefined) continue;\n tx.moveRelation(e, ChildOf, mode === \"top\" ? \"last\" : \"first\");\n }\n });\n },\n arrange(opts) {\n const s = requireWritable(\"arrange\");\n return arrangeWidgets(s.store, s.liveWriter, world, opts);\n },\n zoomToFit(ids) {\n const targets = ids !== undefined && ids.length > 0 ? [...ids] : widgetQuery();\n let minX = Number.POSITIVE_INFINITY;\n let minY = Number.POSITIVE_INFINITY;\n let maxX = Number.NEGATIVE_INFINITY;\n let maxY = Number.NEGATIVE_INFINITY;\n for (const e of targets) {\n const p = world.get(e, Position);\n const s = world.get(e, Size);\n if (p === undefined || s === undefined) continue;\n minX = Math.min(minX, p.x);\n minY = Math.min(minY, p.y);\n maxX = Math.max(maxX, p.x + s.w);\n maxY = Math.max(maxY, p.y + s.h);\n }\n const vp = world.getResource(Viewport);\n if (!Number.isFinite(minX) || vp === undefined || vp.w === 0) return;\n const lim = world.getResource(CameraLimits) ?? CAMERA_DEFAULTS;\n const pad = 80;\n const zoom = Math.min(\n lim.maxZoom,\n Math.max(lim.minZoom, Math.min(vp.w / (maxX - minX + pad * 2), vp.h / (maxY - minY + pad * 2))),\n );\n writeRuntimeResource(world, Camera, {\n x: minX - (vp.w / zoom - (maxX - minX)) / 2,\n y: minY - (vp.h / zoom - (maxY - minY)) / 2,\n zoom,\n gesturing: false,\n });\n },\n frameContent() {\n const targets = widgetQuery();\n const vp = world.getResource(Viewport);\n if (targets.length === 0 || vp === undefined || vp.w === 0) return false;\n let minX = Number.POSITIVE_INFINITY;\n let minY = Number.POSITIVE_INFINITY;\n let maxX = Number.NEGATIVE_INFINITY;\n let maxY = Number.NEGATIVE_INFINITY;\n let any = false;\n for (const e of targets) {\n const p = world.get(e, Position);\n const m = world.get(e, MeasuredSize);\n const s = m !== undefined && m.w > 0 ? m : world.get(e, Size);\n if (p === undefined || s === undefined) continue;\n minX = Math.min(minX, p.x);\n minY = Math.min(minY, p.y);\n maxX = Math.max(maxX, p.x + s.w);\n maxY = Math.max(maxY, p.y + s.h);\n any = true;\n }\n if (!any) return false;\n const lim = world.getResource(CameraLimits) ?? CAMERA_DEFAULTS;\n const cam = fitCamera({ x: minX, y: minY, width: maxX - minX, height: maxY - minY }, vp.w, vp.h, {\n pad: FIT_DEFAULTS.pad,\n // Band ∩ hard limits; on no overlap the hard limit wins (arrival rule).\n minZoom: Math.min(Math.max(FIT_DEFAULTS.minZoom, lim.minZoom), lim.maxZoom),\n maxZoom: Math.max(Math.min(FIT_DEFAULTS.maxZoom, lim.maxZoom), lim.minZoom),\n });\n writeRuntimeResource(world, Camera, { ...cam, gesturing: false });\n return true;\n },\n zoomTo(zoom, anchor) {\n const cam = world.getResource(Camera) ?? { x: 0, y: 0, zoom: 1, gesturing: false };\n const vp = world.getResource(Viewport);\n const lim = world.getResource(CameraLimits) ?? CAMERA_DEFAULTS;\n const z = Math.min(lim.maxZoom, Math.max(lim.minZoom, zoom));\n const a = anchor ?? { x: (vp?.w ?? 0) / 2, y: (vp?.h ?? 0) / 2 };\n const next = zoomAtPoint(cam, a.x, a.y, z);\n writeRuntimeResource(world, Camera, { ...next, gesturing: false });\n },\n panTo(x, y) {\n const cam = world.getResource(Camera) ?? { x: 0, y: 0, zoom: 1, gesturing: false };\n writeRuntimeResource(world, Camera, { x, y, zoom: cam.zoom, gesturing: false });\n },\n enterContainer: (c, opts) => nav.enterContainer(c, opts),\n exitContainer: (opts) => nav.exitContainer(opts),\n exitTo: (d, opts) => nav.exitTo(d, opts),\n cancelActiveGestures: () => cancelActiveGestures(world),\n };\n\n // --- stage holds (StageMode mirror; tokens live HERE, out-of-ECS) ---------\n const stageHolds = new Map<symbol, string>();\n const syncStage = (): void => {\n writeRuntimeResource(world, StageMode, { backgroundHolds: stageHolds.size });\n };\n const stage: StageControl = {\n background(name) {\n const token = Symbol(name);\n stageHolds.set(token, name);\n syncStage();\n let released = false;\n return () => {\n if (released) return; // idempotent — double-release must not eat another hold\n released = true;\n stageHolds.delete(token);\n syncStage();\n };\n },\n isBackgrounded: () => stageHolds.size > 0,\n holds: () => [...stageHolds.values()],\n };\n\n // --- frame freeze wiring (the gate lives on the engine; these are its two\n // stack-level consequences, installed once at construction) ---------------\n //\n // A gesture may not be left in flight across a freeze: its runtime edits are\n // uncommitted until the recognizer reaches JustEnded, and a parked loop never\n // gets there. So a freeze CANCELS between frames and the reporter below keeps\n // the settle walking until the recognizers are terminal — cancellation is a\n // one-tick resource the ctl:spawn sweep acts on NEXT tick, so this is a walk,\n // never a single frame.\n engine.frame.settleWhile(\"gestures\", () => isMidGesture(world));\n engine.frame.onChange(() => {\n if (engine.frame.isFrozen()) {\n cancelActiveGestures(world);\n return;\n }\n // Thaw. The adapters never stopped enqueuing, so the queue holds facts\n // about a canvas nobody could interact with, stamped with a `tMs` that is\n // now minutes stale — replaying them would hand recognizers a burst of\n // impossible history. Drop them, exactly as the adapter drops a pointer\n // across a window blur (design-003 §8).\n stack.queue.drain();\n });\n\n return {\n world,\n engine,\n behaviors,\n stack,\n runtime,\n nav,\n ops,\n docs,\n stage,\n frame: engine.frame,\n budgets,\n step: (now) => engine.step(now),\n dispose() {\n closeDoc();\n // Behaviors before guests: their dispose hooks may still want a live\n // world, and their breaker rows live in the guest registry that the next\n // line tears down.\n behaviors.dispose();\n // Guests first: their dispose may touch doc/runtime state, and a\n // suspended-but-registered guest still holds an instance to tear down.\n engine.disposeGuests();\n runtime.uninstall();\n stack.uninstall();\n },\n };\n}\n","/**\n * insertByDrag — the tray-adoption op (2026-07-19, James: the widget tray).\n *\n * Called from the app's tray-tile `pointerdown` (which `stopPropagation`s the\n * native down — the sanctioned widget-content boundary, design-002 §8). Two\n * event-time moves, then the ENGINE owns everything:\n *\n * 1. DRAFT-spawn the ghost (design-001 §3; instantiate `{ draft: true }`) —\n * a runtime instance of the widget prefab centered under the pointer,\n * equipped + Active + top-of-frame IMMEDIATELY (the equip system runs in\n * `derive`, AFTER this tick's pick — the down below must find the ghost\n * indexed and topmost in the SAME tick, so the op stamps what equip\n * would). Two capability tags are deliberately withheld:\n * - `LongPressDrag`: a tray insert is always instant-drag — nobody holds\n * 500ms over a palette;\n * - `SweepsContained`: a comment ghost at the tray's world point must not\n * sweep the widgets resting under the tray into the insert.\n * The projected twin gets the FULL tag set from the equip system.\n *\n * 2. Enqueue ONE synthetic un-flagged `down` (Law 2 — this op is an adapter\n * here, it only enqueues; the GL router precedent). Next tick: spatialSync\n * indexes the ghost, targeting resolves it topmost, the Drag recognizer\n * captures it — and the ordinary L0–L4 stack runs the whole drag: lift,\n * snap, drop targets, folder consume. moveBehavior's ghost terminals\n * promote (one `create` tx) or fly the ghost home and reap it.\n */\nimport type { Entity, World } from \"@vibecook/strata-ecs\";\nimport { screenToWorld, type CameraState } from \"@ice/kernel\";\nimport { Camera, ChildOf, InsertGhost, LongPressDrag, SweepsContained } from \"../catalog\";\nimport { Active } from \"../catalog/camera-derived\";\nimport { instantiate } from \"../engine/instantiate\";\nimport { NO_MODS, type InputQueue } from \"../input/queue\";\nimport { WidgetEquipped, widgets } from \"../widget/define-widget\";\nimport { widgetSpawnInits } from \"../widget/spawn\";\nimport { frameParent } from \"./sibling-order\";\n\nconst IDENTITY_CAM: CameraState = { x: 0, y: 0, zoom: 1 };\n\nexport interface InsertByDragOpts {\n /** The press point in canvas-container CSS px (the kernel screen space). */\n readonly screenX: number;\n readonly screenY: number;\n /** Prop overrides for the eventual create (validated by widgetSpawnInits). */\n readonly props?: Readonly<Record<string, unknown>>;\n /** Adapter pointer id of the pressing pointer (default \"mouse\"). */\n readonly pointerId?: string;\n readonly device?: \"mouse\" | \"touch\" | \"pen\";\n /** PointerEvent.buttons at the press (default 1 = primary). */\n readonly buttons?: number;\n /**\n * Fly-back HOME in screen px (default: the press point). Apps that adopt\n * the drag AWAY from the tray (the deferred-spawn proxy pattern — the ghost\n * spawns at the tray-EXIT point) aim the cancel/reject return at the\n * persistent chrome (the toolbar) instead of a spot in open canvas.\n */\n readonly home?: { readonly x: number; readonly y: number };\n /**\n * Proportional GRAB POINT (0–1 within the widget rect; default center).\n * The grab point is the drag's INVARIANT (2026-07-19 polish): the spot\n * under the finger in the tray tile stays the same spot of the spawned\n * widget — the proxy→widget morph then composes as a pure scale about the\n * cursor, with no re-anchoring snap.\n */\n readonly anchor?: { readonly u: number; readonly v: number };\n}\n\nexport function insertByDrag(\n world: World,\n queue: InputQueue,\n type: string,\n opts: InsertByDragOpts,\n): Entity {\n const widget = widgets.get(type);\n if (widget === undefined) throw new Error(`ice: insertByDrag — unknown widget type \"${type}\".`);\n\n const cam = world.getResource(Camera) ?? IDENTITY_CAM;\n const wp = screenToWorld(opts.screenX, opts.screenY, cam);\n const w = widget.defaultSize.w;\n const h = widget.defaultSize.h;\n // The pointer pins the ANCHOR point (proportional; default center — the\n // Figma/FigJam palette behavior). Grab latches the offset at claim, and\n // the ghost's zero dead zone (l2) keeps it pinned from the first move.\n const u = opts.anchor?.u ?? 0.5;\n const v = opts.anchor?.v ?? 0.5;\n const { prefab, overrides } = widgetSpawnInits(type, {\n x: wp.x - u * w,\n y: wp.y - v * h,\n w,\n h,\n ...(opts.props !== undefined ? { props: opts.props } : {}),\n });\n\n const ghost = instantiate(prefab, { into: \"world\", world }, { draft: true, overrides });\n world.addComponent(ghost, InsertGhost, {\n type,\n props: JSON.stringify(opts.props ?? {}),\n screenX: opts.home?.x ?? opts.screenX,\n screenY: opts.home?.y ?? opts.screenY,\n });\n for (const tag of widget.capabilityTags) {\n if (tag === LongPressDrag || tag === SweepsContained) continue;\n world.addTag(ghost, tag);\n }\n world.addTag(ghost, WidgetEquipped);\n world.addTag(ghost, Active);\n const parent = frameParent(world);\n if (parent !== undefined) world.setRelation(ghost, ChildOf, parent, \"last\"); // topmost — the pick must hit IT\n\n queue.enqueue({\n kind: \"down\",\n pointerId: opts.pointerId ?? \"mouse\",\n device: opts.device ?? \"mouse\",\n screenX: opts.screenX,\n screenY: opts.screenY,\n buttons: opts.buttons ?? 1,\n mods: NO_MODS,\n });\n return ghost;\n}\n","/**\n * @ice/core — schema+prefabs+sovereignty · phase groups/pipeline · L0–L4 systems ·\n * scene systems · doc kit · publish step · engine facade · reflector registry.\n * Import wall: strata-ecs + @ice/kernel ONLY — never react/dom/three (enforced).\n */\n// Informational only; must track packages/ice/package.json version on publish.\nexport const CORE_VERSION = \"0.6.0\";\n\nexport { defineSchemaOnce, hmrInvalidateOnSchemaChange } from \"./boot/hmr\";\n\n// Strata surface re-exported for downstream packages: dom/react/r3f reach\n// strata ONLY through core (design-002 §6 — strata is core's sole runtime\n// dependency; the import walls make a direct dep a CI failure).\nexport {\n All,\n Any,\n Not,\n Related,\n createWorld,\n defineQuery,\n defineSystem,\n defineTickSystem,\n enumOf,\n field,\n // Query-only for apps (`Not(Local)` = remote presence peers); strata-owned,\n // auto-applied by the ephemeral store on spawn, never transmitted.\n Local,\n} from \"@vibecook/strata-ecs\";\nexport type {\n Batch,\n Component,\n Condition,\n Entity,\n OrderPlace,\n Pipeline,\n Query,\n Relation,\n Resource,\n System,\n SystemCtx,\n Tag,\n TickSystem,\n World,\n} from \"@vibecook/strata-ecs\";\n\n// Schema wrappers (record metadata, delegate to strata) + registries.\nexport {\n defineComponent,\n defineRelation,\n defineResource,\n defineTag,\n schemaMeta,\n type ComponentMeta,\n type RawSchema,\n type RelationMeta,\n type ResourceMeta,\n} from \"./schema/meta\";\n\n// Prefabs — sovereignty at the entity level (design-001 §2).\n// (__resetPrefabsForTests is deliberately NOT re-exported — test-only, import from the module.)\nexport {\n definePrefab,\n init,\n PrefabId,\n prefabs,\n type ComponentInit,\n type FieldWrite,\n type Prefab,\n type PrefabClass,\n type PrefabDef,\n} from \"./schema/prefab\";\n\n// Spawn routing (the class IS the spawn path).\nexport { instantiate, type EphSpawner, type SpawnTarget } from \"./engine/instantiate\";\n\n// The frame contract (design-002): FrameInfo clock, phase-group pipeline,\n// reflector registry, and the engine facade that owns step(now).\nexport { FrameInfo, setFrameInfo } from \"./engine/frame-info\";\nexport { createPipelineRegistry, PHASE_GROUPS, type AnySystem, type PhaseGroup, type PipelineRegistry } from \"./engine/pipeline\";\nexport {\n createReflectorRegistry,\n type ReflectorDef,\n type ReflectorObserve,\n type ReflectorQuerySpec,\n type ReflectorRegistry,\n} from \"./engine/reflectors\";\nexport {\n createEngine,\n type Engine,\n type EngineOpts,\n type FrameTelemetry,\n type PublishHook,\n type SystemRunRecord,\n} from \"./engine/engine\";\nexport { createFrameControl, SETTLE_CAP, type FrameControl } from \"./engine/frame-control\";\n// The guest runtime (petition I14): the named frame slot for work the engine\n// did not write, under a circuit breaker. The behavior framework compiles onto\n// it (design-009); hosts reach it as `engine.guests`.\nexport {\n createGuestRegistry,\n GUEST_BUDGET,\n type GuestFactory,\n type GuestFrame,\n type GuestGeneration,\n type GuestInstance,\n type GuestLedgerRecord,\n type GuestRegistry,\n type GuestRegistryOpts,\n type GuestRun,\n type GuestSpec,\n type GuestStatus,\n} from \"./engine/guests\";\n\n// --- The behavior framework (design-009): ICE's SECOND product surface -------\n// `defineWidget` (faces) · `defineBehavior` (logic + state) · `defineTool`\n// (input policy). `store:` routes everything — where data lives, who sees it,\n// what survives, which write vocabulary the hooks receive, at which cadence.\nexport { behaviors, defineBehavior } from \"./behavior/define-behavior\";\nexport {\n BEHAVIOR_DEFAULT_PHASE,\n BEHAVIOR_PHASES,\n type AnyBehaviorAttachSpec,\n type AnyBehaviorDef,\n type BehaviorAttachSpec,\n type BehaviorChanges,\n type BehaviorCtxBase,\n type BehaviorCtxFor,\n type BehaviorFrame,\n type BehaviorHandle,\n type BehaviorHooks,\n type BehaviorPhase,\n type BehaviorQuery,\n type BehaviorQuerySpec,\n type BehaviorRead,\n type BehaviorSchema,\n type BehaviorSpec,\n type BehaviorStore,\n type BehaviorTx,\n type BehaviorWorld,\n type DataOf,\n type DurableBehaviorCtx,\n type EphemeralBehaviorCtx,\n type PeerFacet,\n type RuntimeBehaviorCtx,\n} from \"./behavior/types\";\nexport { compileBehavior, isDurableEligible, type CompiledBehavior } from \"./behavior/compile\";\nexport {\n behaviorMarkerKey,\n classifyBehaviorVersion,\n docBehaviorVersion,\n stampBehaviorMarker,\n BEHAVIOR_MARKER_PREFIX,\n type BehaviorMeta,\n type BehaviorVerdict,\n} from \"./behavior/migrate\";\n// The testing rig ships WITH the framework, not after it (design-009 §7).\nexport {\n createBehaviorHarness,\n type BehaviorHarness,\n type BehaviorHarnessOpts,\n type HarnessCommit,\n} from \"./behavior/harness\";\n\n// Write-path guards.\nexport { devGuardsEnabled, setDevGuards } from \"./guards/dev\";\nexport { createLiveWriter, type LiveWriter, type LiveWriterOpts } from \"./guards/live-writer\";\nexport { guardedTransaction, type GuardedTx, type GuardedTxOpts } from \"./guards/guarded-tx\";\nexport { writeRuntimeResource } from \"./guards/resource-writer\";\n\n// The component/tag/relation/resource catalog (design-001 §5, faithful transcription).\nexport * from \"./catalog\";\n\n// Engine helpers: PhaseSet + Just* markers (design-003 §4.2), version stamps (design-002 §4).\nexport * from \"./helpers/phase-set\";\nexport * from \"./helpers/version-stamps\";\n// The drain-in-runIf idiom (petition I15): a change-collector gate that stashes\n// its delta for the body, so a skipped system stamps NOTHING (design-002 §4's\n// guard rule). Engine-internal since M6; exported because every derived\n// consumer outside core — plugin systems, and the behavior framework's own\n// delivery loop — needs exactly this and would otherwise hand-roll it.\nexport * from \"./helpers/churn-guard\";\n// Catalog-adjacent ops (app-handler write paths).\nexport * from \"./ops/arrange\";\nexport * from \"./ops/selection\";\nexport * from \"./ops/cascade\";\nexport * from \"./ops/claims\";\nexport * from \"./ops/gestures\";\nexport * from \"./ops/point-pick\";\n// Sibling order (petition 8): THE per-frame stacking source — frame parent,\n// pull-based ordinal cache, and the one comparator paint/pick/drop share.\nexport * from \"./ops/sibling-order\";\n// Port-schema → kernel PortSlot resolution (2026-07-16: exported for the\n// @ice/ground wires pass — rendered and picked anchors agree by construction;\n// retires the wires reflector's local-resolver TODO).\nexport { portSlots, portSlotOf } from \"./ops/port-geometry\";\n\n// The interaction stack (design-003): input queue, commit seam, install.\nexport { createInputQueue, NO_MODS, type InputEvent, type InputEventKind, type InputMods, type InputQueue } from \"./input/queue\";\nexport {\n createRecordingCommitSink,\n type CommitIntent,\n type CommitCreate,\n type CommitOrder,\n type CommitReparent,\n type CommitSink,\n type CommitWrite,\n} from \"./engine/commit-sink\";\nexport {\n ensureCanvasSurface,\n installInteractionCore,\n installInteractionStack,\n type InteractionCore,\n type InteractionCoreOpts,\n type InteractionStack,\n} from \"./interaction/install\";\nexport { anyGestureNonTerminal, isMidGesture } from \"./interaction/gesture-status\";\nexport type { MarqueeBuffer } from \"./systems/l3-marquee\";\nexport { DEFAULT_SPAWN_PROFILES, type SingleKindName, type SpawnProfiles } from \"./systems/l2-recognize\";\nexport { createCursorSync } from \"./systems/l4-cursor\";\n// M8 node-editor core (design-004 §6, design-003 §5.8): wire sync, port\n// materialization, connect gesture + its out-of-ECS preview buffer.\nexport { createWireSync, type WireSyncSystem } from \"./systems/l1-wires\";\nexport { createPortMaterialize } from \"./systems/l3-ports\";\nexport {\n createConnectSystems,\n type ConnectSystems,\n type WirePreviewBuffer,\n} from \"./systems/l3-connect\";\n\n// The doc kit (design-001 §6, design-005 §6): envelope, version gate, sessions.\nexport {\n ENGINE_SCHEMA_VERSION,\n ENVELOPE_MAGIC,\n ENVELOPE_VERSION,\n EnvelopeError,\n decodeEnvelope,\n encodeEnvelope,\n type EnvelopeHeader,\n} from \"./doc/envelope\";\nexport {\n gateVerdict,\n readDocVersionReport,\n stampEngineMeta,\n type DocVersionReport,\n type GateVerdict,\n} from \"./doc/version-gate\";\nexport { createDocCommitSink, createReadOnlyCommitSink } from \"./doc/doc-commit-sink\";\n// Durable undo/redo availability resource (strata plan-undo U2) — re-exported\n// so react's useUndoStatus takes the typed observeResource path (the import\n// wall forbids react reaching @vibecook/strata-ecs/durable directly).\nexport { DurableUndoStatus } from \"@vibecook/strata-ecs/durable\";\nexport type { DurableUndoStatusValue } from \"@vibecook/strata-ecs/durable\";\nexport {\n createDocSession,\n openDocSession,\n type DocSession,\n type DocSessionOpts,\n type OpenDocResult,\n} from \"./doc/doc-kit\";\nexport { runMigrations, type MigrationCtx, type MigrationOutcome } from \"./doc/migrate\";\n\n// The widget runtime core (design-005 §2 + design-004 §2): props DSL,\n// defineWidget compiler, equip, spawn, cull/LRU/mount store.\nexport { p, type JsonShape, type PropSpec, type PropsDecl, type StandardSchemaV1 } from \"./widget/props\";\nexport {\n WidgetEquipped,\n defineWidget,\n renames,\n widgets,\n type SizeMode,\n type WidgetDef,\n type WidgetGroup,\n type WidgetInteraction,\n type WidgetPortDecl,\n type WidgetBehaviorDecl,\n type WidgetBehaviorEntry,\n type WidgetRename,\n type WidgetRenameEntry,\n type WidgetSurface,\n type WidgetType,\n} from \"./widget/define-widget\";\nexport { createWidgetEquipSystem } from \"./widget/equip\";\nexport { attachSpawnBehaviors, attachSpawnParent, spawnWidget, widgetSpawnInits, type SpawnWidgetOpts } from \"./widget/spawn\";\nexport { setWidgetProps } from \"./widget/set-props\";\nexport {\n createWidgetRuntime,\n installWidgetRuntime,\n type MountEntry,\n type WidgetMountStore,\n type WidgetRuntime,\n} from \"./widget/mount-store\";\n\n// Reviewed default constants (citations point at the owning design sections).\nexport * from \"./settings/defaults\";\n// Ground-layer (P0) pass configs — plain data shared by @ice/ground, the react\n// facade, and apps (2026-07-16 extraction; neither may import the other).\nexport * from \"./settings/ground-config\";\n\n// --- M4 camera slice (design-003 §5 item 9 + simulate tail) ---\n// Sole exception to the no-barrel-edit rule: the camera-sim factory + its\n// runtime resource, exported so the DOM demo and integration can wire them.\nexport { CameraInertia, createCameraSystems, type CameraSystems } from \"./systems/camera-sim\";\n\n// --- M5 app-facing doc kit slice (design-005 §6.5–6.6): autosave + dumb relay ---\nexport {\n restoreAutosave,\n startAutosave,\n type Autosave,\n type AutosaveOpts,\n type AutosaveState,\n type AutosaveStatus,\n type AutosaveStorageRead,\n type AutosaveStorageWrite,\n type CancelScheduled,\n type RestoreResult,\n} from \"./doc/autosave\";\nexport {\n attachBroadcastRelay,\n type BroadcastRelay,\n type BroadcastRelayOpts,\n type RelayChannel,\n} from \"./doc/broadcast-relay\";\n\n// --- M6 measurement + chrome + breakpoints (design-004 §2 measure, §5 chrome, §8 LOD) ---\nexport { createMeasureQueue, type MeasureEvent, type MeasureQueue } from \"./input/measure-queue\";\nexport { createMeasureIngest } from \"./systems/measure-ingest\";\nexport { createBreakpointSystem, createSelectionChromeSystem } from \"./systems/chrome\";\n\n// --- M8 nested canvas (design-004 §7): membership, nav ops, integrity ---\nexport {\n createActiveMembership,\n createNestedCanvas,\n currentNavEntry,\n currentNavFrame,\n type NavOpts,\n type NestedCanvas,\n type NestedCanvasOpts,\n} from \"./nav/nested-canvas\";\n// design-006 T1: the flight resource (T2's reflector consumes it) + system factory.\nexport {\n abortNavFlight,\n createNavFlight,\n navFlightActive,\n NavTransition,\n startNavFlight,\n} from \"./systems/nav-flight\";\n\n// --- M9 presence layer (design-005 §6.5, design-001 §5.6) ---\nexport {\n attachPresence,\n createPresencePublish,\n createRemoteCursorsSystem,\n DEFAULT_PRESENCE_TTL_MS,\n installPresence,\n type InstallPresenceOpts,\n type PresenceOpts,\n type PresencePublishOpts,\n type PresenceSession,\n} from \"./presence\";\n\n// --- M9 transport/bootstrap kit (design-005 §6.5): join protocol + byte channels ---\nexport {\n joinDoc,\n offerBase,\n type BootstrapClock,\n type JoinDocOpts,\n type JoinResult,\n} from \"./doc/bootstrap\";\nexport {\n broadcastChannelByteChannel,\n webSocketByteChannel,\n type ByteChannel,\n type OwnedByteChannel,\n type WebSocketLike,\n} from \"./doc/channels\";\n\n// --- M10 published facade (design-005 §3-§4): tools + createCanvasEngine ---\nexport {\n createDrawTool,\n defineTool,\n tools,\n type CanvasDragRoute,\n type Tool,\n type ToolDef,\n type ToolGates,\n type ToolRoute,\n type WidgetDragRoute,\n} from \"./tools/define-tool\";\nexport {\n createCanvasEngine,\n type CanvasDocs,\n type CanvasEngine,\n type CanvasEngineOpts,\n type StageControl,\n type CanvasOps,\n} from \"./facade/create-canvas-engine\";\nexport { createDrawBehavior } from \"./systems/l3-draw\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAQO,SAAS,iBAAoB,KAAaA,QAAmB;AAClE,QAAM,IAAI;AACV,IAAE,iBAAiB,oBAAI,IAAqB;AAC5C,QAAM,MAAM,EAAE;AACd,MAAI,CAAC,IAAI,IAAI,GAAG,EAAG,KAAI,IAAI,KAAKA,OAAM,CAAC;AACvC,SAAO,IAAI,IAAI,GAAG;AACpB;AAEO,SAAS,4BAA4B,KAA+C;AACzF,OAAK,WAAW;AAClB;;;ACRA;AAAA,EACE,mBAAmB;AAAA,EACnB,kBAAkB;AAAA,EAClB,kBAAkB;AAAA,EAClB,aAAa;AAAA,OAMR;AAwBP,IAAM,gBAAgB,oBAAI,IAA8B;AACxD,IAAM,sBAAsB,oBAAI,IAAuB;AACvD,IAAM,WAAW,oBAAI,IAAiB;AACtC,IAAM,eAAe,oBAAI,IAA4B;AACrD,IAAM,eAAe,oBAAI,IAA4B;AAErD,SAAS,WAAW,OAA4B;AAC9C,MAAI,UAAU,MAAO,QAAO;AAC5B,SACE,OAAO,UAAU,YACjB,UAAU,QACT,MAA6B,SAAS;AAE3C;AAEA,SAAS,WAAW,OAA4B;AAG9C,SAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,aAAa;AACrE;AAEO,SAAS,gBACd,MACA,QAC+C;AAC/C,QAAM,IAAI,sBAAsB,MAAM,MAAM;AAC5C,QAAM,SAAS,OAAO,QAAQ,MAAM;AACpC,gBAAc,IAAI,GAAgB;AAAA,IAChC;AAAA,IACA;AAAA,IACA,WAAW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I,WAAW;AACf,aAAO,MAAM;AACX,YAAI,SAAU;AACd,mBAAW;AACX,mBAAW,OAAO,KAAK;AACvB,kBAAU;AAAA,MACZ;AAAA,IACF;AAAA,IACA,gBAAgB,MAAM,WAAW,OAAO;AAAA,IACxC,OAAO,MAAM,CAAC,GAAG,WAAW,OAAO,CAAC;AAAA,EACtC;AAWA,SAAO,MAAM,YAAY,YAAY,MAAM,aAAa,KAAK,CAAC;AAC9D,SAAO,MAAM,SAAS,MAAM;AAC1B,QAAI,OAAO,MAAM,SAAS,GAAG;AAC3B,2BAAqB,KAAK;AAC1B;AAAA,IACF;AAMA,UAAM,MAAM,MAAM;AAAA,EACpB,CAAC;AAED,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA,WAAAD;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,OAAO,OAAO;AAAA,IACd;AAAA,IACA,MAAM,CAAC,QAAQ,OAAO,KAAK,GAAG;AAAA,IAC9B,UAAU;AACR,eAAS;AAIT,MAAAA,WAAU,QAAQ;AAGlB,aAAO,cAAc;AACrB,cAAQ,UAAU;AAClB,YAAM,UAAU;AAAA,IAClB;AAAA,EACF;AACF;;;AExtBA;AAAA,EACE;AAAA,EACA,OAAAG;AAAA,EACA,OAAAC;AAAA,EACA,WAAAC;AAAA,EACA,eAAAC;AAAA,EACA,eAAAC;AAAA,EACA,gBAAAC;AAAA,EACA,oBAAAC;AAAA,EACA,UAAAC;AAAA,EACA,SAAAC;AAAA,EAGA,SAAAC;AAAA,OACK;AA+NP,SAAS,yBAAyB;AApP3B,IAAM,eAAe;","names":["build","field","field","record","frame","ms","frame","validate","field","field","field","field","enumOf","field","enumOf","field","enumOf","field","field","enumOf","phase","field","field","field","enumOf","registry","field","enumOf","phase","fail","p","enumOf","field","enumOf","field","field","field","init","live","field","defineQuery","defineSystem","defineTickSystem","field","defineQuery","defineTickSystem","defineSystem","defineTickSystem","enumOf","field","field","enumOf","defineTickSystem","p","field","enumOf","registry","strataFieldOf","field","enumOf","defineQuery","defineTickSystem","defineQuery","frame","defineTickSystem","p","opts","defineQuery","frame","defineQuery","defineQuery","defineTickSystem","defineQuery","defineTickSystem","registry","registry","Not","defineQuery","defineSystem","defineQuery","Not","pinchQ","P","defineSystem","rec","p","down","defineQuery","defineQuery","defineQuery","defineSystem","defineTickSystem","P","defineQuery","defineSystem","defineTickSystem","defineQuery","defineTickSystem","defineQuery","connectDragQ","compatible","defineTickSystem","p","dist","defineQuery","defineTickSystem","p","defineQuery","defineTickSystem","idx","defineQuery","defineSystem","P","defineQuery","defineSystem","defineQuery","defineSystem","P","defineQuery","defineSystem","p","defineQuery","Any","defineQuery","defineSystem","P","anyKindQ","defineQuery","Any","defineSystem","defineQuery","defineSystem","defineTickSystem","pointerQ","defineQuery","defineSystem","defineTickSystem","defineQuery","defineSystem","defineTickSystem","Not","IDENTITY_CAM","defineQuery","Not","pointerQ","p","defineTickSystem","defineSystem","Any","Not","defineQuery","defineSystem","P","defineQuery","Any","Not","isTerminal","defineSystem","defineQuery","defineSystem","P","defineQuery","IDENTITY_CAM","defineSystem","defineQuery","defineSystem","P","defineQuery","p","defineSystem","defineQuery","defineSystem","defineQuery","defineSystem","p","defineQuery","defineTickSystem","P","IDENTITY_CAM","canvasSurfaceQ","defineQuery","longPressQ","defineTickSystem","defineQuery","defineSystem","P","defineQuery","defineSystem","defineQuery","defineTickSystem","defineQuery","defineTickSystem","enabled","defineQuery","defineSystem","P","defineQuery","isTerminal","defineSystem","canvasSurfaceQ","defineQuery","behaviors","version","defineQuery","defineQuery","PACK_PREFIX","p","defineQuery","PACK_PREFIX","RENAMED_PREFIX","allDurableQ","defineQuery","Any","defineQuery","RENAMED_PREFIX","defineQuery","Any","defineQuery","SCHEMA_PREFIX","allDurableQ","defineQuery","defineQuery","Not","defineQuery","valueEquals","build","byComponent","Not","defineQuery","defineQuery","Not","defineQuery","Not","frame","valueEquals","defineQuery","defineQuery","defineQuery","wireQ","p","Any","defineQuery","defineQuery","Any","P","Not","defineQuery","defineSystem","defineQuery","Not","defineSystem","defineTickSystem","defineTickSystem","Not","defineQuery","defineTickSystem","defineQuery","frame","defineTickSystem","p","Not","defineQuery","defineQuery","p","Not","defineQuery","defineTickSystem","Local","defineQuery","Not","Local","defineTickSystem","fail","createWorld","defineQuery","IDENTITY_CAM","defineQuery","tweenQ","createWorld","behaviors","opts","p","Any","Not","Related","createWorld","defineQuery","defineSystem","defineTickSystem","enumOf","field","Local"]}
|