@vibecook/ice 0.1.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/LICENSE +21 -0
- package/README.md +76 -0
- package/dist/chunk-5S7GSXJG.js +6003 -0
- package/dist/chunk-5S7GSXJG.js.map +1 -0
- package/dist/chunk-BCJ47SX7.js +550 -0
- package/dist/chunk-BCJ47SX7.js.map +1 -0
- package/dist/chunk-FIAXPNNY.js +1446 -0
- package/dist/chunk-FIAXPNNY.js.map +1 -0
- package/dist/devtools.js +417 -0
- package/dist/devtools.js.map +1 -0
- package/dist/dom.js +41 -0
- package/dist/dom.js.map +1 -0
- package/dist/index.js +450 -0
- package/dist/index.js.map +1 -0
- package/dist/kernel.js +63 -0
- package/dist/kernel.js.map +1 -0
- package/dist/r3f.js +1101 -0
- package/dist/r3f.js.map +1 -0
- package/dist/react.js +440 -0
- package/dist/react.js.map +1 -0
- package/dist/types/packages/core/src/boot/hmr.d.ts +12 -0
- package/dist/types/packages/core/src/catalog/camera-derived.d.ts +144 -0
- package/dist/types/packages/core/src/catalog/gesture.d.ts +254 -0
- package/dist/types/packages/core/src/catalog/graph.d.ts +55 -0
- package/dist/types/packages/core/src/catalog/index.d.ts +32 -0
- package/dist/types/packages/core/src/catalog/pointer.d.ts +111 -0
- package/dist/types/packages/core/src/catalog/scene.d.ts +34 -0
- package/dist/types/packages/core/src/catalog/selection-presence.d.ts +53 -0
- package/dist/types/packages/core/src/catalog/settings-resources.d.ts +46 -0
- package/dist/types/packages/core/src/doc/autosave.d.ts +69 -0
- package/dist/types/packages/core/src/doc/bootstrap.d.ts +74 -0
- package/dist/types/packages/core/src/doc/broadcast-relay.d.ts +52 -0
- package/dist/types/packages/core/src/doc/channels.d.ts +49 -0
- package/dist/types/packages/core/src/doc/doc-commit-sink.d.ts +22 -0
- package/dist/types/packages/core/src/doc/doc-kit.d.ts +50 -0
- package/dist/types/packages/core/src/doc/envelope.d.ts +36 -0
- package/dist/types/packages/core/src/doc/migrate.d.ts +69 -0
- package/dist/types/packages/core/src/doc/version-gate.d.ts +49 -0
- package/dist/types/packages/core/src/engine/commit-sink.d.ts +61 -0
- package/dist/types/packages/core/src/engine/engine.d.ts +62 -0
- package/dist/types/packages/core/src/engine/frame-info.d.ts +16 -0
- package/dist/types/packages/core/src/engine/instantiate.d.ts +45 -0
- package/dist/types/packages/core/src/engine/pipeline.d.ts +17 -0
- package/dist/types/packages/core/src/engine/reflectors.d.ts +56 -0
- package/dist/types/packages/core/src/facade/create-canvas-engine.d.ts +120 -0
- package/dist/types/packages/core/src/guards/dev.d.ts +2 -0
- package/dist/types/packages/core/src/guards/guarded-tx.d.ts +51 -0
- package/dist/types/packages/core/src/guards/live-writer.d.ts +33 -0
- package/dist/types/packages/core/src/guards/resource-writer.d.ts +17 -0
- package/dist/types/packages/core/src/helpers/phase-set.d.ts +70 -0
- package/dist/types/packages/core/src/helpers/version-stamps.d.ts +55 -0
- package/dist/types/packages/core/src/index.d.ts +63 -0
- package/dist/types/packages/core/src/input/measure-queue.d.ts +30 -0
- package/dist/types/packages/core/src/input/queue.d.ts +60 -0
- package/dist/types/packages/core/src/interaction/install.d.ts +58 -0
- package/dist/types/packages/core/src/nav/nested-canvas.d.ts +62 -0
- package/dist/types/packages/core/src/ops/cascade.d.ts +18 -0
- package/dist/types/packages/core/src/ops/claims.d.ts +15 -0
- package/dist/types/packages/core/src/ops/gestures.d.ts +10 -0
- package/dist/types/packages/core/src/ops/point-pick.d.ts +42 -0
- package/dist/types/packages/core/src/ops/port-geometry.d.ts +17 -0
- package/dist/types/packages/core/src/ops/selection.d.ts +14 -0
- package/dist/types/packages/core/src/presence/index.d.ts +7 -0
- package/dist/types/packages/core/src/presence/presence-kit.d.ts +39 -0
- package/dist/types/packages/core/src/presence/publish.d.ts +14 -0
- package/dist/types/packages/core/src/presence/remote-cursors.d.ts +18 -0
- package/dist/types/packages/core/src/schema/meta.d.ts +43 -0
- package/dist/types/packages/core/src/schema/prefab.d.ts +69 -0
- package/dist/types/packages/core/src/settings/defaults.d.ts +56 -0
- package/dist/types/packages/core/src/systems/camera-sim.d.ts +19 -0
- package/dist/types/packages/core/src/systems/chrome.d.ts +48 -0
- package/dist/types/packages/core/src/systems/cleanup.d.ts +19 -0
- package/dist/types/packages/core/src/systems/l0-input.d.ts +31 -0
- package/dist/types/packages/core/src/systems/l1-pick.d.ts +44 -0
- package/dist/types/packages/core/src/systems/l1-wires.d.ts +30 -0
- package/dist/types/packages/core/src/systems/l2-arbitrate.d.ts +40 -0
- package/dist/types/packages/core/src/systems/l2-recognize.d.ts +45 -0
- package/dist/types/packages/core/src/systems/l3-behave.d.ts +24 -0
- package/dist/types/packages/core/src/systems/l3-claim.d.ts +26 -0
- package/dist/types/packages/core/src/systems/l3-connect.d.ts +57 -0
- package/dist/types/packages/core/src/systems/l3-draw.d.ts +21 -0
- package/dist/types/packages/core/src/systems/l3-drop.d.ts +21 -0
- package/dist/types/packages/core/src/systems/l3-marquee.d.ts +35 -0
- package/dist/types/packages/core/src/systems/l3-ports.d.ts +30 -0
- package/dist/types/packages/core/src/systems/l3-resize.d.ts +17 -0
- package/dist/types/packages/core/src/systems/l3-snap.d.ts +19 -0
- package/dist/types/packages/core/src/systems/l4-cursor.d.ts +24 -0
- package/dist/types/packages/core/src/systems/measure-ingest.d.ts +26 -0
- package/dist/types/packages/core/src/tools/define-tool.d.ts +79 -0
- package/dist/types/packages/core/src/widget/define-widget.d.ts +124 -0
- package/dist/types/packages/core/src/widget/equip.d.ts +14 -0
- package/dist/types/packages/core/src/widget/mount-store.d.ts +47 -0
- package/dist/types/packages/core/src/widget/props.d.ts +98 -0
- package/dist/types/packages/core/src/widget/spawn.d.ts +30 -0
- package/dist/types/packages/devtools/src/index.d.ts +8 -0
- package/dist/types/packages/devtools/src/panel.d.ts +48 -0
- package/dist/types/packages/dom/src/host.d.ts +24 -0
- package/dist/types/packages/dom/src/index.d.ts +19 -0
- package/dist/types/packages/dom/src/loop.d.ts +11 -0
- package/dist/types/packages/dom/src/measure-adapter.d.ts +31 -0
- package/dist/types/packages/dom/src/measure-wiring.d.ts +49 -0
- package/dist/types/packages/dom/src/planes.d.ts +33 -0
- package/dist/types/packages/dom/src/pointer-adapter.d.ts +48 -0
- package/dist/types/packages/dom/src/reflectors/chrome.d.ts +33 -0
- package/dist/types/packages/dom/src/reflectors/cursor.d.ts +21 -0
- package/dist/types/packages/dom/src/reflectors/dom-widgets.d.ts +54 -0
- package/dist/types/packages/dom/src/reflectors/graybox.d.ts +31 -0
- package/dist/types/packages/dom/src/reflectors/grid.d.ts +63 -0
- package/dist/types/packages/dom/src/reflectors/plane-transform.d.ts +38 -0
- package/dist/types/packages/dom/src/reflectors/remote-cursors.d.ts +20 -0
- package/dist/types/packages/dom/src/reflectors/wires.d.ts +88 -0
- package/dist/types/packages/ice/src/devtools.d.ts +1 -0
- package/dist/types/packages/ice/src/dom.d.ts +1 -0
- package/dist/types/packages/ice/src/index.d.ts +1 -0
- package/dist/types/packages/ice/src/kernel.d.ts +1 -0
- package/dist/types/packages/ice/src/r3f.d.ts +1 -0
- package/dist/types/packages/ice/src/react.d.ts +1 -0
- package/dist/types/packages/kernel/src/anchors.d.ts +18 -0
- package/dist/types/packages/kernel/src/bezier.d.ts +38 -0
- package/dist/types/packages/kernel/src/coords.d.ts +67 -0
- package/dist/types/packages/kernel/src/eviction.d.ts +23 -0
- package/dist/types/packages/kernel/src/index.d.ts +13 -0
- package/dist/types/packages/kernel/src/shapes.d.ts +22 -0
- package/dist/types/packages/kernel/src/snap.d.ts +44 -0
- package/dist/types/packages/kernel/src/spatial-index.d.ts +16 -0
- package/dist/types/packages/kernel/src/zoom-bands.d.ts +19 -0
- package/dist/types/packages/r3f/src/bridge.d.ts +68 -0
- package/dist/types/packages/r3f/src/composite-material.d.ts +17 -0
- package/dist/types/packages/r3f/src/compositor-pass.d.ts +83 -0
- package/dist/types/packages/r3f/src/dev-write-trap.d.ts +30 -0
- package/dist/types/packages/r3f/src/gl-root.d.ts +21 -0
- package/dist/types/packages/r3f/src/gl-router.d.ts +60 -0
- package/dist/types/packages/r3f/src/index.d.ts +16 -0
- package/dist/types/packages/r3f/src/island-state.d.ts +68 -0
- package/dist/types/packages/r3f/src/island.d.ts +13 -0
- package/dist/types/packages/r3f/src/pool.d.ts +56 -0
- package/dist/types/packages/r3f/src/resource-registry.d.ts +30 -0
- package/dist/types/packages/r3f/src/use-island-frame.d.ts +24 -0
- package/dist/types/packages/react/src/engine-context.d.ts +31 -0
- package/dist/types/packages/react/src/hooks.d.ts +40 -0
- package/dist/types/packages/react/src/index.d.ts +14 -0
- package/dist/types/packages/react/src/infinite-canvas.d.ts +71 -0
- package/dist/types/packages/react/src/keymap.d.ts +42 -0
- package/dist/types/packages/react/src/use-commit.d.ts +35 -0
- package/dist/types/packages/react/src/use-presence.d.ts +23 -0
- package/dist/types/packages/react/src/use-tool.d.ts +4 -0
- package/dist/types/packages/react/src/widget-root.d.ts +33 -0
- package/package.json +112 -0
|
@@ -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/engine/engine.ts","../../core/src/guards/dev.ts","../../core/src/guards/live-writer.ts","../../core/src/guards/guarded-tx.ts","../../core/src/guards/resource-writer.ts","../../core/src/catalog/scene.ts","../../core/src/catalog/graph.ts","../../core/src/catalog/pointer.ts","../../core/src/helpers/phase-set.ts","../../core/src/catalog/gesture.ts","../../core/src/catalog/selection-presence.ts","../../core/src/catalog/camera-derived.ts","../../core/src/catalog/settings-resources.ts","../../core/src/helpers/version-stamps.ts","../../core/src/ops/selection.ts","../../core/src/ops/cascade.ts","../../core/src/ops/claims.ts","../../core/src/ops/gestures.ts","../../core/src/ops/point-pick.ts","../../core/src/input/queue.ts","../../core/src/engine/commit-sink.ts","../../core/src/systems/camera-sim.ts","../../core/src/widget/define-widget.ts","../../core/src/systems/l1-wires.ts","../../core/src/ops/port-geometry.ts","../../core/src/tools/define-tool.ts","../../core/src/systems/l2-recognize.ts","../../core/src/systems/l3-connect.ts","../../core/src/systems/l3-ports.ts","../../core/src/systems/chrome.ts","../../core/src/systems/l3-draw.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/doc/envelope.ts","../../core/src/doc/version-gate.ts","../../core/src/widget/spawn.ts","../../core/src/doc/doc-commit-sink.ts","../../core/src/doc/migrate.ts","../../core/src/doc/doc-kit.ts","../../core/src/widget/props.ts","../../core/src/widget/equip.ts","../../core/src/nav/nested-canvas.ts","../../core/src/systems/measure-ingest.ts","../../core/src/widget/mount-store.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/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 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 return c;\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(name: string, opts?: { arity?: \"one\" | \"many\" }): 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} 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/** 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/** 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/** { tick, dt ≤ dtClampMs (ms), now (ms timeline of the caller's clock) }. */\nexport const FrameInfo = defineResource(\"FrameInfo\", {\n tick: field(\"u32\", { default: 0 }),\n dt: field(\"f32\", { default: 0 }),\n now: 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 });\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}\n\ninterface Entry {\n readonly def: ReflectorDef;\n dirty: 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 let flushed: string[] = [];\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, 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 return () => {\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 };\n },\n\n flushAll() {\n flushed = [];\n for (const entry of entries) {\n if (!entry.dirty && entry.def.always !== true) continue;\n entry.dirty = false;\n try {\n entry.def.flush(world);\n flushed.push(entry.def.name);\n } catch (err) {\n onFault(entry.def.name, err);\n }\n }\n },\n\n lastFlushed() {\n return flushed;\n },\n\n names() {\n return entries.map((e) => e.def.name);\n },\n };\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 * 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 { setFrameInfo } from \"./frame-info\";\nimport { createPipelineRegistry, type PhaseGroup } from \"./pipeline\";\nimport { createReflectorRegistry, type ReflectorDef } from \"./reflectors\";\n\nexport type PublishHook = (world: World) => void;\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\nexport interface EngineOpts {\n /** Reflector fault sink (default: console.error, skip this frame). */\n readonly onReflectorFault?: (name: string, err: unknown) => 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 /** Run one full frame. `now` in ms (rAF timestamp or a test counter). */\n step(now: number): void;\n /** Arm per-system run/skip + µs collection (idempotent; costs timer calls per system). */\n enableTelemetry(): 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: PublishHook[] = [];\n\n let telemetryArmed = false;\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\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 publishHooks.push(hook);\n return () => {\n const i = publishHooks.indexOf(hook);\n if (i !== -1) publishHooks.splice(i, 1);\n };\n },\n\n step(now) {\n setFrameInfo(world, now);\n world.sync();\n world.tick(pipeline.assemble());\n for (const hook of publishHooks) hook(world);\n world.reactive.notify();\n reflectors.flushAll();\n },\n\n enableTelemetry() {\n if (telemetryArmed) return;\n telemetryArmed = true;\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 this post-notify — captured lazily below.\n reflectorsFlushed: [],\n };\n building = null;\n },\n });\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 { ...last, reflectorsFlushed: reflectors.lastFlushed() };\n },\n };\n}\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 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 * 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, Relation, Resource, Tag, World } from \"@vibecook/strata-ecs\";\nimport type { Mutator } from \"@vibecook/strata-ecs/durable\";\nimport { instantiate } from \"../engine/instantiate\";\nimport { schemaMeta } from \"../schema/meta\";\nimport { prefabs, PrefabId, type ComponentInit, type Prefab } from \"../schema/prefab\";\nimport { devGuardsEnabled } from \"./dev\";\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): void;\n addRelation(e: Entity, r: Relation, target: Entity): void;\n removeRelation(e: Entity, r: Relation, target?: Entity): void;\n setResource<S>(res: Resource<S>, v: S): 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 }): 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\nexport function guardedTransaction(\n doc: TxDoc,\n world: World,\n run: (tx: GuardedTx) => void,\n opts?: GuardedTxOpts,\n): void {\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 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 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 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) {\n checkRelation(e, r, \"setRelation\");\n tx.setRelation(e, r, target);\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 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\n run(guarded);\n }, opts);\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 * 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 } 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/** Fractional stacking order — z-reorder is one cell write; midpoints jittered, ties break by key. */\nexport const StackZ = defineComponent(\"StackZ\", { z: \"f64\" });\n\n/**\n * child → parent frame (durable-eligible). Replaces the ParentFrame/ContainerChildren triad:\n * children-of-x = `Related(ChildOf, x)`; ancestor walk = forward `getRelation`; engine cascade\n * walks `getReverse(e, ChildOf)` (see ops/cascade.ts).\n */\nexport const ChildOf = defineRelation(\"ChildOf\", { arity: \"one\" });\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): PrefabId \"wire\" + WirePorts;\n * Wire tag + WireFrom/WireTo edges ride the spawn (doc commit sink executes\n * connect intents). Registered here so the version gate stamps\n * `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});\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/** 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 * 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 } 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 * 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/StackZ.\n */\nexport const Grab = defineComponent(\"Grab\", {\n x: \"f64\",\n y: \"f64\",\n w: \"f32\",\n h: \"f32\",\n z: \"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 * 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// --- 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 * 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/** 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. */\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/** 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","/**\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 { CAMERA_DEFAULTS, GESTURE_DEFAULTS, POINTER_DEFAULTS } from \"../settings/defaults\";\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});\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 * 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 * 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 * 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 * 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 * 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 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 by StackZ\n * descending. Deliberately NOT plane-stratified: cross-plane z is stratified\n * visually (P2 GL composites above P1 DOM), but pick order is StackZ across\n * all surfaces — design-004 §1 names the mixed-overlap consequence and\n * 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, StackZ, Wire } from \"../catalog\";\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/**\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 * StackZ → 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): 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 bestWidgetZ = Number.NEGATIVE_INFINITY;\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 const z = reader.get(e, StackZ)?.z ?? 0;\n if (z > bestWidgetZ) {\n bestWidgetZ = z;\n bestWidget = e;\n }\n }\n }\n return bestHandle ?? bestPort ?? bestWidget ?? bestWire;\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 * 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 * 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 } 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 * 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/** A widget creation riding a create outcome (draw tool, design-005 §3). */\nexport interface CommitCreate {\n readonly type: string;\n readonly x: number;\n readonly y: number;\n readonly w: number;\n readonly h: number;\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 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 * 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 } 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/pinch zoom sensitivity — matches the shipped demo pan/zoom feel (design-003 §5 item 9). */\nconst ZOOM_SENSITIVITY = 0.0015;\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.\n const tweenStart = new Map<Entity, { x: number; y: number }>();\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 next = zoomAtPoint(\n { x, y, zoom },\n wz.anchorX,\n wz.anchorY,\n clampZoom(world, zoom * Math.exp(-wz.pinch * ZOOM_SENSITIVITY)),\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 * `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/StackZ + 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, Tag } from \"@vibecook/strata-ecs\";\nimport {\n Accepts,\n ChildOf,\n Container,\n LongPressDrag,\n Movable,\n Position,\n Provides,\n Resizable,\n Selectable,\n Size,\n SnapSource,\n SnapTarget,\n Solid,\n StackZ,\n} from \"../catalog\";\nimport { defineComponent, defineTag } from \"../schema/meta\";\nimport { definePrefab, init, type ComponentInit, type Prefab } from \"../schema/prefab\";\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\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\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 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 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 * 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 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 readonly migrate: Readonly<Record<number, (prev: Record<string, unknown>) => 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>();\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\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 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\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 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 groups.push({ name: g, component: defineComponent(`${def.type}:${g}`, raw) as Component, fields });\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 init(StackZ, { z: 0 }),\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)) {\n if (spec.kind === \"json\") defaults[name] = (spec as JsonSpec).default ?? \"null\";\n else if (spec.kind === \"enum\") defaults[name] = spec.default ?? spec.options[0] ?? \"\";\n else defaults[name] = spec.default ?? (spec.kind === \"string\" ? \"\" : spec.kind === \"number\" ? 0 : false);\n }\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 const version = def.version ?? 1;\n if (def.migrate !== undefined) validateMigrateChain(def.type, version, def.migrate);\n\n const prefab = definePrefab(def.type, {\n store: \"durable\",\n components: essential,\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 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 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 migrate: def.migrate ?? {},\n };\n registry.set(def.type, widget);\n return widget;\n}\n\n/** TEST-ONLY wipe (mirrors __resetPrefabsForTests; not on the barrel). */\nexport function __resetWidgetsForTests(): void {\n registry.clear();\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 * 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 * `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.now (the engine clock); all thresholds read\n * the GestureSettings RESOURCE (live-tunable, design-005 §4) with the\n * GESTURE_DEFAULTS constants as the unset fallback. Gesture math is screen-space totals + zoom-at-claim — never\n * 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 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 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]);\nconst wheelSourceQ = defineQuery([Pointer, PointerWheel, LocalPointer]);\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\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 = ctx.getResource(FrameInfo)?.now ?? 0;\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 down EVENT's timestamp when the adapter\n // supplied one — a stalled frame at pointerdown must not eat into tap/\n // long-press windows (2026-07-12 field debugging: a 640 ms headless\n // stall made long-press unreachable). 0 ⇒ no stamp ⇒ frame now.\n const downStamp = ctx.read(pointer, PointerButtons).downMs;\n const downMs = downStamp > 0 ? downStamp : 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 { name: \"recognizerSpawn\" },\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 = ctx.getResource(FrameInfo)?.now ?? 0;\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 = ctx.getResource(FrameInfo)?.now ?? 0;\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 = ctx.getResource(FrameInfo)?.now ?? 0;\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 if (dist(down.x, down.y, screen.x, screen.y) > gs(ctx).dragSlopPx) {\n // Origin measured FROM DEAD-ZONE EXIT (no jump on promote).\n ctx.edit(e).set(Drag, {\n startX: screen.x,\n startY: 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 = ctx.getResource(FrameInfo)?.now ?? 0;\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 const active = 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 = ctx.getResource(FrameInfo)?.now ?? 0;\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 * 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 * 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 *\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 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\";\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 any = false;\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 for (const e of selectedEntities(world)) {\n if (!ctx.has(e, Position)) 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 const w = m !== undefined && m.w > 0 ? m.w : (s?.w ?? 0);\n const h = 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 + w);\n maxY = Math.max(maxY, p.y + h);\n any = true;\n }\n\n if (!any || !allResizable) {\n // Selection emptied — or contains a non-resizable widget: cards show\n // NO engine chrome at all (box included), v1 parity (field report\n // 2026-07-12); only fully-resizable selections get box + grips.\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 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 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\nconst equippedWidgetQ = defineQuery([Size, WidgetEquipped]);\n\nexport function createBreakpointSystem(_world: World): System {\n return defineSystem(\n equippedWidgetQ,\n (b, ctx) => {\n const sw = b.col(Size).w;\n const sh = b.col(Size).h;\n for (const r of b) {\n const e = b.entity(r);\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 : (sw[r] as number);\n const eh = m !== undefined && m.h > 0 ? m.h : (sh[r] as number);\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 zoom = ctx.getResource(Camera)?.zoom ?? 1;\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 continue;\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 },\n { name: \"breakpoint\", access: { write: [WidgetBreakpoint] } },\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 * 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 { 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 { 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 engine.addSystems(\"simulate\", camera.cameraInertia, camera.tweenSystem),\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 engine.addSystems(\"cleanup\", cleanup.recognizerReap, cleanup.oneTickClear),\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 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 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 Pointer,\n PointerButtons,\n PointerMods,\n PointerRadius,\n PointerScreen,\n PointerWheel,\n PointerWorld,\n WentCancelled,\n WentDown,\n WentUp,\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 mods: { shift: boolean; ctrl: boolean; alt: boolean; meta: boolean };\n wheelDx: number;\n wheelDy: number;\n wheelPinch: number;\n hasWheel: 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 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 };\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 }\n if (ev.surfaceHandled === true) s.handled = true;\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 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 }\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 (strata 0.5.0) so the body runs EVERY frame — it is the writer\n * that bumps\n * `SpatialVersion`, and its own writes have no version stamp to gate on\n * (design-002 §4), so it must run eagerly and stays cheap via a private\n * last-known cache: an entity is re-`upsert`ed only when its AABB actually\n * changed, and a cache-sweep removes entries no longer matched (despawns, or a\n * lost Position/Size). Materialized ports are M8 — 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 by\n * StackZ descending, then the CanvasSurface entity as the guaranteed fallback\n * (design-001 §4). Relations are written change-only (design-002 §4 hygiene).\n * Wires/ports are M8 — skipped.\n */\nimport type { 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 { 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]);\nconst posSizeQ = defineQuery([Position, Size]);\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 // Private last-known AABB cache — the compare-and-skip that keeps spatialSync\n // cheap while running every frame (it is the SpatialVersion writer).\n const cache = new Map<Entity, { x: number; y: number; w: number; h: number }>();\n\n const spatialSync = defineTickSystem(\n (ctx) => {\n const seen = new Set<Entity>();\n let changed = false;\n ctx.query(posSizeQ).each((batch) => {\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 e = batch.entity(row);\n // Nav gating (design-004 §7): only ACTIVE widgets are hittable —\n // container content indexes only inside its frame. Non-widget\n // Position+Size entities (chrome handles) are frame-local already.\n if (world.hasTag(e, WidgetEquipped) && !world.hasTag(e, Active)) continue;\n seen.add(e);\n const x = px[row] as number;\n const y = py[row] as number;\n const w = sw[row] as number;\n const h = sh[row] as number;\n const prev = cache.get(e);\n if (prev === undefined || prev.x !== x || prev.y !== y || prev.w !== w || prev.h !== h) {\n index.upsert(e, { minX: x, minY: y, maxX: x + w, maxY: y + h });\n cache.set(e, { x, y, w, h });\n changed = true;\n }\n }\n });\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 if (changed) 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 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);\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 return { spatialSync, picking, index, clearCaches: () => cache.clear() };\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 StackZ (a forgotten StackZ restore leaves\n * the cell diverged forever); remove riders and gesture-scoped edges on every\n * terminal path. Discrete 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 + StackZ per live Drags edge).\n * Without dropSystem installed no DropTarget ever exists ⇒ plain commits.\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 DropTarget,\n GesturePhases,\n Grab,\n OverlapCandidate,\n OverlapRejected,\n PointerMods,\n Position,\n RoutedMove,\n Selectable,\n Size,\n Selected,\n SnapState,\n StackZ,\n Tap,\n TransformTween,\n Watches,\n Wire,\n} from \"../catalog\";\nimport type { 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/** 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\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.\n for (const w of dragged) {\n if (!ctx.isAlive(w) || !ctx.has(w, Grab)) continue;\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 // Restore StackZ NOW (it is not animated): fly-back commits\n // nothing, so an elevated z left in place would keep the cell\n // diverged forever and hold remote z-edits indefinitely — the\n // same law as the cancel path (design-003 §5.3).\n if (ctx.has(w, StackZ)) ctx.edit(w).set(StackZ, { z: g.z });\n }\n } else if (container !== undefined) {\n // Consume: reparent + final position, one intent (one tx at M5).\n const writes: CommitWrite[] = [];\n const reparents: { entity: Entity; container: Entity }[] = [];\n const containerPos = ctx.get(container, Position) ?? { x: 0, y: 0 };\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 writes.push({\n entity: w,\n component: Position,\n value: { x: g.x + wx - containerPos.x, y: g.y + wy - containerPos.y },\n });\n reparents.push({ entity: w, container });\n }\n if (writes.length > 0) sink.commit({ kind: \"consume\", gesture: rec, writes, reparents });\n } else {\n // Plain move commit: final Position + StackZ per live edge.\n const writes: CommitWrite[] = [];\n for (const w of dragged) {\n if (!ctx.isAlive(w) || !ctx.has(w, Grab)) continue;\n const g = ctx.read(w, Grab);\n writes.push({ entity: w, component: Position, value: { x: g.x + wx, y: g.y + wy } });\n const z = ctx.get(w, StackZ);\n if (z !== undefined) {\n writes.push({ entity: w, component: StackZ, value: { z: z.z } });\n }\n }\n if (writes.length > 0) sink.commit({ kind: \"move\", gesture: rec, writes });\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 StackZ from Grab (design-003 §5.3), then clean up.\n for (const w of dragged) {\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 if (ctx.has(w, StackZ)) ctx.edit(w).set(StackZ, { z: g.z });\n }\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, StackZ], 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/StackZ embedded\n * in the command payload, and the StackZ elevate (an immediate value write —\n * part of the gesture divergence, restored from `Grab.z` on cancel).\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 Captures,\n Drag,\n Drags,\n GesturePhases,\n Grab,\n Movable,\n PointerMods,\n Position,\n Resizable,\n RoutedMove,\n RoutedResize,\n Selected,\n Size,\n StackZ,\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 stackZQ = defineQuery([StackZ]);\n\n/** Fractional-top elevate: max live z + 1 (scan on the claim frame only — O(n) once per gesture). */\nfunction topZ(world: World): number {\n let top = 0;\n world.query(stackZQ).each((b) => {\n const z = b.col(StackZ).z;\n for (const r of b) {\n const v = z[r] as number;\n if (v > top) top = v;\n }\n });\n return top;\n}\n\n/** Attach the drag riders for one widget; returns false if another gesture owns it. */\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 z = ctx.get(widget, StackZ);\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 z: z?.z ?? 0,\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.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 const zBase = topZ(world);\n let elevated = 0;\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 if (ctx.has(w, StackZ)) {\n // Immediate value write — gesture divergence, Grab.z restores on cancel.\n elevated += 1;\n ctx.edit(w).set(StackZ, { z: zBase + elevated });\n }\n }\n }\n },\n { name: \"moveClaim\", access: { write: [StackZ] } },\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 StackZ, 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 StackZ,\n} from \"../catalog\";\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 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 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 let bestZ = Number.NEGATIVE_INFINITY;\n if (any) {\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) && !ctx.hasTag(e, Solid)) continue;\n const z = ctx.get(e, StackZ)?.z ?? 0;\n if (z > bestZ) {\n bestZ = z;\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 // 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 // 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 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 1×1. `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\";\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): 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 1×1 — adjust the moving edge so the fixed edge stays put.\n if (right - left < 1) {\n if (affectsLeft && !affectsRight) left = right - 1;\n else right = left + 1;\n }\n if (bottom - top < 1) {\n if (affectsTop && !affectsBottom) top = bottom - 1;\n else bottom = top + 1;\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 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 rz = computeResize(g, anchor, dx, dy, alt, shift);\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 rz = computeResize(g, anchor, dx, dy, alt, shift);\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 expanded by threshold, filtered to\n * `SnapTarget ∧ ∉dragged`; Visible filtering waits for cull). 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). Guide CHROME entities (`GuideLine`) are deferred\n * to the chrome-reflector milestone — SnapState only here. SnapState clears to 0,0\n * when snap is off / no source / no candidate.\n */\nimport type { Entity, System, SystemCtx, World } from \"@vibecook/strata-ecs\";\nimport { defineQuery, defineSystem } from \"@vibecook/strata-ecs\";\nimport { type EntityBounds, type SpatialIndex, computeSnapGuides } from \"@ice/kernel\";\nimport {\n Captures,\n Drag,\n Drags,\n GestureActive,\n Grab,\n RoutedMove,\n SnapConfig,\n SnapSource,\n SnapState,\n SnapTarget,\n} from \"../catalog\";\nimport { SNAP_DEFAULTS } from \"../settings/defaults\";\n\nconst snapDragQ = defineQuery([Drag, GestureActive, RoutedMove]);\n\nexport function createSnapSystem(world: World, index: SpatialIndex<Entity>): System {\n return defineSystem(\n snapDragQ,\n (b, 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 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 (intended ∪ threshold), SnapTarget ∧ ∉dragged.\n const refs: EntityBounds[] = [];\n for (const entry of index.search({\n minX: minX - threshold,\n minY: minY - threshold,\n maxX: maxX + threshold,\n maxY: maxY + threshold,\n })) {\n const e = entry.id;\n if (draggedSet.has(e) || !ctx.isAlive(e) || !ctx.hasTag(e, SnapTarget)) 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 }\n },\n { name: \"snapSystem\", access: { write: [SnapState] } },\n );\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;\n\n/** The document-format version this build writes (gate compares against it). */\nexport const ENGINE_SCHEMA_VERSION = 1;\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 (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 (typeof header.engineSchema !== \"number\" || typeof header.prefabVersions !== \"object\") {\n throw new EnvelopeError(\"header is missing required fields\", \"header\");\n }\n return { header, payload: bytes.subarray(9 + headerLen) };\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 { ENGINE_SCHEMA_VERSION } from \"./envelope\";\n\nconst SCHEMA_PREFIX = \"engine.schema.\";\nconst PACK_PREFIX = \"engine.pack.\";\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\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/** 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 docPacks: Record<string, number> = {};\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(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 ((docPacks[id] ?? 0) < v) docPacks[id] = v;\n }\n }\n\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\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\n return { docSchema, localSchema: ENGINE_SCHEMA_VERSION, docPacks, localPacks, newerInDoc, olderInDoc };\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 (report.docSchema < report.localSchema || report.olderInDoc.length > 0) return \"migrate\"; // M9 runs the chain; M5 treats as readOnly downstream\n return \"ok\";\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 { Entity, World } from \"@vibecook/strata-ecs\";\nimport type { DurableStore } from \"@vibecook/strata-ecs/durable\";\nimport { Position, Size } from \"../catalog\";\nimport { guardedTransaction } from \"../guards/guarded-tx\";\nimport { init, type ComponentInit } from \"../schema/prefab\";\nimport { widgets } from \"./define-widget\";\n\nexport interface SpawnWidgetOpts {\n readonly x: number;\n readonly y: number;\n readonly w?: number;\n readonly h?: number;\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 * 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 if (spec.kind === \"json\") value[name] = spec.default ?? \"null\";\n else if (spec.kind === \"enum\") value[name] = spec.default ?? spec.options[0] ?? \"\";\n else if (spec.kind === \"string\") value[name] = spec.default ?? \"\";\n else if (spec.kind === \"number\") value[name] = spec.default ?? 0;\n else value[name] = spec.default ?? false;\n }\n }\n overrides.push([g.component, value] as ComponentInit);\n }\n\n return { prefab: widget.prefab, overrides };\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 },\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 { World } from \"@vibecook/strata-ecs\";\nimport { ChildOf } from \"../catalog\";\nimport type { CommitIntent, CommitSink } from \"../engine/commit-sink\";\nimport { PrefabId } from \"../schema/prefab\";\nimport { Wire, WireFrom, WirePorts, WireTo } from \"../catalog/graph\";\nimport { widgetSpawnInits } from \"../widget/spawn\";\nimport { guardedTransaction } from \"../guards/guarded-tx\";\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 const creates = intent.creates ?? [];\n if (liveWrites.length === 0 && liveReparents.length === 0 && liveWires.length === 0 && creates.length === 0) return;\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 tx.setRelation(r.entity, ChildOf, r.container);\n }\n // Draw-tool creations: one prefab spawn per rect (design-005 §3),\n // through the SAME override builder as ops.spawnWidget.\n for (const c of creates) {\n const { prefab, overrides } = widgetSpawnInits(c.type, { x: c.x, y: c.y, w: c.w, h: c.h });\n tx.spawnPrefab(prefab, overrides);\n }\n for (const w of liveWires) {\n const wire = tx.spawn({\n components: [\n [PrefabId, { id: \"wire\" }],\n [WirePorts, { from: w.fromPort, to: w.toPort }],\n ],\n tags: [Wire],\n });\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 * 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\n/**\n * Run every applicable per-type migration against an ATTACHED doc. Reads happen\n * before the write transaction opens (a clean read snapshot → compute → one\n * absolute write pass); each type stamps its new marker in its own\n * `metaTransaction` after its data transaction commits. Never throws for a\n * merely-un-migratable type (missing widget / gappy chain → skipped); a genuine\n * fault (a throwing transform) propagates so 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 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 // --- read pass: gather each entity's current props + fold the chain ---\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\n // --- write pass: ONE non-undoable transaction of absolute per-group writes ---\n // `edit().set` / `addComponent` canon the value against the group schema, so a\n // flat `next` spanning all groups is picked apart per group (extra keys ignored,\n // missing declared-default keys default-filled).\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 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 ENGINE_SCHEMA_VERSION,\n EnvelopeError,\n decodeEnvelope,\n encodeEnvelope,\n type EnvelopeHeader,\n} from \"./envelope\";\nimport { createDocCommitSink, createReadOnlyCommitSink } from \"./doc-commit-sink\";\nimport { runMigrations } from \"./migrate\";\nimport { createLiveWriter, type LiveWriter } from \"../guards/live-writer\";\nimport { makeDefaultMayDiverge } from \"../ops/claims\";\nimport {\n gateVerdict,\n readDocVersionReport,\n stampEngineMeta,\n type DocVersionReport,\n type GateVerdict,\n} from \"./version-gate\";\nimport { prefabs } from \"../schema/prefab\";\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 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 /** 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 localPrefabVersions(): Record<string, number> {\n const out: Record<string, number> = {};\n for (const p of prefabs.all()) if (p.store === \"durable\") out[p.id] = p.version ?? 1;\n return out;\n}\n\nfunction makeSession(\n world: World,\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 let closed = false;\n\n return {\n store,\n sink,\n readOnly,\n liveWriter,\n ...(report !== undefined ? { report } : {}),\n exportEnvelope(savedAt) {\n const header: EnvelopeHeader = {\n engineSchema: ENGINE_SCHEMA_VERSION,\n prefabVersions: localPrefabVersions(),\n ...(savedAt !== undefined ? { savedAt } : {}),\n };\n return encodeEnvelope(header, store.exportSnapshot());\n },\n exportSnapshot: () => store.exportSnapshot(),\n applyRemote: (bytes) => store.applyRemote(bytes),\n close() {\n if (closed) return;\n closed = true;\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 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 return makeSession(world, 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 try {\n payload = decodeEnvelope(bytes).payload;\n } catch (err) {\n const reason = err instanceof EnvelopeError ? err.message : String(err);\n return { ok: false, reason };\n }\n\n const doc = new LoroDoc();\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 const verdict = (opts.onGate ?? ((_, v) => v))(report, gateVerdict(report));\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 const 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 runMigrations({ store, world }, report);\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).\n readOnly = true;\n }\n }\n return { ok: true, session: makeSession(world, 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 return { ok: false, reason: `ice: attach failed — ${String(err)}`, report };\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\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/** 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 // 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 * 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 System } from \"@vibecook/strata-ecs\";\nimport { PrefabId } from \"../schema/prefab\";\nimport { WidgetEquipped, widgets } from \"./define-widget\";\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 }\n ctx.addTag(e, WidgetEquipped);\n }\n },\n { name: \"widgetEquip\" },\n );\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. A nav switch is O(frame\n * content) tag flips — bounded, rare, migration-free. Boards without\n * containers converge to \"everything Active\" on the first pass and never\n * write again (M3–M7 demos unaffected).\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 memory: enter saves the live camera on the pushed entry\n * (NavCamera) and applies the container's `ContainerCamera` rider (else\n * zoom-to-fit over the frame's content, else identity); exit writes the\n * rider back (per-user view memory; lost on undo-despawn — accepted) and\n * restores the entry's NavCamera.\n */\nimport type { Entity, TickSystem, World } from \"@vibecook/strata-ecs\";\nimport { defineQuery, defineTickSystem } from \"@vibecook/strata-ecs\";\nimport type { SpatialIndex } from \"@ice/kernel\";\nimport {\n Camera,\n Container,\n ContainerCamera,\n Culled,\n NavCamera,\n NavDepth,\n NavFrame,\n Position,\n Size,\n Viewport,\n Visible,\n} from \"../catalog\";\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\";\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/** 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 (world.hasTag(cur, Container)) return cur;\n cur = world.getRelation(cur, ChildOf);\n hops += 1;\n }\n return undefined;\n}\n\nexport interface NestedCanvas {\n readonly activeMembership: TickSystem;\n readonly navIntegrity: TickSystem;\n enterContainer(container: Entity): void;\n exitContainer(): 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 */\nexport function createActiveMembership(world: World): TickSystem {\n return defineTickSystem(\n (ctx) => {\n const frame = currentNavFrame(world);\n ctx.query(equippedQ).each((b) => {\n for (const r of b) {\n const e = b.entity(r);\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 },\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 const applyCameraForFrame = (frame: Entity | undefined): void => {\n if (frame === undefined) return;\n const rider = world.get(frame, ContainerCamera);\n if (rider !== undefined && rider.zoom > 0) {\n writeRuntimeResource(world, Camera, { x: rider.x, y: rider.y, zoom: rider.zoom, gesturing: false });\n return;\n }\n // Zoom-to-fit over the frame's direct content (fallback; identity if empty).\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 s = 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 writeRuntimeResource(world, Camera, { x: 0, y: 0, zoom: 1, gesturing: false });\n return;\n }\n const pad = 80;\n const zoom = Math.min(2, Math.max(0.1, Math.min(vp.w / (maxX - minX + pad * 2), vp.h / (maxY - minY + pad * 2))));\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\n const popTo = (targetDepth: number): void => {\n // Destroy entries deeper than targetDepth; restore the camera of the\n // shallowest destroyed entry (the camera as it was before entering it).\n const doomed: Entity[] = [];\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 > targetDepth) doomed.push(e);\n }\n });\n // Shallowest doomed entry's saved camera is the correct restore point.\n let shallowest: Entity | undefined;\n let shallowestD = Number.POSITIVE_INFINITY;\n for (const e of doomed) {\n const d = world.read(e, NavDepth).d;\n if (d < shallowestD) {\n shallowestD = d;\n shallowest = e;\n }\n }\n if (shallowest !== undefined) {\n const cam = world.read(shallowest, NavCamera);\n writeRuntimeResource(world, Camera, { x: cam.x, y: cam.y, zoom: cam.zoom, gesturing: false });\n }\n for (const e of doomed) world.destroy(e); // ops run OUTSIDE the tick — structural world.* is legal here\n rebuildIndex();\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 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 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 return {\n activeMembership,\n navIntegrity,\n enterContainer(container) {\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 applyCameraForFrame(container);\n rebuildIndex();\n },\n exitContainer() {\n const entry = currentNavEntry(world);\n if (entry === undefined) return; // already at root\n // Persist per-user view memory on the frame we're leaving.\n const frame = world.getRelation(entry, NavFrame);\n const cam = world.getResource(Camera);\n if (frame !== undefined && world.isAlive(frame) && cam !== undefined) {\n const rider = { x: cam.x, y: cam.y, zoom: cam.zoom };\n if (world.has(frame, ContainerCamera)) world.edit(frame).set(ContainerCamera, rider);\n else world.addComponent(frame, ContainerCamera, rider);\n }\n popTo(world.read(entry, NavDepth).d - 1);\n },\n depth() {\n const entry = currentNavEntry(world);\n return entry === undefined ? 0 : world.read(entry, NavDepth).d;\n },\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.\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 * - 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, defineSystem, defineTickSystem, type Entity, type System, 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 } from \"../nav/nested-canvas\";\nimport { createMeasureIngest } from \"../systems/measure-ingest\";\nimport type { MeasureQueue } from \"../input/measure-queue\";\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: System;\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 const cullSystem = defineSystem(\n widgetQ,\n (b, ctx) => {\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 for (const r of b) {\n const e = b.entity(r);\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 },\n { name: \"cull\" },\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 // Tick system (strata 0.5.0): one full reconcile per frame by construction\n // (widgetQ spans archetypes; the pre-0.5.0 chunk form needed a\n // reconciledThisTick dedupe flag re-armed from the flush — all gone).\n const mountSystem = defineTickSystem(\n (ctx) => {\n tickCounter += 1;\n let changed = false;\n\n ctx.query(visibleWidgetsQ).each((vb) => {\n for (const r of vb) {\n const e = vb.entity(r);\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 });\n ctx.query(culledWidgetsQ).each((cb) => {\n for (const r of cb) {\n const e = cb.entity(r);\n const entry = mounted.get(e);\n if (entry !== undefined && !entry.hidden) {\n entry.hidden = true;\n changed = true;\n }\n }\n });\n // Sweep dead entities + enforce the keep-mounted LRU budget.\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 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\" },\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 * 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 (the one this kit rides): `DurableStore`'s\n * `subscribeOutbound(fn: (bytes) => void): Unsubscribe` (durable-store.ts) fires\n * SYNCHRONOUSLY on each sealed LOCAL commit and NOT on remote imports\n * (`onLocalBatch` early-returns on `origin !== \"local\"`). That is exactly the\n * autosave trigger: a peer persists what it authored; remote changes are\n * persisted by whichever peer originated them (its own local commit fires its\n * own autosave). No polling — the design's `store.exportSnapshot()` length/\n * frontier poll is 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 a synchronous save (the\n * beforeunload path); `stop()` unsubscribes and cancels the timer.\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 { Any, defineQuery } from \"@vibecook/strata-ecs\";\nimport type { World } from \"@vibecook/strata-ecs\";\nimport {\n Camera,\n Drag,\n GesturePhases,\n LongPress,\n Pinch,\n Tap,\n WheelPan,\n WheelZoom,\n} from \"../catalog\";\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}\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}\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 (beforeunload / explicit save). */\n flush(): Promise<void>;\n /** Unsubscribe and cancel any pending timer. Idempotent. */\n stop(): void;\n /** A pull-based status read for a per-frame HUD (design demo). */\n state(): AutosaveState;\n}\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 * A save while this holds could straddle a gesture's pre-commit runtime edits.\n */\nfunction 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\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\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 stopped = false;\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 =>\n world.getResource(Camera)?.gesturing === true || anyGestureNonTerminal(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) 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) {\n const at = now();\n const bytes = session.exportEnvelope(at);\n dirty = false; // optimistic: a change during the await re-sets it\n saving = true;\n try {\n await storage.put(bytes);\n lastSavedAt = at;\n errored = false;\n } catch {\n errored = 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) return writeInFlight;\n if (!writing) {\n writing = true;\n writeInFlight = runWrites();\n }\n return writeInFlight;\n }\n\n const markDirty = (): void => {\n if (stopped) return;\n if (!dirty) firstDirtyAt = now();\n dirty = true;\n arm();\n };\n\n const unsub = session.store.subscribeOutbound(() => markDirty());\n\n return {\n async flush(): Promise<void> {\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.\n if (dirty) requestWrite();\n await writeInFlight;\n },\n stop(): void {\n if (stopped) return;\n stopped = true;\n clearTimer();\n unsub();\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 const 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 localPeer = eph.spawn({\n components: [[PresenceInfo, { name: opts.name, color: opts.color }]],\n tags: [PresencePeer],\n });\n\n let detached = false;\n return {\n peerId,\n eph,\n localPeer,\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 // 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, localPeer } = 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\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 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\nexport interface JoinResult {\n /** \"seeder\" = we created the doc (timed out); \"joiner\" = we imported a peer's base. */\n readonly role: \"seeder\" | \"joiner\";\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 * 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 };\n\n return new Promise<JoinResult>((resolve, reject) => {\n let session: DocSession | undefined;\n let active = false;\n let settled = 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\n const armTimeout = (): void => {\n timeoutHandle = clock.setTimeout(() => {\n if (!active && !settled) 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) => channel.send(frame(K_UPDATE, bytes)));\n if (!settled) {\n settled = true;\n resolve({ role, session: s, leave });\n }\n };\n\n const becomeSeeder = (): void => {\n if (active || settled) return;\n const s = createDocSession(world, docOpts);\n opts.seed?.(s); // seed BEFORE going active — the state rides every future snapshot\n goActive(s, \"seeder\");\n };\n\n const becomeJoiner = (base: Uint8Array): void => {\n if (active) return;\n clock.clearTimeout(timeoutHandle);\n const result = openDocSession(world, base, docOpts);\n if (!result.ok) {\n // A corrupt/incompatible base — surface and give up (reconnect = re-join).\n if (!settled) {\n settled = true;\n reject(new Error(`ice: bootstrap base import failed — ${result.reason}`));\n }\n return;\n }\n const s = result.session;\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 channel.send(frame(K_SNAPSHOT_OFFER, s.exportEnvelope())); // envelope-framed (a peer may OPEN it)\n goActive(s, \"joiner\");\n for (const bytes of buffered.splice(0)) applyRemoteSafe(bytes);\n };\n\n const rebootstrap = (): void => {\n if (rebootstrapAttempts >= 1) {\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 unsubOutbound?.();\n unsubOutbound = undefined;\n session?.close();\n session = undefined;\n active = false;\n buffered.length = 0;\n channel.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 opts.presence?.wire.apply(payload); // independent of the doc handshake\n return;\n }\n\n if (active) {\n if (kind === K_HELLO) {\n if (session !== undefined) {\n channel.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 const unsubChannel = channel.subscribe(onFrame);\n const unsubPresence = opts.presence?.onOutbound((b) => channel.send(frame(K_PRESENCE, b)));\n\n const leave = (): void => {\n clock.clearTimeout(timeoutHandle);\n unsubChannel();\n unsubPresence?.();\n unsubOutbound?.();\n session?.close();\n };\n\n // Broadcast hello, buffer inbound, wait for a base (or the silence timeout).\n channel.send(frame(K_HELLO, utf8.encode(joinerId)));\n armTimeout();\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\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 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 };\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 { zoomAtPoint } from \"@ice/kernel\";\nimport {\n ActiveTool,\n Camera,\n CameraLimits,\n GestureSettings,\n PointerSettings,\n Position,\n Selectable,\n Size,\n SnapConfig,\n StackZ,\n Viewport,\n} from \"../catalog\";\nimport { Active } from \"../catalog/camera-derived\";\nimport { createEngine, type Engine } from \"../engine/engine\";\nimport type { CommitIntent, CommitSink } from \"../engine/commit-sink\";\nimport { guardedTransaction } from \"../guards/guarded-tx\";\nimport { writeRuntimeResource } from \"../guards/resource-writer\";\nimport { installInteractionStack, type InteractionStack } from \"../interaction/install\";\nimport { createNestedCanvas, type NestedCanvas } from \"../nav/nested-canvas\";\nimport { cancelActiveGestures } from \"../ops/gestures\";\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 { 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 { CAMERA_DEFAULTS, GESTURE_DEFAULTS, POINTER_DEFAULTS, RUNTIME_BUDGETS, SNAP_DEFAULTS } 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 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 };\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 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 /** StackZ sweep, one tx: selection (or ids) to top/bottom. */\n reorder(ids: readonly Entity[], mode: \"top\" | \"bottom\"): void;\n zoomToFit(ids?: readonly Entity[]): void;\n zoomTo(zoom: number, anchor?: { x: number; y: number }): void;\n panTo(x: number, y: number): void;\n enterContainer(container: Entity): void;\n exitContainer(): void;\n cancelActiveGestures(): void;\n}\n\nexport interface CanvasDocs {\n create(opts?: DocSessionOpts): DocSession;\n open(bytes: Uint8Array, opts?: DocSessionOpts): OpenDocResult;\n /** §6.5 bootstrap + optional presence sugar over the same channel. */\n join(\n channel: ByteChannel,\n opts?: Omit<JoinDocOpts, \"presence\"> & { readonly presence?: { name: string; color: string } },\n ): Promise<JoinResult>;\n current(): DocSession | undefined;\n close(): void;\n undo(): boolean;\n redo(): boolean;\n autosave(storage: AutosaveStorageWrite, opts?: Omit<AutosaveOpts, \"storage\" | \"world\">): Autosave;\n}\n\nexport interface CanvasEngine {\n readonly world: World;\n readonly engine: Engine;\n readonly stack: InteractionStack;\n readonly runtime: WidgetRuntime & { uninstall(): void };\n readonly nav: NestedCanvas;\n readonly ops: CanvasOps;\n readonly docs: CanvasDocs;\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]);\nconst stackZQ = defineQuery([StackZ, PrefabId]);\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\n // --- doc lifecycle ---------------------------------------------------------\n let session: DocSession | undefined;\n let presence: PresenceSession | undefined;\n let uninstallPresence: (() => void) | undefined;\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 const adoptSession = (next: DocSession): DocSession => {\n session = next;\n sink.target = next.sink;\n return next;\n };\n\n const closeDoc = (): void => {\n uninstallPresence?.();\n uninstallPresence = undefined;\n presence?.detach();\n presence = undefined;\n session?.close();\n session = undefined;\n sink.target = undefined;\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 { 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 });\n adoptSession(result.session);\n return result;\n },\n current: () => session,\n close: closeDoc,\n undo: () => session?.store.undo() ?? false,\n redo: () => session?.store.redo() ?? false,\n autosave(storage, o) {\n const s = requireSession(\"autosave\");\n return startAutosave(s, { storage, world, ...o });\n },\n };\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 = requireSession(\"spawnWidget\");\n return spawnWidget(s.store, world, type, o);\n },\n deleteSelection() {\n const s = requireSession(\"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 = requireSession(\"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 z = world.get(src, StackZ);\n const overrides: [unknown, unknown][] = [\n [Position, { x: pos.x + 16, y: pos.y + 16 }],\n ...(size !== undefined ? [[Size, { ...size }] as [unknown, unknown]] : []),\n ...(z !== undefined ? [[StackZ, { z: z.z + 1 }] 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 clones.push(tx.spawnPrefab(widget.prefab, overrides as never));\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 = requireSession(\"reorder\");\n // Fractional StackZ sweep above/below the current extremes, one tx.\n let extreme = mode === \"top\" ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY;\n world.query(stackZQ).each((b) => {\n const col = b.col(StackZ).z;\n for (const r of b) {\n const z = col[r] as number;\n extreme = mode === \"top\" ? Math.max(extreme, z) : Math.min(extreme, z);\n }\n });\n if (!Number.isFinite(extreme)) extreme = 0;\n guardedTransaction(s.store, world, (tx) => {\n let step = 1;\n for (const e of ids) {\n if (s.store.keyOf(e) === undefined) continue;\n const z = mode === \"top\" ? extreme + step : extreme - step;\n tx.edit(e).set(StackZ, { z });\n step += 1;\n }\n });\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 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) => nav.enterContainer(c),\n exitContainer: () => nav.exitContainer(),\n cancelActiveGestures: () => cancelActiveGestures(world),\n };\n\n return {\n world,\n engine,\n stack,\n runtime,\n nav,\n ops,\n docs,\n budgets,\n step: (now) => engine.step(now),\n dispose() {\n closeDoc();\n runtime.uninstall();\n stack.uninstall();\n },\n };\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 */\nexport const CORE_VERSION = \"0.0.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 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\";\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\n// Catalog-adjacent ops (app-handler write paths).\nexport * from \"./ops/selection\";\nexport * from \"./ops/cascade\";\nexport * from \"./ops/claims\";\nexport * from \"./ops/gestures\";\nexport * from \"./ops/point-pick\";\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 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 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 widgets,\n type SizeMode,\n type WidgetDef,\n type WidgetGroup,\n type WidgetInteraction,\n type WidgetPortDecl,\n type WidgetSurface,\n type WidgetType,\n} from \"./widget/define-widget\";\nexport { createWidgetEquipSystem } from \"./widget/equip\";\nexport { spawnWidget, widgetSpawnInits, type SpawnWidgetOpts } from \"./widget/spawn\";\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\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 createNestedCanvas,\n currentNavEntry,\n currentNavFrame,\n type NestedCanvas,\n type NestedCanvasOpts,\n} from \"./nav/nested-canvas\";\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 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 CanvasOps,\n} from \"./facade/create-canvas-engine\";\nexport { createDrawBehavior } from \"./systems/l3-draw\";\n"],"mappings":";;;;;;;;;;;;;AAQO,SAAS,iBAAoB,KAAa,OAAmB;AAClE,QAAM,IAAI;AACV,IAAE,iBAAiB,oBAAI,IAAqB;AAC5C,QAAM,MAAM,EAAE;AACd,MAAI,CAAC,IAAI,IAAI,GAAG,EAAG,KAAI,IAAI,KAAK,MAAM,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,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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A;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,MAAM,CAAC,QAAQ,OAAO,KAAK,GAAG;AAAA,IAC9B,UAAU;AACR,eAAS;AACT,cAAQ,UAAU;AAClB,YAAM,UAAU;AAAA,IAClB;AAAA,EACF;AACF;;;ACvZA;AAAA,EACE;AAAA,EACA,OAAAC;AAAA,EACA,OAAAC;AAAA,EACA;AAAA,EACA,eAAAC;AAAA,EACA,eAAAC;AAAA,EACA,gBAAAC;AAAA,EACA,oBAAAC;AAAA,EACA,UAAAC;AAAA,EACA,SAAAC;AAAA,EAGA,SAAAC;AAAA,OACK;AA2IP,SAAS,yBAAyB;AAhK3B,IAAM,eAAe;","names":["init","field","field","field","field","enumOf","field","enumOf","field","phase","field","field","enumOf","field","field","enumOf","enumOf","field","field","enumOf","field","field","field","defineQuery","field","defineQuery","field","enumOf","registry","field","enumOf","defineQuery","defineTickSystem","defineQuery","defineTickSystem","registry","registry","defineQuery","defineSystem","defineQuery","pinchQ","P","defineSystem","rec","p","down","defineQuery","defineSystem","defineTickSystem","P","defineQuery","defineSystem","defineTickSystem","defineQuery","defineTickSystem","defineQuery","connectDragQ","compatible","defineTickSystem","p","dist","defineQuery","defineSystem","defineTickSystem","p","defineQuery","defineTickSystem","defineSystem","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","pointerQ","Not","defineTickSystem","defineSystem","p","Any","Not","defineQuery","defineSystem","P","defineQuery","Any","Not","isTerminal","defineSystem","defineQuery","defineSystem","P","defineQuery","defineSystem","defineQuery","defineSystem","P","defineQuery","defineSystem","defineQuery","defineSystem","defineQuery","defineSystem","p","defineQuery","defineTickSystem","P","IDENTITY_CAM","canvasSurfaceQ","defineQuery","longPressQ","defineTickSystem","defineQuery","defineSystem","P","defineQuery","defineSystem","defineQuery","defineSystem","defineQuery","defineSystem","enabled","canvasSurfaceQ","defineQuery","p","defineQuery","PACK_PREFIX","defineQuery","p","Not","defineQuery","defineSystem","defineQuery","Not","defineSystem","defineQuery","defineTickSystem","defineQuery","frame","defineTickSystem","p","defineTickSystem","defineTickSystem","Not","defineQuery","defineSystem","defineTickSystem","defineQuery","defineSystem","p","Not","defineTickSystem","Any","defineQuery","defineQuery","Any","P","defineQuery","defineQuery","p","Not","defineQuery","defineTickSystem","defineQuery","Not","defineTickSystem","defineQuery","defineQuery","stackZQ","p","Any","Not","createWorld","defineQuery","defineSystem","defineTickSystem","enumOf","field","Local"]}
|