@vibecook/ice 0.16.0 → 0.17.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.
Files changed (52) hide show
  1. package/README.md +10 -5
  2. package/dist/{chunk-ZTY2VRIS.js → chunk-6W2FPXR7.js} +13 -7
  3. package/dist/chunk-6W2FPXR7.js.map +1 -0
  4. package/dist/{chunk-Y7K6CHSF.js → chunk-LAZIY3J7.js} +286 -189
  5. package/dist/chunk-LAZIY3J7.js.map +1 -0
  6. package/dist/{chunk-REJTEK3V.js → chunk-M2HUDENL.js} +288 -318
  7. package/dist/chunk-M2HUDENL.js.map +1 -0
  8. package/dist/{chunk-BH5AFWJX.js → chunk-VZEZ7CYW.js} +9 -13
  9. package/dist/chunk-VZEZ7CYW.js.map +1 -0
  10. package/dist/desk-kit.js +2 -2
  11. package/dist/desk-objects.js +45 -14
  12. package/dist/desk-objects.js.map +1 -1
  13. package/dist/desk.js +3 -3
  14. package/dist/devtools.js +1 -1
  15. package/dist/dom.js +2 -2
  16. package/dist/index.js +7 -1
  17. package/dist/react.js +2 -2
  18. package/dist/types/packages/core/src/canvas/engine-catalog.d.ts +6 -0
  19. package/dist/types/packages/core/src/catalog/desk.d.ts +6 -6
  20. package/dist/types/packages/core/src/catalog/gesture.d.ts +2 -0
  21. package/dist/types/packages/core/src/catalog/selection-presence.d.ts +2 -0
  22. package/dist/types/packages/core/src/catalog/settings-resources.d.ts +8 -4
  23. package/dist/types/packages/core/src/facade/create-canvas-engine.d.ts +11 -5
  24. package/dist/types/packages/core/src/index.d.ts +1 -1
  25. package/dist/types/packages/core/src/ops/selection-drag.d.ts +8 -0
  26. package/dist/types/packages/core/src/settings/defaults.d.ts +2 -0
  27. package/dist/types/packages/core/src/systems/camera-sim.d.ts +13 -0
  28. package/dist/types/packages/core/src/systems/tray.d.ts +5 -4
  29. package/dist/types/packages/core/src/tools/define-tool.d.ts +2 -2
  30. package/dist/types/packages/core/src/widget/define-widget.d.ts +2 -1
  31. package/dist/types/packages/desk/src/ground.d.ts +4 -3
  32. package/dist/types/packages/desk/src/host/layer.d.ts +1 -3
  33. package/dist/types/packages/desk/src/mat/layout.d.ts +45 -5
  34. package/dist/types/packages/desk/src/mat/mat-pass.d.ts +7 -0
  35. package/dist/types/packages/desk/src/mat/ruler-regions.d.ts +17 -0
  36. package/dist/types/packages/desk/src/shaders.gen.d.ts +4 -4
  37. package/dist/types/packages/desk/src/theme.d.ts +0 -15
  38. package/dist/types/packages/desk/src/tray/drawer.d.ts +10 -8
  39. package/dist/types/packages/desk/src/tray/flux.d.ts +2 -3
  40. package/dist/types/packages/desk/src/tray/layout.d.ts +1 -6
  41. package/dist/types/packages/desk/src/tray/look.d.ts +0 -9
  42. package/dist/types/packages/desk/src/tray/pass.d.ts +7 -18
  43. package/dist/types/packages/desk/src/tray/specimens.d.ts +2 -19
  44. package/dist/types/packages/dom/src/pointer-adapter.d.ts +1 -1
  45. package/dist/types/packages/objects/src/minimat/layout.d.ts +1 -1
  46. package/dist/types/packages/objects/src/photo/photo.d.ts +2 -2
  47. package/dist/types/packages/objects/src/preset.d.ts +5 -3
  48. package/package.json +15 -16
  49. package/dist/chunk-BH5AFWJX.js.map +0 -1
  50. package/dist/chunk-REJTEK3V.js.map +0 -1
  51. package/dist/chunk-Y7K6CHSF.js.map +0 -1
  52. package/dist/chunk-ZTY2VRIS.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../core/src/boot/hmr.ts","../../core/src/schema/meta.ts","../../core/src/schema/prefab.ts","../../core/src/engine/instantiate.ts","../../core/src/settings/defaults.ts","../../core/src/engine/frame-info.ts","../../core/src/engine/pipeline.ts","../../core/src/engine/reflectors.ts","../../core/src/catalog/camera-derived.ts","../../core/src/guards/dev.ts","../../core/src/engine/frame-control.ts","../../core/src/engine/guests.ts","../../core/src/engine/world-doors.ts","../../core/src/engine/engine.ts","../../core/src/catalog/desk.ts","../../core/src/helpers/phase-set.ts","../../core/src/catalog/gesture.ts","../../core/src/catalog/graph.ts","../../core/src/catalog/scene.ts","../../core/src/catalog/pointer.ts","../../core/src/catalog/insert.ts","../../core/src/catalog/selection-presence.ts","../../core/src/catalog/settings-resources.ts","../../core/src/catalog/surface.ts","../../core/src/systems/camera-sim.ts","../../core/src/guards/resource-writer.ts","../../core/src/systems/nav-flight.ts","../../core/src/interaction/wakes.ts","../../core/src/widget/props.ts","../../core/src/behavior/types.ts","../../core/src/behavior/public-reads.ts","../../core/src/behavior/define-behavior.ts","../../core/src/tools/define-tool.ts","../../core/src/widget/held-tools.ts","../../core/src/widget/menu-actions.ts","../../core/src/widget/define-widget.ts","../../core/src/canvas/define-canvas-type.ts","../../core/src/canvas/extensions.ts","../../core/src/canvas/frame-projection.ts","../../core/src/canvas/engine-catalog.ts","../../core/src/guards/guarded-tx.ts","../../core/src/behavior/compile.ts","../../core/src/behavior/migrate.ts","../../core/src/behavior/runtime.ts","../../core/src/behavior/differ.ts","../../core/src/behavior/world-view.ts","../../core/src/engine/commit-sink.ts","../../core/src/input/queue.ts","../../core/src/helpers/version-stamps.ts","../../core/src/canvas/frame-view.ts","../../core/src/nav/nav-geometry.ts","../../core/src/nav/nested-canvas.ts","../../core/src/ops/sibling-order.ts","../../core/src/ops/point-pick.ts","../../core/src/ops/port-geometry.ts","../../core/src/systems/l1-wires.ts","../../core/src/canvas/session.ts","../../core/src/systems/l2-recognize.ts","../../core/src/ops/selection-drag.ts","../../core/src/systems/press-button.ts","../../core/src/ops/selection.ts","../../core/src/systems/l3-connect.ts","../../core/src/systems/l3-ports.ts","../../core/src/helpers/churn-guard.ts","../../core/src/systems/chrome.ts","../../core/src/systems/l3-draw.ts","../../core/src/widget/spawn.ts","../../core/src/doc/doc-commit-sink.ts","../../core/src/systems/l4-cursor.ts","../../core/src/systems/held.ts","../../core/src/systems/press-wheel.ts","../../core/src/ops/gestures.ts","../../core/src/systems/tray.ts","../../core/src/ops/tray.ts","../../core/src/systems/nav-tap.ts","../../core/src/systems/zoom-through.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-drop.ts","../../core/src/systems/drag-mods.ts","../../core/src/systems/l3-claim.ts","../../core/src/systems/l3-marquee.ts","../../core/src/systems/l3-resize.ts","../../core/src/systems/l3-snap.ts","../../core/src/systems/insert-ghost.ts","../../core/src/doc/envelope.ts","../../core/src/doc/migrate.ts","../../core/src/guards/live-writer.ts","../../core/src/ops/claims.ts","../../core/src/doc/version-gate.ts","../../core/src/doc/doc-kit.ts","../../core/src/canvas/migrate.ts","../../core/src/doc/rename.ts","../../core/src/doc/rename-sweep.ts","../../core/src/doc/schema-migrate.ts","../../core/src/behavior/harness.ts","../../core/src/ops/arrange.ts","../../core/src/ops/cascade.ts","../../core/src/interaction/gesture-status.ts","../../core/src/canvas/define-container.ts","../../core/src/canvas/placement.ts","../../core/src/canvas/diagnostics.ts","../../core/src/canvas/frame-preview.ts","../../core/src/canvas/presentation-transition.ts","../../core/src/widget/equip.ts","../../core/src/widget/set-props.ts","../../core/src/widget/mount-store.ts","../../core/src/doc/autosave.ts","../../core/src/doc/broadcast-relay.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/canvas/runtime-extension-host.ts","../../core/src/canvas/frame-behavior-host.ts","../../core/src/ops/insert.ts","../../core/src/surface/gpu-device.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 /** A DEPENDENT edge (design-015 D3t-c): its source dies with its target — the cascade walks it as it walks a wire's ends. */\n dependent?: boolean;\n}\n\nexport interface ResourceMeta {\n name: string;\n /** design-001 §2 rule 7: resources declare durable|runtime at definition. */\n durable: boolean;\n}\n\nconst componentMeta = new Map<Component, ComponentMeta>();\nconst componentsByIceName = new Map<string, Component>();\nconst tagNames = new Map<Tag, string>();\nconst relationMeta = new Map<Relation, RelationMeta>();\nconst resourceMeta = new Map<Resource, ResourceMeta>();\n\nfunction isEidField(input: FieldInput): boolean {\n if (input === \"eid\") return true;\n return (\n typeof input === \"object\" &&\n input !== null &&\n (input as { type?: unknown }).type === \"eid\"\n );\n}\n\nfunction hasDefault(input: FieldInput): boolean {\n // Bare string types (\"f32\", \"string\", …) and bare EnumTypes carry no default;\n // field(type, { default }) specs carry a `default` key.\n return typeof input === \"object\" && input !== null && \"default\" in input;\n}\n\nexport function defineComponent<const Sch extends RawSchema>(\n name: string,\n schema: Sch,\n): ReturnType<typeof strataDefineComponent<Sch>> {\n const c = strataDefineComponent(name, schema);\n const fields = Object.entries(schema);\n componentMeta.set(c as Component, {\n name,\n schema,\n eidFields: fields.filter(([, f]) => isEidField(f)).map(([k]) => k),\n requiredFields: fields.filter(([, f]) => !hasDefault(f)).map(([k]) => k),\n });\n componentsByIceName.set(name, c as Component);\n return c;\n}\n\n/**\n * Reuse-or-define by NAME (design-008 §3.1): strata's schema registry throws\n * on duplicate identifiers (its registry.ts:38), and rename legacy components\n * (`<oldType>:<group>`) can legitimately re-enter the process — a test that\n * defined the old widget before resetting ice registries, or a hot-reload\n * double-eval — while strata's global registry survives. An existing\n * SAME-SHAPED component is the same component: reuse its handle. A mismatched\n * shape under the same name is a real collision: throw. The shape compare is\n * JSON-stringify over the recorded raw schema — sound here because both sides\n * are built by the same `strataFieldOf` constructors in the same field order.\n */\nexport function ensureComponent<const Sch extends RawSchema>(\n name: string,\n schema: Sch,\n): Component {\n const existing = componentsByIceName.get(name);\n if (existing === undefined) return defineComponent(name, schema) as Component;\n const recorded = componentMeta.get(existing);\n if (recorded === undefined || JSON.stringify(recorded.schema) !== JSON.stringify(schema)) {\n throw new Error(`ice: ensureComponent(\"${name}\") — a component with this name exists with a DIFFERENT shape.`);\n }\n return existing;\n}\n\nexport function defineTag(name: string): Tag {\n const t = strataDefineTag(name);\n tagNames.set(t, name);\n return t;\n}\n\n/** The relations declared `dependent` (their sources die with their targets), in definition order. */\nconst dependentRelations: Relation[] = [];\n\n/**\n * A relation. `dependent` (design-015 D3t-c — a reified edge, the wire's precedent generalised: the desk calendar's pin → its note):\n * the entity the edge goes OUT of dies with the entity it points AT — `cascadeDestroy` takes it in the same transaction, so one undo\n * brings both back.\n */\nexport function defineRelation(\n name: string,\n opts?: { arity?: \"one\" | \"many\"; ordered?: boolean; dependent?: boolean },\n): Relation {\n const { dependent, ...strataOpts } = opts ?? {};\n const r = strataDefineRelation(name, opts === undefined ? undefined : strataOpts);\n relationMeta.set(r, { name, arity: opts?.arity ?? \"one\", ...(dependent === true ? { dependent: true } : {}) });\n if (dependent === true) dependentRelations.push(r);\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 /** The relations whose sources die with their targets (`defineRelation({ dependent: true })`). */\n dependents(): readonly Relation[] {\n return dependentRelations;\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 * A DATA prefab's own migration chain (design-015 §5.1, D3t-a — an object's data children, the board's\n * strokes): `{ fromVersion: (prev) => next }` over the flat record of its essential components' fields,\n * every version `1..version-1` covered — defineWidget's `migrate` shape. The M9 runner applies it to a\n * document whose `engine.pack.<id>` marker is older, when an engine catalog tracks the prefab (an\n * object's `data`). A widget's own prefab migrates by its widget's chain instead.\n */\n migrate?: Readonly<Record<number, (prev: Record<string, unknown>) => Record<string, unknown>>>;\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 if (def.migrate !== undefined) {\n // the chain covers every step 1..version-1 and nothing else (defineWidget's rule for its `migrate`)\n const version = def.version ?? 1;\n if (def.store !== \"durable\") throw new Error(`ice: prefab \"${id}\": only a durable prefab migrates (its cells live in the document).`);\n for (let v = 1; v < version; v++) {\n if (typeof def.migrate[v] !== \"function\") throw new Error(`ice: prefab \"${id}\": migrate chain has a gap at fromVersion ${v} (version ${version}).`);\n }\n for (const k of Object.keys(def.migrate)) {\n const v = Number(k);\n if (!(Number.isInteger(v) && v >= 1 && v < version)) throw new Error(`ice: prefab \"${id}\": migrate declares fromVersion ${k}, outside 1..${version - 1}.`);\n }\n }\n\n const eligible = new Set<Component>();\n for (const [c] of def.components) eligible.add(c);\n for (const c of def.optional ?? []) eligible.add(c);\n eligible.add(PrefabId as Component);\n\n if (def.store === \"durable\") {\n for (const c of eligible) {\n const meta = schemaMeta.component(c);\n if (meta && meta.eidFields.length > 0) {\n throw new Error(\n `ice: prefab \"${id}\": component \"${meta.name}\" carries eid field(s) [${meta.eidFields.join(\", \")}] — eid is banned in durable cells; use keys or relations (design-001 §2 rule 3).`,\n );\n }\n }\n }\n\n for (const [c, value] of def.components) {\n const meta = schemaMeta.component(c);\n if (!meta) continue; // defined outside @ice/core wrappers — validation is best-effort\n for (const f of meta.requiredFields) {\n if (!(f in value)) {\n throw new Error(\n `ice: prefab \"${id}\": essential component \"${meta.name}\" is missing required field \"${f}\" (no default declared — strata would throw at spawn; supply it in the prefab).`,\n );\n }\n }\n }\n\n const prefab: Prefab = {\n ...def,\n id,\n eligible,\n eligibleRelations: new Set(def.relations ?? []),\n };\n registry.set(id, prefab);\n return prefab;\n}\n\nexport const prefabs = {\n get(id: string): Prefab | undefined {\n return registry.get(id);\n },\n /** Every registered prefab (the version gate stamps/compares the full set). */\n all(): Prefab[] {\n return [...registry.values()];\n },\n};\n\n/**\n * TEST-ONLY registry wipe. Deliberately a standalone export that the public\n * barrel does NOT re-export (review finding A8) — tests import it from this\n * module path directly.\n */\nexport function __resetPrefabsForTests(): void {\n registry.clear();\n}\n","/**\n * Prefab instantiation — THE spawn routing (design-001 §2: the class is the\n * spawn path). Durable → tx · runtime → world/ctx · ephemeral → eph.\n * Every spawn stamps `PrefabId` (uniform identity for guards + devtools;\n * for durable prefabs it is the document identity stamp, §2 rule 5).\n */\nimport type { Component, Entity, SystemCtx, Tag, World } from \"@vibecook/strata-ecs\";\nimport type { Mutator } from \"@vibecook/strata-ecs/durable\";\nimport { PrefabId, type ComponentInit, type Prefab } from \"../schema/prefab\";\n\n/** Structural shape of the ephemeral store's write surface (components+tags only). */\nexport interface EphSpawner {\n spawn(init?: { components?: readonly ComponentInit[] }): Entity;\n addTag(e: Entity, t: Tag): void;\n}\n\nexport type SpawnTarget =\n | { into: \"world\"; world: World }\n | { into: \"ctx\"; ctx: SystemCtx }\n | { into: \"tx\"; tx: Mutator }\n | { into: \"eph\"; eph: EphSpawner };\n\nfunction mergedComponents(prefab: Prefab, overrides?: readonly ComponentInit[]): ComponentInit[] {\n const out = new Map<Component, ComponentInit[1]>();\n for (const [c, v] of prefab.components) out.set(c, v);\n for (const [c, v] of overrides ?? []) {\n if (!prefab.eligible.has(c)) {\n throw new Error(\n `ice: instantiate(\"${prefab.id}\"): override component is not in the prefab's eligible set.`,\n );\n }\n out.set(c, v);\n }\n out.set(PrefabId as Component, { id: prefab.id });\n return [...out.entries()].map(([c, v]) => [c, v] as const);\n}\n\nconst ROUTE: Record<Prefab[\"store\"], SpawnTarget[\"into\"][]> = {\n durable: [\"tx\"],\n runtime: [\"world\", \"ctx\"],\n ephemeral: [\"eph\"],\n};\n\nexport interface InstantiateOpts {\n /**\n * DRAFT spawn (design-001 §3, two-phase promote): a durable prefab spawned\n * into the runtime store — its cells are plain session data (not in the doc,\n * live writes free) until `promote` commits a durable twin. Explicit opt-in:\n * without it, durable→world/ctx throws (never a silent downgrade, §6.3).\n */\n draft?: boolean;\n overrides?: readonly ComponentInit[];\n}\n\n/**\n * Spawn a prefab into the correct store. Wrong-store spawns fail loudly —\n * notably: a durable prefab without an attached doc/tx has NO fallback\n * (design-001 §6.3: never a silent world.spawn downgrade).\n */\nexport function instantiate(\n prefab: Prefab,\n target: SpawnTarget,\n opts?: InstantiateOpts | readonly ComponentInit[],\n): Entity {\n const norm: InstantiateOpts = Array.isArray(opts) ? { overrides: opts } : ((opts as InstantiateOpts | undefined) ?? {});\n const overrides = norm.overrides;\n const draftOk =\n norm.draft === true &&\n prefab.store === \"durable\" &&\n (target.into === \"world\" || target.into === \"ctx\");\n if (!ROUTE[prefab.store].includes(target.into) && !draftOk) {\n const extra = prefab.store === \"durable\" ? \", or world/ctx with { draft: true }\" : \"\";\n throw new Error(\n `ice: instantiate(\"${prefab.id}\"): a ${prefab.store} prefab cannot spawn into \"${target.into}\" (allowed: ${ROUTE[prefab.store].join(\", \")}${extra}). The spawn path IS the sovereignty class (design-001 §2).`,\n );\n }\n const components = mergedComponents(prefab, overrides);\n const tags = prefab.tags ?? [];\n\n switch (target.into) {\n case \"world\": {\n const e = target.world.spawn({ components });\n for (const t of tags) target.world.addTag(e, t);\n return e;\n }\n case \"ctx\": {\n const e = target.ctx.spawn({ components });\n for (const t of tags) target.ctx.addTag(e, t);\n return e;\n }\n case \"tx\": {\n const e = target.tx.spawn({ components });\n for (const t of tags) target.tx.addTag(e, t);\n return e;\n }\n case \"eph\": {\n const e = target.eph.spawn({ components });\n for (const t of tags) target.eph.addTag(e, t);\n return e;\n }\n }\n}\n","/**\n * Runtime default constants transcribed from the reviewed design docs.\n * Not exported from the package barrel yet (design-005 §4 engine facade wires these in later).\n */\n\n/** Recognizer timing/slop defaults (design-003 §4.2 kind table; inertia constants from §5 item 9; multi-tap from v2 gesture.ts). */\nexport const GESTURE_DEFAULTS = {\n tapMaxMs: 250,\n tapSlopPx: 8,\n longPressMs: 500,\n longPressSlopPx: 10,\n dragSlopPx: 10,\n pinchSlopPx: 6,\n wheelEndSilenceMs: 150,\n inertiaMinVelocityPxPerS: 120,\n inertiaDecayMs: 325,\n multiTapWindowMs: 280,\n multiTapSlopPx: 20,\n // Wheel/pinch zoom speed — the v2 prototype curve (gesture.ts:444-449),\n // adopted 2026-07-13: factor = 2^(−clamp(Δ, ±maxStep) · sensitivity).\n // The CLAMP is the load-bearing half: a trackpad pinch sends tiny frequent\n // deltas (~0.5–3) while a mouse notch sends ~100 — capping the per-frame\n // step at ±10 makes one notch ≈ one strong pinch frame (×2^0.1 ≈ 1.07),\n // so both devices share one feel.\n wheelZoomSensitivity: 0.01,\n wheelZoomMaxStep: 10,\n // Ordinary wheel / two-finger scrolling pans. Apps can opt into\n // exponential plain-wheel zoom without changing the pinch response.\n wheel: \"pan\",\n // Pinch / modifier-wheel response is independent of a plain wheel's job.\n // The desk opts into continuous exponential zoom; the bounded legacy curve\n // remains available to consumers that use notch-sized zoom steps.\n wheelZoomCurve: \"clamped\",\n // Continuous zoom rate per normalized wheel-delta unit. Used by plain-wheel\n // zoom and by the exponential pinch curve, independently of the wheel mode.\n wheelZoomRate: 0.0016,\n} as const;\n\n/** What a plain wheel does to the camera (`GestureSettings.wheel`, design-015 §9). */\nexport type WheelMode = \"pan\" | \"zoom\";\nexport type WheelZoomCurve = \"clamped\" | \"exponential\";\n\n/** Pick radii + retarget dead-band (design-003 §3 L1 targeting). */\nexport const POINTER_DEFAULTS = {\n radiusMousePx: 0,\n radiusTouchPx: 12,\n radiusPenPx: 4,\n hoverReleaseDeadBandPx: 4,\n} as const;\n\n/**\n * Wire/port picking geometry (design-003 §3 wires-below-widgets; design-004 §6).\n * `wirePickSlopPx` is added to the pointer radius (screen px, `/zoom` at use) so a\n * thin bezier stays grab-able; `portIndexHalfWorld` is the half-extent of the tiny\n * world AABB a materialized port occupies in the spatial index (design-004 §6 —\n * ports are pickable but carry no Position/Size, so spatialSync never sees them).\n */\nexport const GRAPH_PICK_DEFAULTS = {\n wirePickSlopPx: 8,\n portIndexHalfWorld: 6,\n} as const;\n\n/** SnapConfig resource defaults (design-005 §4 engine facade). */\nexport const SNAP_DEFAULTS = {\n enabled: true,\n thresholdPx: 5,\n} as const;\n\n/**\n * Selection-chrome knobs (2026-07-17). `liftScale` mirrors the app's visual\n * drag-lift scale so the resize handles can inflate a grabbed member's rect\n * and keep WRAPPING the card it sees; 1 = no lift visual, no inflation.\n */\nexport const CHROME_DEFAULTS = {\n liftScale: 1,\n} as const;\n\n/** Zoom clamp (design-003 §5 item 9 cameraControl) and frame dt clamp (design-002 §1). */\nexport const CAMERA_DEFAULTS = {\n minZoom: 0.1,\n maxZoom: 5,\n dtClampMs: 64,\n} as const;\n\n/**\n * The natural auto-framing band (2026-07-18, James: \"not super zoomed in\n * nor super zoomed out, should feel natural\"): every DEFAULT framing —\n * `ops.frameContent` at boot, the folder arrival camera, and the folder\n * minis' portal affine (widgetlab keeps its preview in lockstep) — fits\n * content via kernel `fitCamera` but never lands outside\n * [fitMinZoom, fitMaxZoom], intersected with the session's hard\n * CameraLimits. `ops.zoomToFit` stays UNCAPPED: an explicit \"show me\n * everything\" beats natural.\n */\nexport const FIT_DEFAULTS = {\n pad: 80,\n minZoom: 0.5,\n maxZoom: 1,\n} as const;\n\n/**\n * Nav-transition motion constants (design-006 §4/§5, tuned in the approved\n * 2026-07-15 mock). `responseMs` is the critically-damped spring response for\n * ENTER; exit runs at `exitResponseFactor ×` (returning is lighter). Response\n * scales `durationPerOctave` per zoom-octave beyond `baseOctaves` (Apple's\n * duration-with-distance). Beyond `freezeOctaves` a flight cannot be presented\n * geometrically (Chromium raster-scale swing — design-006 §5): the start depth\n * caps at `capFactor ×` arrival and the transition presents as a crossfade.\n */\nexport const NAV_TRANSITION_DEFAULTS = {\n responseMs: 420,\n exitResponseFactor: 0.8,\n durationPerOctave: 0.12,\n baseOctaves: 3.5,\n freezeOctaves: 4.2,\n capFactor: 10,\n settleP: 0.999,\n settleV: 0.02,\n} as const;\n\n/**\n * The zoom-through (design-015 §9, PORTAL.md §8 — D2b): a wheel zoom IN that leaves a\n * container's face covering the whole view by `in` CSS px cuts into it; a zoom OUT that\n * leaves the current frame's face `out` px short of covering cuts back out — both as cuts\n * nobody can see. `gate` is the face's short side (CSS px) across which a live inside comes\n * in over its far LOD (presence 0 → 1); a face enters only at presence 1. OFF by default: the\n * desk turns it on (`settings.nav.zoomThrough.enabled`); every other app keeps explicit entry.\n */\nexport const ZOOM_THROUGH_DEFAULTS = {\n enabled: false,\n in: 2,\n out: 6,\n gate: [140, 220] as readonly [number, number],\n} as const;\n\n/**\n * Port and cull budgets (design-004 §6 port materialization; ported into design-005 §4 engine\n * facade). `keepMountedWidgets` and `fboBytes` left at design-015 D5b with the mount LRU and the\n * GL allocation ledger they bounded.\n */\nexport const RUNTIME_BUDGETS = {\n portSpawnPerFrame: 64,\n portLightUpRadiusPx: 600,\n portReapGraceMs: 1000,\n cullOverscanWorldPerZoom: 200,\n} as const;\n","/**\n * FrameInfo — the pre-tick frame clock (design-002 §1).\n *\n * Written by `engine.step()` BEFORE `world.sync()` every frame (a plain resource\n * value write, legal outside the tick). Systems read it via `ctx.getResource` —\n * time-based systems are correct by construction (F1: tick-by-default), and dt\n * clamps at `CAMERA_DEFAULTS.dtClampMs` so a background-tab hiccup never turns\n * into a teleport (design-002 §1: \"dt clamps at 64 ms\").\n */\nimport { field } from \"@vibecook/strata-ecs\";\nimport type { World } from \"@vibecook/strata-ecs\";\nimport { defineResource } from \"../schema/meta\";\nimport { CAMERA_DEFAULTS } from \"../settings/defaults\";\n\n/**\n * { tick, dt ≤ dtClampMs (ms), now (ms timeline of the caller's clock),\n * clock (accumulated CLAMPED dt — the gesture clock) }.\n *\n * `clock` exists because `now` cannot be trusted for HUMAN timing windows:\n * rAF timestamps are the compositor's frame clock, and under throttling\n * (occluded window, headless BeginFrame control, software rendering) they lag\n * wall time by 100s of ms to SECONDS (measured 0.3–5.8s, 2026-07-17) — and\n * event.timeStamp does NOT lag, so any `now − eventTs` mixes two clocks and\n * tap/long-press windows evaluate garbage. `clock` is monotonic, advances by\n * the clamped dt each frame (a 640ms stall counts 64ms — the 2026-07-12\n * \"stall must not eat the window\" intent), and is never compared against\n * event timestamps.\n */\nexport const FrameInfo = defineResource(\"FrameInfo\", {\n tick: field(\"u32\", { default: 0 }),\n dt: field(\"f32\", { default: 0 }),\n now: field(\"f64\", { default: 0 }),\n clock: field(\"f64\", { default: 0 }),\n});\n\n/**\n * Advance the frame clock. First frame gets dt 0 (no previous `now` to diff\n * against); negative deltas (clock adjustment) clamp to 0.\n */\nexport function setFrameInfo(world: World, now: number): void {\n const prev = world.getResource(FrameInfo);\n const dt =\n prev === undefined ? 0 : Math.min(Math.max(now - prev.now, 0), CAMERA_DEFAULTS.dtClampMs);\n world.setResource(FrameInfo, { tick: (prev?.tick ?? 0) + 1, dt, now, clock: (prev?.clock ?? 0) + dt });\n}\n","/**\n * The phase-group pipeline (design-002 §2).\n *\n * Seven canonical GROUPS over eleven strata phases — a strata phase boundary\n * (command-buffer flush) is the only structural settle point, so every stage\n * that must SEE the previous stage's spawns/tags/relations within one frame is\n * a separate strata phase. The `ctl:*` sub-phases are the control sweep's\n * settle points (design-002 decision 2; rev 1's \"tail idiom\" is dead — the\n * whole system body is iteration-guarded).\n *\n * Registration order within a group is run order; group order is fixed here\n * and is the sole ordering contract (Law: phases/sub-phases only — never\n * registration-time coupling between groups).\n *\n * ── `present:infra` — ADDED 2026-09-06 (design-013 D1), REMOVED at design-015 D5b ─────\n * A twelfth phase held the surface infra trio (Band → Demand → Residency) after every kind\n * behaviour had spoken, so a pack's behaviour registered after boot still reached the clamp in\n * the frame it wrote. The trio left with the DOM/GPU presentation choice it clamped (design-015\n * §1: nothing presents anywhere but the desk), so the list is eleven phases again — design-002\n * §2's table as first written; its `present:infra` row is struck at the source. `BehaviorPhase`\n * (behavior/types.ts) never admitted the group and needs no change.\n */\nimport { phase } from \"@vibecook/strata-ecs\";\nimport type { Pipeline, System, TickSystem } from \"@vibecook/strata-ecs\";\n\n/** Either system form (strata 0.5.0): chunk-bodied or once-per-dispatch tick. */\nexport type AnySystem = System | TickSystem;\n\n/** The eleven strata phases, in run order (design-002 §2 table). */\nexport const PHASE_GROUPS = [\n \"input\",\n \"react\",\n \"ctl:spawn\",\n \"ctl:recognize\",\n \"ctl:arbitrate\",\n \"ctl:claim\",\n \"ctl:behave\",\n \"simulate\",\n \"derive\",\n \"present\",\n \"cleanup\",\n] as const;\n\nexport type PhaseGroup = (typeof PHASE_GROUPS)[number];\n\nexport interface PipelineRegistry {\n /** Append systems to a group (run order = registration order). Returns a remover (HMR). */\n add(group: PhaseGroup, ...systems: readonly AnySystem[]): () => void;\n /**\n * The pipeline value for this frame (design-002 §1: \"pipeline is a value,\n * rebuilt per frame\"). Cached until the registry changes; empty groups are\n * omitted (an empty phase would flush nothing anyway).\n */\n assemble(): Pipeline;\n}\n\nexport function createPipelineRegistry(): PipelineRegistry {\n const groups = new Map<PhaseGroup, AnySystem[]>();\n let cached: Pipeline | undefined;\n\n return {\n add(group, ...systems) {\n let list = groups.get(group);\n if (list === undefined) {\n list = [];\n groups.set(group, list);\n }\n list.push(...systems);\n cached = undefined;\n return () => {\n const current = groups.get(group);\n if (current === undefined) return;\n for (const s of systems) {\n const i = current.indexOf(s);\n if (i !== -1) current.splice(i, 1);\n }\n cached = undefined;\n };\n },\n\n assemble() {\n if (cached === undefined) {\n const phases = [];\n for (const name of PHASE_GROUPS) {\n const systems = groups.get(name);\n if (systems !== undefined && systems.length > 0) phases.push(phase(name, [...systems]));\n }\n cached = phases;\n }\n return cached;\n },\n };\n}\n","/**\n * The reflector registry (design-002 §5).\n *\n * Reflectors are the ONLY writers of DOM/GL/R3F, run AFTER `notify()`, and\n * never write ECS (L10). The registry arms strata observers ONCE per reflector\n * at registration; observer fires during `notify()` coalesce into a per-\n * reflector dirty flag; `flushAll()` (called by `engine.step()` post-notify)\n * flushes dirty (or `always`) reflectors in registration order.\n *\n * - **First paint**: every reflector registers dirty, so its first `flushAll`\n * paints unconditionally — `observeResource` has no `immediate` option and a\n * world populated before registration never stamps for it (same seed\n * `observeQuery`'s `immediate` would give, applied uniformly).\n * - **Fault isolation**: a throwing reflector is skipped this frame (its dirty\n * flag clears — a faulty reflector must not re-fire hot on a static scene);\n * system throws, by contrast, propagate loudly out of `world.tick()`.\n * - **Write ban**: strata's emit-flag rejects ECS writes inside observer\n * callbacks, but reflector `flush` runs after the emit window — DEV\n * enforcement of the reflect write-ban is deferred (design-002 §8);\n * the contract still binds.\n * - Arming any observer permanently arms reactivity stamping (+17–28% on\n * write-heavy paths — design-002 §4, budgeted).\n */\nimport type { Component, Query, Resource, World } from \"@vibecook/strata-ecs\";\n\nexport interface ReflectorQuerySpec {\n readonly q: Query;\n /** Narrow the Tier-1 wake set to these value columns (plus membership). */\n readonly cols?: readonly Component[];\n}\n\nexport interface ReflectorObserve {\n readonly queries?: readonly ReflectorQuerySpec[];\n // biome-ignore lint/suspicious/noExplicitAny: heterogeneous resource list; S is erased at observe time\n readonly resources?: readonly Resource<any>[];\n}\n\nexport interface ReflectorDef {\n /** Display name (telemetry, fault reports). */\n readonly name: string;\n readonly observe?: ReflectorObserve;\n /** Flush every frame regardless of dirt (cheap-overlay style, v1 lesson). */\n readonly always?: boolean;\n /** Batched output writes; NEVER write ECS, never read layout (L10). */\n readonly flush: (world: World) => void;\n}\n\nexport interface ReflectorRegistry {\n /** Arm observers and enroll; returns an unregister (unsubscribes, removes). */\n register(def: ReflectorDef): () => void;\n /** Post-notify: flush dirty/`always` reflectors in registration order. */\n flushAll(): void;\n /** Names flushed on the most recent `flushAll` (telemetry). */\n lastFlushed(): readonly string[];\n /** Every registered reflector, registration order (devtools enumeration —\n * independent of telemetry; a reflector idle since boot still lists). */\n names(): readonly string[];\n /** Arm flush timing (idempotent). Costs one `performance.now()` pair per\n * flushed reflector per frame, so it rides `engine.enableTelemetry()` and is\n * off by default — the same opt-in posture as per-system timing. */\n armTelemetry(): void;\n /** Total µs of the most recent `flushAll` (0 until armed). */\n lastFlushMicros(): number;\n /** Per-reflector µs of the most recent `flushAll` (empty until armed). */\n lastFlushDetail(): ReadonlyMap<string, number>;\n}\n\ninterface Entry {\n readonly def: ReflectorDef;\n dirty: boolean;\n /** Cleared by the unregister so a reflector removed DURING a flush is not\n * flushed from that frame's snapshot (see `flushAll`). */\n alive: boolean;\n readonly unsubs: (() => void)[];\n}\n\nexport function createReflectorRegistry(\n world: World,\n opts?: { onFault?: (name: string, err: unknown) => void },\n): ReflectorRegistry {\n const entries: Entry[] = [];\n // Snapshot + liveness, for the same reason as the publish-hook loop\n // (engine.ts): `flushAll` iterated the live array, so a reflector whose flush\n // unregistered itself — or an earlier one — skipped its neighbour that frame.\n let snapshot: Entry[] = [];\n let snapshotDirty = true;\n let flushed: string[] = [];\n let telemetryArmed = false;\n let flushMicros = 0;\n let flushDetail = new Map<string, number>();\n const onFault =\n opts?.onFault ??\n ((name: string, err: unknown) => {\n console.error(`[ice] reflector \"${name}\" threw — skipped this frame`, err);\n });\n\n return {\n register(def) {\n const entry: Entry = { def, dirty: true, alive: true, unsubs: [] };\n const wake = () => {\n entry.dirty = true;\n };\n for (const spec of def.observe?.queries ?? []) {\n entry.unsubs.push(\n world.reactive.observeQuery(spec.q, wake, spec.cols ? { cols: spec.cols } : undefined),\n );\n }\n for (const res of def.observe?.resources ?? []) {\n entry.unsubs.push(world.reactive.observeResource(res, wake));\n }\n entries.push(entry);\n snapshotDirty = true;\n return () => {\n if (!entry.alive) return;\n entry.alive = false;\n for (const u of entry.unsubs) u();\n entry.unsubs.length = 0;\n const i = entries.indexOf(entry);\n if (i !== -1) entries.splice(i, 1);\n snapshotDirty = true;\n };\n },\n\n flushAll() {\n flushed = [];\n if (snapshotDirty) {\n snapshot = entries.slice();\n snapshotDirty = false;\n }\n if (telemetryArmed) {\n flushDetail = new Map();\n flushMicros = 0;\n }\n for (const entry of snapshot) {\n if (!entry.alive) continue;\n if (!entry.dirty && entry.def.always !== true) continue;\n entry.dirty = false;\n const t0 = telemetryArmed ? performance.now() : 0;\n try {\n entry.def.flush(world);\n flushed.push(entry.def.name);\n } catch (err) {\n onFault(entry.def.name, err);\n }\n if (telemetryArmed) {\n // Charged whether or not it threw — a faulting reflector's cost is\n // real, and hiding it would make a slow-then-throwing one invisible.\n const us = (performance.now() - t0) * 1000;\n flushDetail.set(entry.def.name, (flushDetail.get(entry.def.name) ?? 0) + us);\n flushMicros += us;\n }\n }\n },\n\n lastFlushed() {\n return flushed;\n },\n\n names() {\n return entries.map((e) => e.def.name);\n },\n\n armTelemetry() {\n telemetryArmed = true;\n },\n\n lastFlushMicros() {\n return flushMicros;\n },\n\n lastFlushDetail() {\n return flushDetail;\n },\n };\n}\n","/**\n * Camera/viewport/tools (design-001 §5.7) + culling, chrome, cursors,\n * breakpoints, navigation (design-001 §5.8, reconciled additions).\n *\n * These are the §2 rule-7 residue (resources with no entity) plus the\n * derive-owned runtime prefabs. All resources here are runtime — Camera writes\n * go through the resource only (no shadow copy). Widgets are positioned in world\n * units inside their plane; the camera is applied as one transform per plane, so\n * there is deliberately no per-widget screen-bounds component — screen-space\n * values are derived only for chrome and cursors (small N).\n *\n * Defaults policy (see catalog/index.ts): resources carry full defaults (a single\n * live value that must initialize sanely — origin, zoom 1, select tool). Derived\n * fields carry zero/identity defaults; enum-identity fields that must be specific\n * per entity (HandleSpec.anchor, GuideLine.axis, CursorVisual.kind) stay bare.\n */\nimport { enumOf, field } from \"@vibecook/strata-ecs\";\nimport { defineComponent, defineRelation, defineResource, defineTag } from \"../schema/meta\";\nimport { SNAP_DEFAULTS } from \"../settings/defaults\";\n\n// --- runtime resources (design-001 §5.7) ---\n\n/** The single live camera (F2). `gesturing` gates the compositor DPR (design-004). */\nexport const Camera = defineResource(\"Camera\", {\n x: field(\"f64\", { default: 0 }),\n y: field(\"f64\", { default: 0 }),\n zoom: field(\"f32\", { default: 1 }),\n gesturing: field(\"bool\", { default: false }),\n});\n\n/** Viewport size + device pixel ratio. */\nexport const Viewport = defineResource(\"Viewport\", {\n w: field(\"f32\", { default: 0 }),\n h: field(\"f32\", { default: 0 }),\n dpr: field(\"f32\", { default: 1 }),\n});\n\n/** The active tool id (defaults to select). */\nexport const ActiveTool = defineResource(\"ActiveTool\", { id: field(\"string\", { default: \"select\" }) });\n\n/**\n * Stage presentation phase (2026-07-19, the widget-tray quiesce): app chrome\n * that covers or recedes the canvas takes a BACKGROUND HOLD via\n * `ce.stage.background(name)` — refcounted here (facade-owned tokens, this\n * resource is the world-truth mirror). While holds > 0 the stage stops\n * DISCRETIONARY per-frame work — animated GL islands freeze on their retained\n * textures (compositor gate, the design-006 §8.2 flight-freeze posture) —\n * but the world STAYS LIVE: systems tick, ops reflect, remote edits apply,\n * tweens land. Backgrounding is rendering policy; whether the canvas is\n * INTERACTABLE stays the overlay's own concern (its backdrop). Deliberately\n * NOT a full step-pause: a menu panel floats over a still-visible canvas,\n * and a frozen world would leave undo/collab visually stale (rev-2 decision,\n * recorded — a stricter frozen-world mode would be a separate concept).\n * That separate concept is now BUILT (2026-08-04): see {@link FrameMode}.\n * Holds keep their exact meaning — nothing here stretched.\n */\nexport const StageMode = defineResource(\"StageMode\", {\n backgroundHolds: field(\"u32\", { default: 0 }),\n});\n\n/**\n * Frame gate mirror (2026-08-04) — the stricter sibling {@link StageMode}'s\n * rev-2 decision named and left for later.\n *\n * A background hold is presentation policy over a LIVE world. A freeze\n * (`engine.frame.freeze(name)`) stops the host loop outright: no step, so no\n * systems, no publish, no notify, no reflectors, no rAF — for chrome that\n * COVERS the canvas, where every frame drawn behind it is work nobody can see.\n * This resource is the world-truth mirror of that refcount; the tokens live on\n * the control, out of ECS, exactly as stage holds do.\n *\n * Reading it tells you the engine is frozen. It cannot tell you a frame is\n * coming, because while the count is non-zero none is — and for the same\n * reason nothing can OBSERVE it while frozen (a parked world fires no\n * observers). It exists for inspection: devtools, tests, and consumers that\n * want the fact in hand on thaw.\n */\nexport const FrameMode = defineResource(\"FrameMode\", {\n freezeHolds: field(\"u32\", { default: 0 }),\n});\n\n/** Global snap toggle + threshold in screen px (scaled by zoom at use, design-003 §5.2). */\nexport const SnapConfig = defineResource(\"SnapConfig\", {\n enabled: field(\"bool\", { default: SNAP_DEFAULTS.enabled }),\n thresholdPx: field(\"f32\", { default: SNAP_DEFAULTS.thresholdPx }),\n});\n\n/** Per-container view-state memory — a runtime rider on container widgets (design-001 §5.7). */\nexport const ContainerCamera = defineComponent(\"ContainerCamera\", {\n x: field(\"f64\", { default: 0 }),\n y: field(\"f64\", { default: 0 }),\n zoom: field(\"f32\", { default: 1 }),\n});\n\n// --- derived tags (design-001 §5.8) ---\n\n/** Widget's ChildOf chain roots in the CURRENT nav frame (activeMembership system). */\nexport const Active = defineTag(\"Active\");\n\n/** In the viewport. Invariant: Active widgets are Visible ⊕ Culled. */\nexport const Visible = defineTag(\"Visible\");\n\n/** Outside the viewport. */\nexport const Culled = defineTag(\"Culled\");\n\n/** LOD tier + the effective size it was computed from (5 thresholds, width AND height). */\nexport const WidgetBreakpoint = defineComponent(\"WidgetBreakpoint\", {\n tier: field(enumOf([\"micro\", \"compact\", \"normal\", \"expanded\", \"detailed\"]), { default: \"normal\" }),\n w: field(\"u16\", { default: 0 }),\n h: field(\"u16\", { default: 0 }),\n});\n\n// --- chrome prefabs (pooled entities, reaped when the source empties) ---\n\n// (`SelectionBox` — the pooled selection outline's rect — left at design-015 D7: nothing read it after the P4 DOM chrome.)\n\n/** A resize handle's anchor (the one chrome kind behaviors capture). */\nexport const HandleSpec = defineComponent(\"HandleSpec\", {\n anchor: enumOf([\"nw\", \"n\", \"ne\", \"e\", \"se\", \"s\", \"sw\", \"w\"]),\n});\n\n/** A snap guide line along one axis. `from == to` ⇒ full-viewport line (v1's full-canvas alignment look — design-003 §6). */\nexport const GuideLine = defineComponent(\"GuideLine\", {\n axis: enumOf([\"x\", \"y\"]),\n at: field(\"f64\", { default: 0 }),\n from: field(\"f64\", { default: 0 }),\n to: field(\"f64\", { default: 0 }),\n});\n\n/**\n * One equal-spacing gap segment (snap chrome's second visual, design-003 §6):\n * a bar along `axis` spanning `from`→`to` at perpendicular position `perp`,\n * marking a gap of `gap` world units. The kernel indicator's two segments\n * flatten to two entities (v1 `u_spacings` parity).\n */\nexport const SpacingBar = defineComponent(\"SpacingBar\", {\n axis: enumOf([\"x\", \"y\"]),\n from: field(\"f64\", { default: 0 }),\n to: field(\"f64\", { default: 0 }),\n perp: field(\"f64\", { default: 0 }),\n gap: field(\"f32\", { default: 0 }),\n});\n\n/** Marquee selection rect. */\nexport const MarqueeBox = defineComponent(\"MarqueeBox\", {\n x: field(\"f64\", { default: 0 }),\n y: field(\"f64\", { default: 0 }),\n w: field(\"f32\", { default: 0 }),\n h: field(\"f32\", { default: 0 }),\n});\n\n/** Cursor appearance — local (OS cursor) vs remote (custom node). */\nexport const CursorVisual = defineComponent(\"CursorVisual\", {\n kind: enumOf([\"local\", \"remote\"]),\n pressed: field(\"bool\", { default: false }),\n});\n\n/** cursor → pointer or presence peer. */\nexport const Follows = defineRelation(\"Follows\", { arity: \"one\" });\n\n// (`VisualOf` — a chrome entity's edge to its source — left with the selection box at design-015 D7: nothing read it.)\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/**\n * Camera stored on a nav entry. `zoom` is f64 (D2b, design-015 §9): the return pose is a\n * flight's ARRIVAL when one is driving (`enterContainer`'s settled-pose rule), and the arrival\n * lives in f64 on the flight resource — an f32 cell here rounded it, and the exit then landed\n * one ulp off the camera the desk had been dressed for.\n */\nexport const NavCamera = defineComponent(\"NavCamera\", {\n x: field(\"f64\", { default: 0 }),\n y: field(\"f64\", { default: 0 }),\n zoom: field(\"f64\", { default: 1 }),\n});\n\n/** Tool active in the departed frame, restored when this nav entry is popped. */\nexport const NavTool = defineComponent(\"NavTool\", {\n id: field(\"string\", { default: \"select\" }),\n});\n\n/** nav entry → container widget. */\nexport const NavFrame = defineRelation(\"NavFrame\", { arity: \"one\" });\n\n/** The canvas background entity, so picking always resolves to *something* (design-001 §4). */\nexport const CanvasSurface = defineTag(\"CanvasSurface\");\n","/** DEV-guard toggle. Guards are on by default; production apps may disable. */\nlet enabled = true;\n\nexport function setDevGuards(on: boolean): void {\n enabled = on;\n}\n\nexport function devGuardsEnabled(): boolean {\n return enabled;\n}\n","/**\n * The frame gate (design-002 §1 amendment, 2026-08-04) — the frozen-world mode\n * design-005 §7 named and deliberately left unbuilt.\n *\n * Stage holds are PRESENTATION policy: `StageMode.backgroundHolds` freezes the\n * compositor on its retained textures while the world keeps stepping, which is\n * exactly what makes a hold safe under a PARTIAL overlay — a menu panel floats\n * over a still-live canvas, undo reflects, collab applies, tweens land. The\n * rev-2 decision recorded that a stricter mode \"would be a SEPARATE concept\".\n * This is that concept: while a freeze is held the host loop stops calling\n * `step` at all — no systems, no publish, no notify, no reflectors, no rAF\n * callback. It is for chrome that COVERS the canvas outright, where every\n * frame drawn behind it is work nobody can see.\n *\n * THE SETTLE — why a freeze does not park on the spot. Parking the instant a\n * freeze is taken would strand the canvas mid-churn: a cancelled gesture that\n * has not reached its commit tick, islands still owed a first paint, a\n * reflector holding a write that landed this frame. So a freeze walks the loop\n * to QUIET — every registered settle reporter idle — then takes ONE further\n * step so the quiet state itself reflects, and only then closes the gate. The\n * walk is bounded by {@link SETTLE_CAP}: a reporter that never goes quiet makes\n * a freeze park LATE, never never.\n *\n * Core stays scheduler-free (design-002 §1). This module owns no timer and\n * starts nothing — it answers {@link FrameControl.claimStep} and announces\n * transitions. The DOM package's rAF loop is what actually parks and restarts;\n * `engine.step(now)` itself stays callable by hand (headless hosts, traces),\n * because the gate governs the LOOP, not the primitive.\n *\n * THE SLEEP (2026-09-27, ICE M21 K7a — design-015 §2.4 idle-zero, §11.4's\n * ≤ 0.1 ms of main thread a second at rest). A freeze is taken; a sleep is\n * FALLEN INTO: a host loop that opts in (`startRafLoop(…, { sleep: true })`,\n * the desk host's default) asks {@link FrameControl.nextStep} after every step\n * and stops scheduling frames once the engine is QUIET — no wake pending, no\n * registered wake due, no settle reporter busy, for {@link SLEEP_TAIL} steps\n * in a row (the tail lets a one-tick protocol — a cleared one-tick tag, a\n * reaped recognizer, a commit at `JustEnded` — finish without a reporter of\n * its own). Nothing is polled at rest: what can change the frame from outside\n * a step says so — the world's outside doors (engine.ts: a write made outside\n * a step), the input queue, the document's and the room's arrivals (the\n * facade), a desk's own flux and its assets (`wake`) — and what is next live at\n * a TIME says when (`wakeWhen`: a flight, a caret's blink, a layer let go,\n * midnight). A step a sleeping loop takes for a registered time alone is\n * {@link FrameControl.settled}: a host that polls its parts (the desk's kinds)\n * asks only the parts that are due. A wake taken INSIDE a step asks for one\n * more frame and restarts no tail (a kind's wanted frame is not an outside event).\n */\nimport type { World } from \"@vibecook/strata-ecs\";\nimport { FrameMode } from \"../catalog/camera-derived\";\nimport { devGuardsEnabled } from \"../guards/dev\";\n\n/**\n * Frames a freeze may spend walking to quiet before it parks regardless.\n * Two seconds at 60 Hz: comfortably longer than a cancelled gesture's path to\n * its commit tick or a cold board's first paints, short enough that a wedged\n * reporter reads as a hiccup rather than a hang.\n */\nexport const SETTLE_CAP = 120;\n\n/**\n * Quiet steps a sleeping loop takes after the last outside wake (or the last\n * busy step) before it sleeps (K7a): enough for the interaction stack's\n * one-tick protocols — a pointer's up processed, its recognizer ended, the\n * one-tick tags cleared and the recognizer reaped a tick later — to land\n * without each needing a reporter. Three steps ≈ 50 ms at 60 Hz, once per\n * outside event; a registered time's step takes none.\n */\nexport const SLEEP_TAIL = 3;\n\n/** What the sleep has done since the control was made (the rigs' and the units' instrument). */\nexport interface SleepStats {\n /** The host loop sleeps now (no frame scheduled; a wake or a registered time restarts it). */\n readonly asleep: boolean;\n /** Times the loop fell asleep. */\n readonly sleeps: number;\n /** Outside wakes by reason (`world`, `input`, `doc`, `presence`, `desk:…`, …) — each call counted, asleep or not. */\n readonly wakes: Readonly<Record<string, number>>;\n /** Steps a registered time started (the loop's own timer, nothing else pending). */\n readonly timed: number;\n /** Steps since the control was made (entered through the engine's `step`). */\n readonly steps: number;\n}\n\nexport interface FrameControl {\n /**\n * Take a named freeze. Returns an IDEMPOTENT thaw — the disposer pattern\n * that makes overlay lifecycles leak-proof (release on unmount), the name\n * that makes \"why is the engine parked?\" answerable. Refcounted: the loop\n * resumes when the LAST freeze thaws.\n */\n freeze(name: string): () => void;\n /** A freeze is held — the loop is settling or already parked. */\n isFrozen(): boolean;\n /** The settle finished and the gate closed: no further steps are being run. */\n isParked(): boolean;\n /** Live freeze names, in take order (debug/devtools). */\n holds(): readonly string[];\n /**\n * Register a settle reporter: while `busy()` is true, a taken freeze keeps\n * stepping instead of parking. This is how a subsystem that owes visible\n * work — the GL compositor's pending first paints, a gesture walking to its\n * commit — keeps a freeze from landing on a half-finished image. Returns an\n * idempotent unregister.\n */\n settleWhile(name: string, busy: () => boolean): () => void;\n /** Reporters answering busy right now (\"why hasn't it parked yet?\"). */\n settling(): readonly string[];\n /**\n * The loop gate. CONSUMING — each call advances the settle walk, so it is\n * for frame hosts only, never a predicate to poll. Use {@link isFrozen} /\n * {@link isParked} to ask questions.\n */\n claimStep(): boolean;\n /** Wake on any freeze/thaw transition (the host loop restarts here). */\n onChange(fn: () => void): () => void;\n /**\n * The park ANNOUNCED (petition I41) — for a host that must know the loop HAS parked (a cover's budget after it rises)\n * without polling {@link isParked} every page frame. `fn(true)` once the loop has parked after a freeze: when the settle\n * walk's last step ENDS (the frame the park leaves standing is drawn — `isParked()` turned true as that step was handed\n * out), or at the first claim the gate refuses where no step followed (the settle cap; a host that claims without\n * stepping). `fn(false)` once when the last thaw reopens a gate that announced its park — after `onChange`, so the loop\n * has restarted. Once per transition, never per frame; a freeze thawed before it parked announces nothing, and a second\n * freeze taken over a park changes nothing. Not replayed on subscribe (read `isParked()` for the state now). A throwing\n * listener is reported and contained — the announcement runs inside the loop's own step and claim. A separate door, not\n * a payload on `onChange`: that one fires at the HOLD's transitions, which the park's are not (a freeze's comes before\n * its settle walk), and its listeners — the loop's restart, the facade's gesture cancel — must not run a third time a\n * cycle. Returns an unsubscribe.\n */\n onParked(fn: (parked: boolean) => void): () => void;\n\n // ── the sleep (K7a) ────────────────────────────────────────────────────────\n /**\n * Something happened that the next frame must see — an input, a write from outside a step, a document's or a room's\n * arrival, an asset landing, a desk's flux: outside a step it restarts a sleeping loop and the tail; inside one it asks\n * for one more frame. Counted by `reason`.\n */\n wake(reason: string): void;\n /**\n * A REGISTERED WAKE: after every step the host asks each source when it is next due, on `performance.now()`'s clock —\n * at or before `now`: the next frame (it still moves); a later time: then (a sleeping loop sets a timer); `Infinity`:\n * never on its own (only a `wake` brings it back). Returns an idempotent unregister.\n */\n wakeWhen(name: string, due: (now: number) => number): () => void;\n /** The sources due at `now` or before (debug/devtools: \"why is the loop awake?\") — settle reporters busy included. */\n due(now: number): readonly string[];\n /**\n * For frame hosts, once after every step: when the next step must run — `≤ now`: the next frame; a later time: then;\n * `Infinity`: only on a wake. CONSUMING (it counts the quiet steps of the tail), never a predicate to poll.\n */\n nextStep(now: number): number;\n /** The host loop fell asleep (`true`) or woke (`false`, `timed`: for a registered time alone) — bookkeeping for the stats. */\n sleeping(asleep: boolean, timed?: boolean): void;\n /** A wake arrived while the host sleeps: restart here (the host loop's subscription). Returns an unsubscribe. */\n onWake(fn: () => void): () => void;\n /**\n * The step in progress began SETTLED — nothing pending, the tail long run: a sleeping loop's step for a registered time\n * alone (or a headless host's step with nothing new). A host that polls its parts asks only those that are due.\n */\n settled(): boolean;\n /** The engine's `step` entered and left (engine.ts): wakes inside a step ask for a frame, never a tail. */\n enterStep(): void;\n leaveStep(): void;\n /** Inside the engine's `step` right now. */\n stepping(): boolean;\n sleepStats(): SleepStats;\n}\n\nexport function createFrameControl(world: World): FrameControl {\n const freezes = new Map<symbol, string>();\n const reporters = new Map<symbol, { readonly name: string; readonly busy: () => boolean }>();\n const listeners = new Set<() => void>();\n let settleLeft = 0;\n let parked = false;\n // the park announced (I41)\n const parkListeners = new Set<(parked: boolean) => void>();\n /** The park the listeners last heard — each transition announced once. */\n let heardParked = false;\n /** The claim that closed the gate handed out the settle walk's last step: that step's end announces the park. */\n let parkOwed = false;\n // the sleep (K7a)\n const sources = new Map<symbol, { readonly name: string; readonly due: (now: number) => number }>();\n const wakeListeners = new Set<() => void>();\n const wakeCounts: Record<string, number> = {};\n /** An outside wake since the step in progress (or the last one) began. */\n let pending = false;\n /** Quiet steps in a row (nothing pending, nothing due or busy at their end) — a sleeping loop sleeps at SLEEP_TAIL. */\n let quiet = 0;\n let inStep = false;\n let settledStep = false;\n let asleep = false;\n let sleeps = 0;\n let timed = 0;\n let steps = 0;\n\n const sync = (): void => {\n world.setResource(FrameMode, { freezeHolds: freezes.size });\n };\n // Copy before iterating: a listener that thaws (and so unsubscribes) mid-\n // announce must not mutate the set being walked.\n const announce = (): void => {\n for (const fn of [...listeners]) fn();\n };\n const busyNames = (): string[] => {\n const names: string[] = [];\n for (const r of reporters.values()) if (r.busy()) names.push(r.name);\n return names;\n };\n // Copied (a listener may unsubscribe mid-announce) and CONTAINED: the park is announced inside the loop's own step and claim,\n // and a host's throw there must not take the loop down with it (petition I14, dom/loop.ts). A listener that thaws at the park\n // announces the reopening from inside this walk — the listeners not yet called hear only that, the state now, never a park\n // already over.\n const announcePark = (on: boolean): void => {\n if (heardParked === on) return;\n heardParked = on;\n for (const fn of [...parkListeners]) {\n if (heardParked !== on) return;\n try {\n fn(on);\n } catch (err) {\n console.error(\"[ice] frame.onParked — a listener threw; the gate stands\", err);\n }\n }\n };\n\n const claim = (): boolean => {\n if (freezes.size === 0) return true;\n if (!parked && settleLeft <= 0) {\n // Cap reached with work still outstanding. Park anyway — a freeze that\n // never lands is worse than one that lands on a stale pixel — but name\n // the reporters, because this is always someone's bug.\n parked = true;\n if (devGuardsEnabled()) {\n console.warn(\n `ice: frame.freeze — settle cap (${SETTLE_CAP} frames) reached with reporters still busy: ${busyNames().join(\", \")}. Parking on a possibly unsettled frame.`,\n );\n }\n }\n if (parked) {\n if (heardParked) return false;\n // A park no ended step has announced — the cap's, or a host that claims without stepping — is announced at its first\n // refusal. A listener may thaw right there (or thaw and freeze again): then this claim is the reopened gate's.\n parkOwed = false;\n announcePark(true);\n return parked ? false : claim();\n }\n settleLeft -= 1;\n // Quiet: this is the LAST step, taken so the settled state reflects — its end announces the park (leaveStep).\n if (busyNames().length === 0) {\n parked = true;\n parkOwed = true;\n }\n return true;\n };\n\n return {\n freeze(name) {\n const token = Symbol(name);\n const first = freezes.size === 0;\n freezes.set(token, name);\n // Only the 0→1 transition arms a settle walk; a second freeze taken\n // while the engine is already parked changes nothing but the refcount.\n if (first) {\n settleLeft = SETTLE_CAP;\n parked = false;\n }\n sync();\n announce();\n let released = false;\n return () => {\n if (released) return; // idempotent — double-thaw must not eat another freeze\n released = true;\n freezes.delete(token);\n const open = freezes.size === 0;\n if (open) {\n settleLeft = 0;\n parked = false;\n parkOwed = false;\n }\n sync();\n announce();\n // The gate reopened (the loop restarted in `announce`): a park the listeners heard is over.\n if (open) announcePark(false);\n };\n },\n\n isFrozen: () => freezes.size > 0,\n isParked: () => parked,\n holds: () => [...freezes.values()],\n\n settleWhile(name, busy) {\n const token = Symbol(name);\n reporters.set(token, { name, busy });\n let released = false;\n return () => {\n if (released) return;\n released = true;\n reporters.delete(token);\n };\n },\n\n settling: () => busyNames(),\n\n claimStep: claim,\n\n onChange(fn) {\n listeners.add(fn);\n return () => {\n listeners.delete(fn);\n };\n },\n\n onParked(fn) {\n parkListeners.add(fn);\n return () => {\n parkListeners.delete(fn);\n };\n },\n\n wake(reason) {\n // Inside a step a wake is the step's own consequence: the part that owes the next frame says so through its registered\n // wake or its settle reporter (a desk's dirt, a kind still moving) — never a tail per frame a kind asked for.\n if (inStep) return;\n wakeCounts[reason] = (wakeCounts[reason] ?? 0) + 1;\n pending = true;\n quiet = 0;\n if (asleep) for (const fn of [...wakeListeners]) fn();\n },\n\n wakeWhen(name, due) {\n const token = Symbol(name);\n sources.set(token, { name, due });\n let released = false;\n return () => {\n if (released) return;\n released = true;\n sources.delete(token);\n };\n },\n\n due(now) {\n const names = busyNames();\n for (const s of sources.values()) if (s.due(now) <= now) names.push(s.name);\n return names;\n },\n\n nextStep(now) {\n let busy = pending;\n let soonest = Number.POSITIVE_INFINITY;\n if (!busy) for (const r of reporters.values()) if (r.busy()) { busy = true; break; }\n if (!busy) {\n for (const s of sources.values()) {\n const t = s.due(now);\n if (t <= now) { busy = true; break; }\n if (t < soonest) soonest = t;\n }\n }\n if (busy) {\n quiet = 0;\n return now;\n }\n quiet += 1;\n return quiet < SLEEP_TAIL ? now : soonest;\n },\n\n sleeping(on, byTimer = false) {\n if (on === asleep) return;\n asleep = on;\n if (on) sleeps += 1;\n else if (byTimer) timed += 1;\n },\n\n onWake(fn) {\n wakeListeners.add(fn);\n return () => {\n wakeListeners.delete(fn);\n };\n },\n\n settled: () => settledStep,\n\n enterStep() {\n inStep = true;\n steps += 1;\n settledStep = !pending && quiet >= SLEEP_TAIL;\n pending = false;\n },\n\n leaveStep() {\n inStep = false;\n // The settle walk's last step has ended: the park is real — announce it.\n if (parkOwed) {\n parkOwed = false;\n announcePark(true);\n }\n },\n\n stepping: () => inStep,\n\n sleepStats: () => ({ asleep, sleeps, wakes: { ...wakeCounts }, timed, steps }),\n };\n}\n","/**\n * The guest runtime (petition I14 — the literal PA-28 \"spine scheduler\").\n *\n * A GUEST is frame-cadence work the engine did not write: a plugin's declared\n * system, a host's derived-state job, and (from design-009) every compiled\n * behavior. Guests get a NAMED slot in the frame contract — design-002 §1 as\n * amended 2026-08-15:\n *\n * setFrameInfo → sync → tick → GUESTS → publish hooks → notify → reflect\n *\n * Guests run BEFORE the publish hooks so derived state has settled by the time\n * presence I/O reads it, and before `notify()` so the same frame reflects their\n * writes. Three properties the engine owes anything it hosts here:\n *\n * 1. **Fault isolation.** A throwing guest is caught, struck, and skipped — it\n * never kills the loop, its neighbours, or the frame. (Engine systems and\n * publish hooks keep propagating loudly by design; guests are the untrusted\n * tier, and the breaker below is what makes hosting them honest.)\n * 2. **The snapshot rule.** `runAll` iterates a snapshot with a liveness check,\n * so a guest that adds or removes guests mid-run never skips a neighbour —\n * the bug this same release fixed in the publish-hook and reflector loops.\n * A guest added during a run starts NEXT frame.\n * 3. **A circuit breaker, named honestly.** A main-thread body cannot be\n * preempted: by the time we measure, the frame is already spent. What the\n * breaker guarantees is that no guest hurts the canvas TWICE sustained.\n *\n * GENERATIONS. `make(gen)` builds a per-generation instance; the generation\n * boundary in ICE is `world.reset()` (doc close/switch — the world is reset in\n * place, so systems, observers and this registry all survive while every entity\n * dies). On reset we mark the generation dirty and rebuild at the TOP of the\n * next guest step — never inside the observer emit, where structural writes are\n * illegal and user code has no business running. `gen.signal` aborts when the\n * generation ends or the guest is removed.\n *\n * THE LEDGER IS HOST-INJECTABLE. Downstream (VibeField) an engine is per-doc, so\n * a registry-local ledger would reset on every doc switch and hand chronic\n * offenders a fresh probation forever. `add({ledger})` seeds prior state and\n * `onLedgerChange` reports every transition, so the host persists across\n * generations it owns.\n */\nimport type { World } from \"@vibecook/strata-ecs\";\nimport { devGuardsEnabled } from \"../guards/dev\";\n\n/** Frame facts a guest may read (FrameInfo, pre-read by the engine). */\nexport interface GuestFrame {\n readonly dtMs: number;\n readonly tick: number;\n /** Accumulated CLAMPED dt — under-reports across freezes; never accumulate\n * wall time from it (frame-info.ts). */\n readonly clock: number;\n}\n\nexport type GuestRun = (frame: GuestFrame) => void;\n\nexport interface GuestInstance {\n run: GuestRun;\n dispose?: () => void;\n /**\n * \"I still owe visible work.\" Feeds the frame gate's settle walk, so a\n * freeze taken mid-derive parks only AFTER the guest has caught up — the\n * canvas is never photographed between a structural change and its reflow.\n * A guest with no owed-work notion simply omits it (the frame gate then\n * treats it as quiet, which is the honest default). The same answer keeps a\n * SLEEPING loop awake (K7a, frame-control.ts): a guest runs on the frames the\n * engine steps — after a wake — and one that animates on its own clock says\n * so here, or it runs only when something else wakes the loop.\n */\n busy?: () => boolean;\n}\n\nexport interface GuestGeneration {\n readonly world: World;\n /** Aborts at generation teardown (world reset), removal, or engine dispose. */\n readonly signal: AbortSignal;\n}\n\nexport type GuestFactory = (gen: GuestGeneration) => GuestInstance | GuestRun;\n\n/** The persistable half of a guest's breaker state. */\nexport interface GuestLedgerRecord {\n /** Cumulative over-budget/fault strikes (never reset by resume — honesty). */\n readonly strikes: number;\n readonly suspended: boolean;\n}\n\nexport interface GuestSpec {\n /** Stable id — the ledger key, the profiler lane name, the doctor's row. */\n readonly id: string;\n readonly make: GuestFactory;\n /** Per-invocation budget request; the effective budget is\n * `min(budgetMs, seamCapMs)` — no single guest may claim the whole seam. */\n readonly budgetMs?: number;\n /** RESERVED. Hosted guests run in the publish slot only — and that is now the\n * settled shape, not a v1 placeholder: M13 reached pipeline cadence through\n * `addDriven` (behaviors run as pipeline systems and CHARGE this breaker)\n * instead of widening this field. A wider value would mean a second way to\n * put foreign code in the tick that `addDriven` already provides. */\n readonly phase?: \"publish\";\n /** Seed prior breaker state (host-persisted across engine generations). */\n readonly ledger?: GuestLedgerRecord;\n}\n\nexport interface GuestStatus {\n readonly id: string;\n readonly status: \"running\" | \"suspended\" | \"failed\";\n /** Last invocation, ms. */\n readonly lastMs: number;\n /** p95 over the rolling window, ms. */\n readonly p95Ms: number;\n readonly strikes: number;\n readonly budgetMs: number;\n}\n\n/**\n * A guest whose CADENCE its owner drives (design-009 §7): compiled behaviors\n * run as ordinary pipeline systems, in their declared phase, inside the tick —\n * so nothing here can call their bodies. What they still need is everything\n * ELSE a guest gets: one breaker, one ledger, one doctor row, one seam total.\n * That is what this handle is — the breaker, detached from the scheduler.\n */\nexport interface DrivenGuest {\n /** Breaker verdict. Cheap and never throws — poll it from a system `runIf`. */\n suspended(): boolean;\n /**\n * Run `body` inside this guest's fault domain, ACCRUING its cost into the\n * current frame's charge. Returns false when the guest is suspended (the\n * body did not run) or the body threw (contained).\n *\n * Accrual, not per-call recording, is what makes the budget mean \"per frame\"\n * for a CHUNKED body: a tick system's body runs once per matching chunk, and\n * recording each chunk as its own invocation would compare a 2ms frame budget\n * against a fraction of the work it was meant to bound. The accrued total is\n * closed as ONE invocation at the guest slot, every frame.\n */\n run(body: () => void): boolean;\n /**\n * Report a fault the caller already CONTAINED — a per-instance hook throw\n * that the delivery loop caught so one bad node cannot kill a 1000-node\n * behavior (BF-D18). It takes the ordinary throw ladder.\n */\n fault(err: unknown): void;\n /** Idempotent. */\n remove(): void;\n}\n\nexport interface DrivenGuestSpec {\n readonly id: string;\n readonly budgetMs?: number;\n readonly ledger?: GuestLedgerRecord;\n /** Owed-work reporter for the frame gate's settle walk. */\n readonly busy?: () => boolean;\n}\n\nexport interface GuestRegistry {\n /** Register a guest. Returns a remover (idempotent; disposes the instance). */\n add(spec: GuestSpec): () => void;\n /**\n * Register a guest the registry does NOT call (see {@link DrivenGuest}).\n * Its cost still lands in this frame's seam total, its strikes in the same\n * ledger, and its row in `list()`.\n */\n addDriven(spec: DrivenGuestSpec): DrivenGuest;\n /** Live status for devtools/doctor — never throws, safe to poll. */\n list(): readonly GuestStatus[];\n /** Fires whenever a guest's persistable breaker state changes. */\n onLedgerChange(cb: (id: string, record: GuestLedgerRecord) => void): () => void;\n /** Clear a suspension (the doctor's explicit action). Cumulative strikes\n * survive; the rolling window is cleared so probation starts fresh. */\n resume(id: string): void;\n}\n\n/** The engine-facing half (step drives it; hosts never see these). */\nexport interface GuestRegistryInternal extends GuestRegistry {\n runAll(frame: GuestFrame): void;\n /** Any live guest reporting owed work — the engine's settle reporter. */\n anyBusy(): boolean;\n dispose(): void;\n}\n\n/**\n * Breaker constants (design-009 §12 / door ED-D3). Exported so tests and the\n * downstream doctor cite ONE source rather than re-deriving thresholds.\n */\nexport const GUEST_BUDGET = {\n /** Default per-invocation budget when a guest declares none. */\n defaultBudgetMs: 2,\n /** The whole guest seam's sustained budget — also the per-guest ceiling. */\n seamCapMs: 8,\n /** Rolling window length, in invocations. */\n window: 120,\n /** Trip: more than this many of the last `window` invocations over budget. */\n overBudgetTrip: 30,\n /** Trip: this many CONSECUTIVE invocations at ≥ `heavyFactor` × budget. */\n consecutiveHeavy: 3,\n heavyFactor: 4,\n /** Trip: this many CONSECUTIVE invocations over `stallMs` (one GC pause or\n * debugger breakpoint must never suspend — hence 2, not 1). */\n consecutiveStall: 2,\n stallMs: 50,\n /** Trip: this many consecutive throws. */\n consecutiveThrows: 3,\n /** Frames the whole seam may sit over `seamCapMs` before the worst offender\n * is suspended. */\n seamOverFrames: 3,\n} as const;\n\ninterface Entry {\n readonly spec: GuestSpec;\n readonly budgetMs: number;\n /** Driven entries have no factory and no instance — their owner calls them. */\n readonly driven: boolean;\n /** Driven entries report owed work directly (there is no instance to ask). */\n readonly busyFn: (() => boolean) | undefined;\n /** ms accrued by `DrivenGuest.run` since the last settle (see the doc there). */\n accruedMs: number;\n accrued: boolean;\n /** Any contained fault since the last settle — the ladder counts frames. */\n faultedThisFrame: boolean;\n instance: GuestInstance | null;\n controller: AbortController | null;\n alive: boolean;\n /** `make` threw — no instance, no runs, reported once. */\n failed: boolean;\n suspended: boolean;\n /** The first invocation of each generation is exempt from TIMING strikes\n * (module warmup, JIT, first-touch allocation — not a hostile body). */\n warmupPending: boolean;\n /** Rolling durations, ms (bounded by GUEST_BUDGET.window). */\n window: number[];\n overInWindow: number;\n consecutiveHeavy: number;\n consecutiveStall: number;\n consecutiveThrows: number;\n lastMs: number;\n strikes: number;\n}\n\nexport interface GuestRegistryOpts {\n /**\n * Dev leniency: while true, TIMING strikes log and never suspend (the throw\n * ladder still bites). Wired to `engine.enableTelemetry()` — i.e. devtools\n * attached — so stepping in a debugger cannot suspend a healthy guest.\n */\n readonly lenient?: () => boolean;\n readonly onFault?: (id: string, err: unknown) => void;\n readonly onNotice?: (message: string) => void;\n}\n\nexport function createGuestRegistry(world: World, opts?: GuestRegistryOpts): GuestRegistryInternal {\n const entries: Entry[] = [];\n let snapshot: Entry[] = [];\n let snapshotDirty = true;\n let generationDirty = false;\n let disposed = false;\n let seamOverFrames = 0;\n const ledgerSubs = new Set<(id: string, record: GuestLedgerRecord) => void>();\n\n const lenient = opts?.lenient ?? (() => false);\n const onFault =\n opts?.onFault ??\n ((id: string, err: unknown) => {\n console.error(`[ice] guest \"${id}\" threw — skipped this frame`, err);\n });\n const onNotice =\n opts?.onNotice ??\n ((message: string) => {\n console.warn(`[ice] ${message}`);\n });\n\n const emitLedger = (e: Entry): void => {\n const record: GuestLedgerRecord = { strikes: e.strikes, suspended: e.suspended };\n for (const cb of ledgerSubs) cb(e.spec.id, record);\n };\n\n const strike = (e: Entry, reason: string, suspendNow: boolean): void => {\n e.strikes++;\n if (suspendNow && !e.suspended) {\n e.suspended = true;\n disposeInstance(e); // a suspended guest holds no live resources\n onNotice(`guest \"${e.spec.id}\" SUSPENDED — ${reason}`);\n }\n emitLedger(e);\n };\n\n const disposeInstance = (e: Entry): void => {\n const inst = e.instance;\n const controller = e.controller;\n e.instance = null;\n e.controller = null;\n // dispose() FIRST, abort SECOND (design-009 §4.3): a teardown that guards\n // on `signal.aborted` — a thoroughly reasonable thing to write — would\n // skip its own cleanup if the signal fired first.\n if (inst?.dispose !== undefined) {\n try {\n inst.dispose();\n } catch (err) {\n // Teardown-sweep discipline: a throwing dispose must not stop the sweep.\n onFault(e.spec.id, err);\n }\n }\n controller?.abort();\n };\n\n const makeInstance = (e: Entry): void => {\n if (e.driven || e.suspended || !e.alive || disposed) return;\n const controller = new AbortController();\n try {\n const made = e.spec.make({ world, signal: controller.signal });\n e.instance = typeof made === \"function\" ? { run: made } : made;\n e.controller = controller;\n e.failed = false;\n e.warmupPending = true;\n } catch (err) {\n controller.abort();\n e.instance = null;\n e.controller = null;\n e.failed = true;\n onFault(e.spec.id, err);\n }\n };\n\n const stopResetWatch = world.observe({\n onReset: () => {\n // Do NOT rebuild here: user factories may write structurally, which is\n // illegal inside an observer emit. Mark and rebuild at the next step's\n // top, before any guest runs against dead handles.\n generationDirty = true;\n },\n });\n\n const rebuildGeneration = (): void => {\n for (const e of entries) disposeInstance(e);\n for (const e of entries) makeInstance(e);\n // A driven guest keeps no instance to rebuild, but it DOES get a fresh\n // warmup exemption: the first frame of a new generation pays the same\n // first-touch costs (rebuilt caches, cold paths) that exempt hosted guests.\n for (const e of entries) if (e.driven) e.warmupPending = true;\n };\n\n const p95 = (samples: readonly number[]): number => {\n if (samples.length === 0) return 0;\n const sorted = [...samples].sort((a, b) => a - b);\n const idx = Math.min(sorted.length - 1, Math.floor(sorted.length * 0.95));\n return sorted[idx] ?? 0;\n };\n\n /** The guest whose suspension buys the seam the most: most strikes, then p95. */\n const worstOffender = (): Entry | null => {\n let worst: Entry | null = null;\n for (const e of snapshot) {\n if (!e.alive || e.suspended || e.instance === null) continue;\n if (worst === null) {\n worst = e;\n continue;\n }\n if (e.overInWindow !== worst.overInWindow) {\n if (e.overInWindow > worst.overInWindow) worst = e;\n continue;\n }\n if (p95(e.window) > p95(worst.window)) worst = e;\n }\n return worst;\n };\n\n const record = (e: Entry, ms: number): void => {\n e.lastMs = ms;\n e.window.push(ms);\n if (ms > e.budgetMs) e.overInWindow++;\n if (e.window.length > GUEST_BUDGET.window) {\n const dropped = e.window.shift() ?? 0;\n if (dropped > e.budgetMs) e.overInWindow--;\n }\n\n // Warmup: the first invocation of a generation is measured and reported,\n // but cannot itself strike (module eval + first-touch costs are not a\n // hostile body). Consecutive counters start clean after it.\n if (e.warmupPending) {\n e.warmupPending = false;\n e.consecutiveHeavy = 0;\n e.consecutiveStall = 0;\n return;\n }\n\n e.consecutiveStall = ms > GUEST_BUDGET.stallMs ? e.consecutiveStall + 1 : 0;\n e.consecutiveHeavy = ms >= e.budgetMs * GUEST_BUDGET.heavyFactor ? e.consecutiveHeavy + 1 : 0;\n\n const timingTrip =\n e.overInWindow > GUEST_BUDGET.overBudgetTrip ||\n e.consecutiveHeavy >= GUEST_BUDGET.consecutiveHeavy ||\n e.consecutiveStall >= GUEST_BUDGET.consecutiveStall;\n\n if (!timingTrip) return;\n\n const why =\n e.consecutiveStall >= GUEST_BUDGET.consecutiveStall\n ? `${e.consecutiveStall} consecutive invocations over ${GUEST_BUDGET.stallMs}ms`\n : e.consecutiveHeavy >= GUEST_BUDGET.consecutiveHeavy\n ? `${e.consecutiveHeavy} consecutive invocations ≥ ${GUEST_BUDGET.heavyFactor}× its ${e.budgetMs}ms budget`\n : `${e.overInWindow} of the last ${e.window.length} invocations over its ${e.budgetMs}ms budget`;\n\n if (lenient()) {\n // Devtools attached: report, never suspend. Counters reset so one paused\n // breakpoint does not queue a suspension for the moment devtools detach.\n e.consecutiveHeavy = 0;\n e.consecutiveStall = 0;\n e.overInWindow = 0;\n e.window.length = 0;\n onNotice(`guest \"${e.spec.id}\" over budget (${why}) — not suspended: devtools attached`);\n return;\n }\n strike(e, why, true);\n };\n\n const makeEntry = (spec: GuestSpec, driven: boolean, busy: (() => boolean) | undefined): Entry => ({\n spec,\n // No guest may claim more than the whole seam.\n budgetMs: Math.max(0, Math.min(spec.budgetMs ?? GUEST_BUDGET.defaultBudgetMs, GUEST_BUDGET.seamCapMs)),\n driven,\n busyFn: busy,\n accruedMs: 0,\n accrued: false,\n faultedThisFrame: false,\n instance: null,\n controller: null,\n alive: true,\n failed: false,\n suspended: spec.ledger?.suspended ?? false,\n warmupPending: true,\n window: [],\n overInWindow: 0,\n consecutiveHeavy: 0,\n consecutiveStall: 0,\n consecutiveThrows: 0,\n lastMs: 0,\n strikes: spec.ledger?.strikes ?? 0,\n });\n\n return {\n add(spec) {\n if (disposed) throw new Error(`ice: guests.add(\"${spec.id}\") after the registry was disposed`);\n if (spec.phase !== undefined && spec.phase !== \"publish\") {\n throw new Error(\n `ice: guests.add(\"${spec.id}\") — phase \"${spec.phase}\" is reserved; v1 hosts the publish slot only (pipeline phases arrive with the behavior framework)`,\n );\n }\n if (entries.some((e) => e.spec.id === spec.id && e.alive)) {\n throw new Error(`ice: guest \"${spec.id}\" is already registered`);\n }\n\n const entry = makeEntry(spec, false, undefined);\n entries.push(entry);\n snapshotDirty = true;\n makeInstance(entry);\n\n return () => {\n if (!entry.alive) return;\n entry.alive = false;\n disposeInstance(entry);\n const i = entries.indexOf(entry);\n if (i !== -1) entries.splice(i, 1);\n snapshotDirty = true;\n };\n },\n\n addDriven(spec) {\n if (disposed) throw new Error(`ice: guests.addDriven(\"${spec.id}\") after the registry was disposed`);\n if (entries.some((e) => e.spec.id === spec.id && e.alive)) {\n throw new Error(`ice: guest \"${spec.id}\" is already registered`);\n }\n const entry = makeEntry(\n { id: spec.id, make: DRIVEN_NO_FACTORY, ...(spec.budgetMs !== undefined ? { budgetMs: spec.budgetMs } : {}), ...(spec.ledger !== undefined ? { ledger: spec.ledger } : {}) },\n true,\n spec.busy,\n );\n entries.push(entry);\n snapshotDirty = true;\n\n return {\n suspended: () => entry.suspended || !entry.alive || disposed,\n run(body) {\n if (entry.suspended || !entry.alive || disposed) return false;\n const t0 = performance.now();\n try {\n body();\n entry.accruedMs += performance.now() - t0;\n entry.accrued = true;\n return true;\n } catch (err) {\n entry.accruedMs += performance.now() - t0;\n entry.accrued = true;\n entry.faultedThisFrame = true;\n entry.consecutiveThrows++;\n onFault(entry.spec.id, err);\n strike(\n entry,\n `${entry.consecutiveThrows} consecutive throws`,\n entry.consecutiveThrows >= GUEST_BUDGET.consecutiveThrows,\n );\n return false;\n }\n },\n fault(err) {\n if (!entry.alive || disposed) return;\n // Suspended = the ladder already did its job. Further faults from\n // the same runaway pass (a chunked body the breaker cannot preempt)\n // must not keep inflating `strikes` — that number is a cumulative\n // record hosts PERSIST across engine generations — nor spam\n // onFault/ledger subscribers per instance (review finding 4).\n if (entry.suspended) return;\n entry.faultedThisFrame = true;\n entry.accrued = true; // ensure the settle pass sees this frame\n entry.consecutiveThrows++;\n onFault(entry.spec.id, err);\n strike(\n entry,\n `${entry.consecutiveThrows} consecutive throws`,\n entry.consecutiveThrows >= GUEST_BUDGET.consecutiveThrows,\n );\n },\n remove() {\n if (!entry.alive) return;\n entry.alive = false;\n const i = entries.indexOf(entry);\n if (i !== -1) entries.splice(i, 1);\n snapshotDirty = true;\n },\n };\n },\n\n runAll(frame) {\n if (disposed) return;\n if (generationDirty) {\n generationDirty = false;\n rebuildGeneration();\n }\n if (snapshotDirty) {\n snapshot = entries.slice();\n snapshotDirty = false;\n }\n\n // Close out every driven guest's frame FIRST: they ran during the tick,\n // so their cost is already spent by the time this slot opens, and the\n // seam total below has to include it or the cap it enforces is fiction.\n let seamMs = 0;\n for (const e of snapshot) {\n if (!e.driven || !e.accrued) continue;\n const ms = e.accruedMs;\n e.accruedMs = 0;\n e.accrued = false;\n seamMs += ms;\n // The throw ladder counts FRAMES, not calls: a chunked body runs many\n // times per frame, and clearing the counter on the first clean chunk\n // after a faulting one would mean three consecutive bad frames never\n // add up to three.\n if (!e.faultedThisFrame) e.consecutiveThrows = 0;\n e.faultedThisFrame = false;\n record(e, ms);\n }\n\n for (const e of snapshot) {\n if (e.driven || !e.alive || e.suspended || e.instance === null) continue;\n const t0 = performance.now();\n try {\n const returned: unknown = e.instance.run(frame);\n // An async body evades BOTH the bracket and the catch: the awaited\n // remainder runs outside the frame with no budget and no fault\n // domain. `(frame) => void` accepts any return type, so only a\n // runtime check catches it. Treated as a FAULT, not a slow frame:\n // under dev guards it suspends immediately (a contract violation is\n // a bug to fix, not a perf blip to ride out); in production it takes\n // the ordinary throw ladder. It is never re-thrown — a guest must not\n // be able to kill the frame, which is the whole point of this tier.\n if (typeof (returned as { then?: unknown } | null | undefined)?.then === \"function\") {\n const ms = performance.now() - t0;\n seamMs += ms;\n e.consecutiveThrows++;\n onFault(\n e.spec.id,\n new Error(\n `guest \"${e.spec.id}\" run() returned a thenable — guest bodies MUST be synchronous`,\n ),\n );\n strike(\n e,\n \"an async run() body\",\n devGuardsEnabled() || e.consecutiveThrows >= GUEST_BUDGET.consecutiveThrows,\n );\n continue;\n }\n const ms = performance.now() - t0;\n seamMs += ms;\n e.consecutiveThrows = 0;\n record(e, ms);\n } catch (err) {\n const ms = performance.now() - t0;\n seamMs += ms;\n e.lastMs = ms;\n e.consecutiveThrows++;\n onFault(e.spec.id, err);\n strike(\n e,\n `${e.consecutiveThrows} consecutive throws`,\n e.consecutiveThrows >= GUEST_BUDGET.consecutiveThrows,\n );\n }\n }\n\n // The seam cap: the canvas never pays twice for the whole guest tier.\n if (seamMs > GUEST_BUDGET.seamCapMs) {\n seamOverFrames++;\n if (seamOverFrames >= GUEST_BUDGET.seamOverFrames && !lenient()) {\n const worst = worstOffender();\n seamOverFrames = 0;\n if (worst !== null) {\n strike(\n worst,\n `the guest seam ran over ${GUEST_BUDGET.seamCapMs}ms for ${GUEST_BUDGET.seamOverFrames} consecutive frames and this was its worst offender`,\n true,\n );\n }\n }\n } else {\n seamOverFrames = 0;\n }\n },\n\n anyBusy() {\n for (const e of entries) {\n if (!e.alive || e.suspended) continue;\n const busy = e.driven ? e.busyFn : e.instance?.busy;\n if (busy === undefined) continue;\n try {\n if (busy()) return true;\n } catch (err) {\n // A throwing predicate must not wedge the settle walk at the cap.\n onFault(e.spec.id, err);\n }\n }\n return false;\n },\n\n list() {\n return entries.map((e) => ({\n id: e.spec.id,\n status: e.suspended ? \"suspended\" : e.failed ? \"failed\" : \"running\",\n lastMs: e.lastMs,\n p95Ms: p95(e.window),\n strikes: e.strikes,\n budgetMs: e.budgetMs,\n }));\n },\n\n onLedgerChange(cb) {\n ledgerSubs.add(cb);\n return () => {\n ledgerSubs.delete(cb);\n };\n },\n\n resume(id) {\n const e = entries.find((x) => x.spec.id === id && x.alive);\n if (e === undefined || !e.suspended) return;\n e.suspended = false;\n e.window.length = 0;\n e.overInWindow = 0;\n e.consecutiveHeavy = 0;\n e.consecutiveStall = 0;\n e.consecutiveThrows = 0;\n makeInstance(e); // a fresh instance: the suspended one was disposed\n emitLedger(e);\n },\n\n dispose() {\n if (disposed) return;\n disposed = true;\n stopResetWatch();\n for (const e of entries) {\n e.alive = false;\n disposeInstance(e);\n }\n entries.length = 0;\n snapshot = [];\n ledgerSubs.clear();\n },\n };\n}\n\n/** Placeholder factory for driven entries — never called (see `makeInstance`). */\nconst DRIVEN_NO_FACTORY: GuestFactory = () => {\n throw new Error(\"ice: internal — a driven guest has no factory\");\n};\n","/**\n * THE WORLD'S OUTSIDE DOORS (2026-09-27, ICE M21 K7a — frame-control.ts's sleep). A write made OUTSIDE a step — an app's\n * command, a rig's camera, the host's viewport sync, a document's transaction projected, a reset or an import — must wake a\n * sleeping loop, or the frame that shows it never comes. Every state-changing method strata names (`WorldMutatorName`,\n * petition 4's exhaustive list, which strata's own devwrite drift test keeps whole) is wrapped ONCE on the world instance\n * to tell its listeners after it returns; the step's own doors (`sync`, `tick`) are not wrapped. A listener decides what a\n * write means — the engine's asks the frame for a wake, which a write INSIDE a step (a system's, a publish hook's, an\n * after-step hook's) never is. The type below fails the build the day strata names a mutator this list does not.\n */\nimport type { World, WorldMutatorName } from \"@vibecook/strata-ecs\";\n\nconst DOORS = [\n \"spawn\",\n \"destroy\",\n \"addComponent\",\n \"removeComponent\",\n \"addTag\",\n \"removeTag\",\n \"setRelation\",\n \"addRelation\",\n \"removeRelation\",\n \"moveRelation\",\n \"setResource\",\n \"updateResource\",\n \"removeResource\",\n \"edit\",\n \"import\",\n \"reset\",\n] as const satisfies readonly WorldMutatorName[];\n\n/** Every mutator strata names is a door, but the step's own two — `never`, or the build names the one missing. */\ntype Unwatched = Exclude<WorldMutatorName, (typeof DOORS)[number] | \"sync\" | \"tick\">;\nconst EXHAUSTIVE: [Unwatched] extends [never] ? true : Unwatched = true;\nvoid EXHAUSTIVE;\n\nconst watchers = new WeakMap<World, (() => void)[]>();\n\n/** Tell `fn` after every write through one of `world`'s doors. Returns an idempotent unwatch. */\nexport function watchWrites(world: World, fn: () => void): () => void {\n let list = watchers.get(world);\n if (list === undefined) {\n const own: (() => void)[] = [];\n list = own;\n watchers.set(world, own);\n const w = world as unknown as Record<string, (...args: unknown[]) => unknown>;\n for (const name of DOORS) {\n const door = w[name];\n if (typeof door !== \"function\") continue;\n w[name] = (...args: unknown[]): unknown => {\n const out = door.apply(world, args);\n for (let i = 0; i < own.length; i++) (own[i] as () => void)();\n return out;\n };\n }\n }\n const live = list;\n live.push(fn);\n let done = false;\n return () => {\n if (done) return;\n done = true;\n const i = live.indexOf(fn);\n if (i !== -1) live.splice(i, 1);\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 * guests [2026-08-15, petition I14] the NAMED guest slot:\n * plugin/host frame work under a circuit breaker\n * (guests.ts). BEFORE publish so derived state has\n * settled when presence I/O reads it, and before\n * notify so the same frame reflects it. Guests are\n * fault-ISOLATED — the one tier here that is.\n * publish hooks POST-TICK, PRE-NOTIFY: presence I/O home — eph\n * structural ops are illegal for the whole tick, this\n * step is theirs; `world.*` is legal here (outside the\n * tick). Hooks throw LOUDLY (unlike reflectors) — a\n * broken publish pre-notify must not be silently\n * half-applied.\n * notify() THE settled point — observers fire once per frame\n * reflect reflector registry flush (post-notify, output-only)\n *\n * The engine is scheduler-free: `step(now)` is the whole surface, and the DOM\n * package owns the rAF loop (core never touches the platform). Telemetry is\n * opt-in — `world.observe` costs a `performance.now()` pair per system when\n * armed, so benches leave it off.\n */\nimport type { World } from \"@vibecook/strata-ecs\";\nimport type { AnySystem } from \"./pipeline\";\nimport { createFrameControl, type FrameControl } from \"./frame-control\";\nimport { FrameInfo, setFrameInfo } from \"./frame-info\";\nimport { createGuestRegistry, type GuestRegistry, type GuestRegistryInternal } from \"./guests\";\nimport { createPipelineRegistry, type PhaseGroup } from \"./pipeline\";\nimport { createReflectorRegistry, type ReflectorDef } from \"./reflectors\";\nimport { watchWrites } from \"./world-doors\";\n\nexport type PublishHook = (world: World) => void;\n\n/**\n * One registered publish hook. The `alive` flag is what makes removal exact\n * under the snapshot rule (below): the same function may be registered twice,\n * so liveness cannot be a Set membership test on the function itself.\n */\ninterface PublishEntry {\n readonly hook: PublishHook;\n alive: boolean;\n}\n\nexport interface SystemRunRecord {\n readonly phase: string;\n readonly system: string;\n readonly ran: boolean;\n readonly micros: number;\n}\n\n/** One frame's run/skip + timing readout (design-002 §4: F1's honest telemetry). */\nexport interface FrameTelemetry {\n readonly tick: number;\n readonly totalMicros: number;\n readonly systems: readonly SystemRunRecord[];\n readonly phaseFlushMicros: ReadonlyMap<string, number>;\n readonly reflectorsFlushed: readonly string[];\n /**\n * Total reflector-flush cost, µs (post-notify — OUTSIDE the tick, which is\n * why it can never appear in `phaseFlushMicros`: that map is keyed by strata\n * PHASE names and reflect is not a phase. Devtools' \"reflect\" lane read that\n * map until 2026-08-15 and therefore never reported at all).\n */\n readonly reflectMicros: number;\n /** Per-reflector flush cost, µs, for the same frame (registration order). */\n readonly reflectorMicros: ReadonlyMap<string, number>;\n}\n\nexport interface EngineOpts {\n /** Reflector fault sink (default: console.error, skip this frame). */\n readonly onReflectorFault?: (name: string, err: unknown) => void;\n /** Guest fault sink (default: console.error). A guest throwing is contained\n * by the breaker; hosts route this to their own diagnostics. */\n readonly onGuestFault?: (id: string, err: unknown) => void;\n /**\n * Guest breaker notices — suspensions and lenient-mode overruns (default:\n * console.warn). Hosts SHOULD route this: a suspended derived guest means\n * derived state silently stops updating, which reads to a user as a broken\n * document rather than a broken plugin (design-009 §7).\n */\n readonly onGuestNotice?: (message: string) => void;\n}\n\nexport interface Engine {\n readonly world: World;\n /** Register systems into a canonical phase group. Returns a remover. */\n addSystems(group: PhaseGroup, ...systems: readonly AnySystem[]): () => void;\n /** Register a post-notify output reflector (design-002 §5). Returns an unregister. */\n registerReflector(def: ReflectorDef): () => void;\n /** All registered reflector names (devtools; telemetry-independent). */\n reflectorNames(): readonly string[];\n /** Register a publish-step hook (post-tick, pre-notify presence I/O). Returns a remover. */\n onPublish(hook: PublishHook): () => void;\n /**\n * The guest runtime (petition I14): frame-cadence work the engine did not\n * write — plugin systems, host derived-state jobs, compiled behaviors — run\n * in a named slot between the tick and the publish hooks, each fault-isolated\n * and budgeted by a circuit breaker (guests.ts).\n */\n readonly guests: GuestRegistry;\n /** Run one full frame. `now` in ms (rAF timestamp or a test counter). */\n step(now: number): void;\n /**\n * Register a hook that runs right AFTER every `step` — outside the tick, after the reflectors\n * (design-015 §9, D2b): where an op a system asked for inside the tick is applied (the facade's\n * nav intent), whichever `step` a host drives. Returns a remover.\n */\n afterStep(hook: () => void): () => void;\n /**\n * The frame gate (2026-08-04): freeze/thaw plus the settle protocol a host\n * loop consults before each frame. It lives HERE, next to the step it\n * governs, so every host gets it without a new argument — and so a\n * subsystem holding only the `Engine` (the GL compositor) can report itself\n * busy. `step()` itself stays unconditional: the gate governs the loop, not\n * the primitive, which keeps headless hosts and traces driving frames by\n * hand exactly as before.\n */\n readonly frame: FrameControl;\n /** Arm per-system run/skip + µs collection (idempotent; costs timer calls per system).\n * Also puts the guest breaker in LENIENT mode — devtools attached means a\n * debugger breakpoint must not suspend a healthy guest. */\n enableTelemetry(): void;\n /** Tear down guest instances (the facade calls this from `dispose()`). */\n disposeGuests(): void;\n /** The most recent completed frame's readout (undefined until telemetry armed + one step). */\n lastFrame(): FrameTelemetry | undefined;\n}\n\nexport function createEngine(world: World, opts?: EngineOpts): Engine {\n const pipeline = createPipelineRegistry();\n const reflectors = createReflectorRegistry(\n world,\n opts?.onReflectorFault ? { onFault: opts.onReflectorFault } : undefined,\n );\n const publishHooks: PublishEntry[] = [];\n /** After-step hooks (design-015 §9, D2b): run once every `step` is over, in registration order. */\n const afterHooks: (() => void)[] = [];\n // The per-frame SNAPSHOT (rebuilt only when the registration set changes, so\n // steady state allocates nothing). Iterating the live array let a hook that\n // removed itself — or an earlier hook — shift the array under the index-based\n // iterator and silently SKIP its neighbour that frame. The contract now:\n // every hook registered at frame start runs exactly once, unless it is\n // unregistered before its turn; a hook registered DURING publish runs next\n // frame (deterministic, and the same rule design-009 gives behaviors).\n let publishSnapshot: PublishEntry[] = [];\n let publishDirty = true;\n const frame = createFrameControl(world);\n // THE SLEEP (K7a, frame-control.ts): a write made outside a step wakes a sleeping loop — one inside a step is the step's own\n watchWrites(world, () => frame.wake(\"world\"));\n\n let telemetryArmed = false;\n // Telemetry armed ⇒ devtools attached ⇒ the breaker reports timing overruns\n // instead of suspending (the throw ladder still bites). Read through a\n // closure so arming later still reaches the registry.\n const guests: GuestRegistryInternal = createGuestRegistry(world, {\n lenient: () => telemetryArmed,\n ...(opts?.onGuestFault ? { onFault: opts.onGuestFault } : {}),\n ...(opts?.onGuestNotice ? { onNotice: opts.onGuestNotice } : {}),\n });\n // A freeze must not photograph the canvas between a structural change and the\n // guest-owned reflow that answers it (design-002 §1's settle protocol).\n frame.settleWhile(\"guests\", () => guests.anyBusy());\n let last: FrameTelemetry | undefined;\n let building: {\n tick: number;\n systems: SystemRunRecord[];\n phaseFlushMicros: Map<string, number>;\n } | null = null;\n\n return {\n world,\n frame,\n guests,\n\n addSystems(group, ...systems) {\n return pipeline.add(group, ...systems);\n },\n\n reflectorNames() {\n return reflectors.names();\n },\n registerReflector(def) {\n return reflectors.register(def);\n },\n\n onPublish(hook) {\n const entry: PublishEntry = { hook, alive: true };\n publishHooks.push(entry);\n publishDirty = true;\n return () => {\n if (!entry.alive) return;\n entry.alive = false;\n const i = publishHooks.indexOf(entry);\n if (i !== -1) publishHooks.splice(i, 1);\n publishDirty = true;\n };\n },\n\n step(now) {\n frame.enterStep();\n try {\n setFrameInfo(world, now);\n world.sync();\n world.tick(pipeline.assemble());\n const info = world.getResource(FrameInfo);\n guests.runAll({\n dtMs: info?.dt ?? 0,\n tick: info?.tick ?? 0,\n clock: info?.clock ?? 0,\n });\n if (publishDirty) {\n publishSnapshot = publishHooks.slice();\n publishDirty = false;\n }\n for (const entry of publishSnapshot) {\n if (entry.alive) entry.hook(world);\n }\n world.reactive.notify();\n reflectors.flushAll();\n if (afterHooks.length > 0) for (const hook of afterHooks.slice()) hook();\n } finally {\n frame.leaveStep();\n }\n },\n\n afterStep(hook) {\n afterHooks.push(hook);\n return () => {\n const i = afterHooks.indexOf(hook);\n if (i !== -1) afterHooks.splice(i, 1);\n };\n },\n\n enableTelemetry() {\n if (telemetryArmed) return;\n telemetryArmed = true;\n reflectors.armTelemetry();\n world.observe({\n onTickStart(tick) {\n building = { tick, systems: [], phaseFlushMicros: new Map() };\n },\n onSystemRun(phaseName, system, ran, micros) {\n building?.systems.push({ phase: phaseName, system, ran, micros });\n },\n onPhaseFlush(phaseName, micros) {\n building?.phaseFlushMicros.set(phaseName, micros);\n },\n onTickEnd(tick, micros) {\n if (building === null || building.tick !== tick) return;\n last = {\n tick,\n totalMicros: micros,\n systems: building.systems,\n phaseFlushMicros: building.phaseFlushMicros,\n // step() overwrites these post-notify — captured lazily below.\n reflectorsFlushed: [],\n reflectMicros: 0,\n reflectorMicros: new Map(),\n };\n building = null;\n },\n });\n },\n\n disposeGuests() {\n guests.dispose();\n },\n\n lastFrame() {\n if (last === undefined) return undefined;\n // Reflector flush happens after onTickEnd, so splice the registry's\n // latest readout in at read time (same frame: step() is synchronous).\n return {\n ...last,\n reflectorsFlushed: reflectors.lastFlushed(),\n reflectMicros: reflectors.lastFlushMicros(),\n reflectorMicros: reflectors.lastFlushDetail(),\n };\n },\n };\n}\n","/**\n * The desk's vocabulary (design-015 §4.2, §5.1 — D2a-core, 2026-09-25).\n *\n * ADDITIVE: nothing in the DOM/GL paths reads or writes these, and a board of\n * pre-desk widgets carries none of them, so every existing order and every\n * existing gesture is what it was.\n *\n * - `Stratum` — which stratum of the desk an object lies in. A runtime rider\n * exactly like the capability tags: derivable from the widget TYPE (its\n * declared `stratum`, an `object` defaulting to `things`), so equip stamps it\n * at projection on every peer and nothing syncs it (design-013 D4's argument\n * for `SurfaceKind`, applied to the one presentation fact that survives the\n * desk). `compareStackOrder` reads it FIRST, so pick order is paint order\n * across kinds (design-015 §4.2's table, D-D4).\n * - `Locked` — the tape (*Marks on the Mat* Q-e): a taped widget is never\n * moved or resized by a gesture (moveClaim and resizeClaim give it no rider)\n * and the marquee passes over it (Q-g), yet it stays selectable, pickable and\n * openable. A DURABLE TAG — document truth that syncs and undoes — with one\n * writer, `ops.setLocked` (one transaction). A tag rather than a zero-field\n * component because a marker IS strata's tag (\"a zero-sized marker\", its own\n * `defineTag` doc) and *Marks on the Mat* named it one; the document holds one\n * `tag:Locked` register per entity. Tags are not prefab-eligibility-checked\n * (guards/guarded-tx.ts header — \"optional-tag modeling is future work\"), so\n * any durable widget carries it with no prefab declaration.\n */\nimport { enumOf, field, type Entity } from \"@vibecook/strata-ecs\";\nimport { defineComponent, defineResource, defineTag } from \"../schema/meta\";\n\n/** A desk stratum an object can declare (design-015 §4.2). The mat, the held set and the marks are the renderer's, never declared. */\nexport type DeskStratum = \"pads\" | \"sheets\" | \"things\";\n\n/**\n * `Stratum.band` per declared stratum — ascending = paint order: pads lie under\n * everything on a desk (the calendar pad), sheets lie flat on the mat and hold a\n * desk (the mini mats), things are every other object.\n */\nexport const STRATUM_BANDS: Readonly<Record<DeskStratum, number>> = Object.freeze({\n pads: 0,\n sheets: 1,\n things: 2,\n});\n\n/**\n * The band an entity WITHOUT a `Stratum` sorts in: things. Every pre-desk widget\n * is one, so an all-dom board stays in one band and its order is exactly its\n * sibling order, as before (design-015 §4.2: \"things … every future kind\").\n */\nexport const DEFAULT_STRATUM_BAND = STRATUM_BANDS.things;\n\n/** Runtime: the object's desk stratum (equip, from the type's `stratum`). Read by `compareStackOrder`. */\nexport const Stratum = defineComponent(\"Stratum\", {\n band: field(\"u8\", { default: DEFAULT_STRATUM_BAND }),\n});\n\n/** Durable: taped down (design-015 §5.1, Q-e). One writer: `ops.setLocked`. */\nexport const Locked = defineTag(\"Locked\");\n\n/**\n * Runtime: the ONE focused editor is on this object (design-015 §5.1, §6.1 — D2c): a note being\n * written. One writer, the desk's typing session (`@ice/desk` objects/typing.ts); a runtime rider,\n * never in the document (a peer's editor is its own). While present it is a GESTURE CLAIM on the\n * object's cells — `makeDefaultMayDiverge` grants the divergence — so the session writes the note's\n * text LIVE through the guarded live writer and commits it ONCE when the session ends (design-001\n * §3's gesture protocol with the keyboard as the gesture: ⌘Z undoes a typing session, never a key).\n */\nexport const Editing = defineTag(\"Editing\");\n\n// ---------------------------------------------------------------- the opening (design-015 §8; D4b)\n\n/**\n * Runtime: this object is IN HAND (design-015 §8 — \"`Held` is the fact\"). ONE writer, the open\n * op: `ops.open(entity)` adds it (with a fresh `HeldView`) and `ops.putDown()` removes it; at most\n * one object on a desk carries it. The pickup's clock, the flight home, the blur amount and the\n * cover spring are the renderer's FLUX, never facts — the tag says only \"in hand\"; an object whose\n * tag just left is flying home in the renderer alone. While an object is held every pointer is\n * the held object's and the desk behind is inert (systems/held.ts). Never in the document.\n */\nexport const Held = defineTag(\"Held\");\n\n/**\n * Runtime: the user's facts about the object in hand — how close it was brought (`zoom`, 1 = the\n * reading size, 0.72 … 3) and where it was moved under the eye (`panX`/`panY`, CSS px from the\n * reading pose's centre). Written by the held input system from the wheel, a pinch and a pan; put\n * on with `Held` at the open and taken off with it. The renderer reads it to pose the object.\n */\nexport const HeldView = defineComponent(\"HeldView\", {\n zoom: field(\"f64\", { default: 1 }),\n panX: field(\"f64\", { default: 0 }),\n panY: field(\"f64\", { default: 0 }),\n});\n\n/**\n * Runtime, on the object in hand: its ACTIVE tool (design-015 §8; D3t-a — widget/held-tools.ts) — the\n * id of the held bar's `mode` in hand (the board's marker in blue, its eraser), and `prev` the one\n * before it (a `toggle` mode chosen again hands that one back). The USER's fact, never in the document.\n * Put on with `Held` by `ops.open` (the type's `heldTool` of its props, else its first mode; \"\" = none)\n * and taken off with it; `ops.useHeldTool` its only other writer. The kind's held behaviours read it.\n */\nexport const HeldTool = defineComponent(\"HeldTool\", {\n id: field(\"string\", { default: \"\" }),\n prev: field(\"string\", { default: \"\" }),\n});\n\n/**\n * A system's IN-TICK request to pick an object up or put it down (D2b's `NavIntent`, applied the\n * same way): the double-tap on an openable object asks to `open`; the ways back that are\n * gestures — a click on the soft desk, a pinch or ⌘-wheel in past 0.72×, a double-tap on the\n * held object's case — ask to `putDown`. The ops are structural (a tag and a component come and\n * go) and run outside the tick: the facade applies the request once `engine.step` returns.\n * `epoch` bumps per request; `target` is the object to open (unused on a put-down).\n */\nexport const HeldIntent = defineResource(\n \"HeldIntent\",\n {\n kind: field(enumOf([\"open\", \"putDown\"]), { default: \"open\" }),\n target: field(\"eid\", { default: 0 as Entity }),\n epoch: field(\"u32\", { default: 0 }),\n },\n { durable: false },\n);\n\n/**\n * A zoom-out put the object down and the REST OF THAT GESTURE is muted (design-015 §8 — \"the v2\n * lesson\"): until `until` (the frame clock, ms) every wheel fact is swallowed before the camera\n * can read it, and each swallowed event pushes the mute 250 ms further. One writer: the held\n * input system.\n */\nexport const HeldMute = defineResource(\"HeldMute\", { until: field(\"f64\", { default: 0 }) }, { durable: false });\n\n/**\n * Runtime, on a LOCAL pointer while an object is held: where the pointer is in the held object's\n * OWN frame — its open extent's units, centred, mapped through the same pose the renderer drew\n * (`HeldPoseSource`) — and whether it is over the object at all. Change-only. What a kind's held\n * behaviours (its parts, its pen — D3t) read; absent when nothing is held or before the first frame.\n * `part` (D3t-a): the kind's part under it as the renderer drew it (the pose seam's `part` — the\n * board's melamine `content`, its aluminium `frame`), \"\" over nothing.\n */\nexport const HeldPointer = defineComponent(\"HeldPointer\", {\n x: field(\"f64\", { default: 0 }),\n y: field(\"f64\", { default: 0 }),\n inside: field(\"bool\", { default: false }),\n part: field(\"string\", { default: \"\" }),\n});\n\n/**\n * Runtime, on a local pointer: a press that began while an object was held — on the soft desk\n * (`desk`: released unmoved, it puts the object down; dragged with the object brought close, it\n * pans), as a pan (`pan`: a middle button or Space, the object brought close), on the object's\n * drawing surface with a mode in hand (`tool`, D3t-a: the TOOL's press — the board's stroke; never\n * a tap that puts it down), on one of the kind's named PARTS (`part`, D3t-b: the kind's own — a\n * notebook's turn, its click and its drag; never a tap that puts it down) or elsewhere on the object\n * itself (`object`: two instant taps put it down). `part`: the part it began on (\"\" — none); `x`/`y`\n * where it began (CSS px), the pan it began from, and whether it has moved past the slop. `count`\n * (design-019 §5, M24 LT2): its CLICK COUNT — 1, then 2, 3… for each primary press that lands within\n * the desk's multi-tap window and slop of the one before (`HeldPressMemo`; a pointerdown's `detail`\n * is 0 in the browser, so the desk counts — by the down events' own times); a middle press's is 1.\n */\nexport const HeldPress = defineComponent(\"HeldPress\", {\n kind: field(enumOf([\"desk\", \"pan\", \"object\", \"tool\", \"part\"]), { default: \"desk\" }),\n part: field(\"string\", { default: \"\" }),\n x: field(\"f64\", { default: 0 }),\n y: field(\"f64\", { default: 0 }),\n panX0: field(\"f64\", { default: 0 }),\n panY0: field(\"f64\", { default: 0 }),\n moved: field(\"bool\", { default: false }),\n count: field(\"u32\", { default: 1 }),\n});\n\n/**\n * The last PRIMARY press in hand (design-019 §5, M24 LT2): where it began (CSS px), when (its down event's own time — the frame's\n * `now` for an input with none) and its click count — the next primary press within `GestureSettings.multiTapWindowMs` and\n * `multiTapSlopPx` of it counts on (down to down, any pointer: each touch is a pointer of its own). Cleared when nothing is held.\n */\nexport const HeldPressMemo = defineResource(\n \"HeldPressMemo\",\n { x: field(\"f64\", { default: 0 }), y: field(\"f64\", { default: 0 }), at: field(\"f64\", { default: 0 }), count: field(\"u32\", { default: 0 }) },\n { durable: false },\n);\n\n/**\n * Runtime, on a local pointer while an object is held whose kind takes the WHEEL (`OpenBinding.wheel: \"kind\"` — design-019 §5, M24\n * LT2): the plain wheel's deltas of the last tick that had any, CSS px of the hand, and `seq` — moved once per such tick, so the\n * desk tells the kind each tick's wheel once (`HeldEvent` \"wheel\"). ⌘/ctrl-wheel and the pinch stay the hand's (they zoom it).\n */\nexport const HeldWheel = defineComponent(\"HeldWheel\", {\n dx: field(\"f64\", { default: 0 }),\n dy: field(\"f64\", { default: 0 }),\n seq: field(\"u32\", { default: 0 }),\n});\n\n/** The last instant tap on the held object: where and when — a second within the window puts it down (the notebook's case, generalised). */\nexport const HeldTapMemo = defineResource(\n \"HeldTapMemo\",\n { x: field(\"f64\", { default: 0 }), y: field(\"f64\", { default: 0 }), at: field(\"f64\", { default: 0 }), seq: field(\"u32\", { default: 0 }) },\n { durable: false },\n);\n\n/**\n * Runtime, ONE per view: THE TRAY (design-016 §7, K-L6; design-017 §2 — K3) — the pegboard drawer's facts. `open`; `scroll`, CSS px\n * of board past its top, within `[0, max]` (the renderer's word on `max` rides the tray pose seam, systems/tray.ts); `stretch`, the\n * rubber band's pull past an end (raw px, signed; 0 at rest); `wheelAt`, the frame clock (ms) of the last scroll input (every wheel\n * the drawer takes while out, a drag on its board) — the band lets go once it is quiet, and a drawer shut before then keeps the wheel\n * until it is (K9). Never in the document, never synced:\n * a peer's tray is its own. Writers: the tray ops (ops/tray.ts) and `trayInput` — and `trayLay`, which clamps `scroll` when a lay\n * or the drawer's face moves its range (K9, D-K9-c.2); the renderer reads it, and owns the motion (the\n * slide, the band's settle — flux). The entity is ensured at install and after every reset (a document switch\n * closes the tray); it roots the tray's runtime canvas (K5's specimens will be its children). design-018 §5 (R2): the lip's hover\n * fact retired with its handle — a closed drawer takes no pointer; its handle is the app's DOM bar (`<TrayBar>`, @ice/react).\n */\nexport const Tray = defineComponent(\"Tray\", {\n open: field(\"bool\", { default: false }),\n scroll: field(\"f64\", { default: 0 }),\n stretch: field(\"f64\", { default: 0 }),\n wheelAt: field(\"f64\", { default: 0 }),\n /**\n * @deprecated Legacy wheel-tail bookkeeping, retained for component compatibility. Wheel scrolling now stays within its\n * bounds and consumes the OS's momentum directly; trayInput no longer reads or writes these fields.\n */\n wheelDy: field(\"f64\", { default: 0 }),\n /** @deprecated See wheelDy. */\n fade: field(\"u32\", { default: 0 }),\n /** K5a: the type of the specimen under the mouse while the drawer is out (\"\" — none): the hover that lifts it (flux). */\n hover: field(\"string\", { default: \"\" }),\n /**\n * K5b — TAKING ONE (design-017 §9): the type whose copy a pointer has lifted off the board (\"\" — none): pressed on its specimen and\n * moved past the slop, still inside the drawer. `takeU`/`takeV` the grab point (0 … 1 across the object as the board draws it — the\n * spot under the finger stays that spot of the object), `takeX`/`takeY` the pointer as last seen (CSS px) — the copy follows it\n * (flux). `handed` counts the takes handed to the desk: it bumps on the tick the copy leaves the drawer's open rect (the drawer slides\n * away, `TrayIntent` spawns the insert ghost after the step); a take that ends without the bump was put back.\n */\n take: field(\"string\", { default: \"\" }),\n takeU: field(\"f64\", { default: 0.5 }),\n takeV: field(\"f64\", { default: 0.5 }),\n takeX: field(\"f64\", { default: 0 }),\n takeY: field(\"f64\", { default: 0 }),\n handed: field(\"u32\", { default: 0 }),\n /**\n * design-018 §6 (R2) — THE FILTER: the tray category the drawer shows (\"\" — all), a tray entry's `category` string (`defineObject({\n * tray: { category } })`). A fact of the view beside `open` — never durable, never synced (each tab its own). Writers: the op\n * `setTrayCategory` (the bar's chips, the desk handle's door) and `trayLay` — which lays only that category's entries, zeroes the\n * scroll and the band when it moves, and falls back to all (\"\") when the frame hangs none of it.\n */\n category: field(\"string\", { default: \"\" }),\n /**\n * Petition I37 — THE KEYBOARD FOCUS on the board: the type of the specimen it is on (\"\" — none), a fact of the view like `hover`.\n * Its writer is the op `focusTray` (next/prev/first/last along the lay's order, or a type by its id); `trayLay` scrolls the\n * specimen it moves to into the board's face, and lets it go when what it was on is laid no more (a category, a frame). The\n * renderer draws no ring for it: a host does, from the desk handle's `TrayAnchor.focused`.\n */\n focus: field(\"string\", { default: \"\" }),\n});\n\n/**\n * K5b — the tray's IN-TICK request to hand a taken copy to the desk (design-017 §9; `HeldIntent`'s shape): the copy left the drawer, so\n * the facade calls `ops.insertByDrag` once the step returns — the op spawns and enqueues, which no system does mid-tick. `type` the\n * object type; `x`/`y` the pointer (CSS px) and `pointerId`/`device`/`buttons` its press, which the insert ghost's synthetic down takes\n * over; `u`/`v` the grab point (the insert's `anchor` — no centre-snap); `homeX`/`homeY` the specimen's spot on screen (the insert's\n * `home`, where a cancel flies the ghost back). `epoch` bumps per request.\n */\nexport const TrayIntent = defineResource(\n \"TrayIntent\",\n {\n type: field(\"string\", { default: \"\" }),\n x: field(\"f64\", { default: 0 }),\n y: field(\"f64\", { default: 0 }),\n pointerId: field(\"string\", { default: \"mouse\" }),\n device: field(enumOf([\"mouse\", \"touch\", \"pen\"]), { default: \"mouse\" }),\n buttons: field(\"u32\", { default: 1 }),\n u: field(\"f64\", { default: 0.5 }),\n v: field(\"f64\", { default: 0.5 }),\n homeX: field(\"f64\", { default: 0 }),\n homeY: field(\"f64\", { default: 0 }),\n epoch: field(\"u32\", { default: 0 }),\n },\n { durable: false },\n);\n\n/**\n * Runtime, on the TRAY entity (design-017 §8; K5a): what the lattice law last laid (systems/tray.ts `createTrayLay`) — the drawer's\n * width it laid for (CSS px, the renderer's word through the pose seam), the content's foot (board px — the scroll's range is that\n * plus a pitch less the face, the renderer's to say) and how many lays so far (a renderer re-reads the specimens when it moves).\n * design-018 §6 (R2): `present`, what the frame could hang before the category's filter — its entries' categories in the lay's\n * order with their counts, JSON `[id, count][]` (\"\" for an entry that names none); `trayCategories` reads it. Petition I37:\n * `order`, the types laid, in the lay's order (row by row) — JSON `string[]`; what the keyboard focus walks (`focusTray`). The\n * specimens' sibling order is not it: a re-lay keeps a specimen where it hangs and appends the new ones.\n */\nexport const TrayContent = defineComponent(\"TrayContent\", {\n width: field(\"f64\", { default: 0 }),\n bottom: field(\"f64\", { default: 0 }),\n laid: field(\"u32\", { default: 0 }),\n present: field(\"string\", { default: \"[]\" }),\n order: field(\"string\", { default: \"[]\" }),\n});\n\n/**\n * Runtime tag: a SPECIMEN (design-017 §8; K5a) — a kind hung on the pegboard tray: `ChildOf` the tray entity (which roots its\n * runtime canvas), `PrefabId` the kind's widget type, `Position` board px (x from the drawer's left edge, y down from the board's\n * top at scroll 0), `Size` its hang's, its entry's props over the widget's defaults. Spawned equipped (no capability tag, no\n * rider, no behaviour — nothing acts on it) and under a canvas that is no frame, so never `Active`: the desk's stack never picks,\n * selects, culls or saves one; never durable, never synced. A host that walks \"the document's widgets\" by `[Position, Size, PrefabId]`\n * excludes it (`Not(Specimen)`) — a durable transaction over a runtime entity is refused (\"op references an entity not in this store\").\n */\nexport const Specimen = defineTag(\"Specimen\");\n\n/**\n * Runtime, on a local pointer: a press the TRAY took (design-017 §4) — on the open drawer (`board`: a drag scrolls it), on the dimmed\n * desk (`desk`: released unmoved, it closes the drawer); a closed drawer takes none (design-018 §5: the lip's `lip` press retired).\n * Where it began (CSS px), the scroll it began from, whether it moved past the slop. K5b (§9): on a SPECIMEN (`specimen`: past the\n * slop its copy lifts; out of the drawer it is handed to the desk) — its `type`, the grab point `u`/`v` across the object as drawn,\n * the specimen's centre on screen `homeX`/`homeY`; and, once handed, the take CARRIED (`carry`: the insert ghost's drag is this\n * pointer's — released back over the drawer as drawn, still sliding away, it is cancelled and the ghost flies home).\n */\nexport const TrayPress = defineComponent(\"TrayPress\", {\n kind: field(enumOf([\"board\", \"desk\", \"specimen\", \"carry\"]), { default: \"desk\" }),\n x: field(\"f64\", { default: 0 }),\n y: field(\"f64\", { default: 0 }),\n scroll0: field(\"f64\", { default: 0 }),\n moved: field(\"bool\", { default: false }),\n type: field(\"string\", { default: \"\" }),\n u: field(\"f64\", { default: 0.5 }),\n v: field(\"f64\", { default: 0.5 }),\n homeX: field(\"f64\", { default: 0 }),\n homeY: field(\"f64\", { default: 0 }),\n});\n","/**\n * PhaseSet — an exclusive tag-encoded state machine with one-tick transition markers\n * (design-003 §4.2, design-002 §2/§3).\n *\n * A phase set is a small, fixed list of mutually-exclusive phases (e.g. a recognizer's\n * `Possible → Active → Ended`). For each phase it mints two tags via the schema wrapper,\n * named by PLAIN CONCATENATION so the doc vocabulary holds (design-001 §5.5: the catalog's\n * gesture set is definePhaseSet(\"Gesture\", [\"Possible\", …]) → \"GesturePossible\"):\n * - a persistent phase tag `${name}${phase}` — \"the entity is in this phase\"\n * - a one-tick `Just` marker `${name}Just${phase}` — \"the entity ENTERED this phase this frame\"\n *\n * Why two tags: terminal phases persist through the reap window (design-003 §4.1), so a\n * behavior that acted on the persistent tag would fire on every frame the tag lingers.\n * Behaviors therefore **edge-trigger on the `Just*` markers only** — discrete actions and\n * terminal handling fire exactly once (design-003 §4.2: shift-tap toggles once, commits\n * never double). The persistent tag is for per-frame work that legitimately repeats.\n *\n * Transition timing: `set` mutates through the caller's structural writer. When that writer\n * is a {@link SystemCtx} the add/remove are DEFERRED to the current strata-phase flush\n * (design-002 §3); consumers in a LATER sub-phase see the new phase the same frame, and\n * that ordering is guaranteed by the sub-phase pipeline layout (design-002 §2), never by\n * immediate application. When the writer is the `World` (app handlers / setup) the writes\n * are immediate. The one-tick markers are cleared by the cleanup phase via\n * {@link PhaseSet.clearMarkers} over {@link PhaseSet.allMarkerTags}.\n */\n\nimport type { Entity, Tag } from \"@vibecook/strata-ecs\";\nimport { devGuardsEnabled } from \"../guards/dev\";\nimport { defineTag } from \"../schema/meta\";\n\n/**\n * The minimal structural-write surface `set`/`clearMarkers` need. Both `SystemCtx` (deferred\n * to the phase flush) and `World` (immediate) satisfy it structurally — the transition is\n * agnostic to which, and the timing follows from the writer (see the module doc).\n */\nexport interface StructuralTagWriter {\n addTag(e: Entity, t: Tag): void;\n removeTag(e: Entity, t: Tag): void;\n}\n\n/** The minimal read surface `current` needs — again satisfied by both `SystemCtx` and `World`. */\nexport interface TagReader {\n hasTag(e: Entity, t: Tag): boolean;\n}\n\n/** The handle returned by {@link definePhaseSet}. `P` is the literal union of phase names. */\nexport interface PhaseSet<P extends string> {\n /** The set name — the prefix of every minted tag. */\n readonly name: string;\n /** The phases in declaration order (the scan order of {@link PhaseSet.current}). */\n readonly phases: readonly P[];\n /** Persistent phase tags, keyed by phase name. */\n readonly tags: Readonly<Record<P, Tag>>;\n /** One-tick `Just<Phase>` marker tags, keyed by phase name. */\n readonly justTags: Readonly<Record<P, Tag>>;\n /** Every marker tag — the cleanup phase clears these once the frame's edges are consumed. */\n readonly allMarkerTags: readonly Tag[];\n /**\n * Transition `e` into `next`: drop the current phase tag + its now-stale marker and add\n * `next` + its fresh `Just` marker (exclusivity is enforced by clearing every phase tag,\n * so a mis-set entity converges). Unknown `next` throws. A transition to the phase the\n * entity is already in is a no-op with a DEV warn (detected only when `m` can also read —\n * `SystemCtx`/`World` both can).\n */\n set(m: StructuralTagWriter, e: Entity, next: P): void;\n /** The entity's current phase, or `undefined` if it holds none. Small-N `hasTag` scan. */\n current(world: TagReader, e: Entity): P | undefined;\n /** Clear every one-tick marker off `e` (the cleanup-phase step). */\n clearMarkers(m: StructuralTagWriter, e: Entity): void;\n}\n\n/** Narrow a structural writer that also happens to read (for the DEV double-set guard). */\nfunction hasReader(m: object): m is TagReader {\n return \"hasTag\" in m && typeof (m as TagReader).hasTag === \"function\";\n}\n\n/**\n * Define an exclusive PhaseSet: one persistent tag + one one-tick `Just` marker per phase.\n * Handles are process-global schema constants (hold them as module constants). See the module\n * doc for transition timing and the edge-trigger contract.\n */\nexport function definePhaseSet<const P extends string>(name: string, phases: readonly P[]): PhaseSet<P> {\n const tags = {} as Record<P, Tag>;\n const justTags = {} as Record<P, Tag>;\n const allMarkerTags: Tag[] = [];\n for (const phase of phases) {\n tags[phase] = defineTag(`${name}${phase}`);\n const marker = defineTag(`${name}Just${phase}`);\n justTags[phase] = marker;\n allMarkerTags.push(marker);\n }\n\n const set: PhaseSet<P>[\"set\"] = (m, e, next) => {\n const nextTag = tags[next];\n if (nextTag === undefined) {\n throw new Error(\n `ice: definePhaseSet(\"${name}\").set — unknown phase \"${next}\" (known: ${phases.join(\", \")}).`,\n );\n }\n if (devGuardsEnabled() && hasReader(m) && m.hasTag(e, nextTag)) {\n // Already in `next` — the transition is a no-op. Warn and skip so the fresh marker\n // is not re-emitted (which would edge-trigger downstream behaviors a second time).\n // BEST-EFFORT detection only: a SystemCtx's hasTag reads pre-flush state, so a\n // deferred same-body double-set is invisible here. That miss is harmless — the\n // clear-then-add below is idempotent and tags dedupe, so the marker still fires\n // exactly once. Reliable detection holds for immediate writers (World).\n console.warn(`ice: definePhaseSet(\"${name}\").set — entity is already in phase \"${next}\"; no-op.`);\n return;\n }\n // Exclusivity: clear every phase tag + every marker (no-op for absent ones), then set\n // `next` + its marker. This subsumes \"remove the current phase + its stale marker\" and\n // converges a mis-set entity to exactly one phase.\n for (const phase of phases) {\n m.removeTag(e, tags[phase]);\n m.removeTag(e, justTags[phase]);\n }\n m.addTag(e, nextTag);\n m.addTag(e, justTags[next]);\n };\n\n const current: PhaseSet<P>[\"current\"] = (world, e) => {\n for (const phase of phases) {\n if (world.hasTag(e, tags[phase])) return phase;\n }\n return undefined;\n };\n\n const clearMarkers: PhaseSet<P>[\"clearMarkers\"] = (m, e) => {\n for (const marker of allMarkerTags) m.removeTag(e, marker);\n };\n\n return { name, phases, tags, justTags, allMarkerTags, set, current, clearMarkers };\n}\n","/**\n * Recognizers & gestures — the L2 runtime recognizer prefabs (design-001 §5.5,\n * design-003 §4).\n *\n * Identity is the KIND component (its presence is the kind; its fields are the\n * working value). Phase is a tag-of-set flipped by the engine PhaseSet helper\n * (strata has no one-of primitive; `Pending` was dropped as dead machinery). All\n * in-flight state lives on the recognizer entity or the grabbed widgets — no\n * singleton trackers — so N concurrent same-kind gestures are structural.\n *\n * Field set for each kind matches design-003 §4.2's revised table (which adds\n * `zoomAtClaim` to Drag and Pinch over design-001 §5.5).\n *\n * Defaults policy (see catalog/index.ts): kind components and per-frame working\n * riders are runtime scratch spawned/written by systems, so they carry full\n * zero/identity defaults (ergonomic `ctx.spawn`). Origin-latch riders that MUST\n * carry real values (Grab, Down) stay bare so a defaulted origin can't silently\n * corrupt a cancel-restore.\n */\nimport { enumOf, field, type Entity } from \"@vibecook/strata-ecs\";\nimport { definePhaseSet } from \"../helpers/phase-set\";\nimport { defineComponent, defineRelation, defineTag } from \"../schema/meta\";\nimport { GESTURE_DEFAULTS } from \"../settings/defaults\";\n\n// --- kind components (design-003 §4.2) ---\n\n/** Continuous drag. Origin from dead-zone exit; totals/velocities accumulate; `zoomAtClaim` anchors widget-move math. */\nexport const Drag = defineComponent(\"Drag\", {\n startX: field(\"f64\", { default: 0 }),\n startY: field(\"f64\", { default: 0 }),\n totalX: field(\"f32\", { default: 0 }),\n totalY: field(\"f32\", { default: 0 }),\n velX: field(\"f32\", { default: 0 }),\n velY: field(\"f32\", { default: 0 }),\n zoomAtClaim: field(\"f32\", { default: 1 }),\n});\n\n/**\n * Discrete tap — claims at up within the tap window & slop. `count` is the\n * multi-tap tally (v2 gesture.ts): 0 while the (next) tap is in progress; each\n * clean release increments it. Without a `MultiTap` opt-in on the capture\n * target the first release Recognizes at count 1 — zero added latency.\n */\nexport const Tap = defineComponent(\"Tap\", {\n downAt: field(\"f64\", { default: 0 }),\n count: field(\"u32\", { default: 0 }),\n});\n\n/** Discrete-with-tail: claims at the long-press hold, then tracks cur X/Y per frame (touch marquee rides it). */\nexport const LongPress = defineComponent(\"LongPress\", {\n downAt: field(\"f64\", { default: 0 }),\n startX: field(\"f64\", { default: 0 }),\n startY: field(\"f64\", { default: 0 }),\n curX: field(\"f64\", { default: 0 }),\n curY: field(\"f64\", { default: 0 }),\n});\n\n/** Continuous two-finger pinch. `startDist` re-baselines at activation; `cx/cy` is the centroid. */\nexport const Pinch = defineComponent(\"Pinch\", {\n startDist: field(\"f32\", { default: 0 }),\n startZoom: field(\"f32\", { default: 1 }),\n cx: field(\"f64\", { default: 0 }),\n cy: field(\"f64\", { default: 0 }),\n zoomAtClaim: field(\"f32\", { default: 1 }),\n});\n\n/** Continuous wheel pan (`Simultaneous` — never claims pointers). `anchorX/Y` is the screen anchor. */\nexport const WheelPan = defineComponent(\"WheelPan\", {\n dx: field(\"f32\", { default: 0 }),\n dy: field(\"f32\", { default: 0 }),\n anchorX: field(\"f32\", { default: 0 }),\n anchorY: field(\"f32\", { default: 0 }),\n});\n\n/** Continuous wheel zoom (`Simultaneous`). `pinch` is the accumulated zoom signal; `anchorX/Y` the pin point. */\nexport const WheelZoom = defineComponent(\"WheelZoom\", {\n pinch: field(\"f32\", { default: 0 }),\n anchorX: field(\"f32\", { default: 0 }),\n anchorY: field(\"f32\", { default: 0 }),\n});\n\n// --- phases (exclusive set + one-tick Just* markers; flipped via the PhaseSet helper) ---\n\n/**\n * The recognizer lifecycle as ONE PhaseSet (design-003 §4.2): seven mutually-exclusive\n * phases. Each mints a persistent `Gesture<Phase>` tag AND a one-tick `GestureJust<Phase>`\n * marker (plain concatenation — the doc vocabulary \"GesturePossible\"… is unchanged), so\n * behaviors edge-trigger discrete/terminal actions on the markers exactly once while a\n * terminal tag lingers through the reap window (§4.2, §4.1). The named phase tags below\n * are re-exports of `GesturePhases.tags.*` for ergonomics + `ops/claims` compatibility.\n * `GesturePossible` etc. is the ONLY definition path for these tag names (strata's schema\n * registry is process-global — a second `defineTag(\"GesturePossible\")` would throw).\n *\n * `Pending` (restored from v2 gesture.ts — the design-003 §4.2 \"dead machinery\" drop is\n * superseded now that a real gesture ships it): criteria met but recognition withheld —\n * a multi-tap awaiting its inter-tap window, or a recognizer parked behind a\n * `Sequence`/`RequiresFail` edge. NEVER reaped; exempt from integrity's watched-pointer\n * count (a pending multi-tap legitimately outlives its lifted touch pointer).\n */\nexport const GesturePhases = definePhaseSet(\"Gesture\", [\n \"Possible\",\n \"Active\",\n \"Pending\",\n \"Recognized\",\n \"Ended\",\n \"Failed\",\n \"Cancelled\",\n] as const);\n\n/** Recognizer alive, not yet claiming. */\nexport const GesturePossible = GesturePhases.tags.Possible;\n\n/** Continuous kinds' claiming phase + per-frame work gate. */\nexport const GestureActive = GesturePhases.tags.Active;\n\n/** Recognition withheld (multi-tap window / dependency edge); never reaped. */\nexport const GesturePending = GesturePhases.tags.Pending;\n\n/** Discrete kinds' terminal claim. */\nexport const GestureRecognized = GesturePhases.tags.Recognized;\n\n/** Continuous kinds' terminal (release). */\nexport const GestureEnded = GesturePhases.tags.Ended;\n\n/** Recognizer failed its predicate or lost arbitration. */\nexport const GestureFailed = GesturePhases.tags.Failed;\n\n/** Recognizer cancelled (pointercancel / integrity / CancelRequest). */\nexport const GestureCancelled = GesturePhases.tags.Cancelled;\n\n/** Suspended (a pinch suspends the single-pointer recognizers) — \"suspend, don't kill\". */\nexport const GestureSuspended = defineTag(\"GestureSuspended\");\n\n/**\n * The recognizer latched a `Captures` target at spawn (design-003 §4.1 integrity).\n * Relations auto-clear on target despawn, so \"had a capture, has none now\" is\n * detectable only with this spawn-time mark — integrity cancels on that edge loss.\n */\nexport const HadCapture = defineTag(\"HadCapture\");\n\n/** Runs alongside claims without competing (wheel pan/zoom) — keeps zoom-while-dragging legal. */\nexport const Simultaneous = defineTag(\"Simultaneous\");\n\n// --- route tags (latched at drag activation; never change mid-gesture, design-003 §4.4) ---\n\n/** A group-move intent, latched at pointer-down so custom carries can yield before lifting. */\nexport const MovesSelection = defineTag(\"MovesSelection\");\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\n/**\n * A move drag that STARTED with ⌥ held (latched by moveClaim, like a route): its release leaves a copy of every\n * widget it carried where that widget lay, just under it, in the move's one transaction (*Marks on the Mat*'s\n * keys — \"⌥ as the drag starts leaves a copy behind\"; design-015 D4a). Runtime, on the recognizer.\n */\nexport const LeavesCopy = defineTag(\"LeavesCopy\");\n/** Draw-tool drag: the release rect creates a widget (design-005 §3, M10). */\nexport const RoutedDraw = defineTag(\"RoutedDraw\");\n\n/**\n * Per-target multi-tap opt-in (v2 gesture.ts): declares \"this target counts\n * multi-taps\", read via the recognizer's `Captures` target. Absent → max 1,\n * zero latency (a plain widget stays instant). `windowMs` = the inter-tap\n * wait; `slopPx` = max screen gap between taps for the rejoin.\n */\nexport const MultiTap = defineComponent(\"MultiTap\", {\n max: field(\"u32\", { default: 2 }),\n windowMs: field(\"f32\", { default: GESTURE_DEFAULTS.multiTapWindowMs }),\n slopPx: field(\"f32\", { default: GESTURE_DEFAULTS.multiTapSlopPx }),\n});\n\n// --- recognizer relations ---\n\n/** recognizer → watched pointer(s). */\nexport const Watches = defineRelation(\"Watches\", { arity: \"many\" });\n\n/**\n * Sequencing edges (v2 gesture.ts; resolved by the dependency system at the end\n * of `ctl:recognize`). `Sequence` gates the ENTRANCE: a `Pending` recognizer\n * waits for `after` to pass (Active/Recognized), then hands off — Down rebases\n * to the current pointer and the source retires. `RequiresFail` gates the EXIT:\n * a `Pending` recognizer finishes only once `other` fails (discrete →\n * Recognized, continuous → Active); if `other` wins, it loses. Edges auto-clear\n * on despawn, so each carries a `Had*` spawn-time mark (the `HadCapture`\n * pattern): \"had an edge, has none\" = orphaned → Failed.\n */\nexport const Sequence = defineRelation(\"Sequence\", { arity: \"one\" });\nexport const RequiresFail = defineRelation(\"RequiresFail\", { arity: \"one\" });\n\n/** The recognizer was given a `Sequence` edge (orphan detection — see above). */\nexport const HadSequence = defineTag(\"HadSequence\");\n\n/** The recognizer was given a `RequiresFail` edge (orphan detection — see above). */\nexport const HadRequiresFail = defineTag(\"HadRequiresFail\");\n\n/** recognizer → grabbed entity (widget/port/handle/canvas), latched at down. */\nexport const Captures = defineRelation(\"Captures\", { arity: \"one\" });\n\n/** recognizer → affected widgets (live edge set; remote despawns auto-clear their edge). */\nexport const Drags = defineRelation(\"Drags\", { arity: \"many\" });\n\n/** pointer → the recognizer that claimed it (arbitration output, design-003 §4.3). */\nexport const ClaimedBy = defineRelation(\"ClaimedBy\", { arity: \"one\" });\n\n/** recognizer → candidate container under the dragged bounds (design-003 §5 dropSystem). */\nexport const DropTarget = defineRelation(\"DropTarget\", { arity: \"one\" });\n\n// --- per-gesture riders ---\n\n/**\n * \"None\" sentinel for Grab's eid fields — strata's reserved null handle\n * (entity 0 is never live; generations start at 1).\n */\nexport const NO_ENTITY = 0 as Entity;\n\n/**\n * Per-dragged-widget origin, attached at claim time with the CURRENT transform embedded\n * (design-001 §3, design-003 §4.5). Bare on purpose: a defaulted zero origin would corrupt\n * the cancel-restore of Position and sibling order.\n *\n * `parent`/`prev`/`ord` are the ORDER MEMO (petition 8) — the claim-time\n * elevate is `moveRelation(w, ChildOf, \"last\")`, so cancel/fly-back must\n * remember where the widget SAT: its `ChildOf` parent (NO_ENTITY = no edge —\n * legacy world, nothing to restore), its nearest non-dragged predecessor\n * sibling (NO_ENTITY = it was first), and its original sibling index (`ord` —\n * the members' relative order at reinsert; see l3-behave's restore walk).\n */\nexport const Grab = defineComponent(\"Grab\", {\n x: \"f64\",\n y: \"f64\",\n w: \"f32\",\n h: \"f32\",\n parent: \"eid\",\n prev: \"eid\",\n ord: \"f64\",\n});\n\n/** Snap offset — in the Drag prefab's essential set (present from spawn, zeroed — writers never race an attach). */\nexport const SnapState = defineComponent(\"SnapState\", {\n dx: field(\"f32\", { default: 0 }),\n dy: field(\"f32\", { default: 0 }),\n});\n\n/**\n * The dragged set's POST-MOVE UNION BOUNDS, on the Drag RECOGNIZER — the heat's\n * one world fact (design-013 §5 rev 6; `draft/ground` GLOW.md §3).\n *\n * The overlap glow is CAST LIGHT: the lifted card's own SDF lights the target\n * beneath it, so the compose reflector needs to know where the lifted set IS.\n * That is not a new computation — `dropSystem` already unions the dragged\n * widgets' post-move `Position + Size` every frame to run its spatial query,\n * and then throws the number away. It writes it here instead, change-only over\n * all four fields, and the heat gets its geometry for free.\n *\n * The rest of the heat needs no component at all: the tier is the tags\n * `dropSystem` already writes (`OverlapCandidate` accept / `OverlapRejected`\n * reject), the target is the `DropTarget` relation, and the presence spring and\n * the held source are FLUX in the compose reflector's per-entity motion cache\n * (§3) — never in the world.\n *\n * In the Drag prefab's essential set beside {@link SnapState}: present from\n * spawn, zeroed, so writers never race an attach. Nothing clears it — the\n * recognizer is reaped at terminal + 1 (`systems/cleanup.ts`), and the\n * component dies with the entity.\n */\nexport const DragBounds = defineComponent(\"DragBounds\", {\n minX: field(\"f64\", { default: 0 }),\n minY: field(\"f64\", { default: 0 }),\n maxX: field(\"f64\", { default: 0 }),\n maxY: field(\"f64\", { 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/**\n * The card program's PART the pointer was on at the down (design-014, B3b) —\n * attached at recognizer spawn from the pointer's `PointerPart` when it names\n * one. Arbitration withholds the move route from a recognizer that carries\n * it (a press on a control never lifts the card); the tap behaviour hands the\n * tap to the app as a `PartTap` instead of selecting.\n */\nexport const DownPart = defineComponent(\"DownPart\", { part: \"string\" });\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 * Node graph — wires, ports, and containment contracts (design-001 §5.3, §5.8).\n *\n * Wires bind to widgets + port *ids* (durable); port *entities* are runtime and\n * materialize on demand (never per-visible-widget). Wire geometry comes from the\n * kernel's pure `portAnchor(...)`, so rendering never reads a port entity and\n * culled endpoints resolve by construction (design-001 §5.3 decision).\n *\n * Defaults policy (see catalog/index.ts): identity/essential fields a wire or\n * derive system always supplies stay bare (WirePorts.from/to, Port.id/side).\n * Derive-owned anchors and the container JSON lists carry ergonomic defaults.\n */\nimport { enumOf, field } from \"@vibecook/strata-ecs\";\nimport { defineComponent, defineRelation, defineTag } from \"../schema/meta\";\nimport { definePrefab, init } from \"../schema/prefab\";\n\n// --- durable wire prefab: a reified edge entity (relations carry no data) ---\n\n/** Marks an entity as a wire. */\nexport const Wire = defineTag(\"Wire\");\n\n/** wire → source widget (durable-eligible). */\nexport const WireFrom = defineRelation(\"WireFrom\", { arity: \"one\" });\n\n/** wire → target widget (durable-eligible). */\nexport const WireTo = defineRelation(\"WireTo\", { arity: \"one\" });\n\n/** The port ids (from each widget's port schema) the wire binds to. */\nexport const WirePorts = defineComponent(\"WirePorts\", { from: \"string\", to: \"string\" });\n\n// --- runtime port prefab: materializes on demand, derive-owned ---\n\n/** A widget port descriptor — spawned only for interaction (connect tool / hover proximity). */\nexport const Port = defineComponent(\"Port\", {\n id: \"string\",\n side: enumOf([\"n\", \"e\", \"s\", \"w\"]),\n index: field(\"u8\", { default: 0 }),\n});\n\n/** port → widget. */\nexport const PortOf = defineRelation(\"PortOf\", { arity: \"one\" });\n\n/** Derive-owned world coordinates of a port anchor. */\nexport const PortAnchor = defineComponent(\"PortAnchor\", {\n x: field(\"f64\", { default: 0 }),\n y: field(\"f64\", { default: 0 }),\n});\n\n// --- containment contracts (durable-eligible on container widget prefabs, RFC-004) ---\n\n/** Marks a widget as a container (accepts children via the drop system). */\nexport const Container = defineTag(\"Container\");\n\n/** JSON list of provides-keys this container accepts. */\nexport const Accepts = defineComponent(\"Accepts\", { list: field(\"string\", { default: \"[]\" }) });\n\n/** JSON list of provides-keys this widget offers to containers. */\nexport const Provides = defineComponent(\"Provides\", { list: field(\"string\", { default: \"[]\" }) });\n\n/**\n * The durable wire prefab (design-001 §5.3): WirePorts + the Wire tag +\n * eligible WireFrom/WireTo edges — the COMPLETE contract, so the doc commit\n * sink spawns through the paved `tx.spawnPrefab` path instead of a raw spawn\n * that bypassed eligibility checks (2026-07-13 review). Registered here so the\n * version gate stamps `engine.pack.wire.<v>` like every durable pack.\n */\nexport const WirePrefab = definePrefab(\"wire\", {\n store: \"durable\",\n version: 1,\n components: [init(WirePorts, { from: \"\", to: \"\" })],\n tags: [Wire],\n relations: [WireFrom, WireTo],\n});\n","/**\n * Scene & geometry catalog (design-001 §5.1).\n *\n * Pure components — \"durable-eligible\" is a property of the prefab that carries\n * them, never of the component (design-001 §2, rev 2). `Position` is reused by\n * cursor/chrome/pointer-adjacent runtime prefabs; that reuse is the point.\n *\n * Defaults policy (see catalog/index.ts): essential geometry that a prefab\n * always supplies stays bare (required at spawn — Position/Size/StackZ). The\n * optional-eligible `Rotation` carries its identity default so an ad-hoc attach\n * is ergonomic.\n */\nimport { field } from \"@vibecook/strata-ecs\";\nimport { defineComponent, defineRelation, defineResource } from \"../schema/meta\";\n\n/** Frame-local position, world units. f64 — the infinite canvas loses integer precision in f32 past ~16.7M. */\nexport const Position = defineComponent(\"Position\", { x: \"f64\", y: \"f64\" });\n\n/** Widget size, world units. f32 — sizes never need f64's range. */\nexport const Size = defineComponent(\"Size\", { w: \"f32\", h: \"f32\" });\n\n/** Optional-eligible rotation, radians. Identity default so a bare attach is ergonomic. */\nexport const Rotation = defineComponent(\"Rotation\", { r: field(\"f32\", { default: 0 }) });\n\n/**\n * Optional-eligible widget opacity, 0..1 (design-004 §3: `{opacity}` is the\n * neutral composite's WHOLE per-widget fact). Reflected by the dom host\n * (style.opacity) and the gl composite quad (uOpacity) alike; absent = 1.\n * Identity default so a bare attach is ergonomic.\n */\nexport const Opacity = defineComponent(\"Opacity\", { a: field(\"f32\", { default: 1 }) });\n\n/**\n * LEGACY (petition 8, engineSchema 2): scalar stacking order, superseded by ordered `ChildOf`\n * sibling sequences. Stays REGISTERED so v1 docs' z cells keep projecting — the schema\n * migration sorts by them, and a v1 doc opened read-only still paints z-correct through the\n * renderers' legacy fallback. Never written for new entities; no new reader outside the\n * migration and the read-only sort fallback.\n */\nexport const StackZ = defineComponent(\"StackZ\", { z: \"f64\" });\n\n/**\n * child → parent frame (durable-eligible), ORDERED (petition 8): each parent's `getReverse` is\n * its children in SIBLING ORDER — paint/pick order within a frame IS this sequence (the\n * per-frame sibling-order law; design-004 §1 amendment). Placement rides\n * `setRelation(child, ChildOf, parent, place)` / `moveRelation`; order converges\n * collaboratively (CRDT movable list). Children-of-x = `Related(ChildOf, x)`; ancestor walk =\n * forward `getRelation`; engine cascade walks `getReverse(e, ChildOf)` (see ops/cascade.ts).\n */\nexport const ChildOf = defineRelation(\"ChildOf\", { arity: \"one\", ordered: true });\n\n/**\n * The BOARD ROOT (petition 8): the componentless durable entity every root-level widget hangs\n * its `ChildOf` edge on, so the root frame has a sibling sequence like any container. Minted\n * once per document (key recorded first-writer-wins in the meta map, `engine.boardRoot`);\n * componentless BY LAW — it must dodge every widget/pick/cull query. This RUNTIME resource\n * names it post-attach; absent = a pre-schema-2 read-only doc (renderers fall back to the\n * legacy StackZ sort).\n */\nexport const BoardRoot = defineResource(\"BoardRoot\", { root: \"eid\" });\n","/**\n * 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/**\n * Runtime, on a local pointer whose press holds a `WheelTurns` widget (D3t-a — systems/press-wheel.ts): the wheel's deltas\n * since the press, summed (never zeroed while the press lasts — a reflector reads it after the tick, when `PointerWheel` is\n * gone); taken off when the press ends.\n */\nexport const PressWheel = defineComponent(\"PressWheel\", {\n dx: field(\"f64\", { default: 0 }),\n dy: field(\"f64\", { default: 0 }),\n});\n\n/** Touch-forgiveness radius, screen px (0 = exact, for mouse/pen). */\nexport const PointerRadius = defineComponent(\"PointerRadius\", { r: field(\"f32\", { default: 0 }) });\n\n/** One-tick: pointer went down this tick (cleared in cleanup). */\nexport const WentDown = defineTag(\"WentDown\");\n\n/** One-tick: pointer went up this tick. */\nexport const WentUp = defineTag(\"WentUp\");\n\n/** One-tick: pointer was cancelled this tick (pointercancel / touch lost / blur). */\nexport const WentCancelled = defineTag(\"WentCancelled\");\n\n/** The down was consumed by a widget's own DOM handler — recognizers skip it. */\nexport const HandledByWidget = defineTag(\"HandledByWidget\");\n\n/**\n * The PART of a card program under the pointer's exact hit (design-014, B3b):\n * a control the ground draws — `close`, `lock`, whatever the registered\n * program names — or `\"\"` for the content, the frame band, the canvas. Written\n * change-only by `picking` from the interaction stack's frame pick source (the\n * ground's `pick()` over its last-drawn geometry); absent while no source is\n * registered. A press that lands on a part is a CLICK on a control, never a\n * move — the recognizer copies it into `DownPart` at spawn.\n */\nexport const PointerPart = defineComponent(\"PointerPart\", { part: field(\"string\", { default: \"\" }) });\n\n/**\n * A tap that landed on a card program's PART (design-014, B3b): the select\n * behaviour writes this instead of selecting — `seq` advances per tap, so a\n * reflector (the ground's) observing it hands `(target, part)` to the app's\n * `onPart`. One record: two part taps in one frame keep the last (a\n * frame-rate event, accepted).\n */\nexport const PartTap = defineResource(\"PartTap\", { seq: \"u32\", target: \"eid\", part: \"string\" });\n\n/**\n * ONE-TICK: this tick's wheel deltas were ceded to scrollable widget content\n * (design-007 §3.5, petition I4) — the adapter let native scroll proceed and\n * flagged the fact `wheelHandled`. Deliberately NOT the shared `HandledByWidget`\n * latch: that tag rides the persistent mouse-pointer entity, and a same-tick\n * wheel-over-widget + down-over-canvas collision would silently drop the\n * legitimate canvas gesture (design-007 F6). Both wheel consumers honor it —\n * `wheelSpawn` skips the tick, `wheelSystem` treats it as wheel silence.\n * Cleared in cleanup like the Went* transition tags.\n */\nexport const WheelHandled = defineTag(\"WheelHandled\");\n\n/**\n * PERSISTENT (not one-tick): the pointer is hovering content that would opt a\n * down out — a native interactive / `[data-canvas-interactive]` (DOM) or\n * claim-capable island content (GL). Written change-only by ingest from the\n * adapters' hover-time `overInteractive` fact (design-002 §8 amendment,\n * 2026-07-18) and held across ticks with no fresh hover information (wheel,\n * blur). Presentation-grade truth — cursor affordances telegraph \"the widget\n * owns your input here\" BEFORE the down; recognizers never read it (the\n * gesture gate stays `HandledByWidget`).\n */\nexport const OverInteractive = defineTag(\"OverInteractive\");\n\n/**\n * PERSISTENT (not one-tick): the pointer LEFT THE HOST with nowhere to go — out of the window, no press of its own live (petition\n * I42): ingest sets it from an adapter's `leave` fact and clears it at the pointer's next fact of any other kind (a move, a press,\n * a wheel — the pointer is back over the host), change-only. Its point stays where it left. Presence reads it on the local mouse:\n * the peer is `away` (presence/publish.ts). Recognizers never read it.\n */\nexport const PointerOutside = defineTag(\"PointerOutside\");\n\n/** Marks the local device's pointer(s) (vs. presence projections). */\nexport const LocalPointer = defineTag(\"LocalPointer\");\n\n/** Derive-owned world position — screen × camera, recomputed every tick. */\nexport const PointerWorld = defineComponent(\"PointerWorld\", {\n x: field(\"f64\", { default: 0 }),\n y: field(\"f64\", { default: 0 }),\n});\n\n/**\n * Keyboard modifier state (design-003 §2 — minimal keyboard). Written by ingest\n * from adapter key events. `space` is the pan gesture modifier (design-003 §4.4);\n * shortcuts are app handlers between frames, never a tick system.\n */\nexport const Keyboard = defineResource(\"Keyboard\", {\n shift: field(\"bool\", { default: false }),\n ctrl: field(\"bool\", { default: false }),\n alt: field(\"bool\", { default: false }),\n meta: field(\"bool\", { default: false }),\n space: field(\"bool\", { default: false }),\n});\n\n/**\n * ONE-TICK cancel request (design-003 §4.1/§8): escape / tool switch / doc\n * detach all converge here via `cancelActiveGestures()`. The ctl:spawn sweep\n * consumes it; cleanup clears it — a latched cancel would kill every future\n * gesture forever.\n */\nexport const CancelRequest = defineResource(\"CancelRequest\", {\n active: field(\"bool\", { default: false }),\n});\n\n/** pointer → hovered entity (radiused pick — \"hover is forgiving\"). */\nexport const Targets = defineRelation(\"Targets\", { arity: \"one\" });\n\n/** pointer → r=0 point-pick target (\"grab is precise\"). */\nexport const TouchesExact = defineRelation(\"TouchesExact\", { arity: \"one\" });\n","/**\n * Tray-insert ghosts (2026-07-19, James: the widget tray — \"the widget\n * duplicate … and user drag it to canvas and drop\").\n *\n * A ghost is a DRAFT spawn (design-001 §3 two-phase promote; instantiate's\n * `{ draft: true }` world-path opt-in): a full, live, runtime-only instance of\n * a durable widget prefab that exists ONLY for the adoption drag. It is picked,\n * lifted, snapped and drop-evaluated exactly like a projected widget — the\n * whole point — and it NEVER touches the document: a successful release\n * promotes it through the gesture's single `create` commit (one tx, one undo\n * step) and the reap system swaps it for the projected twin; a cancel or a\n * rejected drop flies it back to the tray and despawns it, zero undo footprint.\n */\nimport { field } from \"@vibecook/strata-ecs\";\nimport { defineComponent, defineTag } from \"../schema/meta\";\n\n/**\n * The ghost marker + its promote payload, attached at `ops.insertByDrag`:\n * `type`/`props` (JSON) rebuild the widget in the commit's `CommitCreate`;\n * `screenX/screenY` remember the tray press point IN SCREEN SPACE so the\n * cancel fly-back re-projects it through the CURRENT camera — the ghost\n * returns to the tray on screen even if the user zoomed mid-drag.\n */\nexport const InsertGhost = defineComponent(\"InsertGhost\", {\n type: \"string\",\n props: field(\"string\", { default: \"{}\" }),\n screenX: \"f32\",\n screenY: \"f32\",\n});\n\n/**\n * Set by moveBehavior when the ghost's gesture committed its `create` intent.\n * The reap system despawns the ghost ONE tick later — the projected twin lands\n * at the next sync, so the swap happens inside a single reflect flush (no\n * one-frame blink of neither).\n */\nexport const GhostCommitted = defineTag(\"GhostCommitted\");\n\n/**\n * Set on the cancel / rejected-drop paths together with the fly-back\n * `TransformTween`: the reap system despawns the ghost when the tween lands\n * (component removed on arrival — camera-sim).\n */\nexport const GhostRetiring = defineTag(\"GhostRetiring\");\n","/**\n * 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, `keys` an empty JSON list, and the cursor's `away`/`canvas` (I42) the\n * present peer on the root — what an older peer's blob, which has neither, reads as.\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\");\n/** Core moves this widget with a selection; its own driver handles a solo drag. */\nexport const SelectionMovable = defineTag(\"SelectionMovable\");\nexport const Resizable = defineTag(\"Resizable\");\nexport const SnapSource = defineTag(\"SnapSource\");\nexport const SnapTarget = defineTag(\"SnapTarget\");\n/**\n * Comment-box group drag (2026-07-18, James: the UE-Blueprint comment): a\n * move claim on this widget ALSO claims every widget fully inside its bounds\n * at claim time — spatial membership, never reparenting (that's the folder\n * path). Drag a member out and it simply stops being inside.\n */\nexport const SweepsContained = defineTag(\"SweepsContained\");\n/**\n * `interaction.wheelTurns` (design-015 §6's photo — PHOTO.md \"wheel while holding turns the print about the finger\";\n * D3t-a): while a press holds this widget, the wheel on that pointer is the WIDGET's — neither the camera nor the\n * recognizers hear it (`WheelHandled`) — and its deltas add up in the pointer's `PressWheel` for the widget's own\n * behaviour to read (systems/press-wheel.ts).\n */\nexport const WheelTurns = defineTag(\"WheelTurns\");\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/**\n * Peer cursor in world coords — FRAME-LOCAL (design-001 §5.1): `x`/`y` are the coordinates of the canvas the peer is in. `away`\n * (petition I42): the peer's pointer left their host with nowhere to go, or their host said so (`PresenceSession.setAway` — chrome\n * that covers the desk); a receiver hides an away peer. `canvas`: the durable key of the container the peer has ENTERED, \"\" at the\n * root (a container with no durable key is `~<peerId>/<entity>` — never \"\", never another peer's); a receiver draws a peer only in\n * its own canvas. Both default (an older peer's blob carries neither: it reads as present, on the root).\n */\nexport const PresenceCursor = defineComponent(\"PresenceCursor\", {\n x: field(\"f64\", { default: 0 }),\n y: field(\"f64\", { default: 0 }),\n device: enumOf([\"mouse\", \"touch\", \"pen\"]),\n away: field(\"bool\", { default: false }),\n canvas: field(\"string\", { default: \"\" }),\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 * 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 { enumOf, field } from \"@vibecook/strata-ecs\";\nimport { defineResource } from \"../schema/meta\";\nimport {\n CAMERA_DEFAULTS,\n CHROME_DEFAULTS,\n GESTURE_DEFAULTS,\n NAV_TRANSITION_DEFAULTS,\n POINTER_DEFAULTS,\n ZOOM_THROUGH_DEFAULTS,\n} from \"../settings/defaults\";\n\n/**\n * Selection-chrome live mirror (2026-07-17): `liftScale` = the app's visual\n * drag-lift scale factor; `selectionChrome` inflates a Grab-bed member's rect\n * by it (about the rect center) so the resize handles wrap the card the user\n * SEES, not just its ECS footprint (the union box it also inflated left at D7).\n */\nexport const ChromeSettings = defineResource(\"ChromeSettings\", {\n liftScale: field(\"f32\", { default: CHROME_DEFAULTS.liftScale }),\n});\n\n/** Recognizer timing/slop live mirror (design-003 §4.2 kind table; inertia constants §5 item 9). */\nexport const GestureSettings = defineResource(\"GestureSettings\", {\n tapMaxMs: field(\"f32\", { default: GESTURE_DEFAULTS.tapMaxMs }),\n tapSlopPx: field(\"f32\", { default: GESTURE_DEFAULTS.tapSlopPx }),\n longPressMs: field(\"f32\", { default: GESTURE_DEFAULTS.longPressMs }),\n longPressSlopPx: field(\"f32\", { default: GESTURE_DEFAULTS.longPressSlopPx }),\n dragSlopPx: field(\"f32\", { default: GESTURE_DEFAULTS.dragSlopPx }),\n pinchSlopPx: field(\"f32\", { default: GESTURE_DEFAULTS.pinchSlopPx }),\n wheelEndSilenceMs: field(\"f32\", { default: GESTURE_DEFAULTS.wheelEndSilenceMs }),\n inertiaMinVelocityPxPerS: field(\"f32\", { default: GESTURE_DEFAULTS.inertiaMinVelocityPxPerS }),\n inertiaDecayMs: field(\"f32\", { default: GESTURE_DEFAULTS.inertiaDecayMs }),\n multiTapWindowMs: field(\"f32\", { default: GESTURE_DEFAULTS.multiTapWindowMs }),\n multiTapSlopPx: field(\"f32\", { default: GESTURE_DEFAULTS.multiTapSlopPx }),\n wheelZoomSensitivity: field(\"f32\", { default: GESTURE_DEFAULTS.wheelZoomSensitivity }),\n wheelZoomMaxStep: field(\"f32\", { default: GESTURE_DEFAULTS.wheelZoomMaxStep }),\n /** Ordinary scrolling pans by default; apps can opt into cursor-anchored wheel zoom. */\n wheel: field(enumOf([\"pan\", \"zoom\"]), { default: GESTURE_DEFAULTS.wheel }),\n /** Pinch/modifier zoom response, independent of the plain wheel's job. */\n wheelZoomCurve: field(enumOf([\"clamped\", \"exponential\"]), { default: GESTURE_DEFAULTS.wheelZoomCurve }),\n /** Continuous zoom: `zoom · exp(−Δ · wheelZoomRate)`. f64 keeps the configured rate exact. */\n wheelZoomRate: field(\"f64\", { default: GESTURE_DEFAULTS.wheelZoomRate }),\n});\n\n/** Pick radii + retarget dead-band live mirror (design-003 §3 L1 targeting). */\nexport const PointerSettings = defineResource(\"PointerSettings\", {\n radiusMousePx: field(\"f32\", { default: POINTER_DEFAULTS.radiusMousePx }),\n radiusTouchPx: field(\"f32\", { default: POINTER_DEFAULTS.radiusTouchPx }),\n radiusPenPx: field(\"f32\", { default: POINTER_DEFAULTS.radiusPenPx }),\n hoverReleaseDeadBandPx: field(\"f32\", { default: POINTER_DEFAULTS.hoverReleaseDeadBandPx }),\n});\n\n/** Zoom clamp live mirror (design-005 §4 `settings.zoom`; camera-sim consumes). */\nexport const CameraLimits = defineResource(\"CameraLimits\", {\n minZoom: field(\"f32\", { default: CAMERA_DEFAULTS.minZoom }),\n maxZoom: field(\"f32\", { default: CAMERA_DEFAULTS.maxZoom }),\n});\n\n/** Nav-transition spring response live mirror (design-006 §4; navFlight consumes). */\nexport const NavTransitionSettings = defineResource(\"NavTransitionSettings\", {\n responseMs: field(\"f32\", { default: NAV_TRANSITION_DEFAULTS.responseMs }),\n});\n\n/**\n * The zoom-through's live mirror (design-015 §9 — D2b; `settings.nav.zoomThrough`): `enabled`\n * (off unless the app says), the dead band `in`/`out` (CSS px) and the gate `gate0` → `gate1`\n * (the face's short side, CSS px). The `zoomThrough` system consumes it.\n */\nexport const ZoomThroughSettings = defineResource(\"ZoomThroughSettings\", {\n enabled: field(\"bool\", { default: ZOOM_THROUGH_DEFAULTS.enabled }),\n in: field(\"f32\", { default: ZOOM_THROUGH_DEFAULTS.in }),\n out: field(\"f32\", { default: ZOOM_THROUGH_DEFAULTS.out }),\n gate0: field(\"f32\", { default: ZOOM_THROUGH_DEFAULTS.gate[0] }),\n gate1: field(\"f32\", { default: ZOOM_THROUGH_DEFAULTS.gate[1] }),\n});\n","/**\n * `Retained` — the nav crossfade's pin (design-013 §4, §5), kept at design-015 D5b when the rest\n * of the presentation vocabulary this file held — the six surface facts (`SurfaceKind`,\n * `SurfaceTarget`, `RequestedDemand`, `SurfaceDemand`, `SurfaceBand`, `TextureRef`),\n * `NO_TEXTURE` and `effectiveTarget` — left with the DOM/GPU presentation choice it described.\n * Nothing presents anywhere but the desk (design-015 §1).\n *\n * The desk renderer's working set is `Visible`/`Culled` (camera-derived.ts); `Retained` is the\n * one tag that outlives a cull: a departed frame's objects wear it for the length of a nav flight\n * (`systems/nav-flight.ts` tags on departure and releases on arrival — B9 review blocker 4), so a\n * renderer that keeps per-object GPU state — a raster, a texture — knows not to forget it\n * mid-crossfade. Written by the nav flight and by nothing else.\n */\nimport { defineTag } from \"../schema/meta\";\n\nexport const Retained = defineTag(\"Retained\");\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 the `Camera` and input-zoom resources (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, with an independently selected\n * exponential or bounded legacy curve (`GestureSettings.wheelZoomCurve`).\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 *\n * `GestureSettings.wheel` defaults to \"pan\". The optional \"zoom\" mode uses\n * a plain wheel's Δy to zoom about the pointer by `zoom · exp(−Δy · rate)`.\n * Pinch / modifier-wheel uses `wheelZoomCurve` independently; the desk selects\n * exponential pinch with ordinary scrolling to pan. CameraLimits clamps both.\n * WheelZoomStep feeds zoom-through; CameraZoomStep also includes touch pinch\n * and lets feedback distinguish user input from fits, flights and restoration.\n */\nimport { field } from \"@vibecook/strata-ecs\";\nimport type { Entity, System, TickSystem, World } from \"@vibecook/strata-ecs\";\nimport { defineQuery, defineSystem, defineTickSystem } from \"@vibecook/strata-ecs\";\nimport { zoomAtPoint } from \"@ice/kernel\";\nimport {\n Camera,\n Drag,\n GesturePhases,\n LocalPointer,\n Pinch,\n Pointer,\n PointerScreen,\n Position,\n RoutedPan,\n TransformTween,\n Watches,\n WentDown,\n WheelPan,\n WheelZoom,\n} from \"../catalog\";\nimport { CameraLimits, GestureSettings } from \"../catalog/settings-resources\";\nimport { FrameInfo } from \"../engine/frame-info\";\nimport { defineResource } from \"../schema/meta\";\nimport { CAMERA_DEFAULTS, GESTURE_DEFAULTS } from \"../settings/defaults\";\n\nconst P = GesturePhases;\n\n// Wheel-zoom speed is the v2 prototype curve (2026-07-13, superseding the old\n// e^(−Δ·0.0015) demo constant): factor = 2^(−clamp(Δ, ±maxStep) · sensitivity),\n// live-tunable via GestureSettings. See GESTURE_DEFAULTS for why the clamp is\n// the load-bearing half (mouse-notch ≈ pinch-frame parity).\n\n/** Camera default when the resource is unset (tests may never seed it). */\nconst CAMERA_ZERO = { x: 0, y: 0, zoom: 1, gesturing: false } as const;\n\n/**\n * Runtime pan-inertia velocity (screen px/s), seeded by `cameraControl` at pan\n * release and decayed by `cameraInertia`. A resource (not closure state) so\n * devtools sees it and there is no hidden singleton (design-003 §9).\n */\nexport const CameraInertia = defineResource(\n \"CameraInertia\",\n { vx: field(\"f32\", { default: 0 }), vy: field(\"f32\", { default: 0 }) },\n { durable: false },\n);\n\n/**\n * This frame's WHEEL zoom (design-015 §9, D2a-core): the one-tick fact a system\n * that runs after `cameraControl` reads to know \"this frame zoomed in / out\n * about this anchor\" — D2b's zoom-through is the first. `cameraControl` is its\n * one writer, change-only: it writes a step on each frame whose wheel zoom (a\n * plain wheel in `\"zoom\"` mode, or a pinch-wheel in either mode) moved the\n * zoom, and resets `ratio` to 1 on the first frame after that has none; idle\n * frames write nothing.\n * - `ratio`: zoom after ÷ zoom before, over this frame's wheel zooms — `> 1`\n * zoomed in, `< 1` out, `1` no step (a clamped zoom is no step).\n * - `anchorX/Y`: the screen point (CSS px) of the frame's last wheel zoom.\n * - `tick`: the `FrameInfo.tick` it happened on, for a reader that runs BEFORE\n * `cameraControl` and must tell last frame's step from this one's.\n * Not recorded: pans, flights, ops (`zoomTo`, fits) and the TOUCH pinch — whose\n * zoom is absolute from its own start (`startZoom · spread/startDist`), so a\n * consumer that re-bases the camera mid-pinch would have to re-base the pinch\n * too; that is the consumer's call to make, not a fact to hand it silently.\n */\nexport const WheelZoomStep = defineResource(\n \"WheelZoomStep\",\n {\n ratio: field(\"f64\", { default: 1 }),\n anchorX: field(\"f32\", { default: 0 }),\n anchorY: field(\"f32\", { default: 0 }),\n tick: field(\"u32\", { default: 0 }),\n },\n { durable: false },\n);\n\n/** Latest user-driven camera zoom, including touch pinch. Presentation hosts\n * can acknowledge scale crossings without mistaking a fit, flight, document\n * restore or zoom-through rebase for a gesture. Values describe cameraControl's\n * zoom before later navigation systems run. Idle frames never write it. */\nexport const CameraZoomStep = defineResource(\n \"CameraZoomStep\",\n {\n from: field(\"f64\", { default: 1 }),\n to: field(\"f64\", { default: 1 }),\n tick: field(\"u32\", { default: 0 }),\n },\n { durable: false },\n);\n\nexport interface CameraSystems {\n cameraControl: TickSystem;\n cameraInertia: TickSystem;\n tweenSystem: System;\n}\n\nconst panDragQ = defineQuery([Drag, RoutedPan]);\nconst wheelPanQ = defineQuery([WheelPan]);\nconst wheelZoomQ = defineQuery([WheelZoom]);\nconst pinchQ = defineQuery([Pinch]);\nconst downPointerQ = defineQuery([Pointer, WentDown, LocalPointer]);\nconst tweenQ = defineQuery([Position, TransformTween]);\n\nfunction clampZoom(world: World, z: number): number {\n // Live-tunable limits (design-005 §4): resource first, const fallback.\n const lim = world.getResource(CameraLimits) ?? CAMERA_DEFAULTS;\n return Math.min(lim.maxZoom, Math.max(lim.minZoom, z));\n}\n\n/** Cubic ease-out (design-003 §5 item 5 fly-back easing). */\nfunction easeOutCubic(t: number): number {\n const inv = 1 - t;\n return 1 - inv * inv * inv;\n}\n\nexport function createCameraSystems(world: World): CameraSystems {\n // Per-RoutedPan-recognizer last screen total (design decision 14): the pan\n // integrates ONLY this frame's delta at the current zoom, so a Simultaneous\n // wheel-zoom mid-pan never retroactively re-converts the accumulated total.\n const panMemo = new Map<Entity, { x: number; y: number }>();\n\n // Per-entity tween start position: TransformTween carries only the target\n // (design-001 §5 minimal shape), so the eased lerp needs the fly-away origin\n // captured on the attach frame. Cleaned on arrival — and, since 2026-08-15\n // (petition I15), on DEATH too: an entity destroyed mid-glide never reaches\n // the landing branch, so its entry used to sit in this map for the world's\n // whole life. Bounded and harmless (generation-tagged handles never collide),\n // but a leak is a leak — and behaviors will make mid-glide despawns ordinary.\n const tweenStart = new Map<Entity, { x: number; y: number }>();\n world.observe({\n onDestroy: (e) => {\n tweenStart.delete(e);\n },\n onReset: () => {\n tweenStart.clear();\n panMemo.clear();\n },\n });\n\n // Tick system (strata 0.5.0, petition 5): the scheduler owns cardinality —\n // the whole-frame aggregate runs EXACTLY once per frame by construction.\n // (Pre-0.5.0 this was a CanvasSurface-anchored chunk system; a missing\n // count guard multiplied the non-idempotent integrations N-archetypes× —\n // caught by the wheel-pan direction trace, 2026-07-10.)\n const cameraControl = defineTickSystem(\n (ctx) => {\n const cam0 = world.getResource(Camera) ?? CAMERA_ZERO;\n let x = cam0.x;\n let y = cam0.y;\n let zoom = cam0.zoom;\n let anyActive = false;\n // Ordinary wheel behavior and the pinch curve are independent.\n const gmode = world.getResource(GestureSettings);\n const wheelZooms = (gmode?.wheel ?? GESTURE_DEFAULTS.wheel) === \"zoom\";\n const zoomRate = gmode?.wheelZoomRate ?? GESTURE_DEFAULTS.wheelZoomRate;\n // This frame's WHEEL zoom, for WheelZoomStep: the product of its ratios and its last anchor.\n let wheelRatio = 1;\n let wheelAnchorX = 0;\n let wheelAnchorY = 0;\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 if (wheelZooms) {\n // Optional scroll-to-zoom: a plain wheel's Δy zooms about the\n // pointer by the prototype's law; its Δx is not the camera's.\n if (w.dy === 0) continue;\n const next = zoomAtPoint(\n { x, y, zoom },\n w.anchorX,\n w.anchorY,\n clampZoom(world, zoom * Math.exp(-w.dy * zoomRate)),\n );\n wheelRatio *= next.zoom / zoom;\n wheelAnchorX = w.anchorX;\n wheelAnchorY = w.anchorY;\n x = next.x;\n y = next.y;\n zoom = next.zoom;\n continue;\n }\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 let factor: number;\n if ((gmode?.wheelZoomCurve ?? GESTURE_DEFAULTS.wheelZoomCurve) === \"exponential\") {\n // Continuous pinch zoom: integrating the same deltas in one frame\n // or several gives the same scale. Plain scrolling is independent.\n factor = Math.exp(-wz.pinch * zoomRate);\n } else {\n const gset = world.getResource(GestureSettings);\n const sens = gset?.wheelZoomSensitivity ?? GESTURE_DEFAULTS.wheelZoomSensitivity;\n const maxStep = gset?.wheelZoomMaxStep ?? GESTURE_DEFAULTS.wheelZoomMaxStep;\n const step = Math.max(-maxStep, Math.min(maxStep, wz.pinch));\n factor = 2 ** (-step * sens);\n }\n const next = zoomAtPoint(\n { x, y, zoom },\n wz.anchorX,\n wz.anchorY,\n clampZoom(world, zoom * factor),\n );\n wheelRatio *= next.zoom / zoom;\n wheelAnchorX = wz.anchorX;\n wheelAnchorY = wz.anchorY;\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 if (zoom !== cam0.zoom) {\n world.setResource(CameraZoomStep, {\n from: cam0.zoom,\n to: zoom,\n tick: world.getResource(FrameInfo)?.tick ?? 0,\n });\n }\n\n // WheelZoomStep (design-015 §9), change-only: this frame's wheel zoom, or\n // the one reset after the last one. An idle frame writes nothing.\n if (wheelRatio !== 1) {\n world.setResource(WheelZoomStep, {\n ratio: wheelRatio,\n anchorX: wheelAnchorX,\n anchorY: wheelAnchorY,\n tick: world.getResource(FrameInfo)?.tick ?? 0,\n });\n } else {\n const last = world.getResource(WheelZoomStep);\n if (last !== undefined && last.ratio !== 1) world.setResource(WheelZoomStep, { ...last, ratio: 1 });\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 * The paved-road runtime-resource write (design-001 §2 rule 7) — the mirror\n * image of guarded-tx's `tx.setResource` check. A resource declares its write\n * path once at `defineResource` (`durable` vs `runtime`), and the two ends\n * enforce it symmetrically: `tx.setResource` rejects a RUNTIME resource inside\n * a transaction; `writeRuntimeResource` rejects a DURABLE resource on the\n * runtime world. Systems have no `ctx` resource API, so they write runtime\n * resources through the closed-over `world.setResource` (design-002 §3) — this\n * facade is that write, made DEV-checked.\n *\n * Unknown resources — anything not defined through `../schema/meta`'s\n * `defineResource` wrapper — carry no schemaMeta, so the check finds nothing\n * and the write passes untouched. The guard is best-effort by design, exactly\n * like guarded-tx's prefab-eligibility checks.\n */\nimport type { Resource, World } from \"@vibecook/strata-ecs\";\nimport { schemaMeta } from \"../schema/meta\";\nimport { devGuardsEnabled } from \"./dev\";\n\nexport function writeRuntimeResource<S>(world: World, res: Resource<S>, v: S): void {\n if (devGuardsEnabled()) {\n const meta = schemaMeta.resource(res as Resource);\n if (meta?.durable) {\n throw new Error(\n `ice: writeRuntimeResource: resource \"${meta.name}\" is declared durable — durable resources are written in transactions (tx.setResource), not through the runtime world (design-001 §2 rule 7).`,\n );\n }\n }\n world.setResource(res, v);\n}\n","/**\n * Nav-flight — the T1 camera-flight half of design-006 (portal zoom).\n *\n * CUT-FIRST, THEN FLY (§3): the nav ops perform the ECS cut synchronously\n * (frame switch, membership resweep, index rebuild) and then hand presentation\n * to this slice — `startNavFlight` snaps the camera to the continuity-solved\n * start `c0` and arms the `NavTransition` resource; the `navFlight` tick\n * system (simulate, beside cameraInertia) advances a closed-form critically-\n * damped progress spring each frame and writes the camera along the log-zoom\n * path until rest. The transition is PURE PRESENTATION: killing it at any\n * moment leaves a fully consistent world in the destination frame.\n *\n * - `NavTransition` is a RESOURCE, not closure state (the CameraInertia\n * pattern: devtools sees it, no hidden singleton — design-003 §9). Resources\n * cannot be removed, so `active` is the liveness flag; `epoch` bumps on\n * every (re)start so the T2 reflector can distinguish retarget from resume.\n * - Camera writes are UNCLAMPED (design-006 §3.1): flight paths transit far\n * outside the user-gesture zoom band; only the ARRIVAL camera (clamped by\n * the nav op) bounds where the flight rests.\n * - Gestures always win (§4): any active camera gesture — `Camera.gesturing`,\n * stamped by cameraControl in ctl:behave, i.e. EARLIER this same frame —\n * deactivates the flight without touching the camera.\n * - The portal affine (`as/aox/aoy`, departed-frame → destination-frame) and\n * `frozen` ride the resource for T2's departing-plane reflector; T1's camera\n * math only needs c0/c1.\n */\nimport type { Entity, TickSystem, World } from \"@vibecook/strata-ecs\";\nimport { defineQuery, defineTickSystem, enumOf, field } from \"@vibecook/strata-ecs\";\nimport type { CameraState, PortalAffine } from \"@ice/kernel\";\nimport { capFlightStart, flightCamera, flightOctaves, outgoingCamera, springStep } from \"@ice/kernel\";\nimport { Camera, Viewport } from \"../catalog/camera-derived\";\nimport { Container } from \"../catalog/graph\";\nimport { ChildOf, Position, Size } from \"../catalog/scene\";\nimport { NavTransitionSettings } from \"../catalog/settings-resources\";\nimport { Retained } from \"../catalog/surface\";\nimport { FrameInfo } from \"../engine/frame-info\";\nimport { writeRuntimeResource } from \"../guards/resource-writer\";\nimport { defineResource } from \"../schema/meta\";\nimport { PrefabId } from \"../schema/prefab\";\nimport { NAV_TRANSITION_DEFAULTS } from \"../settings/defaults\";\n\nconst NAV = NAV_TRANSITION_DEFAULTS;\n\n/** The one in-flight nav transition (design-006 §3.1). Inactive = at rest. */\nexport const NavTransition = defineResource(\"NavTransition\", {\n active: field(\"bool\", { default: false }),\n kind: field(enumOf([\"enter\", \"exit\"]), { default: \"enter\" }),\n /** Progress spring state (closed-form critically damped, kernel springStep). */\n p: field(\"f32\", { default: 0 }),\n v: field(\"f32\", { default: 0 }),\n /** Depth-capped flight — T2 presents it as a crossfade, not geometry (§5). */\n frozen: field(\"bool\", { default: false }),\n /** Bumps on every flight start; T2 distinguishes retarget from resume. */\n epoch: field(\"u32\", { default: 0 }),\n /** CanvasSession/document identity captured at the authority cut. */\n documentEpoch: field(\"u32\", { default: 0 }),\n fromFrame: field(\"eid\", { default: 0 as Entity }),\n toFrame: field(\"eid\", { default: 0 as Entity }),\n fromTypeId: field(\"string\", { default: \"\" }),\n toTypeId: field(\"string\", { default: \"\" }),\n /** Response multiplier from octave distance (locked at start; §4). */\n durMul: field(\"f32\", { default: 1 }),\n /**\n * The DEPARTED frame's camera at the cut (design-013 §8 B7, D-B7.1): what it renders under\n * at p = 0 — bit for bit, never through the affine and back — and throughout a frozen\n * flight. `departedCameraOf` is the one reader.\n */\n fromX: field(\"f64\", { default: 0 }),\n fromY: field(\"f64\", { default: 0 }),\n fromZ: field(\"f64\", { default: 1 }),\n /**\n * Ticks the spring has stepped. The FIRST tick after the cut holds at p = 0 (B7): one frame\n * is drawn with the camera at the exact `c0` — the arriving frame IS the portal's last frame,\n * the departed frame IS its pre-cut frame — so the cut changes no pixel and the motion begins\n * from a frame that exists. The oracle's `p = 0` still is a product frame, not a fiction.\n */\n ticks: field(\"u32\", { default: 0 }),\n c0x: field(\"f64\", { default: 0 }),\n c0y: field(\"f64\", { default: 0 }),\n c0z: field(\"f64\", { default: 1 }),\n c1x: field(\"f64\", { default: 0 }),\n c1y: field(\"f64\", { default: 0 }),\n c1z: field(\"f64\", { default: 1 }),\n /** Portal affine A: departed-frame coords → destination-frame coords (T2). */\n as: field(\"f64\", { default: 1 }),\n aox: field(\"f64\", { default: 0 }),\n aoy: field(\"f64\", { default: 0 }),\n});\n\nexport interface NavTransitionIdentity {\n readonly documentEpoch: number;\n readonly fromFrame: Entity;\n readonly toFrame: Entity;\n readonly fromTypeId: string;\n readonly toTypeId: string;\n}\n\nconst identityFields = (\n identity: NavTransitionIdentity | undefined,\n): {\n documentEpoch: number;\n fromFrame: Entity;\n toFrame: Entity;\n fromTypeId: string;\n toTypeId: string;\n} => ({\n documentEpoch: identity?.documentEpoch ?? 0,\n fromFrame: identity?.fromFrame ?? (0 as Entity),\n toFrame: identity?.toFrame ?? (0 as Entity),\n fromTypeId: identity?.fromTypeId ?? \"\",\n toTypeId: identity?.toTypeId ?? \"\",\n});\n\n/** The one in-flight transition's field values, as `departedCameraOf` reads them. */\nexport interface DepartedCameraInputs {\n readonly frozen: boolean;\n readonly c0x: number;\n readonly c0y: number;\n readonly c0z: number;\n readonly fromX: number;\n readonly fromY: number;\n readonly fromZ: number;\n readonly as: number;\n readonly aox: number;\n readonly aoy: number;\n}\n\n/**\n * The camera the DEPARTED frame renders under this frame (design-013 §8 B7, D-B7.1; the\n * ground's `departedCamera`, moved onto the resource). Riding the flight through the affine\n * (`outgoingCamera`) — except at the cut itself, where it is the pre-cut camera bit for bit\n * (the affine and its inverse round-trip to within an ulp, and at zoom 1 an ulp is the other\n * side of a decade), and throughout a FROZEN flight, where the departed frame stays at its\n * pre-cut appearance and fades (design-006 §5: the cap broke the geometry, so the story is a\n * dissolve, not a portal). Every presenter of the departed frame — the ground's second slot,\n * the DOM's departing plane — reads this one rule, so they agree to the bit.\n */\nexport function departedCameraOf(t: DepartedCameraInputs, cam: CameraState): CameraState {\n if (t.frozen || (cam.x === t.c0x && cam.y === t.c0y && cam.zoom === t.c0z)) return { x: t.fromX, y: t.fromY, zoom: t.fromZ };\n return outgoingCamera({ s: t.as, ox: t.aox, oy: t.aoy }, cam);\n}\n\n// Every equipped widget, Active or not — the departed frame's cards are culled at the cut.\nconst widgetsQ = defineQuery([Position, Size, PrefabId]);\nconst retainedQ = defineQuery([Retained]);\n\n/** The nav frame a widget belongs to: its first `Container` ancestor on the `ChildOf` chain; `undefined` = the root (nested-canvas's membership rule). */\nfunction navFrameOf(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\n/**\n * Pin the DEPARTED frame's cards for the flight (design-013 §4, §5: `Retained` — \"the nav\n * crossfade\" writes it; Residency's LRU never evicts a retained key, so the departed slot's\n * records keep their textures until the landing). An op-time write: `startNavFlight` runs\n * outside the tick. `fromFrame` is the departed frame — a container, or the board root.\n */\nfunction retainDeparted(world: World, fromFrame: Entity | undefined): number {\n if (fromFrame === undefined || fromFrame === (0 as Entity)) return 0;\n const frame = world.isAlive(fromFrame) && world.hasTag(fromFrame, Container) ? fromFrame : undefined;\n const set: Entity[] = [];\n world.query(widgetsQ).each((b) => { for (const r of b) { const e = b.entity(r); if (navFrameOf(world, e) === frame) set.push(e); } });\n for (const e of set) if (!world.hasTag(e, Retained)) world.addTag(e, Retained);\n return set.length;\n}\n\n/** The flight is over (settled, aborted, yielded): nothing is retained any more. Two-phase — collect, then mutate. */\nfunction releaseRetained(w: { query: World[\"query\"] }, untag: (e: Entity) => void): number {\n const set: Entity[] = [];\n w.query(retainedQ).each((b) => { for (const r of b) set.push(b.entity(r)); });\n for (const e of set) untag(e);\n return set.length;\n}\n\n/**\n * Arm a flight from the already-cut world: continuity-solve was done by the\n * caller (`exact` = c0 in destination-frame coords — from a LIVE PORTAL the\n * camera the inside was already rendering under, `outgoingCamera(M, camPre)`,\n * so the cut changes no pixel; D-B7.1), the arrival `c1` is\n * already clamped. Applies the depth cap (§5), snaps the camera to c0, and\n * activates the resource. Callers guarantee a live Viewport — headless/no-\n * viewport paths snap to the arrival instead and never reach here.\n */\nexport function startNavFlight(\n world: World,\n kind: \"enter\" | \"exit\",\n A: PortalAffine,\n exact: CameraState,\n c1: CameraState,\n identity?: NavTransitionIdentity,\n): void {\n const vp = world.getResource(Viewport);\n const vpW = vp?.w ?? 0;\n const vpH = vp?.h ?? 0;\n const { c0, capped } = capFlightStart(exact, c1, vpW, vpH, NAV.freezeOctaves, NAV.capFactor);\n const octaves = flightOctaves(c0, c1);\n const prev = world.getResource(NavTransition);\n // the departed frame's camera at the cut: the Camera resource BEFORE this write (the cut itself moves it to c0)\n const pre = world.getResource(Camera);\n const from: CameraState = pre === undefined ? c0 : { x: pre.x, y: pre.y, zoom: pre.zoom };\n // A flight interrupted by a flight: the earlier departed set is let go before the new one is\n // pinned — the tick's release runs only for the flight that is active, so an earlier set left\n // tagged here would stay `Retained` for the session (B9 review blocker 4).\n releaseRetained(world, (e) => world.removeTag(e, Retained));\n retainDeparted(world, identity?.fromFrame);\n writeRuntimeResource(world, Camera, { x: c0.x, y: c0.y, zoom: c0.zoom, gesturing: false });\n world.setResource(NavTransition, {\n active: true,\n kind,\n p: 0,\n v: 0,\n frozen: capped,\n epoch: (prev?.epoch ?? 0) + 1,\n ...identityFields(identity),\n durMul: 1 + NAV.durationPerOctave * Math.max(0, octaves - NAV.baseOctaves),\n fromX: from.x,\n fromY: from.y,\n fromZ: from.zoom,\n ticks: 0,\n c0x: c0.x,\n c0y: c0.y,\n c0z: c0.zoom,\n c1x: c1.x,\n c1y: c1.y,\n c1z: c1.zoom,\n as: A.s,\n aox: A.ox,\n aoy: A.oy,\n });\n}\n\n/**\n * Publish an epoch-bound logical switch even when geometry is deliberately cut. A cut that\n * lands mid-flight ENDS that flight: its departed set is released here, because the tick that\n * owns the release never runs for an inactive resource (B9 review blocker 4 — `Retained` leaked\n * for the session, and Residency never evicted those keys).\n */\nexport function publishNavCut(\n world: World,\n kind: \"enter\" | \"exit\",\n from: CameraState,\n to: CameraState,\n identity?: NavTransitionIdentity,\n A: PortalAffine = { s: 1, ox: 0, oy: 0 },\n): void {\n releaseRetained(world, (e) => world.removeTag(e, Retained));\n const prev = world.getResource(NavTransition);\n world.setResource(NavTransition, {\n active: false,\n kind,\n p: 1,\n v: 0,\n frozen: false,\n epoch: (prev?.epoch ?? 0) + 1,\n ...identityFields(identity),\n durMul: 1,\n fromX: from.x,\n fromY: from.y,\n fromZ: from.zoom,\n ticks: 1,\n c0x: from.x,\n c0y: from.y,\n c0z: from.zoom,\n c1x: to.x,\n c1y: to.y,\n c1z: to.zoom,\n as: A.s,\n aox: A.ox,\n aoy: A.oy,\n });\n}\n\n/** Deactivate without touching the camera (integrity pops, gesture yields). */\nexport function abortNavFlight(world: World): void {\n const t = world.getResource(NavTransition);\n if (t?.active) world.setResource(NavTransition, { ...t, active: false });\n releaseRetained(world, (e) => world.removeTag(e, Retained));\n}\n\n/**\n * Is a nav flight driving the camera right now? THE gate for flight-time\n * GPU/paint duty (design-006 §8.2, answered by field testing 2026-07-16):\n * heavy-motion consumers treat `Camera.gesturing ∨ navFlightActive` as one\n * \"camera in transient motion\" signal — composite DPR drop, band-repaint\n * suppression, Hot-island freeze, breakpoint retier deferral. `gesturing`\n * itself stays a pure user-gesture fact (the inertia precedent): flights\n * never stamp it, consumers OR the two.\n */\nexport function navFlightActive(world: World): boolean {\n return world.getResource(NavTransition)?.active === true;\n}\n\nexport function createNavFlight(world: World): TickSystem {\n return defineTickSystem(\n (ctx) => {\n const t = world.getResource(NavTransition);\n if (t === undefined || !t.active) return;\n const release = (): void => { releaseRetained(ctx, (e) => ctx.removeTag(e, Retained)); };\n const cam = world.getResource(Camera);\n if (cam?.gesturing === true) {\n // Touch always wins (§4): yield instantly; the camera stays wherever\n // the flight left it and the gesture composes from there.\n world.setResource(NavTransition, { ...t, active: false });\n release();\n return;\n }\n const vp = world.getResource(Viewport);\n const c1: CameraState = { x: t.c1x, y: t.c1y, zoom: t.c1z };\n if (vp === undefined || vp.w <= 0) {\n // Viewport died mid-flight (teardown) — settle instantly.\n writeRuntimeResource(world, Camera, { ...c1, gesturing: false });\n world.setResource(NavTransition, { ...t, p: 1, v: 0, active: false });\n release();\n return;\n }\n if (t.ticks === 0) {\n // the cut frame (B7): held at p = 0 with the camera at the exact c0 — drawn once, then the spring runs\n world.setResource(NavTransition, { ...t, ticks: 1 });\n return;\n }\n const dtMs = world.getResource(FrameInfo)?.dt ?? 16;\n const responseMs =\n (world.getResource(NavTransitionSettings)?.responseMs ?? NAV.responseMs) *\n (t.kind === \"exit\" ? NAV.exitResponseFactor : 1) *\n t.durMul;\n const omega = (2 * Math.PI) / (responseMs / 1000);\n const { p, v } = springStep(t.p, t.v, omega, dtMs / 1000);\n if (p > NAV.settleP && Math.abs(v) < NAV.settleV) {\n writeRuntimeResource(world, Camera, { ...c1, gesturing: false }); // land EXACTLY\n world.setResource(NavTransition, { ...t, p: 1, v: 0, active: false });\n release();\n return;\n }\n const c0: CameraState = { x: t.c0x, y: t.c0y, zoom: t.c0z };\n const c = flightCamera(c0, c1, Math.min(1, Math.max(0, p)), vp.w, vp.h);\n writeRuntimeResource(world, Camera, { x: c.x, y: c.y, zoom: c.zoom, gesturing: false });\n world.setResource(NavTransition, { ...t, p, v, ticks: t.ticks + 1 });\n },\n {\n name: \"navFlight\",\n runIf: () => world.getResource(NavTransition)?.active === true,\n },\n );\n}\n","/**\n * THE INTERACTION STACK'S REGISTERED WAKE (2026-09-27, ICE M21 K7a — engine/frame-control.ts's sleep). A sleeping loop asks\n * after every step when the stack is next due; it is due EVERY frame while any of its time-driven work is pending, and\n * otherwise never on its own (the next input wakes the loop through the queue). Each pending state is a fact in the world\n * (the engine's law: all interaction state lives there), read O(1) — a queue's length, a resource, `firstOf` a query:\n * - input waiting in the queue;\n * - a gesture RECOGNIZER alive (systems/l2-recognize.ts): a press held (the long-press timer), a tap's multi-tap window\n * after its release, a drag, a pinch, a wheel gesture's end silence (`wheelEndSilenceMs`) — each reaped once it ended;\n * - the camera gesturing, or its inertia still moving (systems/camera-sim.ts `cameraInertia`);\n * - a transform tween running (`TransformTween`, camera-sim.ts `tweenSystem`);\n * - a nav flight (`NavTransition.active`, systems/nav-flight.ts);\n * - the pegboard's band stretched (systems/tray.ts: it lets go `letGoMs` after the last wheel);\n * - ports materialized (systems/l3-ports.ts: staged over frames, reaped `portReapGraceMs` after their trigger lapsed).\n * The one-tick protocols after an input (the tags `oneTickClear` clears, a recognizer reaped a tick after it ended) are the\n * sleep's tail (`SLEEP_TAIL`), not this reporter's.\n */\nimport type { World } from \"@vibecook/strata-ecs\";\nimport { Any, defineQuery } from \"@vibecook/strata-ecs\";\nimport { Camera } from \"../catalog/camera-derived\";\nimport { Tray } from \"../catalog/desk\";\nimport { Drag, LongPress, Pinch, Tap, TransformTween, WheelPan, WheelZoom } from \"../catalog/gesture\";\nimport { Port } from \"../catalog/graph\";\nimport type { InputQueue } from \"../input/queue\";\nimport { CameraInertia } from \"../systems/camera-sim\";\nimport { NavTransition } from \"../systems/nav-flight\";\n\nconst recognizersQ = defineQuery([Any(Tap, LongPress, Drag, Pinch, WheelPan, WheelZoom)]);\nconst tweensQ = defineQuery([TransformTween]);\nconst traysQ = defineQuery([Tray]);\nconst portsQ = defineQuery([Port]);\n\n/** Which of the stack's time-driven work is pending now — the first found, or undefined when the stack is at rest. */\nexport function interactionPending(world: World, queue: InputQueue): string | undefined {\n if (queue.size() > 0) return \"input\";\n if (world.firstOf(recognizersQ) !== undefined) return \"recognizer\";\n const cam = world.getResource(Camera);\n if (cam?.gesturing === true) return \"gesture\";\n const inertia = world.getResource(CameraInertia);\n if (inertia !== undefined && (inertia.vx !== 0 || inertia.vy !== 0)) return \"inertia\";\n if (world.getResource(NavTransition)?.active === true) return \"flight\";\n if (world.firstOf(tweensQ) !== undefined) return \"tween\";\n const tray = world.firstOf(traysQ);\n if (tray !== undefined && (world.get(tray, Tray)?.stretch ?? 0) !== 0) return \"band\";\n if (world.firstOf(portsQ) !== undefined) return \"ports\";\n return undefined;\n}\n\n/** The stack's registered wake: `now` (the next frame) while anything is pending, else never on its own. */\nexport function interactionDue(world: World, queue: InputQueue): (now: number) => number {\n return (now) => (interactionPending(world, queue) === undefined ? Number.POSITIVE_INFINITY : now);\n}\n\n/** The input queue, waking the loop on every enqueue (Law 2: the adapters only enqueue — this is the one door they share). */\nexport function wakefulQueue(queue: InputQueue, wake: () => void): InputQueue {\n return {\n enqueue(event) {\n queue.enqueue(event);\n wake();\n },\n drain: () => queue.drain(),\n size: () => queue.size(),\n };\n}\n","/**\n * The engine props DSL (design-005 §2, amending design-001 §5.2).\n *\n * Standard Schema is validation-only — it exposes `validate()` but no\n * introspectable shape, so arbitrary schemas cannot compile to typed\n * components. This DSL is the compiler's input: it (a) maps 1:1 onto strata\n * field types plus explicit `p.json` string cells, (b) implements the\n * Standard Schema v1 interface so it plugs into ecosystem tooling, and\n * (c) enforces the definition-time rules — every top-level field defaulted\n * (json derives an empty default from its root shape), enums additive-only\n * across versions (checked by the M9 migrator against pack history; recorded\n * here), `p.json` as the ONLY nesting escape hatch (visibly conflict-coarse:\n * one string cell, last-writer-wins whole-value).\n */\n\n// --- Standard Schema v1 (interface only — no runtime dependency) ---\n\nexport interface StandardSchemaV1<Input = unknown, Output = Input> {\n readonly \"~standard\": {\n readonly version: 1;\n readonly vendor: string;\n readonly validate: (\n value: unknown,\n ) => { value: Output } | { issues: readonly { message: string }[] };\n };\n}\n\n// --- spec kinds ---\n\nexport type PropSpec =\n | StringSpec\n | NumberSpec\n | BooleanSpec\n | EnumSpec\n | JsonSpec\n | EntityKeySpec;\n\nexport interface StringSpec extends StandardSchemaV1<unknown, string> {\n readonly kind: \"string\";\n readonly default?: string;\n}\nexport interface NumberSpec extends StandardSchemaV1<unknown, number> {\n readonly kind: \"number\";\n readonly default?: number;\n readonly min?: number;\n readonly max?: number;\n}\nexport interface BooleanSpec extends StandardSchemaV1<unknown, boolean> {\n readonly kind: \"boolean\";\n readonly default?: boolean;\n}\nexport interface EnumSpec extends StandardSchemaV1<unknown, string> {\n readonly kind: \"enum\";\n readonly options: readonly string[];\n readonly default?: string;\n}\n/** One conflict-coarse string cell; `inner` validates the PARSED value. */\nexport interface JsonSpec extends StandardSchemaV1<unknown, unknown> {\n readonly kind: \"json\";\n readonly inner: JsonShape;\n /** Serialized default (derived from the inner root when not given). */\n readonly default?: string;\n}\n/**\n * A DURABLE entity reference (design-009 §4.2): the doc key of another entity,\n * stored as a plain string cell. This is the ONLY legal cross-entity reference\n * in behavior data — Law 7 bans `eid` from durable cells because a runtime\n * handle means nothing to the peer that receives it, while a doc key survives\n * the wire, the file, and a reload. Empty string = no reference; resolution is\n * `ctx.entityFor(key)`, which may legitimately return undefined while the\n * target is not yet projected.\n */\nexport interface EntityKeySpec extends StandardSchemaV1<unknown, string> {\n readonly kind: \"entityKey\";\n readonly default?: string;\n}\n\n/** Shapes legal only INSIDE p.json (validation-only, never components). */\nexport type JsonShape =\n | { readonly kind: \"string\" }\n | { readonly kind: \"number\" }\n | { readonly kind: \"boolean\" }\n | { readonly kind: \"enum\"; readonly options: readonly string[] }\n | { readonly kind: \"array\"; readonly item: JsonShape }\n | { readonly kind: \"object\"; readonly fields: Readonly<Record<string, JsonShape>> };\n\nexport interface ObjectSpec {\n readonly kind: \"object\";\n readonly fields: Readonly<Record<string, PropSpec>>;\n}\n\n// --- validators ---\n\nfunction fail(message: string): { issues: readonly { message: string }[] } {\n return { issues: [{ message }] };\n}\n\nfunction validateShape(shape: JsonShape, v: unknown, path: string): { message: string } | null {\n switch (shape.kind) {\n case \"string\":\n return typeof v === \"string\" ? null : { message: `${path}: expected string` };\n case \"number\":\n return typeof v === \"number\" && Number.isFinite(v) ? null : { message: `${path}: expected number` };\n case \"boolean\":\n return typeof v === \"boolean\" ? null : { message: `${path}: expected boolean` };\n case \"enum\":\n return typeof v === \"string\" && shape.options.includes(v)\n ? null\n : { message: `${path}: expected one of ${shape.options.join(\"|\")}` };\n case \"array\": {\n if (!Array.isArray(v)) return { message: `${path}: expected array` };\n for (let i = 0; i < v.length; i++) {\n const err = validateShape(shape.item, v[i], `${path}[${i}]`);\n if (err) return err;\n }\n return null;\n }\n case \"object\": {\n if (typeof v !== \"object\" || v === null || Array.isArray(v)) {\n return { message: `${path}: expected object` };\n }\n for (const [k, f] of Object.entries(shape.fields)) {\n const err = validateShape(f, (v as Record<string, unknown>)[k], `${path}.${k}`);\n if (err) return err;\n }\n return null;\n }\n }\n}\n\nfunction std<T>(validate: (v: unknown) => { value: T } | { issues: readonly { message: string }[] }) {\n return { version: 1 as const, vendor: \"ice\", validate };\n}\n\n/** Empty value for a json root shape (the derived default). */\nfunction emptyOf(shape: JsonShape): unknown {\n switch (shape.kind) {\n case \"string\":\n return \"\";\n case \"number\":\n return 0;\n case \"boolean\":\n return false;\n case \"enum\":\n return shape.options[0];\n case \"array\":\n return [];\n case \"object\": {\n const out: Record<string, unknown> = {};\n for (const [k, f] of Object.entries(shape.fields)) out[k] = emptyOf(f);\n return out;\n }\n }\n}\n\n// --- the public DSL ---\n\nexport const p = {\n string(opts: { default?: string } = {}): StringSpec {\n return {\n kind: \"string\",\n ...(opts.default !== undefined ? { default: opts.default } : {}),\n \"~standard\": std((v) => (typeof v === \"string\" ? { value: v } : fail(\"expected string\"))),\n };\n },\n\n number(opts: { default?: number; min?: number; max?: number } = {}): NumberSpec {\n return {\n kind: \"number\",\n ...(opts.default !== undefined ? { default: opts.default } : {}),\n ...(opts.min !== undefined ? { min: opts.min } : {}),\n ...(opts.max !== undefined ? { max: opts.max } : {}),\n \"~standard\": std((v) => {\n if (typeof v !== \"number\" || !Number.isFinite(v)) return fail(\"expected number\");\n if (opts.min !== undefined && v < opts.min) return fail(`min ${opts.min}`);\n if (opts.max !== undefined && v > opts.max) return fail(`max ${opts.max}`);\n return { value: v };\n }),\n };\n },\n\n boolean(opts: { default?: boolean } = {}): BooleanSpec {\n return {\n kind: \"boolean\",\n ...(opts.default !== undefined ? { default: opts.default } : {}),\n \"~standard\": std((v) => (typeof v === \"boolean\" ? { value: v } : fail(\"expected boolean\"))),\n };\n },\n\n enum(options: readonly string[], opts: { default?: string } = {}): EnumSpec {\n if (options.length === 0) throw new Error(\"ice: p.enum needs at least one option.\");\n if (opts.default !== undefined && !options.includes(opts.default)) {\n throw new Error(`ice: p.enum default \"${opts.default}\" is not among its options.`);\n }\n return {\n kind: \"enum\",\n options,\n ...(opts.default !== undefined ? { default: opts.default } : {}),\n \"~standard\": std((v) =>\n typeof v === \"string\" && options.includes(v) ? { value: v } : fail(`expected one of ${options.join(\"|\")}`),\n ),\n };\n },\n\n json(inner: JsonShape, opts: { default?: unknown } = {}): JsonSpec {\n const fallback = opts.default !== undefined ? opts.default : emptyOf(inner);\n const err = validateShape(inner, fallback, \"$default\");\n if (err) throw new Error(`ice: p.json default does not match its shape — ${err.message}`);\n return {\n kind: \"json\",\n inner,\n default: JSON.stringify(fallback),\n \"~standard\": std((v) => {\n const e = validateShape(inner, v, \"$\");\n return e ? { issues: [e] } : { value: v };\n }),\n };\n },\n\n /**\n * A durable reference to another entity by DOC KEY (design-009 §4.2).\n * Behavior-facing: `defineWidget` props have no use for it (a widget's\n * references are relations), but nothing rejects it there either — it is an\n * ordinary string cell with a declared meaning.\n */\n entityKey(opts: { default?: string } = {}): EntityKeySpec {\n return {\n kind: \"entityKey\",\n default: opts.default ?? \"\",\n \"~standard\": std((v) => (typeof v === \"string\" ? { value: v } : fail(\"expected an entity key (string)\"))),\n };\n },\n\n // json-only inner shapes (validation, never components):\n array(item: JsonShape): JsonShape {\n return { kind: \"array\", item };\n },\n object(fields: Readonly<Record<string, JsonShape>>): JsonShape {\n return { kind: \"object\", fields };\n },\n};\n\n/** A widget props declaration: top-level named specs (the compiler's input). */\nexport type PropsDecl = Readonly<Record<string, PropSpec>>;\n\n/**\n * The CELL default for a spec — the value a whole-component write fills in for\n * an untouched field, and the value a generated strata field declares.\n *\n * One function, three callers (widget spawn defaults, `defineWidget`'s\n * essential set, `defineBehavior`'s attach defaults): each used to carry its\n * own else-if chain over `spec.kind`, and each chain had to be found and\n * amended when `p.entityKey` was added — one of them by inspection rather than\n * by a type error, since the chains end in a catch-all `else`. It lives here,\n * beside the specs whose shape it reads.\n */\nexport function defaultValueOf(spec: PropSpec): string | number | boolean {\n switch (spec.kind) {\n case \"json\":\n return spec.default ?? \"null\";\n case \"enum\":\n return spec.default ?? spec.options[0] ?? \"\";\n case \"string\":\n case \"entityKey\":\n return spec.default ?? \"\";\n case \"number\":\n return spec.default ?? 0;\n case \"boolean\":\n return spec.default ?? false;\n }\n}\n","/**\n * `defineBehavior` — the type surface (design-009 §3–§4, the pinned API).\n *\n * ICE's userland surface is a triad: `defineWidget` (faces) · **behaviors**\n * (logic + state) · `defineTool` (input policy). A behavior is the A-Frame-class\n * unit — ONE named declaration carrying a data schema, a REQUIRED store class,\n * and lifecycle hooks the engine runs on a curated phase set.\n *\n * `store:` is the load-bearing word: it routes where data lives, who sees it,\n * what survives, WHICH WRITE VOCABULARY the hooks receive, at which cadence.\n * That last routing is the reason the ctx types below are three interfaces and\n * not one with optional members — a durable behavior must not see `ctx.write`\n * in autocomplete at all, or \"store routes everything\" is a doc claim rather\n * than a property of the product.\n */\nimport type { Component, Entity, Relation, Resource, Tag } from \"@vibecook/strata-ecs\";\nimport type { GuardedTx } from \"../guards/guarded-tx\";\nimport type {\n BooleanSpec,\n EntityKeySpec,\n EnumSpec,\n JsonShape,\n JsonSpec,\n NumberSpec,\n PropSpec,\n StringSpec,\n} from \"../widget/props\";\n\n// --- store class + phases ----------------------------------------------------\n\nexport type BehaviorStore = \"durable\" | \"runtime\" | \"ephemeral\";\n\n/**\n * The CURATED phase set (design-009 §4.4, BF-D8) — a deliberate subset of the\n * eleven pipeline groups. Authors get the four that mean something to logic;\n * the control sweep (`ctl:*`), `input`, `react` and `cleanup` stay engine\n * vocabulary. `publish` is not a pipeline group at all — it is the post-tick\n * slot where ephemeral mutation is legal.\n */\nexport type BehaviorPhase = \"simulate\" | \"derive\" | \"present\" | \"publish\";\n\n/** Legal `phase` per store class — the §4.1 validation table, as data. */\nexport const BEHAVIOR_PHASES: Readonly<Record<BehaviorStore, readonly BehaviorPhase[]>> = {\n // Durable is derive-ONLY and the reason is stated: its sole write path is\n // transactional, and `derive` is the settled-input phase — the one place a\n // commit reads inputs that will not move again this frame.\n durable: [\"derive\"],\n runtime: [\"simulate\", \"derive\", \"present\", \"publish\"],\n ephemeral: [\"publish\"],\n};\n\n/** Default phase per store (the one most declarations want). */\nexport const BEHAVIOR_DEFAULT_PHASE: Readonly<Record<BehaviorStore, BehaviorPhase>> = {\n durable: \"derive\",\n runtime: \"simulate\",\n ephemeral: \"publish\",\n};\n\n// --- schema → data typing ----------------------------------------------------\n\n/** A behavior's declared data: the SAME `p.*` DSL `defineWidget` uses. */\nexport type BehaviorSchema = Readonly<Record<string, PropSpec>>;\n\nexport type BehaviorHookName = \"init\" | \"update\" | \"changed\" | \"tick\" | \"dispose\";\n\nexport type BehaviorPropDescription =\n | { readonly kind: \"string\"; readonly default?: string }\n | {\n readonly kind: \"number\";\n readonly default?: number;\n readonly min?: number;\n readonly max?: number;\n }\n | { readonly kind: \"boolean\"; readonly default?: boolean }\n | {\n readonly kind: \"enum\";\n readonly options: readonly string[];\n readonly default?: string;\n }\n | { readonly kind: \"json\"; readonly inner: JsonShape; readonly default?: string }\n | { readonly kind: \"entityKey\"; readonly default?: string };\n\nexport interface BehaviorReadDescription {\n readonly kind: \"behavior\" | \"component\" | \"tag\" | \"relation\" | \"resource\";\n readonly name: string;\n}\n\nexport interface BehaviorDescription {\n readonly id: string;\n readonly store: BehaviorStore;\n readonly derived: boolean;\n readonly deriveDuringGesture: boolean;\n readonly version: number;\n readonly phase: BehaviorPhase;\n readonly budgetMs?: number;\n /**\n * The declared facet byte claim (petition I19), verbatim. ABSENT when the\n * behavior attested no bound — hosts that require one can tell the two\n * apart and refuse admission accordingly.\n */\n readonly maxFacetBytes?: number;\n readonly tickWhile: \"all\" | \"visible\";\n readonly schema: readonly {\n readonly name: string;\n readonly spec: BehaviorPropDescription;\n }[];\n readonly reads: readonly BehaviorReadDescription[];\n readonly writes: readonly string[];\n readonly migrationFrom: readonly number[];\n readonly hooks: readonly BehaviorHookName[];\n}\n\ntype ValueOfSpec<S extends PropSpec> = S extends NumberSpec\n ? number\n : S extends BooleanSpec\n ? boolean\n : S extends EnumSpec\n ? string\n : S extends JsonSpec\n ? unknown\n : S extends StringSpec | EntityKeySpec\n ? string\n : never;\n\n/**\n * The hook-facing data view. `p.json` fields arrive PARSED (the cell is a\n * string; the snapshot carries the value) — parsing happens once per delivery,\n * and delivery only runs on change, so the cost is keyed to churn rather than\n * to frame rate. `ctx.write`/`tx.write` serialize back.\n */\nexport type DataOf<Sch extends BehaviorSchema> = { readonly [K in keyof Sch]: ValueOfSpec<Sch[K]> };\n\n// --- reads ------------------------------------------------------------------\n\n/**\n * Anything a behavior may declare in `reads:` — components, tags, relations,\n * resources, or another behavior (its data component). Each kind is routed to\n * a different change mechanism by the compiler (§5.2), which is why the\n * partition is compiler work and not an author concern.\n */\nexport type BehaviorRead = Component | Tag | Relation | Resource | AnyBehaviorDef;\n\n/** The drained journal summary, valid only for the duration of the hook call. */\nexport interface BehaviorChanges {\n /** Rebuild everything: first run, `world.reset()`, coarse writes, or a poll fired. */\n readonly full: boolean;\n /** Journaled entities — re-read current state to act. */\n readonly changed: readonly Entity[];\n /** DESTROYED entities (packed handles; safe as removal keys). */\n readonly removed: readonly Entity[];\n}\n\n// --- the world wrapper -------------------------------------------------------\n\n/**\n * `ctx.world` is a HOST-BUILT WRAPPER, not a `World` alias and not\n * `ReadonlyWorld` (BF-D19): that type is `Omit<World, WorldMutatorName>`, which\n * keeps `.runtime` — the full mutable store — so it is a naming convention, not\n * a sandbox. This interface exposes exactly the read surface and nothing else.\n *\n * Honesty note: point reads through this wrapper are ATTRIBUTION-ONLY — strata\n * enforces declared reads solely at `batch.col()`, so the compiled delivery\n * walk (`ctx.query`) is where enforcement is real.\n */\nexport interface BehaviorWorld {\n read<S>(e: Entity, c: Component<S>): S;\n get<S>(e: Entity, c: Component<S>): S | undefined;\n readField<S, K extends keyof S & string>(e: Entity, c: Component<S>, field: K): S[K] | undefined;\n has(e: Entity, c: Component): boolean;\n hasTag(e: Entity, t: Tag): boolean;\n getRelation(e: Entity, r: Relation): Entity | undefined;\n getRelations(e: Entity, r: Relation): Entity[];\n getReverse(e: Entity, r: Relation): Entity[];\n /** Sibling-sequence version for one parent — ordered relations (petition 8). */\n orderStamp(parent: Entity, r: Relation): number;\n getResource<S>(res: Resource<S>): S | undefined;\n componentsOf(e: Entity): readonly Component[];\n tagsOf(e: Entity): readonly Tag[];\n isAlive(e: Entity): boolean;\n}\n\n/** A reads-scoped query walk. Terms are restricted to the behavior's `reads`. */\nexport interface BehaviorQuery {\n /** Every matching entity. The array is FRESH per call — retaining it is legal. */\n entities(): Entity[];\n /** Iterate matches one at a time (no array allocated). */\n each(fn: (e: Entity) => void): void;\n /** First match, or undefined. */\n first(): Entity | undefined;\n}\n\n/** Query terms a behavior may build — its declared reads, positively or negatively. */\nexport interface BehaviorQuerySpec {\n /** Entities must carry ALL of these (components/tags from `reads`). */\n readonly all?: readonly (Component | Tag | AnyBehaviorDef)[];\n /** Entities must carry NONE of these. */\n readonly none?: readonly (Component | Tag | AnyBehaviorDef)[];\n}\n\n// --- ctx --------------------------------------------------------------------\n\n/** Frame facts a `tick` hook reads. */\nexport interface BehaviorFrame {\n readonly dtMs: number;\n readonly tick: number;\n /** Accumulated CLAMPED dt — under-reports across freezes; never wall time. */\n readonly clock: number;\n}\n\n/** One remote peer's facet of an ephemeral behavior (`ctx.peers()`). */\nexport interface PeerFacet<Data> {\n /** The remote presence-peer entity (runtime handle — do not persist). */\n readonly entity: Entity;\n readonly data: Readonly<Data>;\n}\n\nexport interface BehaviorCtxBase<Data> {\n /** The read wrapper (above). */\n readonly world: BehaviorWorld;\n /**\n * A reads-SCOPED query. The framework compiles and caches one Query per\n * distinct spec and walks it ATTRIBUTED — strata's only enforced read path,\n * and its only zero-allocation bulk path. Without this, navigation was\n * instances-outward only and `changed` got abused as a discovery channel.\n *\n * The navigation model, stated: behaviors navigate from their instances\n * outward via relations, the change journal, and reads-scoped queries. There\n * is no global search.\n */\n query(spec: BehaviorQuerySpec): BehaviorQuery;\n /** This behavior's own instances, this frame (snapshot — do not retain). */\n entities(): readonly Entity[];\n /** The drained journal summary. Meaningful during `changed`; do not retain. */\n changes(): BehaviorChanges;\n /** The journal ∩ this behavior's instances — the exact set. Do not retain. */\n changedEntities(): readonly Entity[];\n /** Durable doc key for an entity (undefined when not doc-bound). */\n keyOf(e: Entity): string | undefined;\n /** The entity for a durable key — undefined while it is not yet projected. */\n entityFor(key: string): Entity | undefined;\n /** Aborts at generation teardown (`world.reset`), detach, or engine dispose. */\n readonly signal: AbortSignal;\n /** Namespaced logging — routed to the host's diagnostics, never raw console. */\n log(message: string, ...rest: readonly unknown[]): void;\n}\n\nexport interface DurableBehaviorCtx<Data> extends BehaviorCtxBase<Data> {\n /**\n * ONE labeled transaction. The transaction opens INSIDE the hook, in-system\n * (design-002-blessed): values land synchronously and this frame's `notify`\n * sees them — never queued past the tick. `label` is a stable MACHINE id\n * (namespaced), never display text: it feeds undo and in-CRDT provenance.\n *\n * Refuses on a read-only document. `tx.setResource` is MASKED (the §9\n * resource-write fence, made mechanical) — a behavior calling it DEV-throws\n * naming the `singleton` v1.1 seam.\n */\n commit(label: string, fn: (tx: BehaviorTx<Data>) => void, opts?: { undoable?: boolean }): void;\n}\n\nexport interface RuntimeBehaviorCtx<Data> extends BehaviorCtxBase<Data> {\n /** Write this behavior's OWN data on `e` (immediate; session-local). */\n write(e: Entity, patch: Partial<Data>): void;\n /** Write a declared runtime-store `writes:` target (immediate). */\n set<S>(e: Entity, c: Component<S>, v: S): void;\n attach(e: Entity, data?: Partial<Data>): void;\n detach(e: Entity): void;\n /** A runtime behavior may also commit durable state (a settle writing finals once). */\n commit(label: string, fn: (tx: BehaviorTx<Data>) => void, opts?: { undoable?: boolean }): void;\n}\n\nexport interface EphemeralBehaviorCtx<Data> extends BehaviorCtxBase<Data> {\n /**\n * Publish THIS PEER's facet. No entity argument — the instance IS the local\n * presence peer, and there is exactly one. Legal here because ephemeral hooks\n * run at the publish slot, post-tick, where eph mutation is allowed.\n */\n write(patch: Partial<Data>): void;\n /** REMOTE peers' facets of this behavior (read-only; `Not(Local)` projections). */\n peers(): readonly PeerFacet<Data>[];\n}\n\nexport type BehaviorCtxFor<S extends BehaviorStore, Data> = S extends \"durable\"\n ? DurableBehaviorCtx<Data>\n : S extends \"runtime\"\n ? RuntimeBehaviorCtx<Data>\n : EphemeralBehaviorCtx<Data>;\n\n/**\n * The door's transaction: `GuardedTx` plus behavior attachment and typed\n * own-data writes. `setResource` is absent by construction (§4.4's mask).\n */\nexport interface BehaviorTx<Data> extends Omit<GuardedTx, \"setResource\"> {\n /** Write this behavior's own data on `e` (absolute, whole-value). */\n write(e: Entity, patch: Partial<Data>): void;\n /** Attach a behavior as a DOCUMENT op — syncs, undoes, runs on every peer. */\n attach<D>(e: Entity, behavior: BehaviorHandle<D>, data?: Partial<D>): void;\n detach(e: Entity, behavior: AnyBehaviorDef): void;\n}\n\n// --- hooks -------------------------------------------------------------------\n\nexport interface BehaviorHooks<S extends BehaviorStore, Data> {\n /**\n * Instance appeared: attached locally, projected in (REMOTE included), or\n * existing at generation start. Runs before that instance's first `tick`.\n * A throw here marks the INSTANCE failed — no further hooks until re-attach.\n */\n init?(e: Entity, data: Readonly<Data>, ctx: BehaviorCtxFor<S, Data>): void;\n /**\n * OWN declared data changed since the last delivery — by ANY writer: this\n * behavior's commit, another plugin's tx, UNDO, or a remote peer.\n * Per-instance; `prev` is the last-delivered snapshot. \"update is about you.\"\n */\n update?(e: Entity, data: Readonly<Data>, prev: Readonly<Data>, ctx: BehaviorCtxFor<S, Data>): void;\n /**\n * The reads-set changed. ONCE PER BEHAVIOR per frame, not per instance —\n * N instances × one tag flip must not mean N journal scans.\n * \"changed is about the world.\"\n */\n changed?(ctx: BehaviorCtxFor<S, Data>): void;\n /**\n * Per frame per instance — OPT-IN cost. Default is ALL instances (Law 14: an\n * off-screen spring still settles); `tick: { while: \"visible\" }` is the\n * author's DECLARED suspension. `init`/`update`/`changed`/`dispose` never\n * suspend: culling is not lifecycle, and state must be right the moment it\n * becomes visible again.\n */\n tick?(e: Entity, data: Readonly<Data>, frame: BehaviorFrame, ctx: BehaviorCtxFor<S, Data>): void;\n /**\n * Instance gone: detached, despawned, disabled, or generation end. `e` may\n * already be dead (world access is DEV-guarded) — this is for cache cleanup.\n * Runs for ALL instances BEFORE `ctx.signal` aborts.\n */\n dispose?(e: Entity, ctx: BehaviorCtxFor<S, Data>): void;\n}\n\n// --- the declaration ---------------------------------------------------------\n\nexport interface BehaviorSpec<S extends BehaviorStore, Sch extends BehaviorSchema> {\n /** REQUIRED — routes everything (§3). */\n readonly store: S;\n /**\n * This behavior's durable writes are COMPUTED from other state. Durable only.\n * Bundles three protections: non-undoable output, the differ, and\n * claim-scoped delivery suppression (§5.3).\n */\n readonly derived?: boolean;\n /**\n * Opt out of suppression: derive live during gestures (costs accepted).\n * `derived` only.\n */\n readonly deriveDuringGesture?: boolean;\n /** Durable only — the `engine.behavior.<name>.<v>` marker family (§5.6). */\n readonly version?: number;\n readonly schema?: Sch;\n /** Durable only: fromVersion → idempotent absolute transform. */\n readonly migrate?: Readonly<Record<number, (prev: Record<string, unknown>) => Record<string, unknown>>>;\n /** Defaults per store (§4.4); validated against the legal set. */\n readonly phase?: BehaviorPhase;\n /** Per-frame budget request, ms. The breaker caps it at the seam ceiling. */\n readonly budgetMs?: number;\n /**\n * Ephemeral only — the producer's own resource claim (petition I19): a hard\n * ceiling on the canonical UTF-8 JSON bytes of this behavior's COMPLETE\n * facet cell after defaults/merge/serialization (the value placed in the\n * local peer blob — not a wire-frame guess; hosts budget transport headroom\n * separately). Enforced in PRODUCTION, not as a dev advisory: an over-budget\n * default fails the definition before anything publishes, and an over-budget\n * `ctx.write` throws before mutating presence — the prior facet stays\n * intact, and in-hook the throw feeds the ordinary fault ladder (BF-D18\n * attribution, three strikes, I17 withdrawal on quarantine). Identity-\n * bearing: part of the definition signature and of `describeBehavior()`.\n */\n readonly maxFacetBytes?: number;\n readonly reads?: readonly BehaviorRead[];\n readonly writes?: readonly Component[];\n /**\n * `tick` scope. `{ while: \"visible\" }` compiles a `Not(Culled)` term into the\n * chunked tick system — declared suspension, never discovered.\n */\n readonly tick?: { readonly while?: \"visible\" | \"all\" };\n readonly on?: BehaviorHooks<S, DataOf<Sch>>;\n}\n\n/** A behavior pre-attachment: `Layout.with({ gapX: 32 })`. */\nexport interface BehaviorAttachSpec<Data = Record<string, unknown>> {\n readonly behavior: BehaviorHandle<Data>;\n readonly data: Partial<Data>;\n}\n\n/**\n * The compiled declaration. Usable wherever a behavior is expected —\n * `reads: [Glow]`, `behaviors: [Layout]`, `tx.attach(e, Layout)` — plus\n * `.with(data)` for pre-attachment and `.component` for advanced read paths.\n */\nexport interface BehaviorHandle<Data> {\n /** `<namespace>:<name>` — the process-global identity. */\n readonly name: string;\n readonly namespace: string;\n readonly store: BehaviorStore;\n readonly derived: boolean;\n readonly deriveDuringGesture: boolean;\n readonly version: number;\n readonly phase: BehaviorPhase;\n readonly budgetMs: number | undefined;\n /** The I19 facet byte claim; `undefined` = no bound attested. */\n readonly maxFacetBytes: number | undefined;\n readonly schema: BehaviorSchema;\n /** The generated data component (`behavior:<name>`). Advanced read paths. */\n readonly component: Component<Record<string, string | number | boolean>>;\n /** Every field at its declared default (the attach fill). */\n readonly defaults: Readonly<Data>;\n readonly reads: readonly BehaviorRead[];\n readonly writes: readonly Component[];\n readonly migrate: Readonly<Record<number, (prev: Record<string, unknown>) => Record<string, unknown>>>;\n readonly tickWhile: \"all\" | \"visible\";\n /**\n * The hook set. MUTABLE by design: a same-shape re-definition (hot reload,\n * a test re-importing a module) refreshes these in place, so the cached\n * handle keeps its component and collector identity while the new code\n * actually runs. Stale-hook HMR is the wart this avoids.\n */\n on: BehaviorHooks<BehaviorStore, Data>;\n /** Pre-attachment with data: `behaviors: [Layout.with({ gapX: 32 })]`. */\n with(data: Partial<Data>): BehaviorAttachSpec<Data>;\n /** @internal brand — how `reads:` tells a behavior from a component. */\n readonly __behavior: true;\n}\n\n/** A behavior handle of unknown data shape (registries, `reads:` lists). */\n// biome-ignore lint/suspicious/noExplicitAny: the registry is data-shape-agnostic by construction.\nexport type AnyBehaviorDef = BehaviorHandle<any>;\n\n/**\n * A pre-attachment of unknown data shape — what a LIST of them has to be typed\n * as. `BehaviorAttachSpec<never>` looks like the shape-agnostic form and is\n * not: `Layout.with({gapX: 32})` produces `BehaviorAttachSpec<{gapX: number}>`,\n * which is not assignable to it, so the documented `with()` form would not\n * typecheck in `defineWidget({behaviors})` at all.\n */\n// biome-ignore lint/suspicious/noExplicitAny: same reason as AnyBehaviorDef.\nexport type AnyBehaviorAttachSpec = BehaviorAttachSpec<any>;\n","/**\n * The CURATED public read surface for behaviors (design-009 §9).\n *\n * The engine catalog is exposed to behaviors DELIBERATELY, not accidentally.\n * Every name on this list is a published contract: it is what a behavior may\n * declare in `reads:` and expect to keep working across engine versions. Adding\n * a name here is a product decision — it is a promise about a shape, not a\n * convenience.\n *\n * Everything else in the catalog is ENGINE VOCABULARY: recognizers, claims,\n * gesture bookkeeping, one-tick markers. Reading it from a behavior is not\n * forbidden (the escape hatch stays open for engine-grade code), but it\n * dev-WARNS, because those shapes change whenever the interaction stack does\n * and no one will think to tell a plugin author.\n *\n * Two notes authors need and will not guess:\n * - One-tick markers (`WentDown`, the `Just*` family) are already CLEARED by\n * the time the publish slot runs, so an ephemeral behavior can never see\n * them. That is not a bug to route around; it is what \"one tick\" means.\n * - `Grab` and the claim relations are deliberately OFF the list. A behavior\n * that wants to know \"is this being dragged right now\" is usually asking\n * for claim-scoped suppression, which it already gets for free.\n */\nimport type { Component, Relation, Resource, Tag } from \"@vibecook/strata-ecs\";\nimport { CameraLimits } from \"../catalog/settings-resources\";\nimport { Camera, Culled, Viewport, Visible } from \"../catalog/camera-derived\";\nimport { ChildOf, Opacity, Position, Size } from \"../catalog/scene\";\nimport { Accepts, Container, Provides } from \"../catalog/graph\";\nimport { Movable, Resizable, Selectable, Selected } from \"../catalog/selection-presence\";\nimport { Solid } from \"../catalog/gesture\";\nimport { PrefabId } from \"../schema/prefab\";\n\n/**\n * The published set. Ordered by what an author reaches for first: geometry,\n * then structure, then state, then the view.\n */\nexport const PUBLIC_READS: ReadonlySet<Component | Tag | Relation | Resource> = new Set<\n Component | Tag | Relation | Resource\n>([\n // Geometry — the whole reason most behaviors exist.\n Position as Component,\n Size as Component,\n Opacity as Component,\n // Structure.\n ChildOf as Relation,\n PrefabId as Component,\n Accepts as Component,\n Provides as Component,\n // Interaction STATE (never the machinery that produces it).\n Selected as Tag,\n Selectable as Tag,\n Movable as Tag,\n Resizable as Tag,\n Solid as Tag,\n Container as Tag,\n // The view.\n Visible as Tag,\n Culled as Tag,\n Camera as Resource,\n CameraLimits as Resource,\n Viewport as Resource,\n]);\n\n/** Is this handle part of the published behavior read surface? */\nexport function isPublicRead(handle: Component | Tag | Relation | Resource): boolean {\n return PUBLIC_READS.has(handle);\n}\n","/**\n * `defineBehavior` — definition, validation, and the process-global registry\n * (design-009 §4.1).\n *\n * Compile output is one generated component per behavior (`behavior:<name>`),\n * which is also the CONFLICT UNIT: one behavior = one component = one\n * committer-wins cell. The guidance line for authors, worth repeating here\n * because it is the rule that keeps collaboration sane: *would two peers\n * plausibly edit these fields concurrently? Then they are two behaviors.*\n *\n * Everything in this file is definition-time. The compiler (compile.ts) owns\n * the checks that need a populated world — above all the durable-eligibility\n * refusal, which cannot run here: at module-eval time the prefab registry may\n * not yet hold the widget whose Position the behavior writes, and a check that\n * depends on import order is a check that reports differently on a good day.\n */\nimport type { Component, Relation, Resource, Tag } from \"@vibecook/strata-ecs\";\nimport { devGuardsEnabled } from \"../guards/dev\";\nimport { ensureComponent, schemaMeta } from \"../schema/meta\";\nimport {\n defaultValueOf,\n type JsonShape,\n type JsonSpec,\n type PropSpec,\n} from \"../widget/props\";\nimport { isPublicRead } from \"./public-reads\";\nimport { field } from \"@vibecook/strata-ecs\";\nimport { enumOf } from \"@vibecook/strata-ecs\";\nimport {\n BEHAVIOR_DEFAULT_PHASE,\n BEHAVIOR_PHASES,\n type AnyBehaviorDef,\n type BehaviorDescription,\n type BehaviorHandle,\n type BehaviorHookName,\n type BehaviorHooks,\n type BehaviorPropDescription,\n type BehaviorReadDescription,\n type BehaviorRead,\n type BehaviorSchema,\n type BehaviorSpec,\n type BehaviorStore,\n type DataOf,\n} from \"./types\";\n\nconst STORES: readonly BehaviorStore[] = [\"durable\", \"runtime\", \"ephemeral\"];\n\n/**\n * `<namespace>:<name>` — exactly one colon, both halves non-empty, and no\n * whitespace. The namespace is what a plugin host validates against the\n * declaring plugin id (the harness precedent): without that check two\n * colliding same-shape names would silently share one component with BOTH\n * hook sets running.\n */\nconst NAME_RE = /^[A-Za-z0-9][A-Za-z0-9._-]*:[A-Za-z0-9][A-Za-z0-9._-]*$/;\n\n/**\n * The RESERVED namespace (2026-09-06, A3b fix 4). `ice:` names were given two\n * privileges nothing else had — the compiler's `orderIndependent` attestation\n * on their declared writes, and an exemption from the published-read-surface\n * warning — and BOTH were keyed on the string prefix, so a pack that called\n * itself `ice:surface.kiosk` was handed the engine's own promises. The\n * attestation is the sharp end: it said \"these co-writers of `SurfaceTarget`\n * are ICE's and row-disjoint by law\" (the surface vocabulary, retired at\n * design-015 D5b), which silenced precisely the advisory a second writer of\n * one entity's target needed to hear.\n *\n * So the namespace is the engine's alone. The mark is a module-private symbol\n * — not exported, not on the spec type, unforgeable from outside this file —\n * supplied only by `defineEngineBehavior` below. Its three callers, the\n * `ice:surface.*` kind behaviours (`surface/standard-behaviors.ts`), left at\n * design-015 D5b with the DOM/GPU presentation choice they wrote; the door\n * stays for the engine's next behaviour, and the reservation stands.\n */\nconst ENGINE_MARK = Symbol(\"ice.engineBehavior\");\nconst RESERVED_NAMESPACE = \"ice:\";\n\nfunction isEngineSpec(spec: object): boolean {\n return (spec as Record<symbol, unknown>)[ENGINE_MARK] === true;\n}\n\n/**\n * The generated component's name. Prefixed so a behavior can never collide\n * with `defineWidget`'s `<type>:<group>` components — and, because this string\n * is the DURABLE key that projection is driven by, it is a permanent wire\n * format decision, not an implementation detail. A collision anywhere is loud\n * (`ensureComponent` throws on same-name/different-shape), never silent.\n */\nexport function behaviorComponentName(name: string): string {\n return `behavior:${name}`;\n}\n\nconst registry = new Map<string, AnyBehaviorDef>();\nconst byComponent = new Map<Component, AnyBehaviorDef>();\n\nexport const behaviors = {\n get(name: string): AnyBehaviorDef | undefined {\n return registry.get(name);\n },\n all(): AnyBehaviorDef[] {\n return [...registry.values()];\n },\n /** The behavior that owns a generated data component, if any. */\n forComponent(c: Component): AnyBehaviorDef | undefined {\n return byComponent.get(c);\n },\n /** Is `c` a behavior's own data component? (the BF-D6 eligibility branch). */\n isBehaviorComponent(c: Component): boolean {\n return byComponent.has(c);\n },\n};\n\n// --- reads classification ----------------------------------------------------\n\nexport type ReadKind = \"component\" | \"tag\" | \"relation\" | \"resource\" | \"behavior\";\n\n/**\n * Classify a `reads:` entry. Handles are opaque and structurally ambiguous\n * (Component and Resource have IDENTICAL shapes), so classification goes\n * through ICE's own schema registries — which doubles as the §4.1 rule that\n * reads must name REGISTERED schema: anything defined outside the `@ice/core`\n * wrappers is unclassifiable here and is rejected rather than guessed at.\n */\nexport function classifyRead(r: BehaviorRead): { kind: ReadKind; name: string } | undefined {\n if (typeof r === \"object\" && r !== null && (r as AnyBehaviorDef).__behavior === true) {\n return { kind: \"behavior\", name: (r as AnyBehaviorDef).name };\n }\n const c = schemaMeta.component(r as Component);\n if (c !== undefined) return { kind: \"component\", name: c.name };\n const t = schemaMeta.tagName(r as Tag);\n if (t !== undefined) return { kind: \"tag\", name: t };\n const rel = schemaMeta.relation(r as Relation);\n if (rel !== undefined) return { kind: \"relation\", name: rel.name };\n const res = schemaMeta.resource(r as Resource);\n if (res !== undefined) return { kind: \"resource\", name: res.name };\n return undefined;\n}\n\n/** The read component a `reads:` entry contributes, if it contributes one. */\nexport function readComponentOf(r: BehaviorRead): Component | undefined {\n if (typeof r === \"object\" && r !== null && (r as AnyBehaviorDef).__behavior === true) {\n return (r as AnyBehaviorDef).component as Component;\n }\n return schemaMeta.component(r as Component) !== undefined ? (r as Component) : undefined;\n}\n\n// --- schema compilation ------------------------------------------------------\n\nfunction strataFieldOf(behavior: string, name: string, spec: PropSpec) {\n switch (spec.kind) {\n case \"string\":\n return field(\"string\", { default: spec.default ?? \"\" });\n case \"entityKey\":\n return field(\"string\", { default: spec.default ?? \"\" });\n case \"number\":\n return field(\"f64\", { default: spec.default ?? 0 });\n case \"boolean\":\n return field(\"bool\", { default: spec.default ?? false });\n case \"enum\": {\n const fallback = spec.default ?? spec.options[0] ?? \"\";\n return field(enumOf([...spec.options]), { default: fallback });\n }\n case \"json\":\n return field(\"string\", { default: (spec as JsonSpec).default ?? \"null\" });\n default:\n throw new Error(\n `ice: defineBehavior(\"${behavior}\") field \"${name}\" is not a p.* spec — behavior data is declared with the same DSL as widget props.`,\n );\n }\n}\n\n/** The whole-value default record (the attach fill; also the cell defaults). */\nfunction defaultsOf(schema: BehaviorSchema): Record<string, string | number | boolean> {\n const out: Record<string, string | number | boolean> = {};\n for (const [name, spec] of Object.entries(schema)) out[name] = defaultValueOf(spec);\n return out;\n}\n\n// --- the facet byte measure (petition I19) ------------------------------------\n\nconst utf8 = new TextEncoder();\n\n/**\n * The canonical byte measure `maxFacetBytes` is enforced in: UTF-8 JSON of the\n * COMPLETE raw cell (json fields already serialized to strings) with fields in\n * schema declaration order — which is every cell's construction order\n * (`cellForBehavior`, `defaultsOf` both iterate the schema), so a plain\n * `JSON.stringify` is canonical without a key-sort pass. This measures the\n * value placed in the local peer blob, deliberately NOT a wire-frame guess:\n * the I19 division of labor has the host budget encoding/transport headroom\n * on top of the sum of claims it admitted.\n */\nexport function facetBytesOf(cell: Record<string, unknown>): number {\n return utf8.encode(JSON.stringify(cell)).length;\n}\n\n// --- the definition-shape signature (re-definition compare) ------------------\n\n/**\n * What \"the same declaration\" means for the ensure-cache. Hooks are\n * DELIBERATELY excluded: a hot reload hands us new function identities for the\n * same behavior, and refusing that would make HMR throw — so a matching\n * signature refreshes the hooks on the cached handle instead (see below).\n */\nfunction signatureOf(spec: BehaviorSpec<BehaviorStore, BehaviorSchema>, phase: string): string {\n const schema = spec.schema ?? {};\n return JSON.stringify({\n store: spec.store,\n derived: spec.derived === true,\n deriveDuringGesture: spec.deriveDuringGesture === true,\n version: spec.version ?? 1,\n phase,\n tickWhile: spec.tick?.while ?? \"all\",\n // The I19 byte claim is IDENTITY-BEARING: a redefinition that changes only\n // the claim is a different declaration (hosts compare descriptors; the\n // ensure-cache must agree). `?? null` because JSON.stringify drops\n // undefined-valued keys, which would alias \"no claim\" with \"absent field\".\n maxFacetBytes: spec.maxFacetBytes ?? null,\n // Field ORDER is part of the shape: it is the generated component's column\n // order, which the durable cell layout depends on.\n schema: Object.entries(schema).map(([k, s]) => [k, s.kind, defaultValueOf(s)]),\n reads: (spec.reads ?? []).map((r) => classifyRead(r)?.name ?? \"<unregistered>\"),\n writes: (spec.writes ?? []).map((c) => schemaMeta.component(c)?.name ?? \"<unregistered>\"),\n migrate: Object.keys(spec.migrate ?? {}).sort(),\n });\n}\n\nconst signatures = new Map<string, string>();\n\n// --- validation --------------------------------------------------------------\n\nfunction fail(name: string, message: string): never {\n throw new Error(`ice: defineBehavior(\"${name}\") — ${message}`);\n}\n\nfunction validate(name: string, spec: BehaviorSpec<BehaviorStore, BehaviorSchema>, phase: string): void {\n if (!NAME_RE.test(name)) {\n fail(\n name,\n 'names are \"<namespace>:<name>\" (letters, digits, dot, dash, underscore; exactly one colon) — the namespace is what a plugin host validates against the declaring plugin id.',\n );\n }\n if (name.startsWith(RESERVED_NAMESPACE) && !isEngineSpec(spec)) {\n fail(\n name,\n `the \"${RESERVED_NAMESPACE}\" namespace is RESERVED for the engine's own behaviors. It carries privileges a pack must not inherit — the compiler's orderIndependent attestation on declared writes, and an exemption from the published-read-surface warning — so a behavior named into it would silence the very advisory that reports a second writer of one component. Namespace yours after your pack.`,\n );\n }\n if (!STORES.includes(spec.store)) {\n fail(name, `store must be one of ${STORES.join(\" | \")} — it is REQUIRED and it routes everything (§3).`);\n }\n\n const durableOnly: readonly [string, unknown][] = [\n [\"derived\", spec.derived],\n [\"version\", spec.version],\n [\"migrate\", spec.migrate],\n ];\n if (spec.store !== \"durable\") {\n for (const [key, value] of durableOnly) {\n if (value !== undefined) {\n fail(name, `\"${key}\" is durable-only — a ${spec.store} behavior has no document cells to derive, version, or migrate.`);\n }\n }\n }\n if (spec.deriveDuringGesture !== undefined && spec.derived !== true) {\n fail(name, '\"deriveDuringGesture\" opts OUT of claim-scoped suppression, which only derived behaviors are subject to (§5.3).');\n }\n\n const legal = BEHAVIOR_PHASES[spec.store];\n if (!legal.includes(phase as (typeof legal)[number])) {\n fail(\n name,\n `phase \"${phase}\" is not legal for a ${spec.store} behavior — legal: ${legal.join(\" | \")}.${\n spec.store === \"durable\"\n ? \" Durable is derive-only because its sole write path is transactional and derive is the settled-input phase (§3).\"\n : \"\"\n }`,\n );\n }\n\n if (spec.budgetMs !== undefined && (!Number.isFinite(spec.budgetMs) || spec.budgetMs <= 0)) {\n fail(name, `budgetMs must be a positive number (got ${String(spec.budgetMs)}).`);\n }\n\n if (spec.maxFacetBytes !== undefined) {\n if (spec.store !== \"ephemeral\") {\n fail(\n name,\n `\"maxFacetBytes\" is ephemeral-only — it bounds the published presence facet, and only ephemeral behaviors publish one (petition I19).`,\n );\n }\n if (!Number.isSafeInteger(spec.maxFacetBytes) || spec.maxFacetBytes <= 0) {\n fail(name, `maxFacetBytes must be a positive integer byte count (got ${String(spec.maxFacetBytes)}).`);\n }\n }\n\n // Schema: every field must be a recognized p.* spec. That single check\n // carries two of the design's rules for free — the DSL has no `eid` spec at\n // all (Law 7's ban is structural, not policed), and every spec kind yields a\n // default (`defaultValueOf` is total), so \"every field defaulted\" holds by\n // construction rather than by inspection.\n for (const [fieldName, s] of Object.entries(spec.schema ?? {})) {\n if (fieldName.length === 0) fail(name, \"schema field names must be non-empty.\");\n if (typeof s !== \"object\" || s === null || typeof (s as PropSpec).kind !== \"string\") {\n fail(name, `schema field \"${fieldName}\" is not a p.* spec (use p.string/number/boolean/enum/json/entityKey).`);\n }\n if ((s as PropSpec).kind === \"json\" && (s as JsonSpec).inner === undefined) {\n fail(name, `schema field \"${fieldName}\" is a p.json with no declared shape — json cells are BOUNDED, never free-form.`);\n }\n }\n\n for (const r of spec.reads ?? []) {\n const kind = classifyRead(r);\n if (kind === undefined) {\n fail(\n name,\n \"every reads: entry must be a component, tag, relation, resource, or behavior defined through @ice/core — an unregistered handle cannot be routed to a change mechanism.\",\n );\n }\n // The engine catalog is exposed DELIBERATELY (design-009 §9): the curated\n // list is a published contract, everything else is engine vocabulary whose\n // shape moves whenever the interaction stack does. Warn rather than throw —\n // engine-grade code legitimately reaches past the list, and turning that\n // into an error would make the escape hatch a wall.\n //\n // The ENGINE's own behaviors are EXEMPT (2026-09-06, design-013 A1b). The\n // warning says \"this shape is engine vocabulary and may change without\n // notice\", and an engine behaviour ships in the same package as the\n // vocabulary it reads (the retired `ice:surface.domAtRest` read `Grab`,\n // `SurfaceKind` and `FrameInfo` because design-013 §5's table said a kind\n // behaviour reads exactly those). Warning about it addresses nobody — an\n // app cannot act on it — and three lines on every engine import is how\n // people learn to ignore warnings. Third-party behaviours still hear it,\n // which is who it was written for. This does NOT widen `PUBLIC_READS`.\n //\n // Keyed on the MARK, not on the name (A3b fix 4): a pack that named itself\n // into `ice:` used to inherit the exemption. That path is refused above\n // now, but the exemption still keys on the thing it is actually about —\n // \"this declaration came from inside the engine\" — rather than on a string\n // anyone can type.\n if (kind.kind !== \"behavior\" && !isPublicRead(r as Component) && !isEngineSpec(spec)) {\n console.warn(\n `ice: defineBehavior(\"${name}\") reads \"${kind.name}\", which is not on the published behavior read surface (design-009 §9). It works, but its shape is engine vocabulary and may change without notice.`,\n );\n }\n }\n for (const c of spec.writes ?? []) {\n if (schemaMeta.component(c) === undefined) {\n fail(name, \"every writes: entry must be a component defined through @ice/core (tags and relations are not value-write targets).\");\n }\n }\n if (spec.store === \"ephemeral\" && (spec.writes?.length ?? 0) > 0) {\n fail(\n name,\n \"an ephemeral behavior writes only its OWN facet through ctx.write(patch) — it has no cross-entity write vocabulary (strata's eph partition is absolute: every mutator refuses entities this peer did not mint).\",\n );\n }\n\n for (const [hook, fn] of Object.entries(spec.on ?? {})) {\n if (typeof fn !== \"function\") fail(name, `hook \"${hook}\" is not a function.`);\n }\n if (spec.tick?.while !== undefined && spec.on?.tick === undefined) {\n fail(name, '\"tick.while\" scopes the tick hook, but no on.tick is declared.');\n }\n\n // Migration chain: contiguous 1..version-1. Unlike defineWidget (which warns\n // — its docs predate the check), a gap here THROWS: behaviors are a new\n // surface with no legacy chains to be kind to, and a gap means documents at\n // the uncovered version silently keep stale derived state.\n const version = spec.version ?? 1;\n const migrate = spec.migrate ?? {};\n const keys = Object.keys(migrate).map(Number);\n if (keys.length > 0) {\n const gaps: number[] = [];\n for (let v = 1; v < version; v++) if (typeof migrate[v] !== \"function\") gaps.push(v);\n if (gaps.length > 0) {\n fail(name, `migrate chain has gaps at fromVersion(s) [${gaps.join(\", \")}] — docs written there cannot reach v${version}.`);\n }\n const stray = keys.filter((v) => v <= 0 || v >= version);\n if (stray.length > 0) {\n fail(name, `migrate declares transform(s) for fromVersion(s) [${stray.join(\", \")}] outside the migratable range 1..${version - 1}.`);\n }\n }\n}\n\n// --- defineBehavior ----------------------------------------------------------\n\nfunction cloneJsonShape(shape: JsonShape): JsonShape {\n switch (shape.kind) {\n case \"string\":\n case \"number\":\n case \"boolean\":\n return { kind: shape.kind };\n case \"enum\":\n return { kind: \"enum\", options: [...shape.options] };\n case \"array\":\n return { kind: \"array\", item: cloneJsonShape(shape.item) };\n case \"object\":\n return {\n kind: \"object\",\n fields: Object.fromEntries(\n Object.entries(shape.fields).map(([name, field]) => [name, cloneJsonShape(field)]),\n ),\n };\n }\n}\n\nfunction describeProp(spec: PropSpec): BehaviorPropDescription {\n switch (spec.kind) {\n case \"string\":\n return {\n kind: \"string\",\n ...(spec.default === undefined ? {} : { default: spec.default }),\n };\n case \"number\":\n return {\n kind: \"number\",\n ...(spec.default === undefined ? {} : { default: spec.default }),\n ...(spec.min === undefined ? {} : { min: spec.min }),\n ...(spec.max === undefined ? {} : { max: spec.max }),\n };\n case \"boolean\":\n return {\n kind: \"boolean\",\n ...(spec.default === undefined ? {} : { default: spec.default }),\n };\n case \"enum\":\n return {\n kind: \"enum\",\n options: [...spec.options],\n ...(spec.default === undefined ? {} : { default: spec.default }),\n };\n case \"json\":\n return {\n kind: \"json\",\n inner: cloneJsonShape(spec.inner),\n ...(spec.default === undefined ? {} : { default: spec.default }),\n };\n case \"entityKey\":\n return {\n kind: \"entityKey\",\n ...(spec.default === undefined ? {} : { default: spec.default }),\n };\n }\n}\n\nconst DESCRIPTION_HOOK_ORDER: readonly BehaviorHookName[] = [\n \"init\",\n \"update\",\n \"changed\",\n \"tick\",\n \"dispose\",\n];\n\nexport function describeBehavior(behavior: AnyBehaviorDef): BehaviorDescription {\n // Unclassifiable entries are SKIPPED, mirroring the runtime: partitionReads\n // silently drops what it cannot classify, so a dropped read never runs and\n // never delivers — describing it would claim a subscription that does not\n // exist. Throwing here was worse than either (review finding 5): the\n // reads/writes validation is dev-guard-gated, so a production build ACCEPTS\n // a behavior with an unregistered read and runs it fine — a host building\n // its manifest from describeBehavior then crashed in production on a\n // behavior that works. In dev, definition-time validation still names the\n // authoring error loudly.\n const reads: BehaviorReadDescription[] = [];\n for (const read of behavior.reads) {\n const description = classifyRead(read);\n if (description !== undefined) reads.push(description);\n }\n const writes: string[] = [];\n for (const component of behavior.writes) {\n const meta = schemaMeta.component(component);\n if (meta !== undefined) writes.push(meta.name);\n }\n return {\n id: behavior.name,\n store: behavior.store,\n derived: behavior.derived,\n deriveDuringGesture: behavior.deriveDuringGesture,\n version: behavior.version,\n phase: behavior.phase,\n ...(behavior.budgetMs === undefined ? {} : { budgetMs: behavior.budgetMs }),\n ...(behavior.maxFacetBytes === undefined ? {} : { maxFacetBytes: behavior.maxFacetBytes }),\n tickWhile: behavior.tickWhile,\n schema: Object.entries(behavior.schema).map(([name, spec]) => ({\n name,\n spec: describeProp(spec),\n })),\n reads,\n writes,\n migrationFrom: Object.keys(behavior.migrate)\n .map(Number)\n .sort((left, right) => left - right),\n hooks: DESCRIPTION_HOOK_ORDER.filter(\n (hook) => typeof behavior.on[hook] === \"function\",\n ),\n };\n}\n\nexport function defineBehavior<const S extends BehaviorStore, const Sch extends BehaviorSchema = BehaviorSchema>(\n name: string,\n spec: BehaviorSpec<S, Sch>,\n): BehaviorHandle<DataOf<Sch>> {\n const phase = spec.phase ?? BEHAVIOR_DEFAULT_PHASE[spec.store];\n if (devGuardsEnabled()) validate(name, spec as BehaviorSpec<BehaviorStore, BehaviorSchema>, phase);\n\n const signature = signatureOf(spec as BehaviorSpec<BehaviorStore, BehaviorSchema>, phase);\n const existing = registry.get(name);\n if (existing !== undefined) {\n if (signatures.get(name) !== signature) {\n throw new Error(\n `ice: defineBehavior(\"${name}\") — a behavior with this name is already defined with a DIFFERENT shape. Behavior names are process-global; namespace yours.`,\n );\n }\n // Same declaration, re-evaluated (hot reload, a test re-importing a\n // module). Reuse the handle — its component, its collector and every\n // attached instance stay valid — but adopt the NEW hooks: keeping the old\n // ones is how a framework ends up running yesterday's code after a reload.\n existing.on = (spec.on ?? {}) as BehaviorHooks<BehaviorStore, unknown>;\n return existing as BehaviorHandle<DataOf<Sch>>;\n }\n\n const schema = (spec.schema ?? {}) as BehaviorSchema;\n const defaults = defaultsOf(schema);\n\n // Petition I19, ask 4 — and deliberately OUTSIDE the dev-guard gate above:\n // every `p.*` default is total and static, so the default facet is decidable\n // RIGHT HERE, before a component exists to publish through. Enforcement is\n // production behavior (ask 7): a production build that skipped this would\n // let `ensureFacet` mint an over-budget cell the moment presence attaches.\n // Failing the definition leaves no residue — no registry entry, no\n // component, nothing for a registration to publish.\n if (spec.maxFacetBytes !== undefined && spec.store === \"ephemeral\") {\n const bytes = facetBytesOf(defaults);\n if (bytes > spec.maxFacetBytes) {\n throw new Error(\n `ice: defineBehavior(\"${name}\") — the default facet is ${bytes} bytes, over the behavior's own maxFacetBytes=${spec.maxFacetBytes} claim. Nothing was registered.`,\n );\n }\n }\n\n const raw: Record<string, ReturnType<typeof strataFieldOf>> = {};\n for (const [fieldName, s] of Object.entries(schema)) raw[fieldName] = strataFieldOf(name, fieldName, s);\n const component = ensureComponent(behaviorComponentName(name), raw);\n\n const handle: BehaviorHandle<DataOf<Sch>> = {\n name,\n namespace: name.slice(0, name.indexOf(\":\")),\n store: spec.store,\n derived: spec.derived === true,\n deriveDuringGesture: spec.deriveDuringGesture === true,\n version: spec.version ?? 1,\n phase,\n budgetMs: spec.budgetMs,\n maxFacetBytes: spec.maxFacetBytes,\n schema,\n component: component as Component<Record<string, string | number | boolean>>,\n defaults: defaults as unknown as Readonly<DataOf<Sch>>,\n reads: spec.reads ?? [],\n writes: spec.writes ?? [],\n migrate: spec.migrate ?? {},\n tickWhile: spec.tick?.while ?? \"all\",\n on: (spec.on ?? {}) as BehaviorHooks<BehaviorStore, DataOf<Sch>>,\n with(data) {\n return { behavior: handle, data };\n },\n __behavior: true,\n };\n\n registry.set(name, handle as AnyBehaviorDef);\n byComponent.set(component, handle as AnyBehaviorDef);\n signatures.set(name, signature);\n return handle;\n}\n\n/**\n * `defineBehavior` for the ENGINE's own behaviours — the only way into the\n * reserved `ice:` namespace (A3b fix 4).\n *\n * Deliberately NOT on the package barrel: it is not a second public door but\n * the same door with the engine's key in it. `surface/standard-behaviors.ts`\n * is its only caller today; anything else the engine ships in `ice:` uses it\n * for the same two reasons — the compiler's attestation and the read-surface\n * exemption both mean \"ICE wrote this\", and a string prefix cannot say that.\n */\nexport function defineEngineBehavior<\n const S extends BehaviorStore,\n const Sch extends BehaviorSchema = BehaviorSchema,\n>(name: string, spec: BehaviorSpec<S, Sch>): BehaviorHandle<DataOf<Sch>> {\n // A copy, so the mark never lands on a caller's object — and a symbol key,\n // so nothing that walks string keys (`signatureOf`, `describeBehavior`, a\n // host's manifest) ever sees it. Stamped after the copy rather than in the\n // literal: the mark is deliberately absent from `BehaviorSpec`, which is the\n // point — a caller cannot write it.\n const marked: BehaviorSpec<S, Sch> = { ...spec };\n (marked as unknown as Record<symbol, unknown>)[ENGINE_MARK] = true;\n return defineBehavior(name, marked);\n}\n\n/**\n * TEST-ONLY registry wipe (mirrors `__resetPrefabsForTests`; deliberately NOT\n * on the barrel). strata's schema registry has no reset, so a test that wipes\n * this must still use file-unique behavior names.\n */\nexport function __resetBehaviorsForTests(): void {\n registry.clear();\n byComponent.clear();\n signatures.clear();\n}\n","/**\n * `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 * A shift-held canvas drag takes `route.canvasDragShift` (design-015 §9,\n * D2a-core), which defaults to the tool's own `canvasDrag`.\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 /**\n * The same drag with SHIFT held. For example, a custom tool can pan normally\n * and draw its marquee on shift —\n * `{ canvasDrag: \"pan\", canvasDragShift: \"marquee\" }`. Omitted: the tool's\n * own `canvasDrag`, so shift changes nothing (every tool before this field).\n * The device conventions (touch / space / middle → pan) still sit above it.\n */\n readonly canvasDragShift?: 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\", canvasDragShift: \"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 route = { ...SELECT_DEFAULTS.route, ...def.route };\n const tool: Tool = {\n id: def.id,\n cursor: def.cursor,\n spawnProfile: def.spawnProfile ?? SELECT_DEFAULTS.spawnProfile,\n // An omitted shift route is the tool's OWN canvas route — never select's\n // default leaking in (a pan tool's shift-drag pans, as it always did).\n route: { ...route, canvasDragShift: def.route?.canvasDragShift ?? route.canvasDrag },\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 * THE HELD BAR'S TOOLS (design-015 §8; D3t-a) — what an object in hand offers beyond being held: the kind's\n * `open.tools`, declared on its WIDGET TYPE (`defineWidget({ heldTools, heldTool })` — the desk's `defineObject`\n * passes its kind's), so the one keymap and the one held bar reach them through the engine, never through a kind.\n * Each tool is a glyph, a key and a KIND:\n * - a `mode` makes itself the held object's ACTIVE tool — the runtime `HeldTool` on the object in hand, the user's\n * fact, never in the document (the board's four markers and its eraser; a notebook's pens; a calendar's pen). A\n * `toggle` mode chosen again while active hands back the mode before it (the board's eraser lays down for the\n * marker it took over from);\n * - an `action` runs its op once (`run`, handed a `HeldToolApi` — outside the tick, like every op): undo and redo\n * (the DOCUMENT's history: a held object's history is the document's, design-015 §5.1), the board's wipe.\n * Keys route only while an object is held (the keymap asks `matchHeldTool` before its own entries). A tool with no\n * `kind` is DECLARED ONLY — the bar shows it dim and nothing routes to it (a kind whose tools are a later slice's).\n * A tool may say its STATE NOW (petition I49 — `state`): disabled (‹ back with no history — its slot dim, its press and its\n * keys doing nothing), another glyph, another label (↻ reload → ✕ stop while a page loads).\n */\nimport type { Entity, World } from \"@vibecook/strata-ecs\";\nimport type { GuardedTx } from \"../guards/guarded-tx\";\n\n/** What an action's op is handed: the object in hand, the document's history and ONE transaction on the document. */\nexport interface HeldToolApi {\n readonly world: World;\n /** The object in hand. */\n readonly entity: Entity;\n /** The document's history — the one ⌘Z walks (false: nothing to undo, or a read-only document). */\n undo(): boolean;\n redo(): boolean;\n /** ONE transaction on the document (one undo step unless `undoable: false`); false — nothing written — on a read-only one. */\n transact(fn: (tx: GuardedTx) => void, opts?: { readonly undoable?: boolean }): boolean;\n /** The held object's own props as the world holds them now. */\n props(): Readonly<Record<string, unknown>>;\n /** The held object's own props, validated, in ONE transaction (`ops.setWidgetProps`'s path — the board's tip, a calendar's month); false on a read-only document. */\n setProps(props: Readonly<Record<string, unknown>>, opts?: { readonly undoable?: boolean }): boolean;\n}\n\n/**\n * A held tool's GLYPH (design-016 §5 · K-L2, K8a): a NAME the bar draws (its set — `SELECTION_GLYPHS` in `@ice/react`, which an\n * app may extend), or the tool's OWN drawing — SVG path data in the bar's 24-unit box, stroked 2 units in the bar's ink as the\n * bar's own are, or filled (`fill`). A plugin kind in its own package, which draws no React, declares its drawing; a name the bar\n * does not know is never drawn as another glyph (the bar marks it missing and says so).\n */\nexport type HeldGlyph = string | { readonly path: string; readonly fill?: boolean };\n\n/**\n * A held tool's STATE as the bar shows it NOW (petition I49): what its kind says of it each time the selection's anchor is recomposed\n * — the pickup, a held tool's act, every frame drawn in hand — and again when the tool is used. `enabled` false: the tool is DISABLED\n * now — its slot dim and `aria-disabled`, its press and its keys doing nothing (the keys still its own: nothing else takes them);\n * absent or true, live. `glyph` and `label`: shown now instead of the declared ones. Every field absent — or no answer — is the tool\n * as declared.\n */\nexport interface HeldToolState {\n readonly enabled?: boolean;\n readonly glyph?: HeldGlyph;\n readonly label?: string;\n}\n\n/**\n * What a tool's `state` reads (petition I49) — what its kind's `open.readout` reads: the object in hand, its props as the world holds\n * them now, and the kind's STATE ON THE DESK that holds it (`ObjectKind.local` — a live face's `info()`: its history, its loading);\n * `local` is undefined where no desk answers (an engine with no renderer). READ ONLY: a `state` is asked at the host's rate, and\n * writes nothing.\n */\nexport interface HeldToolStateContext extends Pick<HeldToolApi, \"world\" | \"entity\" | \"props\"> {\n readonly local: unknown;\n}\n\n/** One tool of the held bar, as a kind declares it (its `open.tools`). */\nexport interface HeldToolDef {\n /** Unique within the type: what `HeldTool.id` holds for a mode, what `ops.useHeldTool` names. */\n readonly id: string;\n /** Its name — the slot's accessible label and its tip. */\n readonly label: string;\n /** `mode` (the active tool) or `action` (an op, run once); absent = declared only (dim, inert). */\n readonly kind?: \"mode\" | \"action\";\n /** The keys that choose it while held: `KeyboardEvent.key` with `mod+` (⌘ or ctrl), `shift+`, `alt+` — \"1\", \"e\", \"mod+z\", \"mod+Backspace\". */\n readonly keys?: readonly string[];\n /** The key as the tip shows it (\"1\", \"E\", \"⌘Z\"). */\n readonly hint?: string;\n /** Its glyph (`HeldGlyph`, K8a): a name of the bar's set, or its own drawing (`{ path }`). */\n readonly glyph?: HeldGlyph;\n /** A mode chosen again while active hands the hand back the mode before it. */\n readonly toggle?: boolean;\n /** The cursor over the object's drawing surface (its `content` part) while this mode is active — \"none\" where the tool draws itself. */\n readonly cursor?: string;\n /** false: keys only — no slot in the bar (the board's tip, its wipe). */\n readonly bar?: boolean;\n /** An action's op. */\n run?(api: HeldToolApi): void;\n /**\n * Its STATE NOW (petition I49 — `HeldToolState`): asked with the anchor, as the kind's `open.readout` is, and when the tool is used.\n * Undefined — or absent — the tool as declared. One that THROWS is caught where it is asked (the desk says so once, never a strike):\n * the tool stands as declared.\n */\n state?(ctx: HeldToolStateContext): HeldToolState | undefined;\n}\n\n/**\n * A tool's state NOW, read safely (petition I49): its `state(ctx)` with only what is well-formed kept — `enabled` when it is `false`,\n * a glyph that is one (`isHeldGlyph`), a label that is a word — or undefined: none declared, nothing said, or it THREW (`threw` is\n * told; the tool stands as declared).\n */\nexport function readHeldToolState(tool: HeldToolDef, ctx: HeldToolStateContext, threw?: (err: unknown) => void): HeldToolState | undefined {\n if (tool.state === undefined) return undefined;\n let said: HeldToolState | undefined;\n try { said = tool.state(ctx); } catch (err) { threw?.(err); return undefined; }\n if (typeof said !== \"object\" || said === null) return undefined;\n const glyph = said.glyph !== undefined && isHeldGlyph(said.glyph) ? said.glyph : undefined;\n const label = typeof said.label === \"string\" && said.label.length > 0 ? said.label : undefined;\n if (said.enabled !== false && glyph === undefined && label === undefined) return undefined;\n return { ...(said.enabled === false ? { enabled: false } : {}), ...(glyph !== undefined ? { glyph } : {}), ...(label !== undefined ? { label } : {}) };\n}\n\n/** A key press as the keymap reads it: `KeyboardEvent.key`, ⌘-or-ctrl, ⇧, ⌥. */\nexport interface KeyChord {\n readonly key: string;\n readonly mod: boolean;\n readonly shift: boolean;\n readonly alt: boolean;\n}\n\nconst MODS = new Set([\"mod\", \"shift\", \"alt\"]);\n\n/** A key spec's parts, or undefined when malformed: its modifiers and its key. */\nfunction parseKey(spec: string): { readonly key: string; readonly mod: boolean; readonly shift: boolean; readonly alt: boolean } | undefined {\n const parts = spec.split(\"+\");\n const key = parts.pop();\n if (key === undefined || key.length === 0 || parts.some((m) => !MODS.has(m))) return undefined;\n return { key, mod: parts.includes(\"mod\"), shift: parts.includes(\"shift\"), alt: parts.includes(\"alt\") };\n}\n\n/** Does a tool's key spec name this chord? Every modifier must match exactly; the key compares case-blind (Caps Lock types \"E\"). */\nexport function keyMatches(spec: string, chord: KeyChord): boolean {\n const k = parseKey(spec);\n return k !== undefined && k.mod === chord.mod && k.shift === chord.shift && k.alt === chord.alt && k.key.toLowerCase() === chord.key.toLowerCase();\n}\n\n/** The live tool a chord chooses among `tools` — the first whose keys name it; a declared-only tool routes nothing. */\nexport function matchHeldTool(tools: readonly HeldToolDef[], chord: KeyChord): HeldToolDef | undefined {\n return tools.find((t) => t.kind !== undefined && (t.keys ?? []).some((spec) => keyMatches(spec, chord)));\n}\n\n/** A type's tools at definition time: unique ids, a known kind, an action with its op, well-formed keys. */\n/** Is this a glyph a tool may declare — none, a non-empty name, or a drawing with non-empty path data (K8a)? */\nexport function isHeldGlyph(g: unknown): g is HeldGlyph | undefined {\n if (g === undefined) return true;\n if (typeof g === \"string\") return g.length > 0;\n return typeof g === \"object\" && g !== null && typeof (g as { path?: unknown }).path === \"string\" && (g as { path: string }).path.trim().length > 0;\n}\n\nexport function validateHeldTools(type: string, tools: readonly HeldToolDef[]): void {\n const seen = new Set<string>();\n for (const t of tools) {\n if (typeof t.id !== \"string\" || t.id.length === 0) throw new Error(`ice: defineWidget(\"${type}\") heldTools — every tool needs an id.`);\n if (seen.has(t.id)) throw new Error(`ice: defineWidget(\"${type}\") heldTools repeats \"${t.id}\" — a tool's id is unique within its type.`);\n seen.add(t.id);\n if (t.kind !== undefined && t.kind !== \"mode\" && t.kind !== \"action\") throw new Error(`ice: defineWidget(\"${type}\") heldTools \"${t.id}\" — a tool is a \"mode\" or an \"action\" (or declared with neither).`);\n if (t.kind === \"action\" && typeof t.run !== \"function\") throw new Error(`ice: defineWidget(\"${type}\") heldTools \"${t.id}\" — an action runs an op: declare \\`run\\`.`);\n if (t.state !== undefined && typeof t.state !== \"function\") throw new Error(`ice: defineWidget(\"${type}\") heldTools \"${t.id}\" — \\`state\\` is a function of the object in hand: \\`(ctx) => ({ enabled, glyph, label })\\` (petition I49).`);\n if (!isHeldGlyph(t.glyph)) throw new Error(`ice: defineWidget(\"${type}\") heldTools \"${t.id}\" — a glyph is a name of the bar's set or a drawing \\`{ path }\\` (SVG path data in the 24-unit box).`);\n for (const spec of t.keys ?? []) {\n if (parseKey(spec) === undefined) throw new Error(`ice: defineWidget(\"${type}\") heldTools \"${t.id}\" — the key \"${spec}\" is not a key spec (\"1\", \"e\", \"mod+z\", \"mod+shift+z\").`);\n }\n }\n}\n","/**\n * A KIND'S MENU ACTIONS (design-016 §5 · K-L2, K8a) — the acts a widget type offers in the selection menu for a selection of its\n * objects, declared on its TYPE (`defineWidget({ menu })` — the desk's `defineObject` passes them through), so the one menu and\n * an app's keys reach them through the engine (`ops.runMenuAction`), never through a kind: the menu shows an act when EVERY selected\n * object's type declares it (a selection of that kind), and the op runs it on the selected objects whose types declare it — each\n * type's own `run`, handed its own objects. Until K8a a kind's act (the mini mat's vinyl) was app code over a type name.\n */\nimport type { Entity, World } from \"@vibecook/strata-ecs\";\nimport type { GuardedTx } from \"../guards/guarded-tx\";\nimport { type HeldGlyph, isHeldGlyph } from \"./held-tools\";\n\n/** What an act's op is handed (outside the tick, like every op): its type's selected objects and ONE door each to write them. */\nexport interface MenuActionApi {\n readonly world: World;\n /** The selected objects of the declaring type, in selection order. */\n readonly entities: readonly Entity[];\n /** An object's own props as the world holds them now. */\n props(entity: Entity): Readonly<Record<string, unknown>>;\n /** An object's props, validated, in ONE transaction (`ops.setWidgetProps`'s path); false on a read-only document. */\n setProps(entity: Entity, props: Readonly<Record<string, unknown>>, opts?: { readonly undoable?: boolean }): boolean;\n /** ONE transaction on the document (one undo step unless `undoable: false`); false — nothing written — on a read-only one. */\n transact(fn: (tx: GuardedTx) => void, opts?: { readonly undoable?: boolean }): boolean;\n}\n\n/** One act of the selection menu, as a type declares it. */\nexport interface MenuActionDef {\n /** Unique within the type: what `ops.runMenuAction` names (and what an app's key names). */\n readonly id: string;\n /** Its name — the button's accessible label and its tip. */\n readonly label: string;\n /** Its glyph (`HeldGlyph`): a name of the bar's set, or its own drawing (`{ path }`). */\n readonly glyph?: HeldGlyph;\n /** The key that does the same, as the tip and More show it (\"T\") — the app binds it to `ops.runMenuAction`. */\n readonly keys?: string;\n run(api: MenuActionApi): void;\n}\n\nexport function validateMenuActions(type: string, acts: readonly MenuActionDef[]): void {\n const seen = new Set<string>();\n for (const a of acts) {\n if (typeof a.id !== \"string\" || a.id.length === 0) throw new Error(`ice: defineWidget(\"${type}\") menu — every act needs an id.`);\n if (seen.has(a.id)) throw new Error(`ice: defineWidget(\"${type}\") menu repeats \"${a.id}\" — an act's id is unique within its type.`);\n seen.add(a.id);\n if (typeof a.label !== \"string\" || a.label.length === 0) throw new Error(`ice: defineWidget(\"${type}\") menu \"${a.id}\" — an act needs a label.`);\n if (typeof a.run !== \"function\") throw new Error(`ice: defineWidget(\"${type}\") menu \"${a.id}\" — an act runs an op: declare \\`run\\`.`);\n if (!isHeldGlyph(a.glyph)) throw new Error(`ice: defineWidget(\"${type}\") menu \"${a.id}\" — a glyph is a name of the bar's set or a drawing \\`{ path }\\`.`);\n }\n}\n\n/**\n * The acts the selection menu shows for `entities`: those EVERY entity's type declares (by id; the first type's declaration names\n * it), in the first type's order — none for an empty selection or an object of a type that declares none.\n */\nexport function menuActionsFor(entities: readonly Entity[], menuOf: (entity: Entity) => readonly MenuActionDef[]): readonly MenuActionDef[] {\n const first = entities[0];\n if (first === undefined) return [];\n let acts = menuOf(first);\n for (let i = 1; i < entities.length && acts.length > 0; i++) {\n const ids = new Set(menuOf(entities[i] as Entity).map((a) => a.id));\n acts = acts.filter((a) => ids.has(a.id));\n }\n return acts;\n}\n","/**\n * `defineWidget` v1 — the flagship compiler (design-005 §2).\n *\n * Sugar over `definePrefab` + registries — nothing here is unavailable to a\n * hand-rolled prefab. Compile output:\n * - one durable prefab: `PrefabId{type}` + Position/Size + ONE\n * generated component per conflict group (`<type>:<group>`; ungrouped\n * fields form the \"props\" default group) + Accepts/Provides when a\n * container contract is declared;\n * - a capability-stamp recipe (RUNTIME tags at projection — the equip system\n * consumes it; tags stay pure, design-001 §2);\n * - the opaque `object` kind binding and the desk stratum the desk's renderer\n * consumes (design-015 §5.2, D2a-core) — since D5b the ONE face a widget can\n * have (the view registration — surface, component, sizeMode — is gone);\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, Entity, FieldInput, Tag, World } from \"@vibecook/strata-ecs\";\nimport { ensureComponent } from \"../schema/meta\";\nimport type { AnyBehaviorAttachSpec, AnyBehaviorDef } from \"../behavior/types\";\nimport {\n Accepts,\n ChildOf,\n Container,\n LongPressDrag,\n Movable,\n SelectionMovable,\n Opacity,\n Position,\n Provides,\n Resizable,\n STRATUM_BANDS,\n Selectable,\n Size,\n SnapSource,\n SnapTarget,\n Solid,\n SweepsContained,\n WheelTurns,\n type DeskStratum,\n} from \"../catalog\";\nimport { defineComponent, defineTag } from \"../schema/meta\";\nimport { definePrefab, init, type ComponentInit, type Prefab } from \"../schema/prefab\";\nimport { defaultValueOf } from \"./props\";\nimport type { JsonSpec, PropSpec, PropsDecl } from \"./props\";\nimport { type HeldToolDef, validateHeldTools } from \"./held-tools\";\nimport { type MenuActionDef, validateMenuActions } from \"./menu-actions\";\nimport { hangError, type TrayHang } from \"@ice/kernel\";\nimport type { CanvasType } from \"../canvas/define-canvas-type\";\nimport type { FrameProjection } from \"../canvas/frame-projection\";\n\n// `WidgetSurfaceKind` (`dom` · `gl` · `video` · `object`) and `SizeMode` left at design-015 D5b:\n// a widget's face is its `object` kind's program or nothing, and its size is its `Size`. The\n// fields that named a view — `surface`, `component`, `chrome`, `animated`, `preview`,\n// `instancePreview`, `sizeMode` — are refused below for the JS caller TypeScript cannot stop.\n\nexport interface WidgetPortDecl {\n readonly id: string;\n readonly side: \"n\" | \"e\" | \"s\" | \"w\";\n /** Slot index along the side (0-based; anchor spacing is the kernel's). */\n readonly index?: number;\n /** Compatibility keys (empty = connects to anything). */\n readonly accepts?: readonly string[];\n}\n\n/**\n * A prior durable id of this widget type (design-008 §3, petition I5). Docs\n * written under the old id fold to this type at open (doc/rename.ts) and via\n * the live zombie sweep (doc/rename-sweep.ts) — replicas converge through\n * ordinary CRDT delivery, retiring offline byte surgery. Declares group-NAME\n * continuity at the rename boundary (the pack runner's existing fence).\n */\nexport interface WidgetRename {\n /** The old durable type id (`PrefabId.id` in pre-rename docs). */\n readonly type: string;\n /**\n * The pack version old-build writers of `type` were at (default 1). Only\n * the SWEEP consumes it — a late old-shape delivery carries no marker, so\n * its values chain-fold from here; the open-path runner reads the version\n * off the doc's own markers instead (design-008 §6.3).\n */\n readonly atVersion?: number;\n}\n\n/** A rename registry entry (doc/rename runner + sweep input). */\nexport interface WidgetRenameEntry {\n readonly widget: WidgetType;\n readonly oldType: string;\n readonly atVersion: number;\n /** Legacy `<oldType>:<group>` components, index-aligned with `widget.groups`. */\n readonly legacyGroups: readonly Component[];\n}\n\n/**\n * A behavior pre-attachment on a widget type: the bare handle for defaults, or\n * `Behavior.with({...})` for a starting value (design-009 §6).\n */\nexport type WidgetBehaviorDecl = AnyBehaviorDef | AnyBehaviorAttachSpec;\n\nexport interface WidgetPortalInsets {\n readonly top?: number;\n readonly right?: number;\n readonly bottom?: number;\n readonly left?: number;\n}\n\nexport interface WidgetContainerDef {\n /** Compatibility-key projection written to the durable Accepts cell. */\n readonly accepts: readonly string[];\n readonly provides?: readonly string[];\n /** Fixed CanvasType binding; omitted by legacy defineWidget({container}). */\n readonly canvas?: CanvasType;\n /** Explicit narrower ingress WidgetTypes, unioned with accepts keys. */\n readonly widgets?: readonly WidgetType[];\n /** Omitted drop policy inherits the complete CanvasType legal set. */\n readonly inheritCanvasPlacement?: boolean;\n /** Card-local portal insets; full widget body when absent. */\n readonly portal?: WidgetPortalInsets;\n /** Optional declared facet projection overriding the CanvasType default. */\n readonly frameProjection?: FrameProjection;\n /** Internal normalized distinction between defineContainer and legacy sugar. */\n readonly typed?: boolean;\n}\n\nexport interface WidgetContainerEntry {\n readonly canvasTypeId: string;\n readonly canvasSemanticVersion: number;\n readonly accepts: readonly string[];\n readonly widgetTypeIds: readonly string[];\n readonly inheritCanvasPlacement: boolean;\n readonly portal: Readonly<Required<WidgetPortalInsets>>;\n readonly frameProjection: FrameProjection | undefined;\n readonly typed: boolean;\n}\n\n/** Normalized pre-attachment (registry truth for the spawn + equip paths). */\nexport interface WidgetBehaviorEntry {\n readonly behavior: AnyBehaviorDef;\n readonly data: Readonly<Record<string, unknown>>;\n}\n\nexport interface WidgetInteraction {\n readonly selectable?: boolean;\n /** \"selection\": core moves it with a group; a custom driver owns its solo drag. */\n readonly movable?: boolean | \"selection\";\n /**\n * May this widget be dropped INTO an accepting container (design-015 §9, D-D6 — D2b)?\n * `\"into\"` (default): yes — for a GPU object, when its centre is let go over the container's\n * FACE, at the point where it lay in the inside's own units (it takes the inside's scale), ⌥\n * held at the release keeping it out. `\"never\"`: a root object always (D-D18: the notebook, the\n * whiteboard, the calendar) — the widget offers itself to no container (no `Provides`).\n */\n readonly drop?: \"into\" | \"never\";\n readonly resizable?: boolean;\n readonly snap?: \"source\" | \"target\" | \"both\" | \"none\";\n /** Drop-REJECTING target: widgets dropped onto this one fly back (v1 iOS-card contract). */\n readonly solid?: boolean;\n /** \"longPress\": hold-to-lift dragging (iOS home-screen model); default \"press\". */\n readonly dragOn?: \"press\" | \"longPress\";\n /**\n * UE-Blueprint comment-box drag (2026-07-18): a move claim on this widget\n * also claims every widget FULLY INSIDE its bounds at claim time (spatial\n * membership — never reparenting). Default false.\n */\n readonly sweepContained?: boolean;\n /**\n * The wheel TURNS it while a press holds it (design-015 §6's photo, D3t-a — the `WheelTurns` capability): the wheel on\n * that pointer is the widget's, never the camera's; its deltas add up in the pointer's `PressWheel`. Default false.\n */\n readonly wheelTurns?: boolean;\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 /**\n * The KIND BINDING (design-015 §5.2, D-D16) — the widget's FACE: what the\n * desk's renderer dispatches on through `widgetTypeFor`: the kind's program,\n * its pick mirror, its opening. Opaque to core: it carries it and never reads\n * it. Optional — a widget without one (a port, a test fixture) is a type the\n * desk draws nothing for; since D5b there is no other face a widget can have.\n */\n readonly object?: unknown;\n /**\n * Which stratum of the desk instances lie in (design-015 §4.2, D-D4):\n * `pads` under everything, `sheets` flat on the mat holding a desk, `things`\n * above both. Equip stamps it as the runtime `Stratum` rider, and\n * `compareStackOrder` ranks by it before sibling order, so pick order is paint\n * order across kinds. An `object` that declares none is a `things`; any other\n * widget that declares none gets no `Stratum` at all (and sorts as a thing).\n */\n readonly stratum?: DeskStratum;\n /**\n * An object that OPENS (design-015 §8, D4b): its kind declares an `open` binding — an open\n * extent, an open motion, the held bar's tools — and `ops.open(entity)` picks it up into the\n * hand (the double-tap, ⏎). A kind without one is refused by the op: a note is written where it\n * lies, a mini mat is entered, a print has nothing to open. Refused without an `object` binding.\n */\n readonly openable?: boolean;\n /**\n * The held bar's tools of an object that opens (design-015 §8; D3t-a — widget/held-tools.ts): each a mode (the\n * object's active tool in hand) or an action (an op), with its keys. The keymap and the bar reach them through the\n * engine; `ops.useHeldTool` uses one. Refused on anything that does not open.\n */\n readonly heldTools?: readonly HeldToolDef[];\n /** The mode in hand when the object is picked up, from its props (the board: its capped marker's ink). Default: the first mode, else none. */\n readonly heldTool?: (props: Readonly<Record<string, unknown>>) => string;\n /**\n * The WHEEL in hand (design-019 §5, M24 LT2 — the desk's `defineObject` passes its kind's `open.wheel`): `\"hand\"` (the default — a\n * plain wheel moves the object once brought close) or `\"kind\"` — a plain wheel is the kind's (core writes it to the pointer's\n * `HeldWheel`, the desk tells the kind); ⌘/ctrl-wheel and the pinch zoom the hand either way. Refused on anything that does not open.\n */\n readonly heldWheel?: \"hand\" | \"kind\";\n /**\n * ESCAPE in hand (design-019 §5, M24 LT2 — the kind's `open.escape`): `\"desk\"` (the default — Esc puts the object down) or `\"kind\"` —\n * Esc is the kind's (a source that owns it: a terminal), and the keymap never puts the object down for it: Done, a click off it or\n * the pinch do. Refused on anything that does not open.\n */\n readonly heldEscape?: \"desk\" | \"kind\";\n /**\n * The acts the SELECTION MENU offers for a selection of this type's objects (design-016 §5 · K-L2, K8a — widget/menu-actions.ts):\n * each an id, a label, a glyph and an op; the menu shows one when every selected object's type declares it, and\n * `ops.runMenuAction` runs it. A kind's own acts live here, never in app code over its type name.\n */\n readonly menu?: readonly MenuActionDef[];\n /**\n * What RIDES with the widget when a gesture moves it (design-015 D3t-c — the desk calendar's stuck notes): widgets of the same\n * frame the move claim adds to its dragged set, so they move with it live and land in the SAME transaction (one undo step).\n * Read from the world at the claim; a taped rider stays put, as a taped member of a selection does.\n */\n readonly riders?: (world: World, entity: Entity) => readonly Entity[];\n /**\n * The object's DATA prefabs (design-015 §5.1; D3t-a): durable children `ChildOf` it that are never widgets — the board's\n * strokes. An engine catalog that registers the widget tracks them as it tracks the widget's own: their packs are stamped on\n * a new document and gated at open, a guarded transaction resolves them, and one whose version moved migrates by its own\n * `migrate` chain (doc/migrate.ts).\n */\n readonly data?: readonly Prefab[];\n readonly defaultSize?: { readonly w: number; readonly h: number };\n readonly minSize?: { readonly w: number; readonly h: number };\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?: WidgetContainerDef;\n /**\n * Provides-keys WITHOUT container semantics (nodeboard field finding): a\n * leaf that only offers itself to containers must not become a Container\n * (drop target + Enter affordance). Ignored when `container` is present\n * (its `provides` wins).\n */\n readonly provides?: readonly string[];\n /**\n * Prior durable ids folded to this type (design-008; petition I5). Additive:\n * registers read-only LEGACY group components under the old names so\n * pre-rename cells project, gates pre-rename docs \"migrate\" instead of\n * read-only, and arms the live zombie sweep on every writable session.\n */\n readonly renamedFrom?: readonly WidgetRename[];\n /**\n * Behaviors every instance of this type carries (design-009 §6). The store\n * class routes HOW, exactly as it routes everything else:\n * - `durable` behaviors are attached as post-spawn `addComponent` calls in\n * the SAME spawn transaction — document truth, so they sync and undo with\n * the widget. (Not spawn-init overrides: those hit the prefab's\n * all-builds eligibility throw in `instantiate.ts`.)\n * - `runtime` behaviors are stamped at PROJECTION by the equip system,\n * beside the capability tags. That is the only mechanism that also equips\n * a widget arriving from a remote peer or a restored file, which a rider\n * attached at spawn time would miss on every peer but the author's.\n * Ephemeral behaviors are refused: an ephemeral instance IS the local\n * presence peer, so it cannot ride a widget at all.\n */\n readonly behaviors?: readonly WidgetBehaviorDecl[];\n /**\n * fromVersion → idempotent absolute transform (M9's `runMigrations` runs the\n * chain at open; `prev`/return are flat prop records spanning every group).\n *\n * No parallel `legacy` schema field is needed for field-level changes: strata\n * is field-tolerant within a known component name (extra stored fields dropped,\n * missing default-filled — every generated field carries a default), so a v1\n * cell projects into the v2 group component of the same name and the transform\n * reads the already-v2-shaped value. See doc/migrate.ts for the as-built note;\n * migrating data out of a group REMOVED wholesale in v2 is vNext (design-005\n * §6.4 cross-schema movement).\n */\n readonly migrate?: Readonly<Record<number, (prev: Record<string, unknown>) => Record<string, unknown>>>;\n /**\n * The widget's TRAY ENTRY (design-017 §8; K5a — K-L2: a plugin kind declares the same): a specimen of the object hangs on the\n * pegboard tray, drawn by its own kind. No list in the engine names a kind — the catalog's widgets that carry an entry ARE the\n * tray's contents. Only an object has one (a specimen is its face).\n */\n readonly tray?: TrayEntry;\n}\n\n/**\n * A tray entry (design-017 §8): `label` — the specimen's name tag; `props` — the specimen's props over the widget's defaults: its FACE\n * on the board (K5b — a note with a word on it, a print with a picture); `take` — what one taken off the board is made with (K5b,\n * D-K5b.1): absent, the widget's own defaults (a taken note is blank, a taken calendar shows its today's month); `\"face\"`, the\n * specimen's props; a record, those props (each valid as `props`'); `local` — K5b, D-K5b.3: the specimen (and a copy lifted off it) is\n * drawn with its kind's DESK STATE (`ObjectKind.local` — a note's writing, a print's pictures, a pad's print), as its objects are, for a\n * face that lives there; absent, a specimen is its kind's stateless drawing (K5a); `hang` — how it hangs (kernel `TrayHang`: its size on\n * the board in CSS px, its pegs in pitches from its hang point, its accessory); `category`, then `order`, then the type — its place in\n * the lattice law's order.\n */\nexport interface TrayEntry {\n readonly label: string;\n readonly props?: Readonly<Record<string, unknown>>;\n readonly take?: \"face\" | Readonly<Record<string, unknown>>;\n readonly local?: boolean;\n readonly hang: TrayHang;\n readonly order?: number;\n readonly category?: string;\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 /** The `object` kind binding (design-015 §5.2) — the face; opaque; `undefined` for a widget the desk draws nothing for. */\n readonly object: unknown;\n /**\n * The desk stratum equip stamps as `Stratum` (design-015 §4.2): the declared\n * one, `things` for an object that declared none, `undefined` (no rider) for\n * a faceless widget that declared none.\n */\n readonly stratum: DeskStratum | undefined;\n /** An object whose kind opens — `ops.open` picks it up (design-015 §8); false on every other widget. */\n readonly openable: boolean;\n /** The held bar's tools (design-015 §8, D3t-a); empty for anything that does not open. */\n readonly heldTools: readonly HeldToolDef[];\n /** The mode in hand at the pick-up, from the object's props; undefined = the first mode. */\n readonly heldTool: ((props: Readonly<Record<string, unknown>>) => string) | undefined;\n /** The selection menu's acts for this type's objects (K8a); empty when it declares none. */\n readonly menu: readonly MenuActionDef[];\n /** What rides with the widget when a gesture moves it (design-015 D3t-c); undefined = nothing. */\n readonly riders: ((world: World, entity: Entity) => readonly Entity[]) | undefined;\n /** The object's data prefabs (design-015 §5.1, D3t-a) — the catalog tracks them with the widget; empty for most. */\n readonly data: readonly Prefab[];\n readonly defaultSize: { readonly w: number; readonly h: number };\n readonly minSize: { readonly w: number; readonly h: number };\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 /** Normalized capability advertisement; never re-read from durable cells. */\n readonly provides: readonly string[];\n /** Fixed nested-frame binding and ingress/portal metadata, when a container. */\n readonly container: WidgetContainerEntry | undefined;\n /** The plain wheel's owner in hand (M24 LT2): `\"hand\"` unless the object's kind takes it — core's held input reads THIS. */\n readonly heldWheel: \"hand\" | \"kind\";\n /** Escape's owner in hand (M24 LT2): `\"desk\"` unless the object's kind owns it — the keymap reads THIS. */\n readonly heldEscape: \"desk\" | \"kind\";\n /** May instances be dropped INTO an accepting container (design-015 §9; `\"never\"` = a root object always, D-D18)? The drop system reads THIS. */\n readonly drop: \"into\" | \"never\";\n readonly migrate: Readonly<Record<number, (prev: Record<string, unknown>) => Record<string, unknown>>>;\n /** Pre-attached behaviors, normalized (spawn tx for durable, equip for runtime). */\n readonly behaviors: readonly WidgetBehaviorEntry[];\n /** The tray entry (design-017 §8; K5a), validated and frozen; undefined = the widget hangs nothing on the tray. */\n readonly tray: TrayEntry | undefined;\n}\n\n/** Stamped by the equip system once a projected widget carries its capability tags. */\nexport const WidgetEquipped = defineTag(\"WidgetEquipped\");\n\nconst registry = new Map<string, WidgetType>();\nconst renameRegistry = new Map<string, WidgetRenameEntry>();\n\nexport const widgets = {\n get(type: string): WidgetType | undefined {\n return registry.get(type);\n },\n all(): WidgetType[] {\n return [...registry.values()];\n },\n};\n\n/** The rename registry (design-008 §3): old durable id → fold target. */\nexport const renames = {\n get(oldType: string): WidgetRenameEntry | undefined {\n return renameRegistry.get(oldType);\n },\n all(): WidgetRenameEntry[] {\n return [...renameRegistry.values()];\n },\n};\n\nfunction normalizeProps(props: WidgetDef[\"props\"]): PropsDecl {\n if (props === undefined) return {};\n if (\"kind\" in props && props.kind === \"object\") {\n return props.fields as PropsDecl; // p.object(...) authored form\n }\n return props as PropsDecl;\n}\n\nfunction strataFieldOf(name: string, spec: PropSpec) {\n switch (spec.kind) {\n case \"string\":\n return field(\"string\", { default: spec.default ?? \"\" });\n case \"number\":\n return field(\"f64\", { default: spec.default ?? 0 });\n case \"boolean\":\n return field(\"bool\", { default: spec.default ?? false });\n case \"enum\": {\n const fallback = spec.default ?? spec.options[0] ?? \"\"; // p.enum enforces non-empty\n return field(enumOf([...spec.options]), { default: fallback });\n }\n case \"json\":\n return field(\"string\", { default: (spec as JsonSpec).default ?? \"null\" });\n case \"entityKey\":\n // A doc key is a string cell — `p.entityKey` is the DECLARED meaning, not\n // a distinct storage type (design-009 §4.2).\n return field(\"string\", { default: spec.default ?? \"\" });\n default:\n throw new Error(`ice: defineWidget prop \"${name}\" has an unknown spec kind.`);\n }\n}\n\n/**\n * Chain-coverage check (design-005 §6.4): to upgrade a doc written by ANY pack\n * version in `1..version-1`, the migrate chain needs an entry for every one of\n * those fromVersions. A gap means docs at the uncovered version stay read-only\n * (the M9 runner skips a type it cannot reach `version` from), so warn rather\n * than throw — a partial chain is a live-with-it degradation, not a definition\n * error. Keys ≥ `version` or ≤ 0 are meaningless fromVersions; flag them too.\n */\nfunction validateMigrateChain(\n type: string,\n version: number,\n migrate: Readonly<Record<number, unknown>>,\n): void {\n const keys = Object.keys(migrate).map(Number);\n if (keys.length === 0) return;\n const gaps: number[] = [];\n for (let v = 1; v < version; v++) {\n if (typeof migrate[v] !== \"function\") gaps.push(v);\n }\n if (gaps.length > 0) {\n console.warn(\n `ice: defineWidget(\"${type}\") migrate chain has gaps at fromVersion(s) [${gaps.join(\", \")}] — ` +\n `docs written at those versions cannot reach v${version} and will open read-only (design-005 §6.4).`,\n );\n }\n const stray = keys.filter((v) => v <= 0 || v >= version);\n if (stray.length > 0) {\n console.warn(\n `ice: defineWidget(\"${type}\") migrate declares transform(s) for fromVersion(s) [${stray.join(\", \")}] ` +\n `outside the migratable range 1..${version - 1} — they never run.`,\n );\n }\n}\n\nexport function defineWidget(def: WidgetDef): WidgetType {\n if (registry.has(def.type)) {\n throw new Error(`ice: widget type \"${def.type}\" is already defined.`);\n }\n const props = normalizeProps(def.props);\n const portIds = new Set<string>();\n for (const port of def.ports ?? []) {\n if (portIds.has(port.id)) throw new Error(`ice: widget \"${def.type}\" declares duplicate port id \"${port.id}\".`);\n portIds.add(port.id);\n }\n\n // Group membership: total and disjoint; ungrouped → the \"props\" group.\n const propToGroup: Record<string, string> = {};\n for (const [group, names] of Object.entries(def.groups ?? {})) {\n for (const name of names) {\n if (!(name in props)) {\n throw new Error(`ice: widget \"${def.type}\" group \"${group}\" lists unknown prop \"${name}\".`);\n }\n if (propToGroup[name] !== undefined) {\n throw new Error(`ice: widget \"${def.type}\" prop \"${name}\" is in two groups — groups must be disjoint.`);\n }\n propToGroup[name] = group;\n }\n }\n for (const name of Object.keys(props)) {\n propToGroup[name] ??= \"props\";\n }\n\n // One generated component per group, named `<type>:<group>`.\n const byGroup = new Map<string, Record<string, PropSpec>>();\n for (const [name, spec] of Object.entries(props)) {\n const g = propToGroup[name] as string;\n let fields = byGroup.get(g);\n if (fields === undefined) {\n fields = {};\n byGroup.set(g, fields);\n }\n fields[name] = spec;\n }\n const groups: WidgetGroup[] = [];\n // Raw strata field specs per group, kept for rename legacy compilation —\n // the legacy `<oldType>:<group>` components must be BYTE-IDENTICAL shapes.\n const rawByGroup = new Map<string, Record<string, FieldInput>>();\n for (const [g, fields] of byGroup) {\n const raw: Record<string, ReturnType<typeof strataFieldOf>> = {};\n for (const [name, spec] of Object.entries(fields)) raw[name] = strataFieldOf(name, spec);\n rawByGroup.set(g, raw);\n groups.push({ name: g, component: defineComponent(`${def.type}:${g}`, raw) as Component, fields });\n }\n\n // Rename declarations (design-008 §3): validate, then compile one legacy\n // component per CURRENT group under each old id. `ensureComponent` makes\n // re-evals (tests, hot reload) reuse instead of tripping strata's\n // duplicate-name throw; a same-name different-shape collision still throws.\n const renameDecls = def.renamedFrom ?? [];\n const legacyByOld = new Map<string, Component[]>();\n for (const decl of renameDecls) {\n if (decl.type === def.type) {\n throw new Error(`ice: widget \"${def.type}\" lists itself in renamedFrom.`);\n }\n if (registry.has(decl.type)) {\n throw new Error(`ice: widget \"${def.type}\" renamedFrom \"${decl.type}\" — that type is still a registered widget.`);\n }\n const holder = renameRegistry.get(decl.type);\n if (holder !== undefined && holder.widget.type !== def.type) {\n throw new Error(`ice: widget \"${def.type}\" renamedFrom \"${decl.type}\" — already claimed by \"${holder.widget.type}\".`);\n }\n if (legacyByOld.has(decl.type)) {\n throw new Error(`ice: widget \"${def.type}\" lists renamedFrom \"${decl.type}\" twice.`);\n }\n const legacy: Component[] = [];\n for (const g of groups) {\n legacy.push(ensureComponent(`${decl.type}:${g.name}`, rawByGroup.get(g.name) as Record<string, FieldInput>));\n }\n legacyByOld.set(decl.type, legacy);\n }\n\n // Essential set: geometry + every group at its defaults (+ container cells).\n const defaultSize = def.defaultSize ?? { w: 240, h: 160 };\n const essential: ComponentInit[] = [\n init(Position, { x: 0, y: 0 }),\n init(Size, { w: defaultSize.w, h: defaultSize.h }),\n // No StackZ (petition 8): stacking is the frame parent's ChildOf sibling\n // sequence — the spawn path hangs the edge (attachSpawnParent). Not a\n // group component, so no prefab-pack version bump rides its removal.\n ];\n for (const g of groups) {\n const defaults: Record<string, string | number | boolean> = {};\n for (const [name, spec] of Object.entries(g.fields)) defaults[name] = defaultValueOf(spec);\n essential.push([g.component, defaults] as ComponentInit);\n }\n // `interaction.drop: \"never\"` (design-015 D-D18): the widget offers itself to no container — its\n // Provides cell is empty, so no drop ever matches and a release over a container is a plain move.\n const dropNever = def.interaction?.drop === \"never\";\n if (def.container !== undefined) {\n essential.push(init(Accepts, { list: JSON.stringify(def.container.accepts) }));\n essential.push(init(Provides, { list: JSON.stringify(dropNever ? [] : (def.container.provides ?? [])) }));\n } else if (!dropNever && def.provides !== undefined && def.provides.length > 0) {\n essential.push(init(Provides, { list: JSON.stringify(def.provides) })); // leaf: no Container tag\n }\n\n // Pre-attached behaviors: normalize the two authored forms and refuse the\n // one store class that cannot ride an entity.\n const behaviorEntries: WidgetBehaviorEntry[] = [];\n for (const decl of def.behaviors ?? []) {\n const entry: WidgetBehaviorEntry =\n \"behavior\" in (decl as AnyBehaviorAttachSpec)\n ? {\n behavior: (decl as AnyBehaviorAttachSpec).behavior as AnyBehaviorDef,\n data: ((decl as AnyBehaviorAttachSpec).data ?? {}) as Readonly<Record<string, unknown>>,\n }\n : { behavior: decl as AnyBehaviorDef, data: {} };\n if (entry.behavior?.__behavior !== true) {\n throw new Error(`ice: defineWidget(\"${def.type}\") behaviors: entry is not a defineBehavior handle.`);\n }\n if (entry.behavior.store === \"ephemeral\") {\n throw new Error(\n `ice: defineWidget(\"${def.type}\") lists ephemeral behavior \"${entry.behavior.name}\" — an ephemeral instance IS the local presence peer, so it cannot be pre-attached to a widget (design-009 §4.4).`,\n );\n }\n if (behaviorEntries.some((x) => x.behavior === entry.behavior)) {\n throw new Error(`ice: defineWidget(\"${def.type}\") lists behavior \"${entry.behavior.name}\" twice.`);\n }\n behaviorEntries.push(entry);\n }\n\n // THE RETIRED VIEW (design-015 §1, D5b). TypeScript already refuses these\n // fields; this is for the JS caller and the stale build that would otherwise\n // pass a declaration nothing reads — the `presentation` precedent (design-013\n // A1). `surface` chose between DOM, GL and video faces; `component`, `chrome`,\n // `animated`, `preview`, `instancePreview` and `sizeMode` described them.\n // A widget's face is its `object` kind's program now, or nothing.\n const retired = [\"presentation\", \"surface\", \"component\", \"chrome\", \"animated\", \"preview\", \"instancePreview\", \"sizeMode\"]\n .filter((k) => (def as unknown as Record<string, unknown>)[k] !== undefined);\n if (retired.length > 0) {\n throw new Error(\n `ice: defineWidget(\"${def.type}\") declares ${retired.join(\", \")} — the view half of a widget is retired (design-015 D5b): a widget's face is its object kind's program (\\`object:\\`), and nothing mounts a component, a chrome, a preview or a surface for it. Drop ${retired.length > 1 ? \"them\" : \"it\"}.`,\n );\n }\n // THE RETIRED KEYBOARD CLAIM (design-019 §5, M24 LT2): `interaction.keyboard: \"exclusive\"` stamped `KeyboardExclusive`, which nothing\n // has read since D5b (the DOM widgets that held a claim are gone), and `keyboardEscape` was its Escape. The desk's ONE editor's lease\n // IS the claim now (a kind's DOM half leases it), and an object in hand that owns Escape says so with its kind's `open.escape`.\n const claim = [\"keyboard\", \"keyboardEscape\"].filter((k) => (def.interaction as Readonly<Record<string, unknown>> | undefined)?.[k] !== undefined);\n if (claim.length > 0) {\n throw new Error(\n `ice: defineWidget(\"${def.type}\") declares interaction.${claim.join(\" and interaction.\")} — the keyboard claim is retired (design-019 §5, M24 LT2): a kind takes keys by LEASING the desk's one editor (\\`EditorLease\\`), and an object in hand that owns Escape says \\`open.escape: \"kind\"\\`. Drop ${claim.length > 1 ? \"them\" : \"it\"}.`,\n );\n }\n if ((def.container as { framePreview?: unknown } | undefined)?.framePreview !== undefined) {\n throw new Error(\n `ice: defineWidget(\"${def.type}\") container declares framePreview — the container's preview renderer is retired (design-015 D5b): a mini mat's inside is drawn by the desk.`,\n );\n }\n\n // The FACE: an `object` binding, or none. `null` is how a caller says \"none\".\n const hasObject = def.object !== undefined && def.object !== null;\n if (!hasObject && def.openable === true) {\n throw new Error(\n `ice: defineWidget(\"${def.type}\") declares openable and carries no object binding — only an object is picked up into the hand (design-015 §8). Pass object: <a kind that opens>, or drop it.`,\n );\n }\n // the held bar's tools belong to what is held (design-015 §8, D3t-a)\n if ((def.heldTools?.length ?? 0) > 0 || def.heldTool !== undefined) {\n if (!(hasObject && def.openable === true)) {\n throw new Error(`ice: defineWidget(\"${def.type}\") declares held tools but does not open — only an object picked up into the hand has a held bar (design-015 §8).`);\n }\n validateHeldTools(def.type, def.heldTools ?? []);\n }\n // …and so do the wheel's and Escape's owners in hand (design-019 §5, M24 LT2)\n if (def.heldWheel !== undefined || def.heldEscape !== undefined) {\n if (!(hasObject && def.openable === true)) {\n throw new Error(`ice: defineWidget(\"${def.type}\") declares heldWheel or heldEscape but does not open — only an object picked up into the hand has a wheel or an Escape of its own (design-019 §5).`);\n }\n if (def.heldWheel !== undefined && def.heldWheel !== \"hand\" && def.heldWheel !== \"kind\") {\n throw new Error(`ice: defineWidget(\"${def.type}\") declares heldWheel \"${String(def.heldWheel)}\" — the wheel in hand is \"hand\" or \"kind\" (design-019 §5).`);\n }\n if (def.heldEscape !== undefined && def.heldEscape !== \"desk\" && def.heldEscape !== \"kind\") {\n throw new Error(`ice: defineWidget(\"${def.type}\") declares heldEscape \"${String(def.heldEscape)}\" — Escape in hand is \"desk\" or \"kind\" (design-019 §5).`);\n }\n }\n validateMenuActions(def.type, def.menu ?? []);\n for (const d of def.data ?? []) {\n if (d.store !== \"durable\") throw new Error(`ice: defineWidget(\"${def.type}\") data prefab \"${d.id}\" is ${d.store} — an object's data children live in the document (durable).`);\n if (d.id === def.type) throw new Error(`ice: defineWidget(\"${def.type}\") names itself as its own data prefab.`);\n }\n if (def.stratum !== undefined && !Object.hasOwn(STRATUM_BANDS, def.stratum)) {\n throw new Error(\n `ice: defineWidget(\"${def.type}\") declares stratum \"${String(def.stratum)}\" — a desk stratum is \"pads\", \"sheets\" or \"things\" (design-015 §4.2).`,\n );\n }\n\n const tray = def.tray === undefined ? undefined : compileTrayEntry(def.type, def.tray, hasObject, props);\n\n const version = def.version ?? 1;\n if (def.migrate !== undefined) validateMigrateChain(def.type, version, def.migrate);\n\n\n const prefab = definePrefab(def.type, {\n store: \"durable\",\n components: essential,\n // Every widget may carry a durable Opacity (design-004 §3: `{opacity}` is\n // the whole per-widget composite fact) — optional, not essential: widgets\n // pay no storage until one is attached, and readers default absent to 1.\n optional: [Opacity],\n // Every widget is containment-eligible: drop-to-consume commits\n // `ChildOf(widget → container)` in the SAME tx as the final position\n // (design-003 §5.5), and an undeclared relation throws at commit — the\n // widgetlab folder-drop field report (2026-07-12) hit exactly that.\n relations: [ChildOf],\n version,\n });\n\n // Capability recipe → runtime tags at projection (equip system).\n const interaction = def.interaction ?? {};\n const capabilityTags: Tag[] = [];\n if (interaction.selectable !== false) capabilityTags.push(Selectable);\n if (interaction.movable === \"selection\") capabilityTags.push(SelectionMovable);\n else if (interaction.movable !== false) capabilityTags.push(Movable);\n if (interaction.resizable === true) capabilityTags.push(Resizable);\n if (interaction.solid === true) capabilityTags.push(Solid);\n if (interaction.dragOn === \"longPress\") capabilityTags.push(LongPressDrag);\n if (interaction.sweepContained === true) capabilityTags.push(SweepsContained);\n if (interaction.wheelTurns === true) capabilityTags.push(WheelTurns);\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 object: hasObject ? def.object : undefined,\n stratum: def.stratum ?? (hasObject ? \"things\" : undefined),\n openable: hasObject && def.openable === true,\n heldTools: Object.freeze([...(def.heldTools ?? [])]),\n heldTool: def.heldTool,\n menu: Object.freeze([...(def.menu ?? [])]),\n riders: def.riders,\n data: Object.freeze([...(def.data ?? [])]),\n defaultSize,\n minSize: def.minSize ?? { w: 40, h: 40 },\n ports: def.ports ?? [],\n capabilityTags,\n provides: Object.freeze([...(def.container?.provides ?? def.provides ?? [])]),\n container:\n def.container === undefined\n ? undefined\n : Object.freeze({\n canvasTypeId: def.container.canvas?.id ?? \"ice.default\",\n canvasSemanticVersion: def.container.canvas?.semanticVersion ?? 1,\n accepts: Object.freeze([...def.container.accepts]),\n widgetTypeIds: Object.freeze((def.container.widgets ?? []).map((w) => w.type)),\n inheritCanvasPlacement: def.container.inheritCanvasPlacement === true,\n portal: Object.freeze({\n top: def.container.portal?.top ?? 0,\n right: def.container.portal?.right ?? 0,\n bottom: def.container.portal?.bottom ?? 0,\n left: def.container.portal?.left ?? 0,\n }),\n frameProjection: def.container.frameProjection,\n typed: def.container.typed === true,\n }),\n heldWheel: def.heldWheel ?? \"hand\",\n heldEscape: def.heldEscape ?? \"desk\",\n drop: interaction.drop ?? \"into\",\n migrate: def.migrate ?? {},\n behaviors: behaviorEntries,\n tray,\n };\n registry.set(def.type, widget);\n for (const decl of renameDecls) {\n renameRegistry.set(decl.type, {\n widget,\n oldType: decl.type,\n atVersion: decl.atVersion ?? 1,\n legacyGroups: legacyByOld.get(decl.type) as Component[],\n });\n }\n return widget;\n}\n\n/**\n * A tray entry, checked and frozen (design-017 §8): an object's only; a name tag; its props the widget's own, each valid under its\n * spec; a hang the lattice law can lay (kernel `hangError`); a finite order and a string category if given.\n */\nfunction compileTrayEntry(type: string, entry: TrayEntry, hasObject: boolean, props: PropsDecl): TrayEntry {\n const fail = (why: string): never => { throw new Error(`ice: defineWidget(\"${type}\") tray entry — ${why} (design-017 §8).`); };\n if (!hasObject) fail(\"only an object hangs on the tray: a specimen is its kind's own drawing, and this widget has no object binding\");\n if (typeof entry !== \"object\" || entry === null) fail(\"an entry is { label, props?, hang, order?, category? }\");\n if (typeof entry.label !== \"string\" || entry.label.trim() === \"\") fail(\"its label (the specimen's name tag) is not a non-empty string\");\n const valid = (given: unknown, what: string): Readonly<Record<string, unknown>> => {\n if (typeof given !== \"object\" || given === null || Array.isArray(given)) return fail(`its ${what} are not a record`);\n for (const [name, value] of Object.entries(given)) {\n const spec = props[name];\n if (spec === undefined) fail(`its ${what} name \"${name}\", which the widget does not declare`);\n const result = (spec as PropSpec)[\"~standard\"].validate(value);\n if (\"issues\" in result && result.issues !== undefined) fail(`its ${what === \"props\" ? \"prop\" : \"take prop\"} \"${name}\" is invalid — ${result.issues[0]?.message}`);\n }\n return given as Readonly<Record<string, unknown>>;\n };\n const given = valid(entry.props ?? {}, \"props\");\n const take = entry.take === undefined || entry.take === \"face\" ? entry.take : valid(entry.take, \"take props\");\n const why = hangError(entry.hang);\n if (why !== null) fail(`its hang: ${why}`);\n if (entry.order !== undefined && !Number.isFinite(entry.order)) fail(`its order ${String(entry.order)} is not a finite number`);\n if (entry.category !== undefined && typeof entry.category !== \"string\") fail(\"its category is not a string\");\n if (entry.local !== undefined && typeof entry.local !== \"boolean\") fail(\"its local is not a boolean\");\n const hang = entry.hang;\n return Object.freeze({\n label: entry.label,\n props: Object.freeze({ ...given }),\n ...(take !== undefined ? { take: take === \"face\" ? take : Object.freeze({ ...take }) } : {}),\n ...(entry.local === true ? { local: true } : {}),\n hang: Object.freeze({ w: hang.w, h: hang.h, accessory: hang.accessory, pegs: Object.freeze(hang.pegs.map((p) => Object.freeze([p[0], p[1]] as const))) }),\n ...(entry.order !== undefined ? { order: entry.order } : {}),\n ...(entry.category !== undefined ? { category: entry.category } : {}),\n });\n}\n\n/** What one taken off the tray is made with (design-017 §9; K5b, D-K5b.1): the entry's `take` — the face's props, its own, or none (the widget's defaults). */\nexport function trayTakeProps(entry: TrayEntry): Readonly<Record<string, unknown>> | undefined {\n if (entry.take === undefined) return undefined;\n return entry.take === \"face\" ? entry.props : entry.take;\n}\n\n/** TEST-ONLY wipe (mirrors __resetPrefabsForTests; not on the barrel). */\nexport function __resetWidgetsForTests(): void {\n registry.clear();\n renameRegistry.clear();\n}\n","/**\n * CanvasType definitions — the semantic/presentation profile for one frame.\n *\n * Definitions are immutable handles. The process registry is discovery and\n * duplicate-id diagnostics only; an EngineCatalog decides which definitions\n * have authority in a particular engine.\n */\nimport type { Tool } from \"../tools/define-tool\";\nimport type { WidgetType } from \"../widget/define-widget\";\nimport type {\n CanvasRuntimeExtension,\n CanvasSemanticMigration,\n FrameBehavior,\n} from \"./extensions\";\nimport type { CanvasPreviewDeclaration } from \"./frame-projection\";\n\nexport interface CanvasPlacementDef {\n /** Exact capability keys matched against normalized WidgetType.provides. */\n readonly accepts?: readonly string[];\n /** Explicit widget handles admitted independently of capability keys. */\n readonly widgets?: readonly WidgetType[];\n}\n\nexport interface CanvasCatalogSection {\n readonly id: string;\n readonly order?: number;\n readonly items: readonly WidgetType[];\n}\n\nexport interface CanvasCatalogContribution {\n readonly id: string;\n readonly canvas: CanvasType;\n readonly sections: readonly CanvasCatalogSection[];\n}\n\nexport interface CanvasTypeDef {\n readonly id: string;\n readonly semanticVersion: number;\n readonly semantic: {\n readonly placement: CanvasPlacementDef;\n readonly frameBehaviors?: readonly FrameBehavior[];\n };\n /** Consecutive, view-independent semantic upgrades into semanticVersion. */\n readonly migrations?: readonly CanvasSemanticMigration[];\n readonly presentation?: {\n readonly catalog?: { readonly sections: readonly CanvasCatalogSection[] };\n readonly tools?: {\n readonly allowed: readonly Tool[];\n readonly default: Tool;\n };\n /**\n * The type DECLARES the desk's ground (design-013 §8 C2; a bare marker since design-015 D7): its one live\n * meaning is that a flight into or out of the type requires the `ground` presentation plane to prepare.\n * The declaration's fields are gone and REFUSED by name at definition time rather than quietly ignored:\n * `program` (C2 — three's GroundProgramDefinition), and at D7 `glyph`, `grid`, `wires` and `guides`, which\n * nothing had read since D5b (the desk's mat is the one ground; its snap guides are marks, always drawn —\n * `guides: false` no longer hid them; the wire overlay left with dom's world-space half).\n */\n readonly ground?: Readonly<Record<string, never>>;\n readonly camera?: {\n readonly arrival?: \"fit\" | \"identity\";\n readonly padding?: number;\n readonly minZoom?: number;\n readonly maxZoom?: number;\n };\n readonly runtimeExtensions?: readonly CanvasRuntimeExtension[];\n readonly preview?: CanvasPreviewDeclaration;\n };\n}\n\nexport interface CanvasType extends CanvasTypeDef {\n readonly __canvasType: true;\n}\n\nexport interface CanvasTypeIdentity {\n readonly id: string;\n readonly semanticVersion: number;\n}\n\nexport const ROOT_CANVAS_META_KEY = \"ice:rootCanvas\";\n\n/** Existing pack-gate namespace reserved for CanvasType semantics. */\nexport function canvasPackId(id: string): string {\n return `@ice/canvas/${id}`;\n}\n\nexport function canvasIdentityOf(type: CanvasType): CanvasTypeIdentity {\n return { id: type.id, semanticVersion: type.semanticVersion };\n}\n\nexport function sameCanvasIdentity(\n a: CanvasTypeIdentity | undefined,\n b: CanvasTypeIdentity | undefined,\n): boolean {\n return a?.id === b?.id && a?.semanticVersion === b?.semanticVersion;\n}\n\nexport function encodeCanvasIdentity(identity: CanvasTypeIdentity): string {\n return JSON.stringify(identity);\n}\n\nexport function parseCanvasIdentity(value: unknown): CanvasTypeIdentity | undefined {\n if (typeof value !== \"string\") return undefined;\n try {\n const parsed = JSON.parse(value) as Partial<CanvasTypeIdentity> | null;\n if (\n parsed === null ||\n typeof parsed.id !== \"string\" ||\n parsed.id.length === 0 ||\n !Number.isSafeInteger(parsed.semanticVersion) ||\n (parsed.semanticVersion as number) < 1\n ) {\n return undefined;\n }\n return { id: parsed.id, semanticVersion: parsed.semanticVersion as number };\n } catch {\n return undefined;\n }\n}\n\nconst registry = new Map<string, CanvasType>();\n\nexport const canvasTypes = {\n get(id: string): CanvasType | undefined {\n return registry.get(id);\n },\n all(): CanvasType[] {\n return [...registry.values()];\n },\n};\n\nfunction uniqueStrings(owner: string, label: string, values: readonly string[]): readonly string[] {\n const seen = new Set<string>();\n const out: string[] = [];\n for (const value of values) {\n if (typeof value !== \"string\" || value.length === 0 || /\\s/.test(value)) {\n throw new Error(`ice: defineCanvasType(\"${owner}\") ${label} contains invalid key \"${String(value)}\".`);\n }\n if (seen.has(value)) {\n throw new Error(`ice: defineCanvasType(\"${owner}\") ${label} contains duplicate \"${value}\".`);\n }\n seen.add(value);\n out.push(value);\n }\n return Object.freeze(out);\n}\n\nexport function defineCanvasType(def: CanvasTypeDef): CanvasType {\n if (typeof def.id !== \"string\" || def.id.length === 0 || /\\s/.test(def.id)) {\n throw new Error(\"ice: defineCanvasType — id must be a non-empty stable id without whitespace.\");\n }\n if (!Number.isSafeInteger(def.semanticVersion) || def.semanticVersion < 1) {\n throw new Error(\n `ice: defineCanvasType(\"${def.id}\") semanticVersion must be a positive integer.`,\n );\n }\n if (registry.has(def.id)) {\n throw new Error(`ice: canvas type \"${def.id}\" is already defined.`);\n }\n\n const explicit = [...(def.semantic.placement.widgets ?? [])];\n const explicitIds = new Set<string>();\n for (const widget of explicit) {\n if (explicitIds.has(widget.type)) {\n throw new Error(\n `ice: defineCanvasType(\"${def.id}\") placement.widgets contains duplicate \"${widget.type}\".`,\n );\n }\n explicitIds.add(widget.type);\n }\n\n const presentation = def.presentation;\n // design-013 C2: `presentation.ground.program` is gone with the program contract. A JS caller\n // (or an `as` cast) still passing it would otherwise get a plausible default ground and never\n // learn its declaration was dropped — refuse it by name, like `defineWidget({ presentation })`.\n if (presentation?.ground !== undefined && \"program\" in presentation.ground) {\n throw new Error(\n `ice: defineCanvasType(\"${def.id}\") presentation.ground.program is gone (design-013 C2): three's GroundProgramDefinition and its transition ladder are deleted; \\`ground: {}\\` declares the desk's ground.`,\n );\n }\n // design-015 D7: the declaration's fields were validated and never read since D5b — refuse each by name\n const retiredGround = Object.keys(presentation?.ground ?? {}).filter((k) => k !== \"program\");\n if (retiredGround.length > 0) {\n throw new Error(\n `ice: defineCanvasType(\"${def.id}\") presentation.ground.${retiredGround[0]} is gone (design-015 D7): nothing read it since D5b — the desk's mat is the one ground, its snap guides are marks (always drawn: \\`guides: false\\` no longer hid them) and the wire overlay left with dom's world-space half; \\`ground: {}\\` declares the ground.`,\n );\n }\n // …and the preview's two opaque tokens, which no adapter read after the frame-preview renderers left (D5b)\n const retiredPreview = [\"background\", \"renderer\"].filter((k) => presentation?.preview !== undefined && k in presentation.preview);\n if (retiredPreview.length > 0) {\n throw new Error(\n `ice: defineCanvasType(\"${def.id}\") presentation.preview.${retiredPreview[0]} is gone (design-015 D7): no adapter read it after the frame-preview renderers left at D5b — a mini mat's inside is drawn by the desk; \\`preview.projection\\` stays.`,\n );\n }\n const migrations = [...(def.migrations ?? [])].sort((a, b) => a.from - b.from);\n const migrationFrom = new Set<number>();\n for (const migration of migrations) {\n if (\n !Number.isSafeInteger(migration.from) ||\n !Number.isSafeInteger(migration.to) ||\n migration.from < 1 ||\n migration.to !== migration.from + 1 ||\n migration.to > def.semanticVersion\n ) {\n throw new Error(\n `ice: defineCanvasType(\"${def.id}\") migration ${migration.from}→${migration.to} must be one positive consecutive step into semanticVersion ${def.semanticVersion}.`,\n );\n }\n if (migrationFrom.has(migration.from)) {\n throw new Error(\n `ice: defineCanvasType(\"${def.id}\") repeats migration from version ${migration.from}.`,\n );\n }\n migrationFrom.add(migration.from);\n }\n for (let index = 1; index < migrations.length; index++) {\n if (migrations[index]?.from !== migrations[index - 1]?.to) {\n throw new Error(`ice: defineCanvasType(\"${def.id}\") migration chain contains a gap.`);\n }\n }\n if (migrations.length > 0 && migrations[migrations.length - 1]?.to !== def.semanticVersion) {\n throw new Error(\n `ice: defineCanvasType(\"${def.id}\") migration chain must end at semanticVersion ${def.semanticVersion}.`,\n );\n }\n const type: CanvasType = Object.freeze({\n __canvasType: true as const,\n id: def.id,\n semanticVersion: def.semanticVersion,\n semantic: Object.freeze({\n placement: Object.freeze({\n accepts: uniqueStrings(def.id, \"placement.accepts\", def.semantic.placement.accepts ?? []),\n widgets: Object.freeze(explicit),\n }),\n frameBehaviors: Object.freeze([...(def.semantic.frameBehaviors ?? [])]),\n }),\n migrations: Object.freeze(\n migrations.map((migration) =>\n Object.freeze({\n ...migration,\n reads: Object.freeze([...(migration.reads ?? [])]),\n writes: Object.freeze([...(migration.writes ?? [])]),\n }),\n ),\n ),\n ...(presentation === undefined\n ? {}\n : {\n presentation: Object.freeze({\n ...presentation,\n ...(presentation.catalog === undefined\n ? {}\n : {\n catalog: Object.freeze({\n sections: Object.freeze(\n presentation.catalog.sections.map((section) =>\n Object.freeze({ ...section, items: Object.freeze([...section.items]) }),\n ),\n ),\n }),\n }),\n ...(presentation.tools === undefined\n ? {}\n : {\n tools: Object.freeze({\n allowed: Object.freeze([...presentation.tools.allowed]),\n default: presentation.tools.default,\n }),\n }),\n ...(presentation.runtimeExtensions === undefined\n ? {}\n : { runtimeExtensions: Object.freeze([...presentation.runtimeExtensions]) }),\n ...(presentation.ground === undefined ? {} : { ground: Object.freeze({}) }),\n ...(presentation.camera === undefined\n ? {}\n : { camera: Object.freeze({ ...presentation.camera }) }),\n ...(presentation.preview === undefined\n ? {}\n : { preview: Object.freeze({ ...presentation.preview }) }),\n }),\n }),\n });\n registry.set(type.id, type);\n return type;\n}\n\n/** Immutable, explicitly compiled presentation-only catalog contribution. */\nexport function contributeCanvasCatalog(\n contribution: CanvasCatalogContribution,\n): CanvasCatalogContribution {\n if (\n typeof contribution.id !== \"string\" ||\n contribution.id.length === 0 ||\n /\\s/.test(contribution.id)\n ) {\n throw new Error(\"ice: contributeCanvasCatalog — id must be a stable non-empty id.\");\n }\n return Object.freeze({\n ...contribution,\n sections: Object.freeze(\n contribution.sections.map((section) =>\n Object.freeze({ ...section, items: Object.freeze([...section.items]) }),\n ),\n ),\n });\n}\n\n/** Legacy/default CanvasType. Engine compilation expands placement/catalog. */\nexport const DefaultCanvasType = defineCanvasType({\n id: \"ice.default\",\n semanticVersion: 1,\n semantic: { placement: {} },\n});\n","/**\n * Governed Canvas SDK logic definitions.\n *\n * These handles are immutable declarations. Like WidgetType/Tool/CanvasType,\n * their process registries are authoring-time identity stores only; an\n * EngineCatalog decides which declarations exist in one engine.\n */\nimport type {\n Component,\n Entity,\n Relation,\n Resource,\n Tag,\n} from \"@vibecook/strata-ecs\";\nimport type { CanvasSessionValue } from \"./session\";\n\nexport type CanvasReadFacet = Component | Tag | Relation | Resource;\n\nexport interface CanvasRuntimeChanges {\n readonly full: boolean;\n readonly changed: readonly Entity[];\n readonly removed: readonly Entity[];\n}\n\nexport interface CanvasScopedReader {\n readonly frame: Entity;\n readonly children: readonly Entity[];\n read<S>(entity: Entity, component: Component<S>): S;\n get<S>(entity: Entity, component: Component<S>): S | undefined;\n hasTag(entity: Entity, tag: Tag): boolean;\n getRelation(entity: Entity, relation: Relation): Entity | undefined;\n getRelations(entity: Entity, relation: Relation): readonly Entity[];\n getReverse(entity: Entity, relation: Relation): readonly Entity[];\n getResource<S>(resource: Resource<S>): S | undefined;\n}\n\nexport interface CanvasRuntimeExtensionContext extends CanvasScopedReader {\n readonly session: CanvasSessionValue & { readonly state: \"attached\" };\n readonly changes: CanvasRuntimeChanges;\n readonly signal: AbortSignal;\n /** Set one declared runtime-only output on the frame owner or a direct child. */\n set<S>(entity: Entity, component: Component<S>, value: S): void;\n /** Remove one declared runtime-only output owned by this extension. */\n remove(entity: Entity, component: Component): void;\n}\n\nexport interface CanvasRuntimeExtensionDef {\n readonly id: string;\n /** Runtime/cache identity only; never a document requirement. */\n readonly version: number;\n readonly phase?: \"derive\";\n readonly after?: readonly string[];\n readonly before?: readonly string[];\n readonly reads?: readonly CanvasReadFacet[];\n readonly writesRuntime?: readonly Component[];\n readonly budgetMs?: number;\n run(context: CanvasRuntimeExtensionContext): void;\n}\n\nexport interface CanvasRuntimeExtension extends CanvasRuntimeExtensionDef {\n readonly __canvasRuntimeExtension: true;\n readonly phase: \"derive\";\n readonly after: readonly string[];\n readonly before: readonly string[];\n readonly reads: readonly CanvasReadFacet[];\n readonly writesRuntime: readonly Component[];\n}\n\nexport interface FrameBehaviorWriteContext extends CanvasScopedReader {\n readonly canvasTypeId: string;\n /** Absolute, change-only component write queued into this behavior's transaction. */\n set<S>(entity: Entity, component: Component<S>, value: S): void;\n remove(entity: Entity, component: Component): void;\n setRelation(entity: Entity, relation: Relation, target: Entity): void;\n removeRelation(entity: Entity, relation: Relation, target?: Entity): void;\n}\n\nexport interface FrameBehaviorDef {\n readonly id: string;\n readonly version: number;\n readonly phase?: \"postSettle\";\n readonly after?: readonly string[];\n readonly before?: readonly string[];\n readonly reads?: readonly CanvasReadFacet[];\n readonly writesDurable?: readonly Component[];\n readonly writesRelations?: readonly Relation[];\n readonly budget?: { readonly entities?: number; readonly ms?: number };\n run(context: FrameBehaviorWriteContext): void;\n}\n\nexport interface FrameBehavior extends FrameBehaviorDef {\n readonly __frameBehavior: true;\n readonly phase: \"postSettle\";\n readonly after: readonly string[];\n readonly before: readonly string[];\n readonly reads: readonly CanvasReadFacet[];\n readonly writesDurable: readonly Component[];\n readonly writesRelations: readonly Relation[];\n readonly budget: { readonly entities: number; readonly ms: number };\n}\n\nexport type ExistingPlacementPosture = \"preserve-and-warn\" | \"repair\";\n\nexport interface CanvasSemanticMigrationContext extends CanvasScopedReader {\n readonly canvasTypeId: string;\n readonly from: number;\n readonly to: number;\n set<S>(entity: Entity, component: Component<S>, value: S): void;\n remove(entity: Entity, component: Component): void;\n setRelation(entity: Entity, relation: Relation, target: Entity): void;\n removeRelation(entity: Entity, relation: Relation, target?: Entity): void;\n /** Explicit frame-ownership repair; target must be a live valid frame. */\n reparent(entity: Entity, targetFrame: Entity): void;\n}\n\nexport interface CanvasSemanticMigration {\n readonly from: number;\n readonly to: number;\n readonly reads?: readonly CanvasReadFacet[];\n readonly writes?: readonly (Component | Relation)[];\n readonly existingPlacement: ExistingPlacementPosture;\n migrate(context: CanvasSemanticMigrationContext): void;\n}\n\nfunction stableId(kind: string, id: string): void {\n if (typeof id !== \"string\" || id.length === 0 || /\\s/.test(id)) {\n throw new Error(`ice: ${kind} id must be a non-empty stable id without whitespace.`);\n }\n}\n\nfunction positiveVersion(kind: string, id: string, version: number): void {\n if (!Number.isSafeInteger(version) || version < 1) {\n throw new Error(`ice: ${kind}(\"${id}\") version must be a positive integer.`);\n }\n}\n\nfunction uniqueStrings(kind: string, id: string, values: readonly string[]): readonly string[] {\n const out: string[] = [];\n const seen = new Set<string>();\n for (const value of values) {\n stableId(`${kind}(\"${id}\") dependency`, value);\n if (seen.has(value)) {\n throw new Error(`ice: ${kind}(\"${id}\") repeats dependency \"${value}\".`);\n }\n seen.add(value);\n out.push(value);\n }\n return Object.freeze(out);\n}\n\nfunction uniqueHandles<T extends object>(kind: string, id: string, values: readonly T[]): readonly T[] {\n const seen = new Set<T>();\n for (const value of values) {\n if (seen.has(value)) throw new Error(`ice: ${kind}(\"${id}\") repeats a declared facet.`);\n seen.add(value);\n }\n return Object.freeze([...values]);\n}\n\nconst runtimeRegistry = new Map<string, CanvasRuntimeExtension>();\nconst frameRegistry = new Map<string, FrameBehavior>();\n\nexport const canvasRuntimeExtensions = {\n get(id: string): CanvasRuntimeExtension | undefined {\n return runtimeRegistry.get(id);\n },\n all(): readonly CanvasRuntimeExtension[] {\n return [...runtimeRegistry.values()];\n },\n};\n\nexport const frameBehaviors = {\n get(id: string): FrameBehavior | undefined {\n return frameRegistry.get(id);\n },\n all(): readonly FrameBehavior[] {\n return [...frameRegistry.values()];\n },\n};\n\nexport function defineCanvasRuntimeExtension(\n def: CanvasRuntimeExtensionDef,\n): CanvasRuntimeExtension {\n stableId(\"defineCanvasRuntimeExtension\", def.id);\n positiveVersion(\"defineCanvasRuntimeExtension\", def.id, def.version);\n if (runtimeRegistry.has(def.id)) {\n throw new Error(`ice: CanvasRuntimeExtension \"${def.id}\" is already defined.`);\n }\n if (def.phase !== undefined && def.phase !== \"derive\") {\n throw new Error(`ice: CanvasRuntimeExtension \"${def.id}\" only supports phase \"derive\".`);\n }\n if (def.budgetMs !== undefined && (!Number.isFinite(def.budgetMs) || def.budgetMs <= 0)) {\n throw new Error(`ice: CanvasRuntimeExtension \"${def.id}\" has an invalid budgetMs.`);\n }\n const extension: CanvasRuntimeExtension = Object.freeze({\n ...def,\n __canvasRuntimeExtension: true as const,\n phase: \"derive\" as const,\n after: uniqueStrings(\"defineCanvasRuntimeExtension\", def.id, def.after ?? []),\n before: uniqueStrings(\"defineCanvasRuntimeExtension\", def.id, def.before ?? []),\n reads: uniqueHandles(\"defineCanvasRuntimeExtension\", def.id, def.reads ?? []),\n writesRuntime: uniqueHandles(\n \"defineCanvasRuntimeExtension\",\n def.id,\n def.writesRuntime ?? [],\n ),\n });\n runtimeRegistry.set(extension.id, extension);\n return extension;\n}\n\nexport function defineFrameBehavior(def: FrameBehaviorDef): FrameBehavior {\n stableId(\"defineFrameBehavior\", def.id);\n positiveVersion(\"defineFrameBehavior\", def.id, def.version);\n if (frameRegistry.has(def.id)) {\n throw new Error(`ice: FrameBehavior \"${def.id}\" is already defined.`);\n }\n if (def.phase !== undefined && def.phase !== \"postSettle\") {\n throw new Error(`ice: FrameBehavior \"${def.id}\" only supports phase \"postSettle\".`);\n }\n const entities = def.budget?.entities ?? 512;\n const ms = def.budget?.ms ?? 2;\n if (!Number.isSafeInteger(entities) || entities < 1 || entities > 100_000) {\n throw new Error(`ice: FrameBehavior \"${def.id}\" has an invalid entity budget.`);\n }\n if (!Number.isFinite(ms) || ms <= 0) {\n throw new Error(`ice: FrameBehavior \"${def.id}\" has an invalid time budget.`);\n }\n const behavior: FrameBehavior = Object.freeze({\n ...def,\n __frameBehavior: true as const,\n phase: \"postSettle\" as const,\n after: uniqueStrings(\"defineFrameBehavior\", def.id, def.after ?? []),\n before: uniqueStrings(\"defineFrameBehavior\", def.id, def.before ?? []),\n reads: uniqueHandles(\"defineFrameBehavior\", def.id, def.reads ?? []),\n writesDurable: uniqueHandles(\"defineFrameBehavior\", def.id, def.writesDurable ?? []),\n writesRelations: uniqueHandles(\"defineFrameBehavior\", def.id, def.writesRelations ?? []),\n budget: Object.freeze({ entities, ms }),\n });\n frameRegistry.set(behavior.id, behavior);\n return behavior;\n}\n\n/** Existing pack-gate namespace reserved for semantic frame behavior code. */\nexport function frameBehaviorPackId(id: string): string {\n return `@ice/frame-behavior/${id}`;\n}\n","/** Declared, bounded custom facets for semantic container previews. */\nimport type { Component, Relation } from \"@vibecook/strata-ecs\";\n\nexport interface FrameProjectionChildRef {\n readonly key: string;\n readonly widgetType: string;\n readonly order: number;\n}\n\nexport interface FrameProjectionRelationRow {\n readonly source: string;\n readonly target: string;\n}\n\nexport interface FrameProjectionContext {\n readonly frameKey: string;\n readonly children: readonly FrameProjectionChildRef[];\n get<S>(childKey: string, component: Component<S>): S | undefined;\n relations(relation: Relation): readonly FrameProjectionRelationRow[];\n}\n\nexport interface FrameProjectionDef {\n readonly id: string;\n readonly version?: number;\n readonly reads?: readonly Component[];\n readonly relations?: readonly Relation[];\n project(context: FrameProjectionContext): unknown;\n}\n\nexport interface FrameProjection extends FrameProjectionDef {\n readonly __frameProjection: true;\n readonly version: number;\n readonly reads: readonly Component[];\n readonly relations: readonly Relation[];\n}\n\nexport interface CanvasPreviewDeclaration {\n readonly projection?: FrameProjection;\n}\n\nconst registry = new Map<string, FrameProjection>();\n\nexport const frameProjections = {\n get(id: string): FrameProjection | undefined {\n return registry.get(id);\n },\n all(): readonly FrameProjection[] {\n return [...registry.values()];\n },\n};\n\nexport function defineFrameProjection(def: FrameProjectionDef): FrameProjection {\n if (typeof def.id !== \"string\" || def.id.length === 0 || /\\s/.test(def.id)) {\n throw new Error(\"ice: defineFrameProjection — id must be a non-empty stable id without whitespace.\");\n }\n const version = def.version ?? 1;\n if (!Number.isSafeInteger(version) || version < 1) {\n throw new Error(`ice: defineFrameProjection(\"${def.id}\") version must be a positive integer.`);\n }\n if (registry.has(def.id)) {\n throw new Error(`ice: FrameProjection \"${def.id}\" is already defined.`);\n }\n const reads = [...(def.reads ?? [])];\n const relations = [...(def.relations ?? [])];\n if (new Set(reads).size !== reads.length || new Set(relations).size !== relations.length) {\n throw new Error(`ice: defineFrameProjection(\"${def.id}\") repeats a declared facet.`);\n }\n const projection: FrameProjection = Object.freeze({\n ...def,\n __frameProjection: true as const,\n version,\n reads: Object.freeze(reads),\n relations: Object.freeze(relations),\n });\n registry.set(projection.id, projection);\n return projection;\n}\n","/**\n * Immutable, engine-scoped definition authority.\n *\n * Global registries remain definition stores for authoring/HMR. Runtime code\n * resolves through the catalog bound to its World; unbound lower-level test\n * worlds retain the legacy registry fallback.\n */\nimport type { World } from \"@vibecook/strata-ecs\";\nimport { WirePrefab } from \"../catalog/graph\";\nimport { prefabs, type Prefab } from \"../schema/prefab\";\nimport { tools, type Tool } from \"../tools/define-tool\";\nimport { widgets, type WidgetType } from \"../widget/define-widget\";\nimport { schemaMeta } from \"../schema/meta\";\nimport {\n DefaultCanvasType,\n canvasPackId,\n canvasTypes,\n type CanvasCatalogContribution,\n type CanvasCatalogSection,\n type CanvasType,\n} from \"./define-canvas-type\";\nimport {\n canvasRuntimeExtensions,\n frameBehaviorPackId,\n frameBehaviors,\n type CanvasReadFacet,\n type CanvasRuntimeExtension,\n type FrameBehavior,\n} from \"./extensions\";\nimport {\n frameProjections,\n type FrameProjection,\n} from \"./frame-projection\";\n\nexport interface EngineCatalogCompileOpts {\n readonly widgets?: readonly { readonly type: string }[];\n /** Schema compatibility only: no placement, runtime, tray, or canvas presentation. */\n readonly retiredWidgets?: readonly { readonly type: string }[];\n readonly tools?: readonly Tool[];\n readonly canvasTypes?: readonly CanvasType[];\n readonly rootCanvas?: CanvasType;\n readonly presentationFallback?: CanvasType;\n readonly catalogContributions?: readonly CanvasCatalogContribution[];\n readonly canvasRuntimeExtensions?: readonly CanvasRuntimeExtension[];\n readonly frameBehaviors?: readonly FrameBehavior[];\n readonly frameProjections?: readonly FrameProjection[];\n}\n\nexport interface EngineCatalog {\n readonly typed: boolean;\n readonly rootCanvas: CanvasType;\n readonly presentationFallback: CanvasType;\n widget(id: string): WidgetType | undefined;\n /** A dormant schema retained for saved documents, outside the active widget catalog. */\n retiredWidget(id: string): WidgetType | undefined;\n widgetTypes(): readonly WidgetType[];\n tool(id: string): Tool | undefined;\n toolTypes(): readonly Tool[];\n canvasType(id: string): CanvasType | undefined;\n canvasTypeDefs(): readonly CanvasType[];\n runtimeExtension(id: string): CanvasRuntimeExtension | undefined;\n runtimeExtensionsFor(canvasTypeId: string): readonly CanvasRuntimeExtension[];\n frameBehavior(id: string): FrameBehavior | undefined;\n frameBehaviorsFor(canvasTypeId: string): readonly FrameBehavior[];\n frameProjection(id: string): FrameProjection | undefined;\n frameProjectionForContainer(widgetTypeId: string): FrameProjection | undefined;\n canvasForContainer(widgetTypeId: string): CanvasType | undefined;\n placementFor(canvasTypeId: string): ReadonlySet<string>;\n toolsFor(canvasTypeId: string): readonly Tool[];\n defaultToolFor(canvasTypeId: string): Tool;\n catalogFor(canvasTypeId: string): readonly CanvasCatalogSection[];\n /** Every pack/version this engine can interpret while opening a document. */\n localPacks(): Readonly<Record<string, number>>;\n /** Exact capability manifest granted to a newly created document. */\n initialPacks(): Readonly<Record<string, number>>;\n /** Semantic requirement closure keyed by the pack that introduces it. */\n packDependencies(): Readonly<Record<string, Readonly<Record<string, number>>>>;\n /** Requirement closure that must be stamped before this widget can be created. */\n requirementsForWidget(widgetTypeId: string): Readonly<Record<string, number>> | undefined;\n /** A registered widget's DATA prefab by id (design-015 §5.1, D3t-a — the board's strokes): tracked, stamped and gated with the widget. */\n dataPrefab(id: string): Prefab | undefined;\n}\n\nfunction uniqueById<T>(label: string, values: readonly T[], idOf: (value: T) => string): T[] {\n const seen = new Set<string>();\n const out: T[] = [];\n for (const value of values) {\n const id = idOf(value);\n if (seen.has(id)) throw new Error(`ice: createCanvasEngine — duplicate ${label} \"${id}\".`);\n seen.add(id);\n out.push(value);\n }\n return out;\n}\n\nfunction stableTopo<T extends { readonly id: string; readonly after: readonly string[]; readonly before: readonly string[] }>(\n owner: string,\n kind: string,\n values: readonly T[],\n): readonly T[] {\n const byId = new Map(values.map((value) => [value.id, value] as const));\n const outgoing = new Map<string, Set<string>>();\n const indegree = new Map<string, number>();\n for (const value of values) {\n outgoing.set(value.id, new Set());\n indegree.set(value.id, 0);\n }\n const edge = (from: string, to: string): void => {\n if (!byId.has(from) || !byId.has(to)) {\n throw new Error(\n `ice: CanvasType \"${owner}\" ${kind} ordering references uncompiled id ` +\n `\"${byId.has(from) ? to : from}\".`,\n );\n }\n const targets = outgoing.get(from) as Set<string>;\n if (targets.has(to)) return;\n targets.add(to);\n indegree.set(to, (indegree.get(to) ?? 0) + 1);\n };\n for (const value of values) {\n for (const prior of value.after) edge(prior, value.id);\n for (const later of value.before) edge(value.id, later);\n }\n const ready = [...values]\n .filter((value) => indegree.get(value.id) === 0)\n .sort((a, b) => a.id.localeCompare(b.id));\n const ordered: T[] = [];\n while (ready.length > 0) {\n const value = ready.shift() as T;\n ordered.push(value);\n for (const target of [...(outgoing.get(value.id) ?? [])].sort()) {\n const next = (indegree.get(target) ?? 0) - 1;\n indegree.set(target, next);\n if (next === 0) {\n ready.push(byId.get(target) as T);\n ready.sort((a, b) => a.id.localeCompare(b.id));\n }\n }\n }\n if (ordered.length !== values.length) {\n throw new Error(`ice: CanvasType \"${owner}\" ${kind} ordering contains a cycle.`);\n }\n return Object.freeze(ordered);\n}\n\nfunction validateFacet(owner: string, facet: CanvasReadFacet): void {\n if (\n schemaMeta.component(facet as never) === undefined &&\n schemaMeta.tagName(facet as never) === undefined &&\n schemaMeta.relation(facet as never) === undefined &&\n schemaMeta.resource(facet as never) === undefined\n ) {\n throw new Error(`ice: ${owner} declares an unknown read facet.`);\n }\n}\n\nfunction resolveWidgets(list: EngineCatalogCompileOpts[\"widgets\"]): WidgetType[] {\n const source = list ?? widgets.all();\n return uniqueById(\"widget type\", source, (w) => w.type).map((decl) => {\n const resolved = widgets.get(decl.type);\n if (resolved === undefined) {\n throw new Error(`ice: createCanvasEngine — widget type \"${decl.type}\" is not defined.`);\n }\n return resolved;\n });\n}\n\nfunction resolveTools(list: EngineCatalogCompileOpts[\"tools\"], typed: boolean): Tool[] {\n const requested = list ?? tools.all();\n const source = typed ? requested : [tools.get(\"select\"), tools.get(\"pan\"), tools.get(\"connect\"), ...requested];\n const resolved: Tool[] = [];\n const seen = new Set<string>();\n for (const candidate of source) {\n if (candidate === undefined || seen.has(candidate.id)) continue;\n const registered = tools.get(candidate.id);\n if (registered === undefined) {\n throw new Error(`ice: createCanvasEngine — tool \"${candidate.id}\" is not defined.`);\n }\n seen.add(candidate.id);\n resolved.push(registered);\n }\n if (!seen.has(\"select\")) {\n throw new Error('ice: createCanvasEngine — typed Canvas SDK engines must explicitly compile tool \"select\".');\n }\n return resolved;\n}\n\nexport function compileEngineCatalog(opts: EngineCatalogCompileOpts = {}): EngineCatalog {\n const typed =\n opts.canvasTypes !== undefined ||\n opts.rootCanvas !== undefined ||\n opts.presentationFallback !== undefined;\n if (typed && opts.widgets === undefined) {\n throw new Error(\"ice: createCanvasEngine — typed Canvas SDK mode requires an explicit widgets list.\");\n }\n if (typed && opts.tools === undefined) {\n throw new Error(\"ice: createCanvasEngine — typed Canvas SDK mode requires an explicit tools list.\");\n }\n if (typed && opts.presentationFallback === undefined) {\n throw new Error(\n \"ice: createCanvasEngine — typed Canvas SDK mode requires an explicit presentationFallback.\",\n );\n }\n\n const widgetList = resolveWidgets(opts.widgets);\n const retiredList = resolveWidgets(opts.retiredWidgets ?? []);\n const retiredMap = new Map(retiredList.map((w) => [w.type, w] as const));\n for (const widget of widgetList) {\n if (retiredMap.has(widget.type)) throw new Error(`ice: widget \"${widget.type}\" cannot be both active and retired.`);\n }\n const toolList = resolveTools(opts.tools, typed);\n const widgetMap = new Map(widgetList.map((w) => [w.type, w] as const));\n const toolMap = new Map(toolList.map((t) => [t.id, t] as const));\n const extensionList = uniqueById(\n \"CanvasRuntimeExtension\",\n opts.canvasRuntimeExtensions ?? [],\n (extension) => extension.id,\n );\n const behaviorList = uniqueById(\n \"FrameBehavior\",\n opts.frameBehaviors ?? [],\n (behavior) => behavior.id,\n );\n const projectionList = uniqueById(\n \"FrameProjection\",\n opts.frameProjections ?? [],\n (projection) => projection.id,\n );\n const extensionMap = new Map(extensionList.map((extension) => [extension.id, extension] as const));\n const behaviorMap = new Map(behaviorList.map((behavior) => [behavior.id, behavior] as const));\n const projectionMap = new Map(\n projectionList.map((projection) => [projection.id, projection] as const),\n );\n for (const extension of extensionList) {\n if (canvasRuntimeExtensions.get(extension.id) !== extension) {\n throw new Error(\n `ice: createCanvasEngine — CanvasRuntimeExtension \"${extension.id}\" is not its registered definition.`,\n );\n }\n for (const facet of extension.reads) validateFacet(`CanvasRuntimeExtension \"${extension.id}\"`, facet);\n for (const component of extension.writesRuntime) {\n if (schemaMeta.component(component) === undefined) {\n throw new Error(\n `ice: CanvasRuntimeExtension \"${extension.id}\" declares an unknown runtime output.`,\n );\n }\n if (widgetList.some((widget) => widget.prefab.eligible.has(component))) {\n throw new Error(\n `ice: CanvasRuntimeExtension \"${extension.id}\" output is durable-eligible on a compiled widget.`,\n );\n }\n }\n }\n for (const behavior of behaviorList) {\n if (frameBehaviors.get(behavior.id) !== behavior) {\n throw new Error(\n `ice: createCanvasEngine — FrameBehavior \"${behavior.id}\" is not its registered definition.`,\n );\n }\n for (const facet of behavior.reads) validateFacet(`FrameBehavior \"${behavior.id}\"`, facet);\n for (const component of behavior.writesDurable) {\n if (schemaMeta.component(component) === undefined) {\n throw new Error(`ice: FrameBehavior \"${behavior.id}\" declares an unknown component output.`);\n }\n }\n for (const relation of behavior.writesRelations) {\n if (schemaMeta.relation(relation) === undefined) {\n throw new Error(`ice: FrameBehavior \"${behavior.id}\" declares an unknown relation output.`);\n }\n }\n }\n for (const projection of projectionList) {\n if (frameProjections.get(projection.id) !== projection) {\n throw new Error(\n `ice: createCanvasEngine — FrameProjection \"${projection.id}\" is not its registered definition.`,\n );\n }\n for (const component of projection.reads) {\n if (schemaMeta.component(component) === undefined) {\n throw new Error(`ice: FrameProjection \"${projection.id}\" declares an unknown component.`);\n }\n }\n for (const relation of projection.relations) {\n if (schemaMeta.relation(relation) === undefined) {\n throw new Error(`ice: FrameProjection \"${projection.id}\" declares an unknown relation.`);\n }\n }\n }\n\n const requestedCanvasTypes =\n opts.canvasTypes ??\n (typed\n ? [DefaultCanvasType]\n : [\n DefaultCanvasType,\n ...widgetList.flatMap((widget) => {\n const id = widget.container?.canvasTypeId;\n const canvas = id === undefined ? undefined : canvasTypes.get(id);\n return canvas === undefined ? [] : [canvas];\n }),\n ]);\n const normalizedCanvasList: CanvasType[] = [];\n const canvasSeen = new Set<string>();\n const userCanvasSeen = new Set<string>();\n if (opts.canvasTypes !== undefined) {\n for (const type of requestedCanvasTypes) {\n if (userCanvasSeen.has(type.id)) {\n throw new Error(`ice: createCanvasEngine — duplicate CanvasType \"${type.id}\".`);\n }\n userCanvasSeen.add(type.id);\n }\n }\n // The built-in default is an implicit compatibility dependency. Its one\n // explicit occurrence in the user list is therefore harmless.\n for (const type of [DefaultCanvasType, ...requestedCanvasTypes]) {\n if (canvasSeen.has(type.id)) continue;\n const registered = canvasTypes.get(type.id);\n if (registered !== type) {\n throw new Error(`ice: createCanvasEngine — CanvasType \"${type.id}\" is not the registered definition.`);\n }\n canvasSeen.add(type.id);\n normalizedCanvasList.push(type);\n }\n const canvasMap = new Map(normalizedCanvasList.map((c) => [c.id, c] as const));\n const contributionIds = new Set<string>();\n const contributions = new Map<string, CanvasCatalogContribution[]>();\n for (const contribution of opts.catalogContributions ?? []) {\n if (contributionIds.has(contribution.id)) {\n throw new Error(\n `ice: createCanvasEngine — duplicate catalog contribution \"${contribution.id}\".`,\n );\n }\n contributionIds.add(contribution.id);\n if (canvasMap.get(contribution.canvas.id) !== contribution.canvas) {\n throw new Error(\n `ice: catalog contribution \"${contribution.id}\" targets an uncompiled CanvasType.`,\n );\n }\n const list = contributions.get(contribution.canvas.id) ?? [];\n list.push(contribution);\n contributions.set(contribution.canvas.id, list);\n }\n const rootCanvas = opts.rootCanvas ?? DefaultCanvasType;\n const presentationFallback = opts.presentationFallback ?? DefaultCanvasType;\n if (canvasMap.get(rootCanvas.id) !== rootCanvas) {\n throw new Error(`ice: createCanvasEngine — root CanvasType \"${rootCanvas.id}\" is not listed.`);\n }\n if (canvasMap.get(presentationFallback.id) !== presentationFallback) {\n throw new Error(\n `ice: createCanvasEngine — presentation fallback CanvasType \"${presentationFallback.id}\" is not listed.`,\n );\n }\n\n const placement = new Map<string, ReadonlySet<string>>();\n const allowedTools = new Map<string, readonly Tool[]>();\n const defaultTools = new Map<string, Tool>();\n const catalogs = new Map<string, readonly CanvasCatalogSection[]>();\n const runtimeByCanvas = new Map<string, readonly CanvasRuntimeExtension[]>();\n const behaviorsByCanvas = new Map<string, readonly FrameBehavior[]>();\n const select = toolMap.get(\"select\") as Tool;\n\n for (const canvas of normalizedCanvasList) {\n const canvasProjection = canvas.presentation?.preview?.projection;\n if (\n canvasProjection !== undefined &&\n projectionMap.get(canvasProjection.id) !== canvasProjection\n ) {\n throw new Error(\n `ice: CanvasType \"${canvas.id}\" references uncompiled FrameProjection \"${canvasProjection.id}\".`,\n );\n }\n const camera = canvas.presentation?.camera;\n if (\n (camera?.padding !== undefined &&\n (!Number.isFinite(camera.padding) || camera.padding < 0)) ||\n (camera?.minZoom !== undefined &&\n (!Number.isFinite(camera.minZoom) || camera.minZoom <= 0)) ||\n (camera?.maxZoom !== undefined &&\n (!Number.isFinite(camera.maxZoom) || camera.maxZoom <= 0)) ||\n (camera?.minZoom !== undefined &&\n camera.maxZoom !== undefined &&\n camera.minZoom > camera.maxZoom)\n ) {\n throw new Error(`ice: CanvasType \"${canvas.id}\" has invalid finite camera limits.`);\n }\n const legal = new Set<string>();\n if (canvas.id === DefaultCanvasType.id) {\n for (const widget of widgetList) legal.add(widget.type);\n } else {\n for (const declared of canvas.semantic.placement.widgets ?? []) {\n if (widgetMap.get(declared.type) !== declared) {\n throw new Error(\n `ice: CanvasType \"${canvas.id}\" places uncompiled widget \"${declared.type}\".`,\n );\n }\n legal.add(declared.type);\n }\n const accepts = new Set(canvas.semantic.placement.accepts ?? []);\n if (accepts.size > 0) {\n for (const widget of widgetList) {\n if (widget.provides.some((key) => accepts.has(key))) legal.add(widget.type);\n }\n }\n }\n placement.set(canvas.id, legal);\n\n const toolDecl = canvas.presentation?.tools;\n const canvasTools =\n canvas.id === DefaultCanvasType.id && !typed\n ? toolList\n : toolDecl?.allowed ?? [select, ...(toolMap.get(\"pan\") === undefined ? [] : [toolMap.get(\"pan\") as Tool])];\n const normalizedTools = uniqueById(\"CanvasType tool\", canvasTools, (tool) => tool.id).map((tool) => {\n const compiled = toolMap.get(tool.id);\n if (compiled === undefined) {\n throw new Error(`ice: CanvasType \"${canvas.id}\" allows uncompiled tool \"${tool.id}\".`);\n }\n if (compiled.draw !== undefined && !legal.has(compiled.draw.widgetType)) {\n throw new Error(\n `ice: CanvasType \"${canvas.id}\" tool \"${compiled.id}\" creates placement-illegal widget \"${compiled.draw.widgetType}\".`,\n );\n }\n return compiled;\n });\n const defaultTool = toolDecl?.default ?? select;\n if (!normalizedTools.some((tool) => tool.id === defaultTool.id)) {\n throw new Error(\n `ice: CanvasType \"${canvas.id}\" default tool \"${defaultTool.id}\" is not in its allowed set.`,\n );\n }\n allowedTools.set(canvas.id, Object.freeze(normalizedTools));\n defaultTools.set(canvas.id, toolMap.get(defaultTool.id) as Tool);\n\n const contributed = [...(contributions.get(canvas.id) ?? [])].sort((a, b) =>\n a.id.localeCompare(b.id),\n );\n const sections = [\n ...(canvas.presentation?.catalog?.sections ?? []),\n ...contributed.flatMap((contribution) => contribution.sections),\n ];\n const sectionIds = new Set<string>();\n const itemIds = new Set<string>();\n for (const section of sections) {\n if (sectionIds.has(section.id)) {\n throw new Error(`ice: CanvasType \"${canvas.id}\" has duplicate catalog section \"${section.id}\".`);\n }\n sectionIds.add(section.id);\n for (const item of section.items) {\n if (!widgetMap.has(item.type)) {\n throw new Error(\n `ice: CanvasType \"${canvas.id}\" catalog references uncompiled widget \"${item.type}\".`,\n );\n }\n if (!legal.has(item.type)) {\n throw new Error(\n `ice: CanvasType \"${canvas.id}\" catalog exposes placement-illegal widget \"${item.type}\".`,\n );\n }\n if (itemIds.has(item.type)) {\n throw new Error(`ice: CanvasType \"${canvas.id}\" catalog repeats widget \"${item.type}\".`);\n }\n itemIds.add(item.type);\n }\n }\n catalogs.set(\n canvas.id,\n Object.freeze(\n [...sections]\n .sort((a, b) => (a.order ?? 0) - (b.order ?? 0) || a.id.localeCompare(b.id))\n .map((section) => Object.freeze({ ...section, items: Object.freeze([...section.items]) })),\n ),\n );\n\n const runtimeExtensions = uniqueById(\n `CanvasType \"${canvas.id}\" runtime extension`,\n canvas.presentation?.runtimeExtensions ?? [],\n (extension) => extension.id,\n ).map((extension) => {\n if (extensionMap.get(extension.id) !== extension) {\n throw new Error(\n `ice: CanvasType \"${canvas.id}\" references uncompiled CanvasRuntimeExtension \"${extension.id}\".`,\n );\n }\n return extension;\n });\n const extensionOutputs = new Map<object, string>();\n for (const extension of runtimeExtensions) {\n for (const output of extension.writesRuntime) {\n const prior = extensionOutputs.get(output);\n if (prior !== undefined) {\n throw new Error(\n `ice: CanvasType \"${canvas.id}\" runtime extensions \"${prior}\" and ` +\n `\"${extension.id}\" claim the same exclusive output.`,\n );\n }\n extensionOutputs.set(output, extension.id);\n }\n }\n runtimeByCanvas.set(\n canvas.id,\n stableTopo(canvas.id, \"runtime extension\", runtimeExtensions),\n );\n\n const semanticBehaviors = uniqueById(\n `CanvasType \"${canvas.id}\" FrameBehavior`,\n canvas.semantic.frameBehaviors ?? [],\n (behavior) => behavior.id,\n ).map((behavior) => {\n if (behaviorMap.get(behavior.id) !== behavior) {\n throw new Error(\n `ice: CanvasType \"${canvas.id}\" references uncompiled FrameBehavior \"${behavior.id}\".`,\n );\n }\n return behavior;\n });\n const behaviorOutputs = new Map<object, string>();\n for (const behavior of semanticBehaviors) {\n for (const output of [...behavior.writesDurable, ...behavior.writesRelations]) {\n const prior = behaviorOutputs.get(output);\n if (prior !== undefined) {\n throw new Error(\n `ice: CanvasType \"${canvas.id}\" FrameBehaviors \"${prior}\" and ` +\n `\"${behavior.id}\" claim the same semantic output without a reducer.`,\n );\n }\n behaviorOutputs.set(output, behavior.id);\n }\n }\n behaviorsByCanvas.set(\n canvas.id,\n stableTopo(canvas.id, \"FrameBehavior\", semanticBehaviors),\n );\n\n for (const migration of canvas.migrations ?? []) {\n for (const facet of migration.reads ?? []) {\n validateFacet(`CanvasType \"${canvas.id}\" migration ${migration.from}→${migration.to}`, facet);\n }\n for (const output of migration.writes ?? []) {\n if (\n schemaMeta.component(output as never) === undefined &&\n schemaMeta.relation(output as never) === undefined\n ) {\n throw new Error(\n `ice: CanvasType \"${canvas.id}\" migration ${migration.from}→${migration.to} declares an unknown output.`,\n );\n }\n }\n }\n\n }\n\n const requiredCanvasIds = new Set<string>([rootCanvas.id]);\n for (const widget of widgetList) {\n const container = widget.container;\n if (container === undefined) continue;\n const bound = canvasMap.get(container.canvasTypeId);\n if (bound === undefined || bound.semanticVersion !== container.canvasSemanticVersion) {\n throw new Error(\n `ice: container widget \"${widget.type}\" binds unavailable CanvasType ` +\n `\"${container.canvasTypeId}\"@${container.canvasSemanticVersion}.`,\n );\n }\n requiredCanvasIds.add(bound.id);\n if (\n container.frameProjection !== undefined &&\n projectionMap.get(container.frameProjection.id) !== container.frameProjection\n ) {\n throw new Error(\n `ice: container widget \"${widget.type}\" references uncompiled FrameProjection ` +\n `\"${container.frameProjection.id}\".`,\n );\n }\n const insets = Object.values(container.portal);\n if (\n insets.some((value) => !Number.isFinite(value) || value < 0) ||\n container.portal.left + container.portal.right >= widget.defaultSize.w ||\n container.portal.top + container.portal.bottom >= widget.defaultSize.h\n ) {\n throw new Error(`ice: container widget \"${widget.type}\" has an invalid portal rectangle.`);\n }\n if (!container.inheritCanvasPlacement) {\n const ingress = new Set(container.widgetTypeIds);\n const accepts = new Set(container.accepts);\n for (const candidate of widgetList) {\n if (candidate.provides.some((key) => accepts.has(key))) ingress.add(candidate.type);\n }\n const legal = placement.get(bound.id) as ReadonlySet<string>;\n for (const id of ingress) {\n if (!legal.has(id)) {\n throw new Error(\n `ice: container widget \"${widget.type}\" admits \"${id}\" but CanvasType \"${bound.id}\" does not.`,\n );\n }\n }\n }\n }\n\n // an object's DATA prefabs (design-015 §5.1, D3t-a): tracked with the widget that declares them — one prefab per id, whoever declares it\n const dataPrefabs = new Map<string, Prefab>();\n for (const widget of [...widgetList, ...retiredList]) {\n for (const d of widget.data) {\n const had = dataPrefabs.get(d.id);\n if (had !== undefined && had !== d) throw new Error(`ice: data prefab \"${d.id}\" is declared twice with different definitions.`);\n if (widgetMap.has(d.id) || retiredMap.has(d.id) || d.id === WirePrefab.id) throw new Error(`ice: data prefab \"${d.id}\" collides with a widget's own prefab.`);\n dataPrefabs.set(d.id, d);\n }\n }\n const localPacks: Record<string, number> = { [WirePrefab.id]: WirePrefab.version ?? 1 };\n for (const widget of [...widgetList, ...retiredList]) localPacks[widget.prefab.id] = widget.prefab.version ?? 1;\n for (const d of dataPrefabs.values()) localPacks[d.id] = d.version ?? 1;\n for (const canvas of normalizedCanvasList) {\n localPacks[canvasPackId(canvas.id)] = canvas.semanticVersion;\n }\n for (const behavior of behaviorList) {\n localPacks[frameBehaviorPackId(behavior.id)] = behavior.version;\n }\n const initialPacks: Record<string, number> = { [WirePrefab.id]: WirePrefab.version ?? 1 };\n for (const widget of widgetList) initialPacks[widget.prefab.id] = widget.prefab.version ?? 1;\n for (const widget of widgetList) for (const d of widget.data) initialPacks[d.id] = d.version ?? 1;\n for (const id of requiredCanvasIds) {\n const canvas = canvasMap.get(id) as CanvasType;\n initialPacks[canvasPackId(id)] = canvas.semanticVersion;\n for (const behavior of behaviorsByCanvas.get(id) ?? []) {\n initialPacks[frameBehaviorPackId(behavior.id)] = behavior.version;\n }\n }\n const frozenLocalPacks = Object.freeze({ ...localPacks });\n const frozenInitialPacks = Object.freeze({ ...initialPacks });\n const packDependencies: Record<string, Readonly<Record<string, number>>> = {};\n for (const canvas of normalizedCanvasList) {\n const dependencies: Record<string, number> = {};\n for (const behavior of behaviorsByCanvas.get(canvas.id) ?? []) {\n dependencies[frameBehaviorPackId(behavior.id)] = behavior.version;\n }\n packDependencies[canvasPackId(canvas.id)] = Object.freeze(dependencies);\n }\n for (const widget of widgetList) {\n if (widget.container === undefined) continue;\n const dependencies: Record<string, number> = {\n [canvasPackId(widget.container.canvasTypeId)]: widget.container.canvasSemanticVersion,\n };\n for (const behavior of behaviorsByCanvas.get(widget.container.canvasTypeId) ?? []) {\n dependencies[frameBehaviorPackId(behavior.id)] = behavior.version;\n }\n packDependencies[widget.prefab.id] = Object.freeze(dependencies);\n }\n const frozenPackDependencies = Object.freeze(packDependencies);\n const frozenWidgets = Object.freeze([...widgetList]);\n const frozenTools = Object.freeze([...toolList]);\n const frozenCanvases = Object.freeze([...normalizedCanvasList]);\n const emptyPlacement = new Set<string>() as ReadonlySet<string>;\n\n return Object.freeze({\n typed,\n rootCanvas,\n presentationFallback,\n widget: (id: string) => widgetMap.get(id),\n retiredWidget: (id: string) => retiredMap.get(id),\n widgetTypes: () => frozenWidgets,\n tool: (id: string) => toolMap.get(id),\n toolTypes: () => frozenTools,\n canvasType: (id: string) => canvasMap.get(id),\n canvasTypeDefs: () => frozenCanvases,\n runtimeExtension: (id: string) => extensionMap.get(id),\n runtimeExtensionsFor: (canvasTypeId: string) => runtimeByCanvas.get(canvasTypeId) ?? [],\n frameBehavior: (id: string) => behaviorMap.get(id),\n frameBehaviorsFor: (canvasTypeId: string) => behaviorsByCanvas.get(canvasTypeId) ?? [],\n frameProjection: (id: string) => projectionMap.get(id),\n frameProjectionForContainer(widgetTypeId: string) {\n const widget = widgetMap.get(widgetTypeId);\n const binding = widget?.container;\n if (binding === undefined) return undefined;\n return (\n binding.frameProjection ??\n canvasMap.get(binding.canvasTypeId)?.presentation?.preview?.projection\n );\n },\n canvasForContainer(widgetTypeId: string) {\n const binding = widgetMap.get(widgetTypeId)?.container;\n return binding === undefined ? undefined : canvasMap.get(binding.canvasTypeId);\n },\n placementFor: (canvasTypeId: string) => placement.get(canvasTypeId) ?? emptyPlacement,\n toolsFor: (canvasTypeId: string) => allowedTools.get(canvasTypeId) ?? [select],\n defaultToolFor: (canvasTypeId: string) => defaultTools.get(canvasTypeId) ?? select,\n catalogFor: (canvasTypeId: string) => catalogs.get(canvasTypeId) ?? [],\n localPacks: () => frozenLocalPacks,\n initialPacks: () => frozenInitialPacks,\n packDependencies: () => frozenPackDependencies,\n requirementsForWidget(widgetTypeId: string) {\n const widget = widgetMap.get(widgetTypeId);\n if (widget === undefined) return undefined;\n const requirements: Record<string, number> = {\n [widget.prefab.id]: widget.prefab.version ?? 1,\n };\n if (widget.container !== undefined) {\n requirements[canvasPackId(widget.container.canvasTypeId)] =\n widget.container.canvasSemanticVersion;\n for (const behavior of behaviorsByCanvas.get(widget.container.canvasTypeId) ?? []) {\n requirements[frameBehaviorPackId(behavior.id)] = behavior.version;\n }\n }\n return Object.freeze(requirements);\n },\n dataPrefab: (id: string) => dataPrefabs.get(id),\n });\n}\n\nconst byWorld = new WeakMap<World, EngineCatalog>();\n\nexport function bindEngineCatalog(world: World, catalog: EngineCatalog): () => void {\n if (byWorld.has(world)) throw new Error(\"ice: a World already has an EngineCatalog.\");\n byWorld.set(world, catalog);\n return () => {\n if (byWorld.get(world) === catalog) byWorld.delete(world);\n };\n}\n\nexport function engineCatalogFor(world: World): EngineCatalog | undefined {\n return byWorld.get(world);\n}\n\nexport function widgetTypeFor(world: World, id: string): WidgetType | undefined {\n const catalog = byWorld.get(world);\n if (catalog !== undefined) return catalog.widget(id);\n return widgets.get(id);\n}\n\nexport function toolTypeFor(world: World, id: string): Tool | undefined {\n const catalog = byWorld.get(world);\n if (catalog !== undefined) return catalog.tool(id);\n return tools.get(id);\n}\n\n/** Unknown tools retain select semantics only in unbound legacy worlds. */\nexport function resolveToolFor(world: World, id: string): Tool {\n const catalog = byWorld.get(world);\n if (catalog !== undefined) return catalog.tool(id) ?? (catalog.tool(\"select\") as Tool);\n return tools.resolve(id);\n}\n\n/** Engine-scoped durable prefab resolution for transaction/live-write guards. */\nexport function durablePrefabFor(world: World, id: string): Prefab | undefined {\n const catalog = byWorld.get(world);\n if (catalog !== undefined) {\n return catalog.widget(id)?.prefab ?? catalog.retiredWidget(id)?.prefab ?? catalog.dataPrefab(id) ?? (id === WirePrefab.id ? WirePrefab : undefined);\n }\n return prefabs.get(id);\n}\n\n/** A DATA prefab the engine tracks (an object's `data` — D3t-a), or, in an unbound legacy world, any registered durable prefab that is no widget's. */\nexport function dataPrefabFor(world: World, id: string): Prefab | undefined {\n const catalog = byWorld.get(world);\n if (catalog !== undefined) return catalog.dataPrefab(id);\n const p = prefabs.get(id);\n return p !== undefined && p.store === \"durable\" && widgets.get(id) === undefined ? p : undefined;\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, OrderPlace, Relation, Resource, Tag, World } from \"@vibecook/strata-ecs\";\nimport type { Mutator } from \"@vibecook/strata-ecs/durable\";\nimport { behaviors } from \"../behavior/define-behavior\";\nimport { Grab, Position, TransformTween } from \"../catalog\";\nimport { instantiate } from \"../engine/instantiate\";\nimport { schemaMeta } from \"../schema/meta\";\nimport { PrefabId, type ComponentInit, type Prefab } from \"../schema/prefab\";\nimport { devGuardsEnabled } from \"./dev\";\nimport type { LiveWriter } from \"./live-writer\";\nimport { durablePrefabFor } from \"../canvas/engine-catalog\";\n\nexport interface GuardedTx {\n spawnPrefab(prefab: Prefab, overrides?: readonly ComponentInit[]): Entity;\n /** Raw spawn — entity is unknown to the guard (prefer spawnPrefab). */\n spawn: Mutator[\"spawn\"];\n destroy(e: Entity): void;\n addComponent<S>(e: Entity, c: Component<S>, v: S): void;\n removeComponent(e: Entity, c: Component): void;\n edit(e: Entity): { set<S>(c: Component<S>, v: S): GuardedEditor };\n addTag(e: Entity, t: Tag): void;\n removeTag(e: Entity, t: Tag): void;\n setRelation(e: Entity, r: Relation, target: Entity, place?: OrderPlace): void;\n addRelation(e: Entity, r: Relation, target: Entity): void;\n removeRelation(e: Entity, r: Relation, target?: Entity): void;\n /** Reorder within the current parent's sibling sequence — ordered relations only (petition 8). */\n moveRelation(e: Entity, r: Relation, place: OrderPlace): void;\n setResource<S>(res: Resource<S>, v: S): void;\n /**\n * Animation-integrated write (petition I15): ONE commit owns the capture, the\n * durable final, and the glide. `from` is read AT CALL TIME (pre-commit by\n * construction), the final lands in THIS transaction — inheriting its\n * `undoable` — and after a successful seal the tail installs the verified\n * public-surface glide: `TransformTween` (which GRANTS the divergence) then a\n * live rewind to `from`. One commit, one undo entry, no double-write.\n *\n * `animateMs` absent/0 = snap (no tween attached at all). A `Grab`-held\n * entity is SKIPPED — the gesture owns its divergence. An entity already\n * tweening is RETARGETED (its `toX/toY` rewritten) rather than restarted, so\n * a re-layout mid-glide re-aims instead of completing at a stale target.\n *\n * Requires `opts.live` (the session's LiveWriter) — without it the rewind\n * could not be divergence-guarded, so the call refuses rather than writing\n * around the guard.\n */\n move(e: Entity, to: { x: number; y: number }, opts?: { animateMs?: number }): void;\n}\n\ninterface GuardedEditor {\n set<S>(c: Component<S>, v: S): GuardedEditor;\n}\n\ninterface TxDoc {\n transaction(fn: (tx: Mutator) => void, opts?: { undoable?: boolean; meta?: Record<string, unknown> }): void;\n}\n\nexport interface GuardedTxOpts {\n /**\n * strata 0.3.0 passthrough: `false` excludes this commit from the LOCAL\n * undo stack (batch seeds, janitorial writes — retires the cardboard\n * first-⌘Z-removes-a-seed quirk). Default true: one tx = one undo step.\n */\n readonly undoable?: boolean;\n /**\n * The session's live writer. Required by {@link GuardedTx.move} (its\n * post-commit rewind is a live write to a doc cell, legal only under the\n * tween grant) and by the post-seal retarget sweep below.\n */\n readonly live?: LiveWriter;\n /** Optional entity → doc-key probe; when absent every entity is treated as\n * durable-if-Position-eligible. Used to skip runtime-only movers' tx write. */\n readonly keyOf?: (e: Entity) => string | undefined;\n /**\n * Per-commit PROVENANCE (strata 0.12.0, petition 9): a small record carried\n * in-CRDT with the batch, so a receiving peer can say who wrote this and why.\n * The behavior framework stamps `{ behavior, label }` on every `ctx.commit`\n * (design-009 §4.4 — `label` is a stable machine id, never display text).\n * Note that shallow saves erase provenance below the compaction boundary, so\n * it is diagnostics, never a data dependency.\n */\n readonly meta?: Record<string, unknown>;\n}\n\n/**\n * Retarget a live tween onto `to`, or start one from `from`.\n * Returns false when the entity is Grab-held (the gesture owns its divergence).\n */\nfunction glide(\n world: World,\n live: LiveWriter,\n e: Entity,\n from: { x: number; y: number },\n to: { x: number; y: number },\n durationMs: number,\n): boolean {\n if (!world.isAlive(e) || world.has(e, Grab)) return false;\n const existing = world.get(e, TransformTween);\n if (existing !== undefined) {\n // RETARGET, never restart: the ease continues from its captured origin at\n // current progress, so a re-layout mid-glide re-aims smoothly.\n world.edit(e).set(TransformTween, { ...existing, toX: to.x, toY: to.y });\n return true;\n }\n world.addComponent(e, TransformTween, {\n toX: to.x,\n toY: to.y,\n durationMs,\n elapsedMs: 0,\n });\n live.set(e, Position, { x: from.x, y: from.y });\n return true;\n}\n\nexport function guardedTransaction(\n doc: TxDoc,\n world: World,\n run: (tx: GuardedTx) => void,\n opts?: GuardedTxOpts,\n): void {\n // Post-commit work: the glide tail (tx.move) and the retarget sweep. Both\n // run ONLY if the seal succeeded — a throwing body propagates and skips them,\n // so a rolled-back transaction never leaves a tween pointing anywhere.\n const tail: Array<() => void> = [];\n /** Entities this tx moved through `move` — exempt from the sweep below. */\n const moved = new Set<Entity>();\n /** Entities whose Position this tx wrote by any OTHER path. */\n const positionWrites = new Map<Entity, { x: number; y: number }>();\n\n doc.transaction((tx) => {\n const spawned = new Map<Entity, Prefab>();\n\n const prefabOf = (e: Entity): Prefab | undefined => {\n const local = spawned.get(e);\n if (local) return local;\n const id = world.get(e, PrefabId)?.id;\n return typeof id === \"string\" ? durablePrefabFor(world, id) : undefined;\n };\n\n const checkComponent = (e: Entity, c: Component, op: string): void => {\n if (!devGuardsEnabled()) return;\n // BF-D6 (design-001 amendment): a registered DURABLE behavior's own data\n // component is universally durable-eligible. Behaviors attach to any\n // entity the host's write gate allows, so per-prefab eligibility cannot\n // express them — and design-001's eligibility rationale (\"typo/schema\n // safety\") is met a different way here, by definition-time name\n // registration: an unregistered component simply is not a behavior.\n //\n // This branch is LOAD-BEARING IN PRODUCTION, not a dev nicety: guards are\n // opt-OUT (guards/dev.ts), so without it every durable behavior write\n // would throw in a shipped build.\n if (behaviors.isBehaviorComponent(c) && behaviors.forComponent(c)?.store === \"durable\") return;\n const prefab = prefabOf(e);\n if (prefab && !prefab.eligible.has(c)) {\n const name = schemaMeta.component(c)?.name ?? \"<component>\";\n throw new Error(\n `ice: tx.${op}: component \"${name}\" is not durable-eligible on prefab \"${prefab.id}\" — declare it in the prefab's essential or optional set (design-001 §2 rule 3).`,\n );\n }\n };\n\n const checkRelation = (e: Entity, r: Relation, op: string): void => {\n if (!devGuardsEnabled()) return;\n const prefab = prefabOf(e);\n if (prefab && !prefab.eligibleRelations.has(r)) {\n const name = schemaMeta.relation(r)?.name ?? \"<relation>\";\n throw new Error(\n `ice: tx.${op}: relation \"${name}\" is not durable-eligible on prefab \"${prefab.id}\" — declare it in the prefab's relations (design-001 §2 rule 6).`,\n );\n }\n };\n\n const guarded: GuardedTx = {\n spawnPrefab(prefab, overrides) {\n const e = instantiate(prefab, { into: \"tx\", tx }, overrides);\n spawned.set(e, prefab);\n return e;\n },\n spawn: (init) => tx.spawn(init),\n destroy: (e) => tx.destroy(e),\n addComponent(e, c, v) {\n checkComponent(e, c as Component, \"addComponent\");\n if ((c as Component) === (Position as Component)) {\n positionWrites.set(e, v as { x: number; y: number });\n }\n tx.addComponent(e, c, v);\n },\n removeComponent: (e, c) => tx.removeComponent(e, c),\n edit(e) {\n const editor: GuardedEditor = {\n set(c, v) {\n checkComponent(e, c as Component, \"edit().set\");\n if ((c as Component) === (Position as Component)) {\n positionWrites.set(e, v as { x: number; y: number });\n }\n tx.edit(e).set(c, v);\n return editor;\n },\n };\n return editor;\n },\n addTag: (e, t) => tx.addTag(e, t),\n removeTag: (e, t) => tx.removeTag(e, t),\n setRelation(e, r, target, place) {\n checkRelation(e, r, \"setRelation\");\n tx.setRelation(e, r, target, place);\n },\n addRelation(e, r, target) {\n checkRelation(e, r, \"addRelation\");\n tx.addRelation(e, r, target);\n },\n removeRelation: (e, r, target) => tx.removeRelation(e, r, target),\n moveRelation(e, r, place) {\n checkRelation(e, r, \"moveRelation\");\n tx.moveRelation(e, r, place);\n },\n setResource(res, v) {\n if (devGuardsEnabled()) {\n const meta = schemaMeta.resource(res as Resource);\n if (meta && !meta.durable) {\n throw new Error(\n `ice: tx.setResource: resource \"${meta.name}\" is declared runtime — durable resources opt in at definition (design-001 §2 rule 7).`,\n );\n }\n }\n tx.setResource(res, v);\n },\n\n move(e, to, mopts) {\n const live = opts?.live;\n if (live === undefined) {\n throw new Error(\n \"ice: tx.move requires the session's live writer — pass `live` in the transaction options (the post-commit rewind is a guarded live write, not a raw one).\",\n );\n }\n if (!world.isAlive(e)) return;\n // A gesture already owns this entity's divergence; re-aiming it here\n // would fight the drag (arrange's own rule).\n if (world.has(e, Grab)) return;\n\n const from = world.get(e, Position) as { x: number; y: number } | undefined;\n if (from === undefined) return;\n const start = { x: from.x, y: from.y }; // captured PRE-commit, by construction\n\n // The durable final rides THIS transaction (inheriting its undoable);\n // runtime-only movers get their value write in the tail instead.\n const durable = opts?.keyOf === undefined || opts.keyOf(e) !== undefined;\n if (durable) {\n checkComponent(e, Position as Component, \"move\");\n tx.edit(e).set(Position, { x: to.x, y: to.y });\n }\n moved.add(e);\n\n const ms = mopts?.animateMs ?? 0;\n tail.push(() => {\n if (!world.isAlive(e)) return;\n if (ms > 0) {\n glide(world, live, e, start, to, ms);\n return;\n }\n // SNAP. If a glide is in flight it must END here, or the stale tween\n // would keep easing the runtime cell toward its old target and undo\n // the very write this call just committed. Order matters: write the\n // value FIRST (the tween still grants divergence, so the guard admits\n // it), THEN drop the tween — which leaves runtime == durable == `to`,\n // converged, with no divergence left to strand.\n const inFlight = world.get(e, TransformTween) !== undefined;\n if (inFlight) {\n live.set(e, Position, { x: to.x, y: to.y });\n world.removeComponent(e, TransformTween);\n return;\n }\n // No tween: a durable mover already landed via the commit's\n // write-through; a runtime-only one still needs its value write.\n if (!durable) world.edit(e).set(Position, { x: to.x, y: to.y });\n });\n },\n };\n\n run(guarded);\n }, opts);\n\n // ── THE POST-SEAL RETARGET CHOKEPOINT (petition I15) ──────────────────────\n // A durable Position write that did NOT come through `move` must retarget any\n // live tween on that entity. Without it the tween keeps gliding to a stale\n // target and lands there: runtime ≠ baseline with nothing banked, which is\n // divergence that NEVER reconciles (strata's `(own, value)` branch advances\n // the baseline alone) and poisons the cell against later remote updates.\n const live = opts?.live;\n if (live !== undefined) {\n for (const [e, to] of positionWrites) {\n if (moved.has(e)) continue;\n if (!world.isAlive(e) || world.get(e, TransformTween) === undefined) continue;\n const existing = world.get(e, TransformTween);\n if (existing === undefined) continue;\n world.edit(e).set(TransformTween, { ...existing, toX: to.x, toY: to.y });\n }\n }\n\n for (const t of tail) t();\n}\n\n/**\n * Retarget every live tween onto its DURABLE truth — the undo/redo chokepoint\n * (petition I15). Undo does not pass through {@link guardedTransaction}: it is\n * strata's own local batch, so a glide in flight when ⌘Z lands would otherwise\n * complete at the pre-undo target and strand the cell exactly as above.\n *\n * `durablePositionOf` reads the committed value (the doc's, not the runtime's).\n * A tween whose entity has no durable Position is left alone — nothing to\n * reconcile against.\n */\nexport function retargetTweensToDoc(\n world: World,\n entities: Iterable<Entity>,\n durablePositionOf: (e: Entity) => { x: number; y: number } | undefined,\n): void {\n for (const e of entities) {\n if (!world.isAlive(e)) continue;\n const tw = world.get(e, TransformTween);\n if (tw === undefined) continue;\n const doc = durablePositionOf(e);\n if (doc === undefined) continue;\n if (tw.toX === doc.x && tw.toY === doc.y) continue;\n world.edit(e).set(TransformTween, { ...tw, toX: doc.x, toY: doc.y });\n }\n}\n","/**\n * The behavior compiler (design-009 §7, BF-D16/BF-D17) — declaration → systems.\n *\n * Three things happen here, and each one was broken twice in review before it\n * settled:\n *\n * 1. **The SPLIT rule.** A behavior compiles to UP TO TWO systems per phase.\n * The DELIVERY system is collector-gated and carries `access.write` = own\n * component + ALL `writes:` targets, DURABLE ONES INCLUDED (design-002\n * decision 7 charges in-system commits to the running system's declared\n * writes — the earlier \"runtime targets only\" formula would have DEV-thrown\n * the flagship mind map's very first commit). The TICK system exists only\n * when an `on.tick` hook does, and carries `access.write` = the own\n * component ONLY. The split exists because strata blanket-stamps a ran\n * system's declared writes whether or not it wrote: a ticking system\n * carrying `writes: [Position]` would stamp Position every single frame and\n * wake every downstream observer. Say it to authors as the stamping tax —\n * declare minimally.\n *\n * 2. **The reads PARTITION.** `SystemAccess` is components-only, so tag ids\n * must never be spread into the component-id set: ids are dense per KIND, so\n * tag #7 would silently whitelist component #7 (the id-space trap).\n * Components → `access.read` + the collector; tags → the collector only;\n * relations and resources → polls, which the runtime arms.\n *\n * 3. **`coarse: false`.** Non-negotiable, and an engine-wide LAW rather than a\n * local option: strata blanket-marks coarse for every ran system with\n * declared writes, so without the attestation ANY ticking system with writes\n * would put every behavior collector on those components into a full rescan\n * every frame. The attestation says \"no raw `batch.col()` writes to\n * behavior-read components anywhere in ICE\" — ICE is the only party that can\n * make that promise (the engine already attests it at four sites; see\n * `systems/l1-pick.ts`). A future raw writer of a behavior-read component\n * silently degrades every behavior's precision.\n *\n * Systems are built ONCE here and registered once — never re-wrapped per\n * assemble, because strata memoizes per-system access in a WeakMap keyed on the\n * system OBJECT: a fresh wrapper each frame would leak entries and defeat the\n * memoization it was leaking into.\n */\nimport { Not, defineQuery, defineSystem, defineTickSystem } from \"@vibecook/strata-ecs\";\nimport type {\n Batch,\n CollectOptions,\n Component,\n Relation,\n Resource,\n System,\n SystemAccess,\n SystemCtx,\n Tag,\n TickSystem,\n} from \"@vibecook/strata-ecs\";\nimport { Culled } from \"../catalog/camera-derived\";\nimport type { AnySystem } from \"../engine/pipeline\";\nimport { prefabs } from \"../schema/prefab\";\nimport { schemaMeta } from \"../schema/meta\";\nimport { behaviors, classifyRead, readComponentOf } from \"./define-behavior\";\nimport type { AnyBehaviorDef, BehaviorPhase } from \"./types\";\n\n/**\n * The bodies the runtime supplies. Compilation owns SHAPE (query, access,\n * runIf, name, registration identity); the runtime owns behavior. Keeping the\n * seam here means the compiler's rules — the split, the partition, the gating —\n * are unit-testable without standing up a delivery loop.\n */\nexport interface BehaviorSystemHooks {\n /**\n * The delivery `runIf`: drains the collector, stashes the delta for the body,\n * evaluates the polls, and decides. Side-effecting BY DESIGN — there is no\n * non-destructive peek on a `ChangeCollector`, so the drain has to happen\n * in the gate or the gate cannot see the work (the `makeChurnGuard` idiom).\n */\n shouldDeliver(ctx: SystemCtx): boolean;\n deliver(ctx: SystemCtx): void;\n /** The tick `runIf` — cheap: instance count, suspension, freeze. */\n shouldTick(ctx: SystemCtx): boolean;\n tickChunk(batch: Batch, ctx: SystemCtx): void;\n /**\n * Run `body` inside this behavior's breaker bracket + fault domain. Returns\n * false when the breaker is holding the behavior down or the body threw.\n */\n charge(body: () => void): boolean;\n /** Breaker verdict — polled from `runIf`, so it must be cheap and never throw. */\n suspended(): boolean;\n /**\n * A frame the behavior sat out because the breaker suspended it. The runtime\n * DISCARDS its collectors here: a suspended behavior that stops draining\n * still journals, so its collectors would grow for as long as the suspension\n * lasts and then hand the resumed behavior a delta describing a world many\n * frames old.\n */\n onSuspendedFrame(): void;\n}\n\nexport interface CompiledBehavior {\n readonly behavior: AnyBehaviorDef;\n readonly phase: BehaviorPhase;\n /** The framework collector's subscription (always `coarse: false`). */\n readonly collect: CollectOptions;\n /** `reads:` partitioned by kind — each routed to a different mechanism. */\n readonly readComponents: readonly Component[];\n readonly readTags: readonly Tag[];\n readonly readRelations: readonly Relation[];\n readonly readResources: readonly Resource[];\n readonly deliveryAccess: SystemAccess;\n readonly tickAccess: SystemAccess | undefined;\n readonly delivery: TickSystem;\n /** Present only when the declaration has an `on.tick` hook. */\n readonly tick: System | undefined;\n /** Registration order: delivery first, then tick. */\n readonly systems: readonly AnySystem[];\n}\n\n/**\n * Is `c` a cell the document can hold? Two sources: a durable prefab's\n * eligible set, and (BF-D6) any durable behavior's own data component —\n * registered behavior components are UNIVERSALLY durable-eligible.\n *\n * This is deliberately compile-time and not definition-time. At module-eval\n * time the prefab registry may not yet hold the widget whose Position a\n * behavior writes, so a definition-time answer would depend on import order —\n * and an import-order-dependent refusal is worse than no refusal, because it\n * passes on the developer's machine and fails in the bundle.\n */\nexport function isDurableEligible(c: Component): boolean {\n if (behaviors.forComponent(c)?.store === \"durable\") return true;\n for (const p of prefabs.all()) {\n if (p.store === \"durable\" && p.eligible.has(c)) return true;\n }\n return false;\n}\n\n/** Hook names that can open a transaction (the only legal durable write path). */\nfunction hasCommitCapableHook(b: AnyBehaviorDef): boolean {\n return b.on.init !== undefined || b.on.update !== undefined || b.on.changed !== undefined;\n}\n\nexport function partitionReads(b: AnyBehaviorDef): {\n components: Component[];\n tags: Tag[];\n relations: Relation[];\n resources: Resource[];\n} {\n const components: Component[] = [];\n const tags: Tag[] = [];\n const relations: Relation[] = [];\n const resources: Resource[] = [];\n for (const r of b.reads) {\n const kind = classifyRead(r)?.kind;\n switch (kind) {\n case \"component\":\n case \"behavior\": {\n const c = readComponentOf(r);\n if (c !== undefined && !components.includes(c)) components.push(c);\n break;\n }\n case \"tag\":\n if (!tags.includes(r as Tag)) tags.push(r as Tag);\n break;\n case \"relation\":\n if (!relations.includes(r as Relation)) relations.push(r as Relation);\n break;\n case \"resource\":\n if (!resources.includes(r as Resource)) resources.push(r as Resource);\n break;\n default:\n // Unclassifiable reads are refused at definition time; a behavior built\n // with dev guards off can still reach here — drop it rather than\n // corrupt the id space.\n break;\n }\n }\n return { components, tags, relations, resources };\n}\n\nexport function compileBehavior(b: AnyBehaviorDef, hooks: BehaviorSystemHooks): CompiledBehavior {\n const own = b.component as Component;\n const { components: readComponents, tags: readTags, relations: readRelations, resources: readResources } =\n partitionReads(b);\n\n // The static divergence refusal (§3): a durable-eligible target in `writes:`\n // is reachable ONLY through `ctx.commit`, and only init/update/changed can\n // commit. A behavior whose sole hook is `tick` therefore declares a write it\n // has no legal way to make — and the way authors discover that today is a\n // divergence throw at runtime, on someone else's machine.\n if (!hasCommitCapableHook(b)) {\n for (const w of b.writes) {\n if (isDurableEligible(w)) {\n const name = schemaMeta.component(w)?.name ?? \"<component>\";\n throw new Error(\n `ice: behavior \"${b.name}\" declares writes: [${name}], a durable-eligible cell, but has no init/update/changed hook — durable cells are written ONLY inside ctx.commit, and a tick hook cannot commit (design-009 §3). Per-frame motion belongs in the behavior's own runtime data, or in tx.move.`,\n );\n }\n }\n }\n\n const writeSet = new Set<Component>([own, ...(b.writes as readonly Component[])]);\n // `read` is the literal declaration strata stores; a component in `write`\n // must not be repeated here (the write set already grants `col()` access, and\n // duplicating it only makes the diagnostics lie about intent).\n const declaredRead = readComponents.filter((c) => !writeSet.has(c));\n\n // The two systems of the SPLIT both write the own component, in the same\n // phase, on the same rows — which is exactly strata's same-phase writer-pair\n // advisory (001 §3.3). Here the pair is order-tolerant in the sanctioned\n // sense: the framework FIXES their order (delivery is registered before tick,\n // always), the writes are whole-cell absolute values, and delivery-then-tick\n // is last-write-wins-safe by construction. So both attest — and the\n // attestation is scoped to the own component ONLY. Declared `writes:` targets\n // are never attested: those DO have engine co-writers, and claiming\n // order-tolerance on the engine's behalf is not ours to do.\n //\n // Without this, every ticking behavior would print a strata advisory at\n // registration — a framework must not make its users read a warning that\n // describes its own deliberate design.\n // (Until design-015 D5b there was ONE exception — the engine's own three\n // `ice:surface.*` kind behaviours, co-writers of `SurfaceTarget` by law, were\n // attested on the three exact names, A3b fix 4. They left with the DOM/GPU\n // presentation choice, and with them the exception.)\n const attested: Component[] = b.on.tick !== undefined ? [own] : [];\n const deliveryAccess: SystemAccess = {\n write: [...writeSet],\n ...(declaredRead.length > 0 ? { read: declaredRead } : {}),\n ...(attested.length > 0 ? { orderIndependent: attested } : {}),\n };\n\n const collect: CollectOptions = {\n // Own component FIRST: it is what makes appear/depart detectable at all.\n components: [own, ...readComponents.filter((c) => c !== own)],\n ...(readTags.length > 0 ? { tags: readTags } : {}),\n coarse: false,\n };\n\n const delivery = defineTickSystem(\n (ctx) => {\n hooks.charge(() => hooks.deliver(ctx));\n },\n {\n name: `behavior:${b.name}:deliver`,\n runIf: (ctx) => {\n if (hooks.suspended()) {\n hooks.onSuspendedFrame();\n return false;\n }\n return hooks.shouldDeliver(ctx);\n },\n access: deliveryAccess,\n },\n );\n\n let tick: System | undefined;\n let tickAccess: SystemAccess | undefined;\n if (b.on.tick !== undefined) {\n // `tick: { while: \"visible\" }` — declared suspension, compiled INTO the\n // query so culled instances never reach a chunk, rather than tested per\n // instance in the body. Default is every instance (Law 14).\n const query =\n b.tickWhile === \"visible\" ? defineQuery([own, Not(Culled)]) : defineQuery([own]);\n tickAccess = {\n write: [own],\n ...(declaredRead.length > 0 ? { read: declaredRead } : {}),\n orderIndependent: [own], // the delivery system's twin — see above\n };\n tick = defineSystem(\n query,\n (batch, ctx) => {\n hooks.charge(() => hooks.tickChunk(batch, ctx));\n },\n {\n name: `behavior:${b.name}:tick`,\n runIf: (ctx) => !hooks.suspended() && hooks.shouldTick(ctx),\n access: tickAccess,\n },\n );\n }\n\n return {\n behavior: b,\n phase: b.phase,\n collect,\n readComponents,\n readTags,\n readRelations,\n readResources,\n deliveryAccess,\n tickAccess,\n delivery,\n tick,\n systems: tick === undefined ? [delivery] : [delivery, tick],\n };\n}\n","/**\n * Behavior schema evolution (design-009 §5.5–§5.6, BF-D14) — M13g.\n *\n * Markers are `engine.behavior.<name>.<v>` write-once keys: a monotone key SET,\n * never a mutated cell, so concurrent peers converge on the union instead of\n * racing a single slot. They are a SEPARATE FAMILY from `engine.pack.*`, and\n * that separation is the whole point of this file.\n *\n * **Why not fold them into the pack compare.** The pack compare classifies a\n * doc marker with no local counterpart as `newerInDoc`, which read-onlys the\n * document. For prefabs that is right — an unknown prefab means the doc was\n * written by a newer build. For behaviors it is catastrophic: behaviors ship in\n * PLUGINS, so \"no local counterpart\" is the ordinary state of every document\n * whose author had a plugin this reader does not. Folding them in would brick a\n * document because a plugin is missing — design-008's exact failure shape,\n * which cost us a release to learn.\n *\n * So behaviors get their own compare with the **absent-is-not-newer** rule:\n * - a locally-unregistered behavior name is IGNORED ENTIRELY (its cells sit\n * in the doc un-projected and dormant — strata's projection is\n * name-registry-driven, so they are inert, not corrupt);\n * - `v > installed` for an INSTALLED behavior triggers per-behavior DORMANCY\n * (refuse hook delivery — projection is version-blind, so newer-shaped data\n * WOULD otherwise flow into older hooks), never a doc verdict;\n * - `v < installed` runs the migration chain.\n *\n * Behavior version state NEVER affects the document's gate verdict. That is a\n * standing guarantee, and the anti-brick test in CI is what keeps it one.\n */\nimport type { Component, Entity, World } from \"@vibecook/strata-ecs\";\nimport { guardedTransaction } from \"../guards/guarded-tx\";\nimport type { LiveWriter } from \"../guards/live-writer\";\nimport type { AnyBehaviorDef } from \"./types\";\n\nexport const BEHAVIOR_MARKER_PREFIX = \"engine.behavior.\";\n\n/**\n * Markers carry the STRING `\"1\"`, not the boolean `engine.pack.*` uses.\n * `readMeta` is the only key-addressed read the durable store offers and it\n * returns strings only, so a boolean marker would be invisible to every reader\n * that is not enumerating the raw Loro map — which mid-session installs cannot\n * do. Presence is still the semantics; the value is never read.\n */\nconst MARKER_VALUE = \"1\";\n\nexport function behaviorMarkerKey(name: string, version: number): string {\n return `${BEHAVIOR_MARKER_PREFIX}${name}.${version}`;\n}\n\n/**\n * How far ABOVE the installed version to probe for a newer marker. There is no\n * key enumeration on an attached store, so dormancy detection is a bounded\n * scan; a document more than this many versions ahead of this build reads as\n * \"not newer\" and runs normally, which is the same honest failure a doc from\n * the future has always had.\n */\nconst PROBE_AHEAD = 16;\n\nexport interface BehaviorMeta {\n readMeta(key: string): string | undefined;\n metaTransaction(fn: (meta: { get(key: string): unknown; set(key: string, value: string): void }) => void): void;\n}\n\n/** The highest marker version present for `name` (0 = never stamped). */\nexport function docBehaviorVersion(meta: BehaviorMeta, name: string, installed: number): number {\n let highest = 0;\n for (let v = 1; v <= installed + PROBE_AHEAD; v++) {\n if (meta.readMeta(behaviorMarkerKey(name, v)) !== undefined) highest = v;\n }\n return highest;\n}\n\n/** Stamp the marker for `version` if it is not already present (write-once). */\nexport function stampBehaviorMarker(meta: BehaviorMeta, name: string, version: number): void {\n const key = behaviorMarkerKey(name, version);\n if (meta.readMeta(key) !== undefined) return;\n meta.metaTransaction((m) => {\n if (m.get(key) === undefined) m.set(key, MARKER_VALUE);\n });\n}\n\nexport type BehaviorVerdict =\n | { readonly kind: \"ok\" }\n /** The doc is at a NEWER version than this build installs — refuse delivery. */\n | { readonly kind: \"dormant\"; readonly docVersion: number; readonly installed: number }\n /** The doc is OLDER — the chain has work to do. */\n | { readonly kind: \"migrate\"; readonly from: number; readonly installed: number }\n /** Older, but the chain cannot reach `installed` from there. */\n | { readonly kind: \"unreachable\"; readonly from: number; readonly installed: number };\n\nexport function classifyBehaviorVersion(b: AnyBehaviorDef, docVersion: number): BehaviorVerdict {\n if (docVersion === 0 || docVersion === b.version) return { kind: \"ok\" };\n if (docVersion > b.version) return { kind: \"dormant\", docVersion, installed: b.version };\n for (let v = docVersion; v < b.version; v++) {\n if (typeof b.migrate[v] !== \"function\") {\n return { kind: \"unreachable\", from: docVersion, installed: b.version };\n }\n }\n return { kind: \"migrate\", from: docVersion, installed: b.version };\n}\n\nexport interface MigrateDeps {\n readonly world: World;\n readonly meta: BehaviorMeta;\n /** The doc store, for the one `{undoable: false}` transaction. */\n // biome-ignore lint/suspicious/noExplicitAny: structural — the guarded-tx doc seam.\n readonly store: any;\n readonly liveWriter?: LiveWriter;\n /** Every entity currently carrying the behavior's component. */\n carriers(): readonly Entity[];\n}\n\n/**\n * Run `b`'s migrate chain over every carrier, in ONE non-undoable transaction,\n * then stamp the new marker.\n *\n * A SECOND plan+write pass, not a reuse of the M9 prefab runner: that one\n * filters by `PrefabId`, and a behavior rides entities of any kind — its own\n * component is the only thing that identifies its cells.\n *\n * Returns the number of migrated carriers.\n */\nexport function runBehaviorMigration(b: AnyBehaviorDef, from: number, deps: MigrateDeps): number {\n const c = b.component as Component;\n const carriers = deps.carriers();\n const plan: { e: Entity; value: Record<string, unknown> }[] = [];\n for (const e of carriers) {\n const current = deps.world.get(e, c) as Record<string, unknown> | undefined;\n if (current === undefined) continue;\n let value: Record<string, unknown> = { ...current };\n for (let v = from; v < b.version; v++) {\n const step = b.migrate[v];\n if (typeof step !== \"function\") break;\n value = { ...value, ...step(value) };\n }\n plan.push({ e, value });\n }\n if (plan.length > 0) {\n guardedTransaction(\n deps.store,\n deps.world,\n (tx) => {\n for (const { e, value } of plan) tx.edit(e).set(c as Component<unknown>, value);\n },\n // Never an undo step: a migration is not something a user did.\n { undoable: false, ...(deps.liveWriter !== undefined ? { live: deps.liveWriter } : {}) },\n );\n }\n // Stamp even when nothing needed migrating — the marker records that THIS\n // build's version is now represented in the document, which is what stops the\n // runner from re-planning on every registration.\n stampBehaviorMarker(deps.meta, b.name, b.version);\n return plan.length;\n}\n","/**\n * The behavior runtime (design-009 §4.3, §5.1, §5.2) — one delivery loop for\n * every behavior, compiled onto the guest breaker rather than beside it.\n *\n * Delivery order, per frame, at the behavior's phase:\n *\n * drain → init (appeared) → update → changed → tick → dispose (departed)\n *\n * The instance list is a SNAPSHOT taken at phase entry, so a hook that attaches\n * or detaches affects the NEXT frame — the live-array lesson from the publish\n * and reflector loops, applied before it could bite here.\n *\n * TWO COLLECTORS, not one. Own-component churn and reads churn mean different\n * things to an author — \"update is about you, changed is about the world\" — and\n * a single collector cannot tell them apart after the drain, because the delta\n * reports ENTITIES, not which component moved. Merging them would fire\n * `changed` on every own-data write, which is exactly the hook authors put\n * expensive whole-graph work in. The cost of honesty is one extra drain.\n *\n * Change delivery rides strata's REAL change detection, which is why every\n * behavior is collaboration-native with zero author code: `applyRemote`\n * journals into collectors exactly like a local write, so `update` fires for a\n * remote peer's edit and for a local undo through the same path.\n */\nimport { Local, Not, defineQuery, type Query } from \"@vibecook/strata-ecs\";\nimport { valueEquals } from \"@vibecook/strata-ecs\";\nimport type {\n Batch,\n ChangeCollector,\n Component,\n Entity,\n Relation,\n Resource,\n SystemCtx,\n Tag,\n World,\n} from \"@vibecook/strata-ecs\";\nimport type { DrivenGuest, GuestLedgerRecord, GuestRegistry } from \"../engine/guests\";\nimport { Captures, Drags, GestureActive } from \"../catalog/gesture\";\nimport { FrameInfo } from \"../engine/frame-info\";\nimport type { PhaseGroup } from \"../engine/pipeline\";\nimport { devGuardsEnabled } from \"../guards/dev\";\nimport type { LiveWriter } from \"../guards/live-writer\";\nimport { guardedTransaction } from \"../guards/guarded-tx\";\nimport type { GuardedTx } from \"../guards/guarded-tx\";\nimport type { JsonSpec, PropSpec } from \"../widget/props\";\nimport { compileBehavior, type BehaviorSystemHooks, type CompiledBehavior } from \"./compile\";\nimport { facetBytesOf } from \"./define-behavior\";\nimport { diffOps, recordDerivedOps, replayOps } from \"./differ\";\nimport {\n classifyBehaviorVersion,\n docBehaviorVersion,\n runBehaviorMigration,\n stampBehaviorMarker,\n type BehaviorMeta,\n} from \"./migrate\";\nimport {\n allowedQueryTerms,\n createBehaviorWorld,\n createQueryScope,\n publishWalker,\n systemWalker,\n type BehaviorWalker,\n} from \"./world-view\";\nimport type {\n AnyBehaviorDef,\n BehaviorChanges,\n BehaviorCtxBase,\n BehaviorFrame,\n BehaviorTx,\n} from \"./types\";\n\n/** The slice of a doc session the runtime needs (structural: tests fake it). */\nexport interface BehaviorSession {\n readonly readOnly: boolean;\n readonly liveWriter: LiveWriter;\n readonly store: {\n transaction(fn: (tx: never) => void, opts?: { undoable?: boolean }): void;\n keyOf(e: Entity): unknown;\n resolve(key: never): Entity | undefined;\n getComponent<S>(e: Entity, c: Component<S>): S | undefined;\n /** The version-marker surface (behavior/migrate.ts). Absent = no markers. */\n readonly snapshot?: BehaviorMeta;\n metaTransaction?(fn: (meta: { get(key: string): unknown; set(key: string, value: string): void }) => void): void;\n };\n}\n\n/**\n * The slice of a presence session an ephemeral behavior needs. Structural so\n * tests can fake it, and a FUNCTION on the opts so it can swap with the doc —\n * presence attaches and detaches with `docs.join`, and a behavior installed\n * before either must simply lie dormant until one exists.\n */\nexport interface BehaviorPresence {\n /** The local peer entity. A GETTER upstream: a world reset re-mints it. */\n readonly localPeer: Entity;\n readonly eph: {\n addComponent(e: Entity, c: Component<unknown>, v: unknown): void;\n removeComponent(e: Entity, c: Component): void;\n edit(e: Entity): { set(c: Component<unknown>, v: unknown): unknown };\n };\n}\n\nexport interface BehaviorRuntimeOpts {\n readonly world: World;\n readonly engine: {\n addSystems(group: PhaseGroup, ...systems: readonly never[]): () => void;\n readonly guests: GuestRegistry;\n onPublish(hook: (world: World) => void): () => void;\n /** The frame gate's registered wakes (K7a): a behavior with a `tick` hook and instances is due every frame. */\n readonly frame?: { wakeWhen(name: string, due: (now: number) => number): () => void };\n };\n /** The FORWARDING session seam — the target swaps per doc open/close. */\n readonly session?: () => BehaviorSession | undefined;\n /**\n * The presence seam. Absent (or returning undefined) leaves every ephemeral\n * behavior DORMANT — installed, costing nothing, publishing nothing. That is\n * honest state, not a failure: a presence-less engine has no peer to be.\n */\n readonly presence?: () => BehaviorPresence | undefined;\n readonly onLog?: (behavior: string, message: string, rest: readonly unknown[]) => void;\n /**\n * A contained hook fault. Defaults to `console.error`. Hosts route this: a\n * quarantined instance in a derived behavior means part of the document\n * silently stops updating, which reads to a user as a broken document.\n */\n readonly onFault?: (behavior: string, hook: string, entity: Entity | undefined, err: unknown) => void;\n}\n\nexport interface BehaviorStatus {\n readonly name: string;\n readonly store: string;\n readonly phase: string;\n readonly instances: number;\n /** Instances quarantined by repeated hook throws (BF-D18). */\n readonly failed: number;\n readonly ticking: number;\n readonly suspended: boolean;\n /**\n * The EPHEMERAL singleton was quarantined this generation (I17): its facet\n * is withdrawn and stays withdrawn until a fresh registration. Without this\n * field a quarantined singleton is indistinguishable from a dormant one —\n * withdrawal makes the instance depart, so `failed` reads 0. Always false\n * for durable/runtime behaviors (their quarantine stays visible in `failed`).\n */\n readonly quarantined: boolean;\n}\n\nexport interface BehaviorRegistrationOptions {\n /** Stable host policy key. Explicitly ordered registrations run before unkeyed registrations. */\n readonly orderKey?: string;\n /** Prior breaker state, normally persisted by a host across engine generations. */\n readonly ledger?: GuestLedgerRecord;\n}\n\nexport interface BehaviorRuntime {\n /** Compile + install a behavior. Returns an uninstaller. */\n register(b: AnyBehaviorDef, options?: BehaviorRegistrationOptions): () => void;\n registered(): readonly AnyBehaviorDef[];\n /** Runtime/ephemeral attach from OUTSIDE a hook (the facade surface). */\n attach(e: Entity, b: AnyBehaviorDef, data?: Record<string, unknown>): void;\n detach(e: Entity, b: AnyBehaviorDef): void;\n has(e: Entity, b: AnyBehaviorDef): boolean;\n read(e: Entity, b: AnyBehaviorDef): Record<string, unknown> | undefined;\n list(): readonly BehaviorStatus[];\n dispose(): void;\n}\n\n/** One entity's watched state at the moment a commit sealed (see `echo`). */\ninterface EchoSnapshot {\n readonly cells: readonly [Component, unknown][];\n readonly tags: readonly [Tag, boolean][];\n}\n\n/** How many consecutive throws quarantine ONE instance (BF-D18). */\nconst INSTANCE_THROW_LIMIT = 3;\n\n/** Suppressed frames before the dev-warn names the behavior and the claimant. */\nconst SUPPRESSION_WARN_FRAMES = 600;\n\nfunction isThenable(value: unknown): value is PromiseLike<unknown> {\n return (\n (typeof value === \"object\" || typeof value === \"function\") &&\n value !== null &&\n typeof (value as { then?: unknown }).then === \"function\"\n );\n}\n\nclass BehaviorHookThenableError extends TypeError {}\n\nfunction invokeHook(behavior: string, hook: string, body: () => unknown): void {\n const result = body();\n if (!isThenable(result)) return;\n void Promise.resolve(result).catch(() => undefined);\n throw new BehaviorHookThenableError(\n `ice: behavior \"${behavior}\" ${hook} returned a thenable; behavior hooks are synchronous`,\n );\n}\n\n/**\n * Is `e` under a LIVE gesture claim right now?\n *\n * Deliberately NARROWER than `makeDefaultMayDiverge`: a `TransformTween` also\n * grants divergence, but a glide is not a gesture — suppressing derives for the\n * duration of every fly-back would stall exactly the reflow the fly-back is\n * waiting for.\n */\nfunction isClaimed(world: World, e: Entity): boolean {\n if (!world.isAlive(e)) return false;\n for (const claimant of world.getReverse(e, Captures)) {\n if (world.hasTag(claimant, GestureActive)) return true;\n }\n for (const claimant of world.getReverse(e, Drags)) {\n if (world.hasTag(claimant, GestureActive)) return true;\n }\n return false;\n}\n\n/**\n * A patch → the ABSOLUTE whole-cell value a write commits (Law 5). Fields the\n * patch omits are read back off the entity when it already carries the\n * behavior, and only fall to the declared defaults when it does not — which is\n * what makes attach-when-attached an idempotent no-op that PRESERVES existing\n * data rather than resetting it.\n *\n * Module-scope on purpose: `tx.attach(e, Other)` may name a behavior this\n * engine never registered, and the earlier node-bound version silently fell\n * back to bare defaults there — clobbering the very data the idempotence rule\n * exists to protect.\n */\nfunction cellForBehavior(\n world: World,\n b: AnyBehaviorDef,\n e: Entity | undefined,\n patch: Record<string, unknown>,\n): Record<string, unknown> {\n const c = b.component as unknown as Component<Record<string, unknown>>;\n const carries = e !== undefined && world.isAlive(e) && world.has(e, c as unknown as Component);\n const out: Record<string, unknown> = {};\n for (const [f, spec] of Object.entries(b.schema)) {\n const given = patch[f];\n if (given !== undefined) {\n out[f] = (spec as PropSpec).kind === \"json\" ? JSON.stringify(given) : given;\n continue;\n }\n out[f] = carries ? world.readField(e as Entity, c, f) : (b.defaults as Record<string, unknown>)[f];\n }\n return out;\n}\n\ninterface Instance {\n readonly e: Entity;\n /** The last DELIVERED cell (raw, retained) — `update`'s `prev`. */\n prevCell: Record<string, unknown>;\n inited: boolean;\n /** Quarantined: hooks stop until re-attach. Doctor-visible. */\n failed: boolean;\n consecutiveThrows: number;\n}\n\nexport function createBehaviorRuntime(opts: BehaviorRuntimeOpts): BehaviorRuntime {\n const { world } = opts;\n const nodes = new Map<string, Node>();\n let nextRegistrationSequence = 0;\n const onFault =\n opts.onFault ??\n ((behavior: string, hook: string, entity: Entity | undefined, err: unknown) => {\n console.error(`[ice] behavior \"${behavior}\" ${hook}${entity === undefined ? \"\" : ` on entity ${entity}`} threw`, err);\n });\n const onLog =\n opts.onLog ??\n ((behavior: string, message: string, rest: readonly unknown[]) => {\n console.log(`[ice:${behavior}] ${message}`, ...rest);\n });\n\n // ONE reset watch for the whole runtime. Structural writes are illegal inside\n // an observer emit, so this only MARKS: every node rebuilds at the top of its\n // own delivery body, in its own phase, where writes are legal again.\n const stopResetWatch = world.observe({\n onReset: () => {\n for (const n of nodes.values()) n.markGeneration();\n },\n });\n\n // --- the ONE stable publish hook (pre-publish review, finding 2) -----------\n // Publish-phase nodes and deferred facet withdrawals both ride a SINGLE\n // engine hook the runtime owns. Reorder mutates OUR array, never the\n // engine's: under the per-node-hook shape, reorderExecution's\n // unregister/re-register churn invalidated the engine's frame snapshot\n // (`entry.alive = false`) for every not-yet-run publish behavior, costing\n // each of them a whole publish slot whenever register() ran from inside a\n // publish hook. Withdrawals flush FIRST, before the node passes: an\n // unregister-then-re-register in one frame must remove the OLD facet before\n // the fresh node's ensureFacet mints the new one, never after.\n const publishOrder: Node[] = [];\n const pendingWithdrawals: (() => void)[] = [];\n let publishHookRemover: (() => void) | undefined;\n\n function ensurePublishHook(): void {\n if (publishHookRemover !== undefined) return;\n publishHookRemover = opts.engine.onPublish(() => {\n if (pendingWithdrawals.length > 0) {\n const jobs = pendingWithdrawals.splice(0, pendingWithdrawals.length);\n for (const job of jobs) job(); // each job guards + swallows for itself\n }\n if (publishOrder.length > 0) {\n // Copy + stopped-gating mirrors the engine's own snapshot discipline:\n // a node removed mid-pass is skipped, one added mid-pass starts next\n // frame, and nobody ELSE is ever skipped for it.\n const pass = publishOrder.slice();\n for (const node of pass) if (!node.isStopped()) node.runPublish();\n }\n if (publishOrder.length === 0 && pendingWithdrawals.length === 0) {\n // Self-reap on the frame AFTER the last consumer left — removing it\n // eagerly at uninstall would drop the withdrawal that teardown just\n // deferred.\n publishHookRemover?.();\n publishHookRemover = undefined;\n }\n });\n }\n\n function installPublishNode(node: Node): () => void {\n publishOrder.push(node);\n ensurePublishHook();\n return () => {\n const i = publishOrder.indexOf(node);\n if (i !== -1) publishOrder.splice(i, 1);\n };\n }\n\n function deferWithdrawal(job: () => void): void {\n pendingWithdrawals.push(job);\n ensurePublishHook();\n }\n\n class Node {\n readonly b: AnyBehaviorDef;\n readonly orderKey: string | undefined;\n readonly registrationSequence: number;\n readonly compiled: CompiledBehavior;\n readonly own: Component;\n /** The same handle, typed for `readField`'s keyof-based field parameter. */\n readonly ownFields: Component<Record<string, unknown>>;\n readonly guest: DrivenGuest;\n /** Its registered wake (K7a): frame-cadence code — a `tick` hook with instances keeps a sleeping loop awake. */\n private readonly stopWake: (() => void) | undefined;\n readonly ownQuery: Query;\n /** Ephemeral only: REMOTE peers' facets of this behavior (read-only). */\n readonly peersQuery: Query | undefined;\n /** Ephemeral only: the local peer this node last published a facet on. */\n private facetPeer: Entity | undefined;\n /**\n * The entity whose HOOK is currently executing (review finding 2, 0.8.0).\n * `writeFacet` consults it so a hook writes only the peer whose instance\n * it runs for — a same-gap presence swap otherwise lets the OLD peer's\n * dispose resolve `localPeer` LIVE and land a corpse's farewell on the\n * fresh peer. Unset outside hooks (captured `ctx.write` closures keep the\n * blessed behavior: they publish the CURRENT peer).\n */\n private hookEntity: Entity | undefined;\n /** The ephemeral singleton was quarantined THIS generation (I17). */\n private singletonQuarantined = false;\n /** Uninstalled — a captured ctx.write closure must go inert (I17). */\n private stopped = false;\n /** Per-FRAME strike dedupe (review finding 4): the ladder counts FRAMES,\n * not calls — 500 async instances must cost ONE strike, not write 500\n * into a ledger hosts persist across engine generations. Keyed by\n * FrameInfo.tick because no single pass entry point runs every frame\n * (the delivery system is runIf-gated off on no-churn frames while the\n * tick system keeps running). */\n private strikeFrame = -1;\n private thenableStruckPass = false;\n private spanStruckPass = false;\n /** The session whose version state has already been checked (§5.6). */\n private checkedSession: unknown;\n /**\n * The doc holds NEWER data than this build understands. Projection is\n * version-blind — a known name at a newer version projects straight into\n * older hooks — so dormancy has to be ACTIVE, not free.\n */\n private dormant = false;\n readonly instances = new Map<Entity, Instance>();\n readonly fieldNames: readonly string[];\n readonly jsonFields: readonly string[];\n readonly schema: Readonly<Record<string, PropSpec>>;\n\n private ownCollector: ChangeCollector | undefined;\n private readsCollector: ChangeCollector | undefined;\n private generation = new AbortController();\n private generationDirty = false;\n private seeded = false;\n /** Collectors detached because the breaker suspended us (see `goCold`). */\n private cold = false;\n private removeSystems: (() => void) | undefined;\n\n /** Stashed by `shouldDeliver` for the body — the drain-and-stash idiom. */\n private stash:\n | { full: boolean; ownChanged: readonly Entity[]; ownRemoved: readonly Entity[]; readsFired: boolean; readsChanged: readonly Entity[]; readsRemoved: readonly Entity[] }\n | undefined;\n\n /**\n * The ECHO snapshot (§3 own-write subtraction): for every entity this\n * behavior's last commit wrote, the values of every component it watches,\n * captured immediately after the seal.\n *\n * Why it exists: a derived commit journals the entities it just wrote, the\n * next frame reads that as churn, recomputes, diffs everything away and\n * commits nothing. One wasted full recompute per change event. Subtracting\n * the echo makes a derived behavior quiesce in ONE frame.\n *\n * Why it stores VALUES and not just entity ids: the journal reports\n * ENTITIES, not components, so an id-only subtraction cannot tell our own\n * echo from a real write that landed on the same entity inside the same\n * drain window — and it would DROP that real write permanently, since\n * nothing will journal it again. Comparing the watched values answers the\n * question exactly: unchanged everywhere means the entry was ours.\n *\n * \"Watched\" means EVERY subscription, tags included. Snapshotting only the\n * components left a hole with the same shape as the one this whole memo\n * exists to avoid: a tag in the reads set flipping on an entity we had just\n * written looked identical to our own echo, and was swallowed.\n */\n private echo: Map<Entity, EchoSnapshot> = new Map();\n\n /** Poll state (relations and resources cannot journal — see §5.2). */\n private readonly resourceStamps = new Map<Resource, number>();\n private readonly parentStamps = new Map<Entity, number>();\n private parentsDirty = true;\n\n // Scratch — reused between hook calls by DEFAULT (at 10k instances fresh\n // objects are ~600k allocs/sec). The do-not-retain rule in the docs is what\n // pays for this; it applies to `data`, `prev`, `changes()` and\n // `changedEntities()` alike.\n private readonly scratchCell: Record<string, unknown> = {};\n private readonly scratchData: Record<string, unknown>;\n private readonly scratchPrevData: Record<string, unknown>;\n\n private snapshot: Entity[] = [];\n /**\n * Does `snapshot` still describe `instances`? (A3b fix 5 — the idle tax.)\n *\n * `this.instances` is mutated in exactly THREE places: the departed and\n * appeared loops in `runDeliver`, both above the rebuild, and\n * `endGeneration`'s `clear()`. Each of the three sets this flag, and the\n * rebuild reads it. Everything else in this class only reads the map.\n */\n private snapshotDirty = true;\n /** What `ctx.entities()` reports for the CURRENTLY RUNNING pass. */\n private visible: Entity[] = [];\n /** Instances held back by a live claim (§5.3) — instance-scoped, always. */\n private readonly suppressed = new Set<Entity>();\n /** Consecutive suppressed frames per instance (the dev-warn's counter). */\n private readonly suppressedFrames = new Map<Entity, number>();\n /** Churn seen while suppressed — replayed in the coalesced delivery. */\n private readonly carry = new Set<Entity>();\n private changesView: BehaviorChanges = { full: false, changed: [], removed: [] };\n private changedEntitiesCache: Entity[] | undefined;\n /** Set for the duration of a delivery/tick pass; see BehaviorWalker. */\n private walker: BehaviorWalker | undefined;\n private readonly ctx: BehaviorCtxBase<Record<string, unknown>> & Record<string, unknown>;\n\n constructor(\n b: AnyBehaviorDef,\n registration: BehaviorRegistrationOptions,\n registrationSequence: number,\n ) {\n this.b = b;\n this.orderKey = registration.orderKey;\n this.registrationSequence = registrationSequence;\n this.own = b.component as Component;\n this.ownFields = b.component as unknown as Component<Record<string, unknown>>;\n this.schema = b.schema;\n this.fieldNames = Object.keys(b.schema);\n this.jsonFields = this.fieldNames.filter((f) => (b.schema[f] as PropSpec).kind === \"json\");\n // With no json fields the data view IS the raw cell — one object, no copy.\n this.scratchData = this.jsonFields.length === 0 ? this.scratchCell : {};\n this.scratchPrevData = {};\n // An ephemeral behavior is a SINGLETON on the local peer, so remote\n // peers' projected facets must never become instances — they are read\n // through `ctx.peers()` instead. `Local` is strata's own marker for\n // entities THIS peer minted, which is exactly the distinction.\n this.ownQuery =\n b.store === \"ephemeral\" ? defineQuery([this.own, Local]) : defineQuery([this.own]);\n this.peersQuery = b.store === \"ephemeral\" ? defineQuery([this.own, Not(Local)]) : undefined;\n\n const hooks: BehaviorSystemHooks = {\n shouldDeliver: () => this.shouldDeliver(),\n deliver: (ctx) => this.runDeliver(systemWalker(ctx)),\n shouldTick: () => this.instances.size > 0 && !this.generationDirty,\n tickChunk: (batch, ctx) => this.tickChunk(batch, ctx),\n charge: (body) => this.guest.run(body),\n suspended: () => this.guest.suspended(),\n onSuspendedFrame: () => this.goCold(),\n };\n this.compiled = compileBehavior(b, hooks);\n this.guest = opts.engine.guests.addDriven({\n id: `behavior:${b.name}`,\n ...(b.budgetMs !== undefined ? { budgetMs: b.budgetMs } : {}),\n ...(registration.ledger === undefined ? {} : { ledger: registration.ledger }),\n busy: () => this.owed(),\n });\n this.stopWake = opts.engine.frame?.wakeWhen(`behavior:${b.name}`, (now) => (b.on.tick !== undefined && this.instances.size > 0 ? now : Number.POSITIVE_INFINITY));\n this.ctx = this.buildCtx();\n }\n\n // --- installation ------------------------------------------------------\n\n /**\n * Attach this behavior's two collectors. Separate from `install` because\n * suspension DETACHES them and resume re-attaches (see `goCold`/`goWarm`).\n */\n private installCollectors(): void {\n this.ownCollector = world.changes.collect({ components: [this.own], coarse: false });\n // The reads collector subscribes to everything EXCEPT the own component,\n // which the own collector already covers — so a behavior whose only\n // declared read is itself gets no second collector at all, rather than\n // one subscribed to nothing.\n const readsComponents = this.compiled.readComponents.filter((c) => c !== this.own);\n if (readsComponents.length > 0 || this.compiled.readTags.length > 0) {\n this.readsCollector = world.changes.collect({\n components: readsComponents,\n ...(this.compiled.readTags.length > 0 ? { tags: this.compiled.readTags } : {}),\n coarse: false,\n });\n }\n }\n\n /**\n * The breaker suspended us. DETACH the collectors — a suspended behavior\n * that keeps them alive keeps costing: strata journals every subscribed\n * write into buffers we then throw away, every frame, for as long as the\n * suspension lasts. Suspension is supposed to stop the cost, not launder it.\n */\n private goCold(): void {\n if (this.cold) return;\n this.cold = true;\n this.ownCollector?.dispose();\n this.readsCollector?.dispose();\n this.ownCollector = undefined;\n this.readsCollector = undefined;\n // A suspended producer must also stop PUBLISHING (I17): the facet comes\n // back through `ensureFacet` on the first post-resume run.\n this.withdrawFacet();\n }\n\n /**\n * Resumed. Fresh collectors journal from NOW, so everything that happened\n * during the suspension is invisible to them — which is exactly the state a\n * newly registered behavior is in, and `seeded` already means \"rebuild from\n * the world rather than trust a delta\". Without this, `guests.resume()` —\n * the doctor's own repair action — hands back a behavior whose instance\n * registry has silently lost everything attached while it was down.\n */\n private goWarm(): void {\n if (!this.cold) return;\n this.cold = false;\n this.installCollectors();\n this.seeded = false;\n }\n\n install(): void {\n this.installCollectors();\n // ARM THE POLLS AT REGISTRATION, not at first use. Both stamp families\n // are dormant until their FIRST READ: a poll armed late reports its first\n // compare as \"unchanged\" and silently misses every write before it. Both\n // arming flags are WORLD-WIDE — one read of any resource, or of any\n // ordered relation, starts collection for all of them — so the hazard\n // applies to the first registration and not to later ones. The\n // order-stamp read below is purely for its arming side effect, which is\n // why the parent it names does not matter.\n for (const res of this.compiled.readResources) this.resourceStamps.set(res, world.resourceStamp(res));\n if (this.compiled.readRelations.length > 0) {\n world.orderStamp(0 as Entity, this.compiled.readRelations[0] as Relation);\n }\n }\n\n installExecution(): void {\n if (this.b.phase === \"publish\") {\n // The publish slot is not a pipeline phase: it is the post-tick step\n // where ephemeral mutation is legal and there is no iteration bracket.\n // So no systems are registered — the node runs from the runtime's ONE\n // stable publish hook (see ensurePublishHook), with a walker that goes\n // straight to the world.\n //\n // Accounting note: a driven guest's accrual is closed at the GUEST\n // SLOT, which runs before publish hooks, so a publish behavior's cost\n // lands in the NEXT frame's seam total. The ladder counts invocations,\n // not wall alignment, so every trip rule still fires on schedule — the\n // seam CAP is what sees this one frame late.\n this.removeSystems = installPublishNode(this);\n } else {\n this.removeSystems = opts.engine.addSystems(\n this.b.phase as PhaseGroup,\n ...(this.compiled.systems as readonly never[]),\n );\n }\n }\n\n /** The publish-slot body — driven by the runtime's one stable hook. */\n runPublish(): void {\n if (this.guest.suspended()) {\n this.goCold();\n return;\n }\n this.guest.run(() => {\n if (this.b.store === \"ephemeral\") this.ensureFacet();\n if (this.shouldDeliver()) this.runDeliver(publishWalker(world));\n this.publishTick();\n });\n }\n\n isStopped(): boolean {\n return this.stopped;\n }\n\n uninstallExecution(): void {\n this.removeSystems?.();\n this.removeSystems = undefined;\n }\n\n /** The version-marker surface for the current session, if it has one. */\n private metaOf(session: BehaviorSession | undefined): BehaviorMeta | undefined {\n const snapshot = session?.store.snapshot;\n if (snapshot === undefined || typeof snapshot.readMeta !== \"function\") return undefined;\n const metaTransaction = session?.store.metaTransaction;\n if (typeof metaTransaction !== \"function\") return undefined;\n return {\n readMeta: (key) => snapshot.readMeta(key),\n metaTransaction: (fn) => metaTransaction.call(session?.store, fn),\n };\n }\n\n /** Classify this doc's version for this behavior, and act on the verdict. */\n private syncVersion(session: BehaviorSession | undefined): void {\n this.dormant = false;\n if (this.b.store !== \"durable\" || session === undefined) return;\n const meta = this.metaOf(session);\n if (meta === undefined) return;\n const docVersion = docBehaviorVersion(meta, this.b.name, this.b.version);\n const verdict = classifyBehaviorVersion(this.b, docVersion);\n switch (verdict.kind) {\n case \"ok\":\n return;\n case \"dormant\":\n this.dormant = true;\n onLog(\n this.b.name,\n `the document holds v${verdict.docVersion} data and this build installs v${verdict.installed} — hook delivery is REFUSED for this behavior (its cells stay untouched). The document itself is unaffected and stays writable.`,\n [],\n );\n return;\n case \"unreachable\":\n onLog(\n this.b.name,\n `the document holds v${verdict.from} data and this build's migrate chain cannot reach v${verdict.installed} — its cells stay at v${verdict.from}.`,\n [],\n );\n return;\n case \"migrate\": {\n if (session.readOnly) return; // nothing to write to\n const carriers: Entity[] = [];\n world.query(this.ownQuery).each((b) => {\n for (const row of b) carriers.push(b.entity(row));\n });\n const n = runBehaviorMigration(this.b, verdict.from, {\n world,\n meta,\n store: session.store,\n liveWriter: session.liveWriter,\n carriers: () => carriers,\n });\n onLog(this.b.name, `migrated ${n} instance(s) from v${verdict.from} to v${verdict.installed}.`, []);\n return;\n }\n }\n }\n\n /** Stamp this build's marker the first time a cell of ours enters the doc. */\n private stampFirstAttach(): void {\n if (this.b.store !== \"durable\") return;\n const session = opts.session?.();\n if (session === undefined || session.readOnly) return;\n const meta = this.metaOf(session);\n if (meta === undefined) return;\n stampBehaviorMarker(meta, this.b.name, this.b.version);\n }\n\n /** Does `e` carry this behavior AS AN INSTANCE? (ephemeral: local peer only) */\n private carries(e: Entity): boolean {\n if (!world.isAlive(e) || !world.has(e, this.own)) return false;\n return this.b.store !== \"ephemeral\" || world.hasTag(e, Local);\n }\n\n /**\n * Mint (or re-mint) the local peer's facet. `localPeer` is a getter that a\n * world reset replaces — the fresh peer carries NO facets, so the identity\n * swap is what tells us to attach again rather than edit a dead entity.\n */\n private ensureFacet(): void {\n const presence = opts.presence?.();\n if (presence === undefined) {\n this.facetPeer = undefined;\n return; // dormant: no peer to be\n }\n const peer = presence.localPeer;\n // A world reset kills the minted peer, and presence re-mints it a\n // MICROTASK later (attaching an ephemeral store is illegal inside an\n // observer emit). Between the two there is a window where `localPeer` is\n // a dead handle — writing through it throws inside strata's projector,\n // which the breaker then charges to a behavior that did nothing wrong.\n // Skip the frame; the fresh peer arrives on the next one.\n if (!world.isAlive(peer)) {\n this.facetPeer = undefined;\n return;\n }\n // A quarantined singleton is a producer that STOPPED (I17): re-minting\n // here would undo the withdrawal one frame after quarantine performed it,\n // and remote peers would go right back to reading a value nobody\n // maintains. The memo lives on the NODE, not the instance — withdrawal\n // makes the instance DEPART on the next deliver, and an instance-keyed\n // check would then forget the quarantine and re-mint into an infinite\n // quarantine/remint oscillation that never even strikes the guest\n // (a singleton's throws cannot span instances). The facet returns with a\n // fresh generation or a fresh registration, never sooner.\n if (this.singletonQuarantined) {\n this.facetPeer = undefined;\n return;\n }\n // A PRIOR peer's instance is still awaiting departure (a same-gap\n // presence detach→reattach, or the publish straddling a world reset\n // before the generation flip): minting now would put the new peer's\n // `init` in the SAME deliver as — and, by the documented hook order\n // (drain → init → … → dispose), BEFORE — the old instance's `dispose`.\n // Skip this publish: the departure drains in it, and the mint lands on\n // the next one. Dispose-before-init across a swap, at the cost of one\n // publish of activation latency in exactly that case (review finding 2).\n if (this.instances.size > 0 && !this.instances.has(peer)) {\n this.facetPeer = undefined;\n return;\n }\n if (peer === this.facetPeer && world.has(peer, this.own)) return;\n this.facetPeer = peer;\n if (!world.has(peer, this.own)) {\n // No I19 re-measure here: an over-budget DEFAULT cell fails\n // `defineBehavior` itself (unconditionally, not dev-gated), so a\n // registered behavior's defaults are within claim by construction.\n presence.eph.addComponent(\n peer,\n this.own as Component<unknown>,\n { ...(this.b.defaults as Record<string, unknown>) },\n );\n }\n }\n\n /**\n * Withdraw the published facet (petition I17). An ephemeral facet is LIVE\n * PUBLICATION — the local peer telling every remote peer \"this value is\n * current\" — so every edge where the producer stops executing must reverse\n * the publication too, or a disabled, suspended, or quarantined behavior\n * keeps asserting its last value forever (remote peers have no TTL for a\n * peer that is still connected). Idempotent by construction: presence\n * absent, a dead peer (mid re-mint window), and an already-gone facet are\n * all quiet no-ops. The removal goes through the PRESENCE writer, never\n * `world.removeComponent`, because only the presence path encodes a\n * tombstone remote projections honor.\n */\n private withdrawFacet(): void {\n if (this.b.store !== \"ephemeral\") return;\n this.facetPeer = undefined;\n const presence = opts.presence?.();\n if (presence === undefined) return;\n const peer = presence.localPeer;\n if (!(world.isAlive(peer) && world.has(peer, this.own))) return;\n // strata's own guard predicate for exactly this — public API since\n // strata 0.13.0 (petition 11, filed + landed 2026-08-16 from this exact\n // call site; docs/petitions/petition-11-projection-unsafe-context.md.\n // ICE 0.7.0–0.8.0 shipped a typed cast against the @internal-stripped\n // 0.12.0 d.ts; the pin bump retired it). The try/catch and the deferral\n // STAY: they guard the mid-observer-emit boundary — deliberately outside\n // the predicate — and teardown-never-throws, not the type.\n const midTick = world.inImmediateProjectionUnsafeContext;\n if (midTick) {\n // Structural eph ops THROW mid-tick/mid-walk (strata's projector\n // guard), and withdrawal's call sites include mid-tick edges: an\n // unregister from inside a hook, goCold from a driven runIf, a\n // quarantine landing inside the delivery pass. Deferring to the\n // publish slot — the post-tick step where eph structural ops are the\n // designed legality — keeps every one of those exception-safe\n // (review finding 1: the throw used to escape the remover\n // mid-uninstall and strand the node with an orphan published facet).\n const behaviorName = this.b.name;\n const own = this.own;\n deferWithdrawal(() => {\n const p = opts.presence?.();\n if (p === undefined) return;\n // Same-peer check: a reset between defer and flush re-mints the\n // peer; the old facet died with the old world and the NEW peer's\n // facet (if any) belongs to whoever minted it, not to this job.\n if (p.localPeer !== peer) return;\n if (!(world.isAlive(peer) && world.has(peer, own))) return;\n try {\n p.eph.removeComponent(peer, own);\n } catch (err) {\n onFault(behaviorName, \"withdraw\", peer, err);\n }\n });\n return;\n }\n try {\n presence.eph.removeComponent(peer, this.own);\n } catch (err) {\n // Withdrawal must never abort a teardown (the guests.ts sweep rule).\n onFault(this.b.name, \"withdraw\", peer, err);\n }\n }\n\n /** The publish-slot twin of the tick SYSTEM (no query, no chunks). */\n private publishTick(): void {\n const on = this.b.on;\n if (on.tick === undefined || this.snapshot.length === 0) return;\n const info = world.getResource(FrameInfo);\n const frame: BehaviorFrame = { dtMs: info?.dt ?? 0, tick: info?.tick ?? 0, clock: info?.clock ?? 0 };\n const faulted = new Set<Entity>();\n this.walker = publishWalker(world);\n for (const e of this.snapshot) {\n const inst = this.instances.get(e);\n if (inst === undefined || inst.failed || !inst.inited) continue;\n const data = this.dataOf(e);\n this.callHook(\"tick\", inst, faulted, () =>\n on.tick?.(e, data as never, frame, this.ctx as never),\n );\n }\n this.walker = undefined;\n }\n\n uninstall(): void {\n // Before endGeneration, so a dispose hook's ctx.write is already inert\n // (endGeneration's withdrawFacet is what makes dispose-then-withdraw\n // safe on THIS path; the flag is for closures that outlive the node).\n this.stopped = true;\n this.endGeneration();\n this.uninstallExecution();\n this.ownCollector?.dispose();\n this.readsCollector?.dispose();\n this.ownCollector = undefined;\n this.readsCollector = undefined;\n this.guest.remove();\n this.stopWake?.();\n }\n\n markGeneration(): void {\n this.generationDirty = true;\n }\n\n /** Owed work for the frame gate — a freeze must not park mid-reflow. */\n owed(): boolean {\n return this.generationDirty;\n }\n\n // --- the gate ----------------------------------------------------------\n\n private shouldDeliver(): boolean {\n // Reached only while NOT suspended, so this is the resume edge.\n if (this.cold) this.goWarm();\n // The drain is UNCONDITIONAL even when the answer is \"no work\": a\n // collector nobody drains grows without bound, and the next real drain\n // would hand the body a delta describing a world several frames old.\n const ownDelta = this.ownCollector?.drain();\n const readsDelta = this.readsCollector?.drain();\n const pollFired = this.pollResources() || this.pollOrder();\n\n const full =\n this.generationDirty ||\n !this.seeded ||\n (ownDelta?.reset ?? false) ||\n (ownDelta?.coarse.length ?? 0) > 0 ||\n (readsDelta?.reset ?? false) ||\n (readsDelta?.coarse.length ?? 0) > 0;\n\n // The echo memo is consumed by INVALIDATION, not by a frame count.\n // A one-drain window would in fact suffice for the ordinary case — a\n // durable write journals twice (write-through now, batch re-projection at\n // the following `world.sync()`) but both copies land inside one drain —\n // so this is a margin, not a fix: it costs nothing, it does not depend on\n // that timing holding, and the first genuine change on an entity fails\n // the compare, wakes the behavior, and drops the entry anyway.\n const echo = this.echo;\n const isEcho = (e: Entity): boolean => {\n const snap = echo.get(e);\n if (snap === undefined) return false;\n const alive = world.isAlive(e);\n for (const [c, v] of snap.cells) {\n const now = alive && world.has(e, c) ? world.get(e, c) : undefined;\n const same = now === undefined || v === undefined ? now === v : valueEquals(c, now, v);\n if (!same) {\n echo.delete(e);\n return false;\n }\n }\n for (const [t, had] of snap.tags) {\n if ((alive && world.hasTag(e, t)) !== had) {\n echo.delete(e);\n return false;\n }\n }\n return true;\n };\n const keep = (list: readonly Entity[]): readonly Entity[] =>\n echo.size === 0 || list.length === 0 ? list : list.filter((e) => !isEcho(e));\n\n const ownChanged = keep(ownDelta?.changed ?? []);\n const ownRemoved = ownDelta?.removed ?? [];\n const readsChanged = keep(readsDelta?.changed ?? []);\n const readsRemoved = readsDelta?.removed ?? [];\n const ownWork = ownChanged.length > 0 || ownRemoved.length > 0;\n const readsWork = pollFired || readsChanged.length > 0 || readsRemoved.length > 0;\n\n // `instances > 0` gates the READS path only. It cannot gate the own path:\n // the very first attach arrives as own-component churn on a behavior that\n // has no instances yet, and gating that is how an installed behavior\n // never wakes up.\n // A claim clearing is WORK even on an otherwise silent frame: the\n // gesture's own commit landed at `ctl:behave`, `derive` runs later the\n // same frame, and the coalesced delivery has to happen against that\n // settled truth or the reflow waits for unrelated churn to wake it.\n const lifted = this.suppressionLifted();\n if (!full && !ownWork && !lifted && !(readsWork && this.instances.size > 0)) {\n if (this.suppressed.size > 0) {\n for (const e of readsChanged) this.carry.add(e);\n for (const e of ownChanged) this.carry.add(e);\n }\n this.stash = undefined;\n return false;\n }\n this.stash = { full, ownChanged, ownRemoved, readsFired: readsWork, readsChanged, readsRemoved };\n return true;\n }\n\n /** Any suppressed instance whose claim has cleared since last frame. */\n private suppressionLifted(): boolean {\n if (this.suppressed.size === 0) return false;\n for (const e of this.suppressed) {\n if (!this.isSuppressible(e)) return true;\n }\n return false;\n }\n\n /**\n * Is this instance held by a live claim? Two ways, and the second is what\n * makes the flagship case work: the CARRIER of a mind map is never itself\n * grabbed — its member node is. So a claimed entity that reaches an\n * instance through one of the behavior's own DECLARED read relations\n * suppresses that instance, and only that instance.\n */\n private isSuppressible(e: Entity): boolean {\n if (isClaimed(world, e)) return true;\n for (const r of this.compiled.readRelations) {\n for (const child of world.getReverse(e, r)) {\n if (isClaimed(world, child)) return true;\n }\n }\n return false;\n }\n\n /** Recompute the suppressed set for this delivery (derived behaviors only). */\n private updateSuppression(): void {\n const gone: Entity[] = [];\n for (const e of this.suppressed) if (!this.instances.has(e)) gone.push(e);\n for (const e of gone) {\n this.suppressed.delete(e);\n this.suppressedFrames.delete(e);\n }\n for (const e of this.snapshot) {\n if (this.isSuppressible(e)) {\n this.suppressed.add(e);\n const n = (this.suppressedFrames.get(e) ?? 0) + 1;\n this.suppressedFrames.set(e, n);\n if (n === SUPPRESSION_WARN_FRAMES) {\n onLog(\n this.b.name,\n `derive suppressed for ${n} frames on entity ${e} — a gesture claim on it (or on one of its members) has not cleared. Derived state for that instance is frozen until it does.`,\n [],\n );\n }\n continue;\n }\n this.suppressed.delete(e);\n this.suppressedFrames.delete(e);\n }\n }\n\n private pollResources(): boolean {\n let fired = false;\n for (const [res, last] of this.resourceStamps) {\n // A per-WRITE counter, not a frame stamp: same-frame rewrites each bump\n // it, so a poller can never miss a value that was written and\n // overwritten inside one frame. It also never moves backward — a\n // `world.reset()` bumps every held resource, which presents to this\n // poll as an ordinary change to everything, correctly.\n const now = world.resourceStamp(res);\n if (now !== last) {\n this.resourceStamps.set(res, now);\n fired = true;\n }\n }\n return fired;\n }\n\n /**\n * Poll the watched sequences. Sibling order is the one thing `reads:` can\n * name that NEVER reaches a change collector, so this poll is not an\n * optimization — it is the only mechanism there is.\n *\n * The per-parent value SUMS the stamps of every declared relation, which is\n * sound only because the stamps come from one shared monotonic counter:\n * they never decrease, so two relations cannot move in opposite directions\n * and cancel to the same total.\n */\n private pollOrder(): boolean {\n const rels = this.compiled.readRelations;\n if (rels.length === 0) return false;\n if (this.parentsDirty) this.rebuildParents();\n let fired = false;\n for (const [parent, last] of this.parentStamps) {\n let now = 0;\n for (const r of rels) now += world.orderStamp(parent, r);\n if (now !== last) {\n this.parentStamps.set(parent, now);\n fired = true;\n }\n }\n // A fired stamp usually means membership under that parent moved, so the\n // watch SET itself may be stale. Rebuilding next frame (rather than now)\n // is safe: the stamp we just banked is current, so nothing is missed in\n // the gap.\n if (fired) this.parentsDirty = true;\n return fired;\n }\n\n /**\n * Rebuild the set of sequences this behavior watches.\n *\n * BOTH DIRECTIONS, and the second is the load-bearing one. An instance\n * participates in an ordered relation two ways: as a CHILD (its own\n * parent's sequence moved) or as the PARENT (its members were reordered\n * under it). Watching only the first misses the flagship shape entirely — a\n * mind map's carrier holds the behavior and its NODES are the children, so\n * a pure reorder of those nodes would wake nothing at all.\n *\n * A CHILDLESS instance is watched too, and deliberately: its stamp reads 0\n * until it gains a first child, and that transition is precisely what has\n * to be detectable. Skipping childless parents would reintroduce the same\n * blind spot one case down.\n *\n * COST, stated honestly because design-009 §5.2 says \"O(distinct parents)\"\n * and this is not that: the watch set is instances ∪ instances' parents, so\n * the poll is O(instances) map lookups per frame for a behavior that\n * declares an ordered relation. Two consequences worth knowing — declare a\n * relation only when you navigate it, and prefer the §10 carrier idiom,\n * where the instance count is small by construction.\n */\n private rebuildParents(): void {\n this.parentsDirty = false;\n this.parentStamps.clear();\n if (this.compiled.readRelations.length === 0) return;\n const watch = (parent: Entity): void => {\n let total = 0;\n for (const rr of this.compiled.readRelations) total += world.orderStamp(parent, rr);\n this.parentStamps.set(parent, total);\n };\n for (const e of this.instances.keys()) {\n if (!world.isAlive(e)) continue;\n watch(e); // as a PARENT: its members' sequence\n for (const r of this.compiled.readRelations) {\n const parent = world.getRelation(e, r);\n if (parent !== undefined) watch(parent); // as a CHILD: its own sequence\n }\n }\n }\n\n // --- delivery ----------------------------------------------------------\n\n private runDeliver(walker: BehaviorWalker): void {\n this.walker = walker;\n if (this.generationDirty) {\n this.generationDirty = false;\n this.endGeneration();\n this.generation = new AbortController();\n this.seeded = false;\n }\n // The version check is RE-ENTRANT by construction: it re-runs whenever\n // the session identity changes, which covers doc open, doc switch, and\n // (because a plugin host installs mid-session) a behavior registered long\n // after the document was opened. \"Migrate at open\" alone would miss that\n // last path entirely, which is the normal one for plugins.\n const session = opts.session?.();\n if (session !== this.checkedSession) {\n this.checkedSession = session;\n this.syncVersion(session);\n }\n\n const work = this.stash;\n this.stash = undefined;\n const full = work?.full ?? true;\n\n if (this.dormant) {\n // Refuse hook delivery, but keep draining: the moment a build that\n // understands this data opens the doc, its own runtime picks up where\n // this one honestly declined to guess.\n this.walker = undefined;\n return;\n }\n\n const appeared: Entity[] = [];\n const departed: Instance[] = [];\n\n if (full) {\n // Rebuild: every carrier is an instance, every non-carrier is not.\n const carriers = new Set<Entity>();\n walker.each(this.ownQuery, (e) => carriers.add(e));\n for (const e of carriers) if (!this.instances.has(e)) appeared.push(e);\n for (const [e, inst] of this.instances) if (!carriers.has(e)) departed.push(inst);\n this.seeded = true;\n } else {\n // O(changed), never O(instances): structural changes arrive as\n // over-reporting archetype records, so the exact question — \"does this\n // entity carry my component NOW?\" — is one `has` per journaled entity.\n for (const e of work?.ownChanged ?? []) {\n const carries = this.carries(e);\n const known = this.instances.get(e);\n if (carries && known === undefined) appeared.push(e);\n else if (!carries && known !== undefined) departed.push(known);\n }\n for (const e of work?.ownRemoved ?? []) {\n const known = this.instances.get(e);\n if (known !== undefined) departed.push(known);\n }\n }\n\n for (const inst of departed) this.instances.delete(inst.e);\n for (const e of appeared) {\n this.instances.set(e, {\n e,\n prevCell: this.readCell(e, {}),\n inited: false,\n failed: false,\n consecutiveThrows: 0,\n });\n }\n // The two mutation sites above, and `endGeneration`'s clear, are the\n // only three — see `snapshotDirty`.\n if (appeared.length > 0 || departed.length > 0) this.snapshotDirty = true;\n // Rebuild the order-poll's watch set NOW, not lazily on the next poll:\n // the stamps have to be banked in the same frame the instance set\n // changed, or a reorder landing in between is compared against a stamp\n // taken AFTER it — \"late arming misses changes\", at instance granularity.\n // (No-op when the behavior declares no ordered relation.)\n if (appeared.length > 0 || departed.length > 0) this.rebuildParents();\n // FIRST-ATTACH stamping (§5.6): not at doc create, where the behavior may\n // not exist yet — a plugin installs later, and a marker for something the\n // document has no cells of is a lie about what is in it.\n if (appeared.length > 0) this.stampFirstAttach();\n\n // The instance SNAPSHOT: hooks below may attach or detach, and those\n // land next frame. Nothing after this line re-reads `this.instances` for\n // iteration.\n //\n // CACHED (A3b fix 5) — and this is the whole of the idle tax A1b\n // recorded on the engine's kind behaviour of the day (`ice:surface.domAtRest`,\n // retired at design-015 D5b): it read `FrameInfo`, a resource, so its poll\n // fired every frame and delivery ran every frame; the walks inside are\n // all O(changed), but this spread was O(instances)\n // unconditionally: 18 µs at 10k, 165 µs at 100k, ≈1.6 ns an element for\n // an array whose contents had not moved since the frame before. The\n // membership it describes changes only where `snapshotDirty` is set, so\n // that is when it is rebuilt.\n //\n // The array is REPLACED, never filled in place: `this.visible` aliases\n // it and `ctx.entities()` hands that to hooks. The documented semantics\n // are unchanged — the list is still the membership as of phase entry,\n // and a hook that attaches or detaches still affects the NEXT frame,\n // because the flag it sets is read on the next delivery.\n if (this.snapshotDirty) {\n this.snapshot = [...this.instances.keys()];\n this.snapshotDirty = false;\n }\n\n // Claim-scoped delivery suppression (§5.3). It REPLACED a deferred-commit\n // queue that re-ran a stale closure after the gesture's own commit — two\n // commits, the first gliding to the pre-drag layout. Here the hook simply\n // does not run while a claim is live, so closure freshness is structural\n // and `ctx.commit` stays a plain write-now call.\n const suppressing = this.b.derived && !this.b.deriveDuringGesture;\n const wasSuppressed = suppressing ? new Set(this.suppressed) : undefined;\n if (suppressing) this.updateSuppression();\n this.visible =\n suppressing && this.suppressed.size > 0\n ? this.snapshot.filter((e) => !this.suppressed.has(e))\n : this.snapshot;\n // A claim CLEARING is itself the trigger for the coalesced delivery. On\n // that frame there is usually no fresh churn at all — the gesture's last\n // write landed frames ago — so without this the settle would sit waiting\n // for unrelated churn to wake it.\n const lifted =\n wasSuppressed !== undefined && [...wasSuppressed].some((e) => !this.suppressed.has(e));\n\n let changedList = work?.readsChanged ?? [];\n if (this.carry.size > 0) {\n // Churn that arrived while suppressed, replayed ONCE at the settle so\n // the coalesced delivery's `ctx.changes()` describes the whole gesture,\n // not just its final frame.\n const merged = new Set<Entity>(changedList);\n for (const e of this.carry) merged.add(e);\n this.carry.clear();\n changedList = [...merged];\n }\n if (this.suppressed.size > 0) for (const e of changedList) this.carry.add(e);\n this.changesView = { full, changed: changedList, removed: work?.readsRemoved ?? [] };\n this.changedEntitiesCache = undefined;\n\n const on = this.b.on;\n const faultedEntities = new Set<Entity>();\n\n // 1. init — appeared instances, before their first tick.\n if (on.init !== undefined) {\n for (const e of appeared) {\n const inst = this.instances.get(e);\n if (inst === undefined || inst.failed) continue;\n if (\n this.callHook(\"init\", inst, faultedEntities, () =>\n on.init?.(e, this.dataOf(e) as never, this.ctx as never),\n )\n ) {\n inst.inited = true;\n }\n }\n } else {\n for (const e of appeared) {\n const inst = this.instances.get(e);\n if (inst !== undefined) inst.inited = true;\n }\n }\n\n // 2. update — own data changed since the last delivery, by ANY writer.\n if (on.update !== undefined) {\n const candidates = full ? this.snapshot : (work?.ownChanged ?? []);\n for (const e of candidates) {\n const inst = this.instances.get(e);\n if (inst === undefined || inst.failed || !inst.inited) continue;\n if (this.suppressed.has(e)) continue; // held by a live claim\n // Just-appeared instances got current data in `init`; `prev` would be\n // that same value, so there is nothing to report.\n if (appeared.includes(e)) continue;\n if (!world.isAlive(e)) continue;\n this.readCell(e, this.scratchCell);\n // The journal OVER-REPORTS (an archetype migration reports every\n // carried component), so a real value compare is what keeps `update`\n // meaning \"your data changed\". strata's own equality, never a\n // hand-rolled one: a local comparison drifts on exactly the cells\n // reconcile considers settled (f32 fround, enum labels, ±0).\n if (valueEquals(this.own, this.scratchCell, inst.prevCell)) continue;\n const data = this.viewOf(this.scratchCell, this.scratchData);\n const prev = this.viewOf(inst.prevCell, this.scratchPrevData);\n this.callHook(\"update\", inst, faultedEntities, () =>\n on.update?.(e, data as never, prev as never, this.ctx as never),\n );\n // Bank the delivered value even when the hook threw: re-delivering\n // the same change to an instance that failed on it is a loop.\n this.copyInto(this.scratchCell, inst.prevCell);\n }\n }\n\n // 3. changed — ONCE per behavior, not per instance. N instances × one tag\n // flip must not mean N journal scans.\n const anyVisible = this.visible.length > 0;\n if (on.changed !== undefined && (full || (work?.readsFired ?? false) || lifted) && anyVisible) {\n try {\n invokeHook(this.b.name, \"changed\", () => on.changed?.(this.ctx as never));\n } catch (err) {\n // No entity to quarantine — this one is the behavior's.\n onFault(this.b.name, \"changed\", undefined, err);\n this.guest.fault(err);\n }\n }\n\n // 4. dispose — departed instances. Runs before the tick SYSTEM in this\n // phase, which is unobservable: a departed instance no longer carries\n // the component the tick query matches on.\n if (on.dispose !== undefined) {\n for (const inst of departed) {\n this.hookEntity = inst.e;\n try {\n invokeHook(this.b.name, \"dispose\", () =>\n on.dispose?.(inst.e, this.ctx as never),\n );\n } catch (err) {\n // Swallowed by contract (§4.3): teardown must not stop teardown.\n onFault(this.b.name, \"dispose\", inst.e, err);\n } finally {\n this.hookEntity = undefined;\n }\n }\n }\n\n this.walker = undefined;\n }\n\n private tickChunk(batch: Batch, ctx: SystemCtx): void {\n const on = this.b.on;\n if (on.tick === undefined) return;\n this.walker = systemWalker(ctx);\n const info = world.getResource(FrameInfo);\n const frame: BehaviorFrame = {\n dtMs: info?.dt ?? 0,\n tick: info?.tick ?? 0,\n clock: info?.clock ?? 0,\n };\n const faulted = new Set<Entity>();\n this.visible = this.snapshot;\n for (const row of batch) {\n const e = batch.entity(row);\n const inst = this.instances.get(e);\n // A carrier the delivery pass has not adopted yet (attached this frame\n // after delivery ran) has had no `init`; ticking it would violate\n // \"init runs before that instance's first tick\".\n if (inst === undefined || inst.failed || !inst.inited) continue;\n const data = this.dataOf(e);\n this.callHook(\"tick\", inst, faulted, () =>\n on.tick?.(e, data as never, frame, this.ctx as never),\n );\n }\n this.walker = undefined;\n }\n\n /**\n * Per-(behavior, hook, entity) fault attribution (BF-D18): three\n * consecutive throws on ONE entity quarantine that INSTANCE; the behavior\n * itself is only struck when throws SPAN instances. One bad node must not\n * kill a 1000-node layout.\n */\n private callHook(\n hook: string,\n inst: Instance,\n faulted: Set<Entity>,\n body: () => unknown,\n ): boolean {\n this.hookEntity = inst.e;\n try {\n invokeHook(this.b.name, hook, body);\n inst.consecutiveThrows = 0;\n return true;\n } catch (err) {\n inst.consecutiveThrows++;\n onFault(this.b.name, hook, inst.e, err);\n if (inst.consecutiveThrows >= INSTANCE_THROW_LIMIT) {\n inst.failed = true;\n // Quarantining the EPHEMERAL singleton stops the producer without any\n // guest-ledger edge a host could react to — so the runtime itself\n // must reverse the publication here (I17). Non-ephemeral: no-op.\n if (this.b.store === \"ephemeral\") this.singletonQuarantined = true;\n this.withdrawFacet();\n }\n faulted.add(inst.e);\n // ONE strike per frame per reason: onFault above keeps full per-entity\n // attribution, but the guest ladder counts FRAMES, and strikes are a\n // cumulative number hosts PERSIST — striking per instance wrote a\n // 500-instance behavior's whole population into the ledger in one\n // frame (review finding 4).\n const frameTick = world.getResource(FrameInfo)?.tick ?? -1;\n if (frameTick !== this.strikeFrame) {\n this.strikeFrame = frameTick;\n this.thenableStruckPass = false;\n this.spanStruckPass = false;\n }\n if (err instanceof BehaviorHookThenableError) {\n if (!this.thenableStruckPass) {\n this.thenableStruckPass = true;\n this.guest.fault(err);\n }\n } else if (faulted.size > 1 && !this.spanStruckPass) {\n this.spanStruckPass = true;\n this.guest.fault(err);\n }\n return false;\n } finally {\n this.hookEntity = undefined;\n }\n }\n\n // --- generation --------------------------------------------------------\n\n private endGeneration(): void {\n const on = this.b.on;\n if (on.dispose !== undefined) {\n for (const inst of this.instances.values()) {\n this.hookEntity = inst.e;\n try {\n invokeHook(this.b.name, \"dispose\", () =>\n on.dispose?.(inst.e, this.ctx as never),\n );\n } catch (err) {\n onFault(this.b.name, \"dispose\", inst.e, err);\n } finally {\n this.hookEntity = undefined;\n }\n }\n }\n this.instances.clear();\n // The third mutation site (see `snapshotDirty`). The generation that\n // follows usually rebuilds anyway — `full` is forced and every carrier\n // reappears — but a generation that ends with NO carriers at all would\n // otherwise leave the previous generation's entities in the cache.\n this.snapshotDirty = true;\n // After the dispose hooks, before ownership is forgotten (I17): on\n // unregister this withdraws the live facet; on a world-reset generation\n // end the old peer is already dead and this is a quiet no-op. The\n // quarantine memo resets WITH the generation — same forgiveness the\n // instance map always had (a fresh peer re-mints and re-inits).\n this.withdrawFacet();\n this.singletonQuarantined = false;\n this.suppressed.clear();\n this.suppressedFrames.clear();\n this.carry.clear();\n this.parentStamps.clear();\n this.parentsDirty = true;\n // dispose FIRST, abort SECOND: a teardown that guards on\n // `signal.aborted` would otherwise skip its own cleanup.\n this.generation.abort();\n }\n\n // --- data views --------------------------------------------------------\n\n /** Fill `target` with `e`'s raw cell, field by field — no intermediate object. */\n private readCell(e: Entity, target: Record<string, unknown>): Record<string, unknown> {\n for (const f of this.fieldNames) target[f] = world.readField(e, this.ownFields, f);\n return target;\n }\n\n /** The hook-facing view of a raw cell (json fields parsed). */\n private viewOf(cell: Record<string, unknown>, target: Record<string, unknown>): Record<string, unknown> {\n if (this.jsonFields.length === 0) return cell;\n for (const f of this.fieldNames) target[f] = cell[f];\n for (const f of this.jsonFields) {\n const raw = cell[f];\n target[f] = typeof raw === \"string\" ? safeParse(raw) : raw;\n }\n return target;\n }\n\n private dataOf(e: Entity): Record<string, unknown> {\n this.readCell(e, this.scratchCell);\n return this.viewOf(this.scratchCell, this.scratchData);\n }\n\n private copyInto(src: Record<string, unknown>, dst: Record<string, unknown>): void {\n for (const f of this.fieldNames) dst[f] = src[f];\n }\n\n cellFor(e: Entity | undefined, patch: Record<string, unknown>): Record<string, unknown> {\n return cellForBehavior(world, this.b, e, patch);\n }\n\n // --- ctx ---------------------------------------------------------------\n\n private buildCtx(): BehaviorCtxBase<Record<string, unknown>> & Record<string, unknown> {\n const scopedQuery = createQueryScope(\n this.b,\n allowedQueryTerms(this.b, this.compiled.readComponents, this.compiled.readTags),\n );\n const behaviorWorld = createBehaviorWorld(world);\n const node = this;\n\n const requireWalker = (what: string): BehaviorWalker => {\n const w = node.walker;\n if (w === undefined) {\n throw new Error(\n `ice: behavior \"${node.b.name}\" called ctx.${what} outside a hook — the ctx is valid only for the duration of the hook call (its walks are attributed to the running system, and there is none here).`,\n );\n }\n return w;\n };\n\n const base: BehaviorCtxBase<Record<string, unknown>> = {\n world: behaviorWorld,\n query: (spec) => scopedQuery(requireWalker(\"query\"), spec),\n entities: () => node.visible,\n changes: () => node.changesView,\n changedEntities: () => {\n if (node.changedEntitiesCache === undefined) {\n const out: Entity[] = [];\n // Instances MINUS the suppressed ones — the same set `ctx.entities()`\n // reports, derived from the same two collections rather than from\n // `visible`, which is per-PASS state (the tick pass resets it) and\n // would make this answer depend on who asked. Reporting a suppressed\n // instance here would invite the hook to act on exactly the instance\n // suppression exists to leave alone.\n for (const e of node.changesView.changed) {\n if (node.instances.has(e) && !node.suppressed.has(e)) out.push(e);\n }\n node.changedEntitiesCache = out;\n }\n return node.changedEntitiesCache;\n },\n keyOf: (e) => {\n const key = opts.session?.()?.store.keyOf(e);\n return typeof key === \"string\" ? key : undefined;\n },\n entityFor: (key) => opts.session?.()?.store.resolve(key as never),\n get signal() {\n return node.generation.signal;\n },\n log: (message, ...rest) => onLog(node.b.name, message, rest),\n };\n\n // The store class routes the WRITE VOCABULARY. Assembling it here — one\n // object per behavior, built once — is what makes \"you cannot misuse the\n // two-worlds model\" a property of the object rather than a doc promise.\n const extra: Record<string, unknown> = {};\n if (this.b.store === \"runtime\") {\n extra.write = (e: Entity, patch: Record<string, unknown>) => node.writeOwn(e, patch);\n extra.set = (e: Entity, c: Component, v: unknown) => node.writeTarget(e, c, v);\n extra.attach = (e: Entity, data?: Record<string, unknown>) => {\n requireWalker(\"attach\").addComponent(e, node.own, node.cellFor(undefined, data ?? {}));\n };\n extra.detach = (e: Entity) => {\n requireWalker(\"detach\").removeComponent(e, node.own);\n };\n }\n if (this.b.store === \"ephemeral\") {\n // No entity argument: the instance IS the local peer, and there is\n // exactly one. Legal without a queue because ephemeral hooks run at the\n // publish slot — post-tick, where eph mutation is allowed.\n extra.write = (patch: Record<string, unknown>) => node.writeFacet(patch);\n extra.peers = () => node.readPeers();\n }\n if (this.b.store === \"durable\" || this.b.store === \"runtime\") {\n extra.commit = (label: string, fn: (tx: BehaviorTx<Record<string, unknown>>) => void, o?: { undoable?: boolean }) =>\n node.commit(label, fn, o);\n }\n return Object.assign(base, extra) as BehaviorCtxBase<Record<string, unknown>> & Record<string, unknown>;\n }\n\n /** `ctx.write(patch)` for the ephemeral class — publish THIS peer's facet. */\n private writeFacet(patch: Record<string, unknown>): void {\n // A STOPPED producer must not publish (I17): the `addComponent` branch\n // below would silently re-create a withdrawn facet — through a dispose\n // hook running after quarantine, or through a captured `ctx.write`\n // closure (a blessed outside-hook pattern) called after suspension or\n // unregister — and nothing would ever withdraw it again. Same edges as\n // `withdrawFacet`, refused rather than reversed.\n if (this.stopped || this.cold || this.singletonQuarantined) return;\n const presence = opts.presence?.();\n if (presence === undefined) return; // dormant\n const peer = presence.localPeer;\n if (!world.isAlive(peer)) return; // mid re-mint (see ensureFacet)\n // A hook writes ONLY the peer whose instance it is running for (review\n // finding 2, 0.8.0): across a same-gap presence detach→reattach the OLD\n // instance's dispose still runs, and resolving `localPeer` live would\n // land the corpse's farewell on the FRESH peer — broadcast to every\n // remote as current, never recomputed. Outside a hook (`hookEntity`\n // unset) the blessed captured-closure pattern publishes the current\n // peer, unchanged.\n if (this.hookEntity !== undefined && this.hookEntity !== peer) return;\n const cell = cellForBehavior(world, this.b, peer, patch);\n // Petition I19: the producer's own byte claim, checked on the COMPLETE\n // merged cell BEFORE any mutation — the prior facet stays intact and the\n // throw is deliberate fail-loud (the silent returns above are lifecycle\n // races; an over-budget write is an authoring contract violation).\n // In-hook, `callHook` catches it: onFault attribution, one\n // consecutiveThrows strike, and the BF-D18 third strike quarantines the\n // singleton and withdraws the facet (I17). Outside a hook — the blessed\n // captured-closure pattern — the throw reaches the captured caller\n // synchronously; the write is refused either way, so the bound cannot be\n // bypassed. Production behavior, not a DEV advisory (I19 ask 7).\n const bound = this.b.maxFacetBytes;\n if (bound !== undefined) {\n const bytes = facetBytesOf(cell);\n if (bytes > bound) {\n throw new Error(\n `ice: behavior \"${this.b.name}\" ctx.write produced a ${bytes}-byte facet, over its declared maxFacetBytes=${bound} — the write was refused and the prior facet left intact.`,\n );\n }\n }\n if (world.has(peer, this.own)) presence.eph.edit(peer).set(this.own as Component<unknown>, cell);\n else presence.eph.addComponent(peer, this.own as Component<unknown>, cell);\n }\n\n /** `ctx.peers()` — REMOTE peers' facets, read-only. The read side of presence. */\n private readPeers(): { entity: Entity; data: Record<string, unknown> }[] {\n const q = this.peersQuery;\n if (q === undefined) return [];\n const out: { entity: Entity; data: Record<string, unknown> }[] = [];\n world.query(q).each((b) => {\n for (const row of b) {\n const e = b.entity(row);\n const cell = this.readCell(e, {});\n out.push({ entity: e, data: this.viewOf(cell, {}) });\n }\n });\n return out;\n }\n\n /** `ctx.write` — own runtime data, immediate, through the armed guard. */\n private writeOwn(e: Entity, patch: Record<string, unknown>): void {\n if (!world.isAlive(e) || !world.has(e, this.own)) return;\n this.writeTarget(e, this.own, this.cellFor(e, patch));\n }\n\n /**\n * `ctx.set` — a declared `writes:` target, immediate. Routed through the\n * session's LiveWriter, which is what makes the divergence law ARMED rather\n * than aspirational: a per-frame write to a DURABLE-eligible cell without a\n * gesture claim or tween grant throws here, naming the law. Doc-less\n * engines write direct — nothing is doc-sovereign without a document.\n */\n private writeTarget(e: Entity, c: Component, v: unknown): void {\n if (devGuardsEnabled() && c !== this.own && !this.b.writes.includes(c)) {\n throw new Error(\n `ice: behavior \"${this.b.name}\" wrote a component it did not declare in writes: — declared writes are what the compiler derives access from (design-009 §7).`,\n );\n }\n const live = opts.session?.()?.liveWriter;\n if (live !== undefined) live.set(e, c as Component<unknown>, v);\n else world.edit(e).set(c as Component<unknown>, v);\n }\n\n /** `ctx.commit` — ONE labeled transaction, opened INSIDE the hook. */\n private commit(\n label: string,\n fn: (tx: BehaviorTx<Record<string, unknown>>) => void,\n o?: { undoable?: boolean },\n ): void {\n const session = opts.session?.();\n if (session === undefined) {\n throw new Error(\n `ice: behavior \"${this.b.name}\" called ctx.commit(\"${label}\") with no document attached — durable writes need a doc (engine.docs.create()/open()/join()).`,\n );\n }\n if (session.readOnly) {\n throw new Error(\n `ice: behavior \"${this.b.name}\" called ctx.commit(\"${label}\") on a READ-ONLY document (version gate) — writes are disabled.`,\n );\n }\n const store = session.store as unknown as Parameters<typeof guardedTransaction>[0];\n const keyOf = (e: Entity): string | undefined => {\n const key = session.store.keyOf(e);\n return typeof key === \"string\" ? key : undefined;\n };\n // `label` is a stable MACHINE id, never display text: it rides in-CRDT as\n // provenance (strata 0.12.0 petition 9) and a receiving peer reads it.\n const meta = { behavior: this.b.name, label };\n\n if (!this.b.derived) {\n guardedTransaction(store, world, (tx) => fn(this.wrapTx(tx)), {\n ...(o?.undoable !== undefined ? { undoable: o.undoable } : {}),\n live: session.liveWriter,\n keyOf,\n meta,\n });\n return;\n }\n\n // The derived path BUFFERS: `undoable` has to be decided before the\n // transaction opens, and whether this commit is derived output or an\n // authorial config edit is only knowable from its ops.\n const recorded = recordDerivedOps(this.b.name, (rec) => fn(this.wrapTx(rec)));\n const diff = diffOps(recorded, {\n world,\n docValue: (e, c) => session.store.getComponent(e, c),\n writeTargets: new Set(this.b.writes as readonly Component[]),\n });\n if (diff.ops.length === 0) return; // zero ops opens NO transaction\n guardedTransaction(store, world, (tx) => replayOps(diff.ops, tx), {\n // ⌘Z must never un-derive. Output rides non-undoable; a commit that\n // only touches the behavior's OWN data is authorial and keeps undo.\n undoable: diff.derivedOutput ? false : (o?.undoable ?? true),\n live: session.liveWriter,\n keyOf,\n meta,\n });\n this.captureEcho(diff.writtenEntities, diff.writtenValues);\n }\n\n /**\n * Snapshot what the world will look like once this commit projects.\n *\n * Committed components take the value the COMMIT wrote — a durable write\n * lands in the doc now and projects at the next `world.sync()`, so reading\n * the world here would snapshot the value being replaced and every echo\n * would then look like a real change. Everything else the behavior watches\n * is read from the world, where it is already current.\n */\n private captureEcho(\n entities: readonly Entity[],\n committed: ReadonlyMap<Entity, ReadonlyMap<Component, unknown>>,\n ): void {\n const watched: Component[] = [this.own, ...this.compiled.readComponents];\n this.echo = new Map();\n for (const e of entities) {\n const wrote = committed.get(e);\n const alive = world.isAlive(e);\n const cells: [Component, unknown][] = [];\n for (const c of watched) {\n const v = wrote?.get(c);\n cells.push([c, v !== undefined ? v : alive && world.has(e, c) ? world.get(e, c) : undefined]);\n }\n const tags: [Tag, boolean][] = [];\n for (const t of this.compiled.readTags) tags.push([t, alive && world.hasTag(e, t)]);\n this.echo.set(e, { cells, tags });\n }\n }\n\n /**\n * The door's transaction. `setResource` is MASKED — the §9 resource-write\n * fence made mechanical rather than doctrinal: `GuardedTx` structurally\n * carries it, so leaving it reachable would make the fence a comment.\n */\n private wrapTx(tx: GuardedTx): BehaviorTx<Record<string, unknown>> {\n const node = this;\n const wrapped = {\n ...tx,\n spawnPrefab: tx.spawnPrefab.bind(tx),\n spawn: tx.spawn.bind(tx),\n destroy: tx.destroy.bind(tx),\n addComponent: tx.addComponent.bind(tx),\n removeComponent: tx.removeComponent.bind(tx),\n edit: tx.edit.bind(tx),\n addTag: tx.addTag.bind(tx),\n removeTag: tx.removeTag.bind(tx),\n setRelation: tx.setRelation.bind(tx),\n addRelation: tx.addRelation.bind(tx),\n removeRelation: tx.removeRelation.bind(tx),\n moveRelation: tx.moveRelation.bind(tx),\n move: tx.move.bind(tx),\n setResource: () => {\n throw new Error(\n `ice: behavior \"${node.b.name}\" called tx.setResource — behaviors do not write resources (design-009 §4.4). A resource-backed behavior is the named \"singleton\" v1.1 shape.`,\n );\n },\n write(e: Entity, patch: Record<string, unknown>) {\n tx.edit(e).set(node.own as Component<unknown>, node.cellFor(e, patch));\n },\n attach(e: Entity, behavior: { component: unknown; defaults: unknown; name: string }, data?: Record<string, unknown>) {\n const other = behavior as unknown as AnyBehaviorDef;\n // An ephemeral behavior's component must never enter the DOCUMENT:\n // its facet lives in the presence partition, minted by the runtime\n // on the local peer only (I19 round's store-routing audit).\n if (other.store === \"ephemeral\") {\n throw new Error(\n `ice: behavior \"${node.b.name}\" called tx.attach(\"${other.name}\") — an ephemeral behavior's facet is presence data and cannot be attached into the document.`,\n );\n }\n const cell = cellForBehavior(world, other, e, data ?? {});\n // Attach-when-attached is an IDEMPOTENT no-op that preserves existing\n // data (§6) — expressed as a value write, which the differ then sees\n // as an ordinary value diff rather than a structural op.\n if (world.has(e, other.component as Component)) {\n tx.edit(e).set(other.component as Component<unknown>, cell);\n } else {\n tx.addComponent(e, other.component as Component<unknown>, cell);\n }\n },\n detach(e: Entity, behavior: AnyBehaviorDef) {\n if (behavior.store === \"ephemeral\") {\n throw new Error(\n `ice: behavior \"${node.b.name}\" called tx.detach(\"${behavior.name}\") — ephemeral facets are withdrawn by the runtime (I17) or the presence layer's tombstones, never through the document.`,\n );\n }\n tx.removeComponent(e, behavior.component as Component);\n },\n };\n return wrapped as unknown as BehaviorTx<Record<string, unknown>>;\n }\n\n status(): BehaviorStatus {\n let failed = 0;\n for (const inst of this.instances.values()) if (inst.failed) failed++;\n return {\n name: this.b.name,\n store: this.b.store,\n phase: this.b.phase,\n instances: this.instances.size,\n failed,\n ticking: this.b.on.tick === undefined ? 0 : this.instances.size - failed,\n suspended: this.guest.suspended(),\n quarantined: this.singletonQuarantined,\n };\n }\n }\n\n function orderedNodes(): Node[] {\n return [...nodes.values()].sort((left, right) => {\n if (left.orderKey !== undefined || right.orderKey !== undefined) {\n if (left.orderKey === undefined) return 1;\n if (right.orderKey === undefined) return -1;\n if (left.orderKey < right.orderKey) return -1;\n if (left.orderKey > right.orderKey) return 1;\n }\n return left.registrationSequence - right.registrationSequence;\n });\n }\n\n /**\n * Bring `inserted` into execution at its sorted position. The COMMON case —\n * the new node sorts last (every unkeyed registration; every host that\n * registers in ascending key order, which a manifest-ordered host does by\n * construction) — is a plain append: nobody else moves, so host systems\n * registered between behaviors keep their interleaved positions exactly as\n * under 0.6.0. Only a genuinely out-of-order keyed insert reinstalls the\n * SUFFIX (the nodes that must run after it); the untouched prefix keeps its\n * position relative to everything else in its phase groups (review\n * finding 3 — reordering is the documented cost of asking for a reorder,\n * never a tax on appending).\n */\n function reorderExecution(inserted: Node): void {\n const order = orderedNodes();\n const at = order.indexOf(inserted);\n if (at === order.length - 1) {\n inserted.installExecution();\n return;\n }\n for (let i = order.length - 1; i > at; i--) order[i]?.uninstallExecution();\n for (let i = at; i < order.length; i++) order[i]?.installExecution();\n }\n\n function safeParse(raw: string): unknown {\n try {\n return JSON.parse(raw);\n } catch {\n return undefined;\n }\n }\n\n return {\n register(b, options = {}) {\n if (\n options.orderKey !== undefined &&\n (typeof options.orderKey !== \"string\" || options.orderKey.length === 0)\n ) {\n throw new TypeError(\"ice: behavior registration orderKey must be a non-empty string\");\n }\n if (nodes.has(b.name)) {\n throw new Error(`ice: behavior \"${b.name}\" is already registered with this engine.`);\n }\n const node = new Node(b, options, nextRegistrationSequence++);\n nodes.set(b.name, node);\n node.install();\n reorderExecution(node);\n return () => {\n if (nodes.get(b.name) !== node) return;\n nodes.delete(b.name);\n node.uninstall();\n };\n },\n\n registered() {\n return orderedNodes().map((n) => n.b);\n },\n\n attach(e, b, data) {\n if (b.store === \"durable\") {\n throw new Error(\n `ice: engine.behaviors.attach(\"${b.name}\") — durable attachment is a DOCUMENT op: use tx.attach inside a transaction so it syncs and undoes.`,\n );\n }\n // An ephemeral instance IS the local presence peer (design-009 §4.4):\n // a world-write attach here would put the facet component on an\n // arbitrary entity, which `ctx.peers()` cannot tell from a projected\n // REMOTE facet — a local spoof that is never published and never\n // withdrawn, and a bypass of the I19 byte claim's two real mint paths.\n if (b.store === \"ephemeral\") {\n throw new Error(\n `ice: engine.behaviors.attach(\"${b.name}\") — an ephemeral behavior's facet is minted by the runtime on the local peer; it cannot be attached to an entity.`,\n );\n }\n const cell = cellForBehavior(world, b, e, data ?? {});\n if (world.has(e, b.component as Component)) world.edit(e).set(b.component as Component<unknown>, cell);\n else world.addComponent(e, b.component as Component<unknown>, cell);\n },\n\n detach(e, b) {\n if (b.store === \"durable\") {\n throw new Error(\n `ice: engine.behaviors.detach(\"${b.name}\") — durable detachment is a DOCUMENT op: use tx.detach inside a transaction.`,\n );\n }\n // Symmetric with attach: a world-write removal of a facet component\n // would silently delete a REMOTE peer's projected facet locally —\n // withdrawal is the runtime's (I17) and tombstones are the presence\n // layer's; neither goes through this surface.\n if (b.store === \"ephemeral\") {\n throw new Error(\n `ice: engine.behaviors.detach(\"${b.name}\") — ephemeral facets are withdrawn by the runtime (I17) or the presence layer's tombstones, never detached through the world.`,\n );\n }\n if (world.has(e, b.component as Component)) world.removeComponent(e, b.component as Component);\n },\n\n has: (e, b) => world.isAlive(e) && world.has(e, b.component as Component),\n\n read(e, b) {\n if (!world.isAlive(e) || !world.has(e, b.component as Component)) return undefined;\n const cell = world.get(e, b.component as Component) as Record<string, unknown> | undefined;\n if (cell === undefined) return undefined;\n for (const [f, spec] of Object.entries(b.schema)) {\n if ((spec as JsonSpec).kind !== \"json\") continue;\n const raw = cell[f];\n if (typeof raw === \"string\") cell[f] = safeParse(raw);\n }\n return cell;\n },\n\n list() {\n return orderedNodes().map((n) => n.status());\n },\n\n dispose() {\n stopResetWatch();\n for (const n of nodes.values()) n.uninstall();\n nodes.clear();\n // Uninstalls may have deferred withdrawals; the publish slot that would\n // flush them is not coming (the hook is about to go). Flush here — each\n // job guards and swallows for itself — then drop the hook.\n if (pendingWithdrawals.length > 0) {\n const jobs = pendingWithdrawals.splice(0, pendingWithdrawals.length);\n for (const job of jobs) job();\n }\n publishHookRemover?.();\n publishHookRemover = undefined;\n },\n };\n}\n","/**\n * The `derived` differ (design-009 §3, BF-D5) — M13c.\n *\n * A derived behavior recomputes from other state, so it re-writes the same\n * values constantly. Left alone that is a CRDT catastrophe: every frame of\n * churn becomes journal entries, undo steps, and wire bytes for values that did\n * not change. The differ makes a derived commit cost nothing when nothing moved.\n *\n * Three protections ride together, and they only make sense together:\n *\n * 1. **Value writes equal to the current projection are dropped.** Equality is\n * strata's OWN — `valueEquals`, the predicate reconcile itself judges\n * settlement by. A hand-rolled comparison WOULD drift on exactly the cells\n * reconcile considers settled (f32 fround, integer wrap, enum labels, ±0\n * collapse), which is the one place a differ must never disagree.\n * 2. **Structural ops are diffed too** — attach-when-attached falls through to\n * a value diff, detach-when-absent and destroy-when-dead are dropped, and\n * `spawn` under `derived` throws outright (a derived behavior that mints\n * entities has no convergent story; `tx.ensure` is the named seam).\n * Without this the differ was writable around: one structural op per frame\n * and the whole protection lapses.\n * 3. **Zero remaining ops opens NO transaction.** Not an empty one — none.\n *\n * The buffering this requires is not a cost, it is the enabler: `undoable` has\n * to be decided BEFORE the transaction opens, and whether a commit is derived\n * OUTPUT (never undoable — ⌘Z must not un-derive) or an authorial config edit\n * (ordinarily undoable) is only knowable once you have seen its ops.\n */\nimport { valueEquals } from \"@vibecook/strata-ecs\";\nimport type { Component, Entity, OrderPlace, Relation, Tag, World } from \"@vibecook/strata-ecs\";\nimport { Position } from \"../catalog\";\nimport type { GuardedTx } from \"../guards/guarded-tx\";\n\nexport type RecOp =\n | { readonly kind: \"set\"; readonly e: Entity; readonly c: Component; readonly v: unknown }\n | { readonly kind: \"add\"; readonly e: Entity; readonly c: Component; readonly v: unknown }\n | { readonly kind: \"removeComponent\"; readonly e: Entity; readonly c: Component }\n | { readonly kind: \"destroy\"; readonly e: Entity }\n | { readonly kind: \"addTag\"; readonly e: Entity; readonly t: Tag }\n | { readonly kind: \"removeTag\"; readonly e: Entity; readonly t: Tag }\n | { readonly kind: \"setRelation\"; readonly e: Entity; readonly r: Relation; readonly target: Entity; readonly place?: OrderPlace }\n | { readonly kind: \"addRelation\"; readonly e: Entity; readonly r: Relation; readonly target: Entity }\n | { readonly kind: \"removeRelation\"; readonly e: Entity; readonly r: Relation; readonly target?: Entity }\n | { readonly kind: \"moveRelation\"; readonly e: Entity; readonly r: Relation; readonly place: OrderPlace }\n | { readonly kind: \"move\"; readonly e: Entity; readonly to: { x: number; y: number }; readonly animateMs: number };\n\nexport interface DiffDeps {\n readonly world: World;\n /** The DOC's value for a cell — what a commit would actually be compared to. */\n docValue(e: Entity, c: Component): unknown;\n /** The behavior's declared `writes:` targets (the derived-output test). */\n readonly writeTargets: ReadonlySet<Component>;\n}\n\nexport interface DiffResult {\n readonly ops: readonly RecOp[];\n /**\n * The commit touches a declared `writes:` target — it is derived OUTPUT, so\n * it is forced non-undoable. A commit that only touches the behavior's OWN\n * data is an authorial config edit and keeps normal undo.\n */\n readonly derivedOutput: boolean;\n /** Entities this commit wrote — the next drain's subtraction set. */\n readonly writtenEntities: readonly Entity[];\n /**\n * The VALUES the surviving ops commit, per entity per component. The echo\n * snapshot needs these rather than a post-seal world read: a durable write\n * lands in the doc now but projects into the world at the NEXT `world.sync()`,\n * so reading the world here would capture the value the commit is replacing.\n */\n readonly writtenValues: ReadonlyMap<Entity, ReadonlyMap<Component, unknown>>;\n}\n\n/**\n * Record a DERIVED commit body's ops without performing any of them. Only the\n * derived path buffers: a plain durable behavior commits straight through, so\n * it keeps `tx.spawn` and pays no recording cost.\n */\nexport function recordDerivedOps(behaviorName: string, build: (rec: GuardedTx) => void): RecOp[] {\n const ops: RecOp[] = [];\n const refuseSpawn = (): never => {\n throw new Error(\n `ice: behavior \"${behaviorName}\" called tx.spawn under derived: true — a derived behavior may not spawn entities (design-009 §11). Its output must be a function of state that already exists; \\`tx.ensure(key, …)\\` is the named idempotent-spawn seam.`,\n );\n };\n const editor = (e: Entity) => {\n const chain = {\n set(c: Component, v: unknown) {\n ops.push({ kind: \"set\", e, c, v });\n return chain;\n },\n };\n return chain;\n };\n const rec = {\n spawnPrefab: refuseSpawn,\n spawn: refuseSpawn,\n destroy: (e: Entity) => ops.push({ kind: \"destroy\", e }),\n addComponent: (e: Entity, c: Component, v: unknown) => ops.push({ kind: \"add\", e, c, v }),\n removeComponent: (e: Entity, c: Component) => ops.push({ kind: \"removeComponent\", e, c }),\n edit: editor,\n addTag: (e: Entity, t: Tag) => ops.push({ kind: \"addTag\", e, t }),\n removeTag: (e: Entity, t: Tag) => ops.push({ kind: \"removeTag\", e, t }),\n setRelation: (e: Entity, r: Relation, target: Entity, place?: OrderPlace) =>\n ops.push({ kind: \"setRelation\", e, r, target, ...(place !== undefined ? { place } : {}) }),\n addRelation: (e: Entity, r: Relation, target: Entity) => ops.push({ kind: \"addRelation\", e, r, target }),\n removeRelation: (e: Entity, r: Relation, target?: Entity) =>\n ops.push({ kind: \"removeRelation\", e, r, ...(target !== undefined ? { target } : {}) }),\n moveRelation: (e: Entity, r: Relation, place: OrderPlace) => ops.push({ kind: \"moveRelation\", e, r, place }),\n setResource: () => {\n throw new Error(`ice: behavior \"${behaviorName}\" called tx.setResource — behaviors do not write resources.`);\n },\n move: (e: Entity, to: { x: number; y: number }, o?: { animateMs?: number }) =>\n ops.push({ kind: \"move\", e, to, animateMs: o?.animateMs ?? 0 }),\n };\n build(rec as unknown as GuardedTx);\n return ops;\n}\n\nexport function diffOps(ops: readonly RecOp[], deps: DiffDeps): DiffResult {\n const kept: RecOp[] = [];\n const written = new Set<Entity>();\n const values = new Map<Entity, Map<Component, unknown>>();\n const noteValue = (e: Entity, c: Component, v: unknown): void => {\n let byComponent = values.get(e);\n if (byComponent === undefined) {\n byComponent = new Map();\n values.set(e, byComponent);\n }\n byComponent.set(c, v);\n };\n let derivedOutput = false;\n\n for (const op of ops) {\n switch (op.kind) {\n case \"set\":\n case \"add\": {\n const current = deps.docValue(op.e, op.c);\n // `undefined` means CELL ABSENT — an add, never a no-op. Present and\n // canonically equal means the CRDT would stage nothing: drop it here so\n // no journal entry, no undo step and no wire bytes are produced either.\n if (current !== undefined && valueEquals(op.c, op.v, current)) continue;\n if (deps.writeTargets.has(op.c)) derivedOutput = true;\n written.add(op.e);\n noteValue(op.e, op.c, op.v);\n kept.push(op);\n break;\n }\n case \"removeComponent\": {\n if (!deps.world.isAlive(op.e) || !deps.world.has(op.e, op.c)) continue;\n if (deps.writeTargets.has(op.c)) derivedOutput = true;\n written.add(op.e);\n kept.push(op);\n break;\n }\n case \"destroy\": {\n if (!deps.world.isAlive(op.e)) continue;\n written.add(op.e);\n kept.push(op);\n break;\n }\n case \"addTag\": {\n if (deps.world.isAlive(op.e) && deps.world.hasTag(op.e, op.t)) continue;\n written.add(op.e);\n kept.push(op);\n break;\n }\n case \"removeTag\": {\n if (!deps.world.isAlive(op.e) || !deps.world.hasTag(op.e, op.t)) continue;\n written.add(op.e);\n kept.push(op);\n break;\n }\n case \"setRelation\": {\n // An edge already pointing at the same target with no reorder asked for\n // is the relation twin of a same-value write.\n if (op.place === undefined && deps.world.getRelation(op.e, op.r) === op.target) continue;\n written.add(op.e);\n kept.push(op);\n break;\n }\n case \"removeRelation\": {\n if (deps.world.getRelations(op.e, op.r).length === 0) continue;\n written.add(op.e);\n kept.push(op);\n break;\n }\n case \"move\": {\n // `move` IS diffed, and the reason it is safe to diff is petition I15's\n // two chokepoints. The worry was a glide in flight: drop the move and\n // the tween keeps easing toward a stale target. But every path that\n // moves the durable value — a post-seal write, an undo — already\n // retargets live tweens onto doc truth, so \"the doc already says `to`\"\n // means \"any live tween already aims at `to`\". There is nothing to\n // strand.\n //\n // Not diffing it was not a small conservatism: the flagship path\n // commits its whole layout through `move`, so an undiffed move meant\n // every peer that merely OPENED a laid-out document immediately wrote\n // the same layout back to it.\n const current = deps.docValue(op.e, Position as Component) as\n | { x: number; y: number }\n | undefined;\n if (current !== undefined && valueEquals(Position as Component, { x: op.to.x, y: op.to.y }, current)) {\n continue;\n }\n if (deps.writeTargets.has(Position as Component)) derivedOutput = true;\n noteValue(op.e, Position as Component, { x: op.to.x, y: op.to.y });\n written.add(op.e);\n kept.push(op);\n break;\n }\n default: {\n written.add(op.e);\n kept.push(op);\n break;\n }\n }\n }\n\n return { ops: kept, derivedOutput, writtenEntities: [...written], writtenValues: values };\n}\n\n/** Replay diffed ops onto the real transaction. */\nexport function replayOps(ops: readonly RecOp[], tx: GuardedTx): void {\n for (const op of ops) {\n switch (op.kind) {\n case \"set\":\n tx.edit(op.e).set(op.c as Component<unknown>, op.v);\n break;\n case \"add\":\n tx.addComponent(op.e, op.c as Component<unknown>, op.v);\n break;\n case \"removeComponent\":\n tx.removeComponent(op.e, op.c);\n break;\n case \"destroy\":\n tx.destroy(op.e);\n break;\n case \"addTag\":\n tx.addTag(op.e, op.t);\n break;\n case \"removeTag\":\n tx.removeTag(op.e, op.t);\n break;\n case \"setRelation\":\n tx.setRelation(op.e, op.r, op.target, op.place);\n break;\n case \"addRelation\":\n tx.addRelation(op.e, op.r, op.target);\n break;\n case \"removeRelation\":\n tx.removeRelation(op.e, op.r, op.target);\n break;\n case \"moveRelation\":\n tx.moveRelation(op.e, op.r, op.place);\n break;\n case \"move\":\n tx.move(op.e, op.to, { animateMs: op.animateMs });\n break;\n }\n }\n}\n","/**\n * `ctx.world` and `ctx.query` — the behavior read surface (design-009 §4.4,\n * BF-D19).\n *\n * `ctx.world` is a HOST-BUILT WRAPPER and that is a decision, not an\n * implementation shortcut. The obvious alternative — hand authors strata's\n * `ReadonlyWorld` — is not a sandbox: it is `Omit<World, WorldMutatorName>`,\n * which keeps `.runtime` (the full mutable store) and, being a type, erases at\n * runtime anyway. A wrapper object exposes exactly what it forwards.\n *\n * `ctx.query` closes the DISCOVERY hole. Without it a behavior could navigate\n * only outward from its own instances, and `changed` got abused as a discovery\n * channel — a journal is a terrible search index. Scoping the terms to the\n * declared `reads` keeps the access story honest, and walking through the\n * running system's `SystemCtx` means the walk is ATTRIBUTED: strata's only\n * ENFORCED read path and its only zero-allocation bulk path. Three arguments,\n * one mechanism.\n */\nimport { Not, defineQuery } from \"@vibecook/strata-ecs\";\nimport type { Component, Entity, Query, Relation, Resource, SystemCtx, Tag, World } from \"@vibecook/strata-ecs\";\nimport { devGuardsEnabled } from \"../guards/dev\";\nimport { schemaMeta } from \"../schema/meta\";\nimport type { AnyBehaviorDef, BehaviorQuery, BehaviorQuerySpec, BehaviorWorld } from \"./types\";\n\nexport function createBehaviorWorld(world: World): BehaviorWorld {\n return {\n read: (e, c) => world.read(e, c),\n get: (e, c) => world.get(e, c),\n readField: (e, c, f) => world.readField(e, c, f),\n has: (e, c) => world.has(e, c),\n hasTag: (e, t) => world.hasTag(e, t),\n getRelation: (e, r) => world.getRelation(e, r),\n getRelations: (e, r) => world.getRelations(e, r),\n getReverse: (e, r) => world.getReverse(e, r),\n orderStamp: (parent, r) => world.orderStamp(parent, r),\n getResource: (res) => world.getResource(res),\n componentsOf: (e) => world.componentsOf(e),\n tagsOf: (e) => world.tagsOf(e),\n isAlive: (e) => world.isAlive(e),\n };\n}\n\n/** Resolve a query term to its underlying handle (a behavior means its component). */\nfunction termOf(t: Component | Tag | AnyBehaviorDef): Component | Tag {\n if (typeof t === \"object\" && t !== null && (t as AnyBehaviorDef).__behavior === true) {\n return (t as AnyBehaviorDef).component as Component;\n }\n return t as Component | Tag;\n}\n\nfunction termName(t: Component | Tag): string {\n return schemaMeta.component(t as Component)?.name ?? schemaMeta.tagName(t as Tag) ?? \"<handle>\";\n}\n\n/**\n * The compiled-query cache for one behavior. Keyed on the term identity list,\n * so the common case (a behavior calling `ctx.query` with the same spec every\n * frame) compiles ONCE — `defineQuery` identity is strata's own cache key for\n * the matched-archetype list, so re-compiling per call would defeat two caches.\n */\nexport function createQueryScope(behavior: AnyBehaviorDef, allowed: ReadonlySet<Component | Tag>) {\n const cache = new Map<string, Query>();\n let nextId = 0;\n const ids = new Map<Component | Tag, number>();\n const idOf = (t: Component | Tag): number => {\n let id = ids.get(t);\n if (id === undefined) {\n id = nextId++;\n ids.set(t, id);\n }\n return id;\n };\n\n const check = (t: Component | Tag): void => {\n if (!devGuardsEnabled() || allowed.has(t)) return;\n throw new Error(\n `ice: behavior \"${behavior.name}\" queried \"${termName(t)}\", which is not in its reads: — a behavior may only query what it declared (design-009 §4.4). Add it to reads:, or navigate from ctx.entities() instead.`,\n );\n };\n\n const compile = (spec: BehaviorQuerySpec): Query => {\n const all = (spec.all ?? []).map(termOf);\n const none = (spec.none ?? []).map(termOf);\n for (const t of all) check(t);\n for (const t of none) check(t);\n const key = `${all.map(idOf).join(\",\")}|${none.map(idOf).join(\",\")}`;\n let q = cache.get(key);\n if (q === undefined) {\n q = defineQuery([...all, ...none.map((t) => Not(t))]);\n cache.set(key, q);\n }\n return q;\n };\n\n /** Build the per-call query handle bound to the current walker. */\n return function scopedQuery(walker: BehaviorWalker, spec: BehaviorQuerySpec): BehaviorQuery {\n const q = compile(spec);\n return {\n entities() {\n const out: Entity[] = [];\n walker.each(q, (e) => out.push(e));\n return out;\n },\n each(fn) {\n walker.each(q, fn);\n },\n first() {\n return walker.first(q);\n },\n };\n };\n}\n\n/**\n * Where a behavior's walks and structural ops go, which depends on WHERE it is\n * running — and the difference is not cosmetic.\n *\n * In a pipeline phase the behavior is inside a system: walks go through\n * `SystemCtx` (attributed — strata's enforced read path), and structural ops\n * are DEFERRED to the phase boundary because immediate `world.*` structural\n * mutation throws at iteration depth > 0.\n *\n * At the publish slot there is no running system and no iteration bracket:\n * walks are plain `world.query` (unattributed — nothing to attribute them to),\n * and structural ops are immediate and legal. Ephemeral behaviors live here,\n * which is exactly why eph structural writes are legal for them and illegal\n * for everyone else.\n */\nexport interface BehaviorWalker {\n each(q: Query, fn: (e: Entity) => void): void;\n first(q: Query): Entity | undefined;\n addComponent(e: Entity, c: Component, v: unknown): void;\n removeComponent(e: Entity, c: Component): void;\n}\n\nexport function systemWalker(ctx: SystemCtx): BehaviorWalker {\n return {\n each(q, fn) {\n ctx.query(q).each((b) => {\n for (const row of b) fn(b.entity(row));\n });\n },\n first: (q) => ctx.firstOf(q),\n addComponent: (e, c, v) => ctx.addComponent(e, c as Component<unknown>, v),\n removeComponent: (e, c) => ctx.removeComponent(e, c),\n };\n}\n\nexport function publishWalker(world: World): BehaviorWalker {\n return {\n each(q, fn) {\n world.query(q).each((b) => {\n for (const row of b) fn(b.entity(row));\n });\n },\n first: (q) => world.firstOf(q),\n addComponent: (e, c, v) => world.addComponent(e, c as Component<unknown>, v),\n removeComponent: (e, c) => world.removeComponent(e, c),\n };\n}\n\n/** The term set a behavior may query: its own component ∪ declared components/tags. */\nexport function allowedQueryTerms(\n behavior: AnyBehaviorDef,\n readComponents: readonly Component[],\n readTags: readonly Tag[],\n): ReadonlySet<Component | Tag> {\n const set = new Set<Component | Tag>([behavior.component as Component]);\n for (const c of readComponents) set.add(c);\n for (const t of readTags) set.add(t);\n return set;\n}\n\nexport type { Relation, Resource };\n","/**\n * The commit seam (design-001 §3 gesture protocol × implementation-plan M4/M5).\n *\n * Behaviors end a gesture with ONE commit (design-002 decision 4). Until the\n * durable layer lands (M5), commits are recorded as INTENTS through this seam:\n * the M4 frame traces assert runtime state + commit intents, and M5 swaps in a\n * doc-backed sink that turns an intent into one `guardedTransaction` per\n * gesture (liveness guards re-checked inside the tx via live edges + keyOf —\n * the intent carries the already-liveness-filtered write set, but the doc sink\n * re-guards because the doc is the authority).\n *\n * The seam is deliberately dumb data: no callbacks into behaviors, no partial\n * application — a whole gesture outcome in one value.\n */\nimport type { Component, Entity, OrderPlace } from \"@vibecook/strata-ecs\";\n\n/** One absolute component write inside a commit (whole-value, design-001 §2). */\nexport interface CommitWrite {\n readonly entity: Entity;\n // biome-ignore lint/suspicious/noExplicitAny: heterogeneous write list; the value is validated against the component schema at apply time\n readonly component: Component<any>;\n readonly value: Record<string, unknown>;\n}\n\n/** A structural reparent riding a consume outcome (design-003 §5.5). */\nexport interface CommitReparent {\n readonly entity: Entity;\n readonly container: Entity;\n}\n\n/**\n * An ordered-relation placement riding a commit (petition 8): the gesture's\n * final sibling position lands IN the gesture's single transaction — one\n * gesture stays one undo step. `parent` is re-asserted absolutely (a\n * same-target `setRelation` WITH a place is a move, never a duplicate).\n */\nexport interface CommitOrder {\n readonly entity: Entity;\n readonly parent: Entity;\n readonly place: OrderPlace;\n}\n\n/**\n * A wire creation riding a connect outcome (design-003 §5.8; design-001\n * §5.3): wires bind WIDGET entities + port IDS — never port entities.\n */\nexport interface CommitWireSpawn {\n readonly from: Entity;\n readonly to: Entity;\n readonly fromPort: string;\n readonly toPort: string;\n}\n\n/**\n * A widget creation riding a create outcome (draw tool, design-005 §3;\n * tray-insert promote, 2026-07-19). `props`/`parent` extend the draw shape for\n * ghost promotes: prop overrides rebuild the tray instance, `parent` lands a\n * consume-into-container insert (x/y are container-LOCAL then, matching the\n * reparent convention). `select` asks the sink to hand the projected twin to\n * the reap system's selection transfer — the tray's select-on-drop.\n */\nexport interface CommitCreate {\n readonly type: string;\n readonly x: number;\n readonly y: number;\n readonly w: number;\n readonly h: number;\n readonly props?: Readonly<Record<string, unknown>>;\n readonly parent?: Entity;\n readonly select?: boolean;\n /** Where the widget joins its parent's sibling sequence (default: last — on top). An ⌥-drag's copy goes `{ before: original }` (D4a). */\n readonly order?: OrderPlace;\n}\n\n/** Generation key captured by an interactive commit before final validation. */\nexport interface CommitScope {\n readonly documentEpoch: number;\n readonly canvasEpoch: 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 orders?: readonly CommitOrder[];\n readonly wires?: readonly CommitWireSpawn[];\n readonly creates?: readonly CommitCreate[];\n readonly scope?: CommitScope;\n}\n\nexport interface CommitSink {\n /** `false` asks gesture behavior to restore/fly back its runtime draft. */\n // biome-ignore lint/suspicious/noConfusingVoidType: legacy observer sinks intentionally return nothing.\n commit(intent: CommitIntent): boolean | void;\n}\n\n/** The M4 default: record intents for traces/devtools; commit nothing. */\nexport function createRecordingCommitSink(): CommitSink & { readonly intents: CommitIntent[] } {\n const intents: CommitIntent[] = [];\n return {\n intents,\n commit(intent) {\n intents.push(intent);\n },\n };\n}\n","/**\n * The input queue — the ONE input path's front door (Law 2, design-003 §2).\n *\n * Adapters (DOM pointer/wheel/keyboard, R3F router verdicts, test drivers) ONLY\n * enqueue normalized {@link InputEvent}s; `pointerIngest` drains the queue once\n * per tick and turns events into world facts. Handlers run mid-frame at\n * arbitrary times — the queue is what keeps every world write inside the frame\n * contract (design-002 §3). It is pre-ingest TRANSPORT, not world state: no\n * system reads it, nothing observes it, and it holds nothing across a drain but\n * the tail ingest hands back — the events past a pointer's transition, which\n * are the next tick's facts (l0-input.ts, the fold's cut).\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\n/**\n * `leave` (petition I42): the pointer left the host with nowhere to go — out of the window, no press of its own live — at its last\n * point; ingest tags it `PointerOutside` until its next fact of any other kind.\n */\nexport type InputEventKind = \"down\" | \"move\" | \"up\" | \"cancel\" | \"wheel\" | \"key\" | \"leave\";\n\nexport interface InputMods {\n readonly shift: boolean;\n readonly ctrl: boolean;\n readonly alt: boolean;\n readonly meta: boolean;\n /** Space-held (pan gesture modifier, design-003 §4.4) — not a PointerMods field. */\n readonly space: boolean;\n}\n\nexport interface InputEvent {\n readonly kind: InputEventKind;\n /** Stable adapter pointer id (\"mouse\" | \"touch:<n>\" | \"pen\"). Empty for kind:\"key\". */\n readonly pointerId: string;\n readonly device: \"mouse\" | \"touch\" | \"pen\";\n /** Canvas-container-relative CSS px (the kernel screen space). */\n readonly screenX: number;\n readonly screenY: number;\n /** Button bitmask as of this event (PointerEvent.buttons semantics). */\n readonly buttons: number;\n readonly mods: InputMods;\n /** Wheel deltas for kind:\"wheel\" (`pinch` = ctrl-wheel / trackpad zoom signal). */\n readonly wheel?: { readonly dx: number; readonly dy: number; readonly pinch: number };\n /** GL-island opt-out (pinned widget-event contract, design-002 §8): fact still lands, recognizers skip. */\n readonly surfaceHandled?: boolean;\n /**\n * Wheel-only opt-out (design-007 §3.5, petition I4): this wheel's deltas were\n * ceded to scrollable widget content — the adapter skipped `preventDefault`\n * and native scroll consumed them. The fact still lands (one input path);\n * ingest stamps the one-tick `WheelHandled` tag so the wheel recognizers skip\n * the tick. DISTINCT from `surfaceHandled` on purpose: the shared latch on\n * the persistent mouse pointer would collide with a same-tick canvas down.\n */\n readonly wheelHandled?: boolean;\n /**\n * Hover-time widget-boundary fact (design-002 §8 amendment, 2026-07-18): the\n * pointer is currently over content that would opt a down out — a native\n * interactive / `[data-canvas-interactive]` (DOM) or claim-capable island\n * content (GL). Stamped on down/move by adapters that track it; ABSENT means\n * \"no hover information this event\" (wheel, key, blur-cancel) — ingest keeps\n * the pointer's `OverInteractive` tag unchanged, it never treats absent as\n * false. Presentation-grade truth (cursor affordances), never a gesture gate:\n * recognizers keep reading `surfaceHandled`/`HandledByWidget` only.\n */\n readonly overInteractive?: boolean;\n /**\n * Event timestamp (DOMHighResTimeStamp — the same clock rAF hands\n * `engine.step`). Gesture timing anchors on THIS, not the processing frame:\n * a stalled main thread (GC, cold paints) otherwise eats into hold windows —\n * a 640 ms stall at pointerdown made long-press unreachable (2026-07-12\n * field debugging). Absent ⇒ the processing frame's now.\n */\n readonly tMs?: number;\n}\n\nexport const NO_MODS: InputMods = { shift: false, ctrl: false, alt: false, meta: false, space: false };\n\nexport interface InputQueue {\n enqueue(event: InputEvent): void;\n /** Drain in arrival order. Called ONLY by `pointerIngest`, once per tick. */\n drain(): readonly InputEvent[];\n /** Events waiting (telemetry/tests). */\n size(): number;\n}\n\nexport function createInputQueue(): InputQueue {\n let buffer: InputEvent[] = [];\n return {\n enqueue(event) {\n buffer.push(event);\n },\n drain() {\n const drained = buffer;\n buffer = [];\n return drained;\n },\n size() {\n return buffer.length;\n },\n };\n}\n","/**\n * 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","/** Shared portal geometry and frame-arrival view resolution. */\nimport type { Entity, World } from \"@vibecook/strata-ecs\";\nimport { fitCamera, type CameraState } from \"@ice/kernel\";\nimport {\n CameraLimits,\n Position,\n Size,\n Viewport,\n} from \"../catalog\";\nimport { ChildOf } from \"../catalog/scene\";\nimport { CAMERA_DEFAULTS, FIT_DEFAULTS } from \"../settings/defaults\";\nimport type { CanvasType } from \"./define-canvas-type\";\nimport type { WidgetContainerEntry } from \"../widget/define-widget\";\n\nexport interface CanvasRect {\n readonly x: number;\n readonly y: number;\n readonly width: number;\n readonly height: number;\n}\n\nexport interface ResolvedPortal {\n readonly local: CanvasRect;\n readonly parent: CanvasRect;\n /** False means authored insets were invalid at the effective instance size. */\n readonly authored: boolean;\n}\n\nexport interface ResolvedFrameView {\n readonly bounds: CanvasRect;\n readonly camera: CameraState;\n readonly totalChildren: number;\n}\n\nexport interface FrameChildrenOpts {\n /** When supplied, malformed descendants inherit the nearest container frame. */\n readonly isContainer?: (entity: Entity) => boolean;\n}\n\nfunction effectiveSize(world: World, entity: Entity): { w: number; h: number } | undefined {\n return world.get(entity, Size);\n}\n\n/**\n * Converged effective frame order. Without a container predicate this is the\n * ordinary direct sequence. Compatibility callers supply the engine-scoped\n * predicate to include malformed descendants and stop at nested frames.\n */\nexport function resolveFrameChildren(\n world: World,\n frame: Entity,\n opts: FrameChildrenOpts = {},\n): readonly Entity[] {\n if (!world.isAlive(frame)) return Object.freeze([]);\n const direct = world.getReverse(frame, ChildOf).filter((entity) => world.isAlive(entity));\n if (opts.isContainer === undefined) return Object.freeze(direct);\n const result: Entity[] = [];\n const seen = new Set<Entity>([frame]);\n const pending = [...direct].reverse();\n while (pending.length > 0) {\n const child = pending.pop() as Entity;\n if (seen.has(child)) continue;\n seen.add(child);\n result.push(child);\n if (opts.isContainer(child)) continue;\n const descendants = world\n .getReverse(child, ChildOf)\n .filter((entity) => world.isAlive(entity));\n for (let index = descendants.length - 1; index >= 0; index -= 1) {\n pending.push(descendants[index] as Entity);\n }\n }\n return Object.freeze(result);\n}\n\n/** One source for preview clipping and navigation/transition portal math. */\nexport function resolvePortal(\n world: World,\n container: Entity,\n binding: WidgetContainerEntry | undefined,\n): ResolvedPortal | undefined {\n const position = world.get(container, Position);\n const size = effectiveSize(world, container);\n if (position === undefined || size === undefined || size.w <= 0 || size.h <= 0) return undefined;\n const portal = binding?.portal ?? { top: 0, right: 0, bottom: 0, left: 0 };\n const width = size.w - portal.left - portal.right;\n const height = size.h - portal.top - portal.bottom;\n const authored =\n [portal.top, portal.right, portal.bottom, portal.left].every(\n (value) => Number.isFinite(value) && value >= 0,\n ) &&\n width > 0 &&\n height > 0;\n const local: CanvasRect = authored\n ? { x: portal.left, y: portal.top, width, height }\n : { x: 0, y: 0, width: size.w, height: size.h };\n return {\n local,\n parent: {\n x: position.x + local.x,\n y: position.y + local.y,\n width: local.width,\n height: local.height,\n },\n authored,\n };\n}\n\n/** One source for arrival camera and semantic preview projection. */\nexport function resolveFrameView(\n world: World,\n frame: Entity,\n canvas: CanvasType | undefined,\n opts: FrameChildrenOpts = {},\n): ResolvedFrameView {\n const limits = world.getResource(CameraLimits) ?? CAMERA_DEFAULTS;\n const cameraPolicy = canvas?.presentation?.camera;\n const requestedMin = cameraPolicy?.minZoom ?? FIT_DEFAULTS.minZoom;\n const requestedMax = cameraPolicy?.maxZoom ?? FIT_DEFAULTS.maxZoom;\n const minZoom = Math.min(Math.max(requestedMin, limits.minZoom), limits.maxZoom);\n const maxZoom = Math.max(Math.min(requestedMax, limits.maxZoom), limits.minZoom);\n const identity: CameraState = {\n x: 0,\n y: 0,\n zoom: Math.min(maxZoom, Math.max(minZoom, 1)),\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 totalChildren = 0;\n for (const child of resolveFrameChildren(world, frame, opts)) {\n totalChildren += 1;\n const position = world.get(child, Position);\n const size = effectiveSize(world, child);\n if (position === undefined || size === undefined) continue;\n minX = Math.min(minX, position.x);\n minY = Math.min(minY, position.y);\n maxX = Math.max(maxX, position.x + size.w);\n maxY = Math.max(maxY, position.y + size.h);\n }\n const hasBounds = Number.isFinite(minX);\n const bounds: CanvasRect = hasBounds\n ? { x: minX, y: minY, width: maxX - minX, height: maxY - minY }\n : { x: 0, y: 0, width: 0, height: 0 };\n const viewport = world.getResource(Viewport);\n if (\n cameraPolicy?.arrival === \"identity\" ||\n !hasBounds ||\n viewport === undefined ||\n viewport.w <= 0 ||\n viewport.h <= 0\n ) {\n return { bounds, camera: identity, totalChildren };\n }\n return {\n bounds,\n camera: fitCamera(bounds, viewport.w, viewport.h, {\n pad: cameraPolicy?.padding ?? FIT_DEFAULTS.pad,\n minZoom,\n maxZoom,\n }),\n totalChildren,\n };\n}\n","/**\n * The NAV GEOMETRY seam (design-015 §9; D2b) — the renderer as the authority on its\n * containers' DRAWN geometry, exactly as it is on picking (`framePick`, design-014 B3b).\n *\n * The cut is exact only on the face AS DRAWN. The desk resolves a mini mat's face through\n * its springs (a hover's rise, a hold's lift) and draws the live inside under the camera that\n * face implies; a flight that starts from the container's STATIC rect starts a different face\n * whenever a spring is not at rest, and the cut jumps. So the interaction stack carries a\n * second slot beside `framePick`: `navGeometry.current`, which the renderer fills at mount\n * and clears at dispose, and which core's nav — `enterContainer`/`exitTo`, the zoom-through,\n * the drop-into's affine — asks first. The answer is one `NavFace`: the face in the parent\n * frame's units, the inside's arrival camera, the embedding `M` (inside → parent), the camera\n * the inside renders under at the host camera (the enter cut's exact `c0`), the gate's answer\n * and \"does the face cover the viewport\". Core's own computation — the static portal rect\n * through `resolvePortal`, the arrival through `resolveFrameView`, a sharp-cornered cover\n * test — stays the FALLBACK for every app that mounts no renderer with a word on it\n * (`resolveNavFace` below), so nothing an existing app does changes.\n *\n * Two facts ride here as well, both one-writer and one-tick:\n * - `NavIntent` — a nav op requested from INSIDE the tick (the double-tap gesture, the\n * zoom-through), which the facade applies right after `engine.step` (ops are structural —\n * `world.spawn`, tag writes, the index rebuild — and illegal mid-tick). The frame in between\n * is drawn under the old camera; for the zoom-through that frame IS the covering face, the\n * same pixels the cut then shows.\n * - `NavRedress` — a zoom-through cut left a desk DRESSED for another zoom (design-015 §9,\n * PORTAL.md §9): `kind: \"in\"` = the desk entered is dressed for its arrival (`from`) and\n * re-dresses to the camera's zoom; `\"out\"` = the desk left — now a live inside of `frame` —\n * is dressed for the camera it was cut at (`from`) and re-dresses to its arrival. The\n * renderer eases over its own ramp (320 ms, log space) and hands the lamp over on the same\n * ramp; core states the fact and nothing else.\n */\nimport { field, enumOf } from \"@vibecook/strata-ecs\";\nimport type { Entity, World } from \"@vibecook/strata-ecs\";\nimport { type CameraState, outgoingCamera, type PortalAffine, portalAffine, visibleRect } from \"@ice/kernel\";\nimport { Viewport } from \"../catalog/camera-derived\";\nimport { ZoomThroughSettings } from \"../catalog/settings-resources\";\nimport { engineCatalogFor, widgetTypeFor } from \"../canvas/engine-catalog\";\nimport { type CanvasRect, resolveFrameView, resolvePortal } from \"../canvas/frame-view\";\nimport { defineResource } from \"../schema/meta\";\nimport { PrefabId } from \"../schema/prefab\";\nimport { ZOOM_THROUGH_DEFAULTS } from \"../settings/defaults\";\n\n/** A container's face and its inside's embedding, under one host camera. */\nexport interface NavFace {\n /** The FACE — the portal rect — in the parent frame's world units, as drawn this frame (springs included) or at rest. */\n readonly face: CanvasRect;\n /** The inside's arrival camera: what its lattice is dressed for and what a flight lands on. */\n readonly arrival: CameraState;\n /** The embedding `M`: inside → parent (`portalAffine(visibleRect(arrival), face)`), the flight's own. */\n readonly affine: PortalAffine;\n /** The camera the inside renders under at the host camera — the enter cut's exact `c0` (`outgoingCamera(M, cam)`). */\n readonly camera: CameraState;\n /** The gate's answer at the host camera, 0..1: 0 = the far LOD alone, 1 = the live inside whole. */\n readonly presence: number;\n /** Does the face cover the whole viewport at the host camera by `marginPx` CSS px (negative: it may poke out by that much)? */\n covers(marginPx: number): boolean;\n}\n\n/** What a renderer with a word on its containers' geometry answers. */\nexport interface NavGeometrySource {\n /**\n * The container's face under the host camera `cam`: as DRAWN when the container is in the current\n * frame, at REST when it is not (the current frame's own container, an exit's); `undefined` = no\n * word — core computes from the static rect.\n */\n face(container: Entity, cam: CameraState): NavFace | undefined;\n}\n\n/** The stack's slot for the nav geometry source — a mutable box beside `framePick`, so the renderer can arrive after install. */\nexport interface NavGeometrySlot { current: NavGeometrySource | null }\n\n/** Smooth at both ends; exactly 0 below `a` and 1 above `b`. */\nexport const smoothstep = (a: number, b: number, x: number): number => {\n const t = Math.min(1, Math.max(0, (x - a) / (b - a)));\n return t * t * (3 - 2 * t);\n};\n\n/**\n * The DEFAULT arrival camera for a frame (design-006 as amended; nested-canvas's rule): kernel\n * `fitCamera` over its direct content, capped into the natural band (FIT_DEFAULTS ∩ the\n * session's CameraLimits ∩ the canvas type's camera policy); identity when empty or headless.\n */\nexport function defaultArrivalCamera(world: World, frame: Entity, isContainer?: (e: Entity) => boolean): CameraState {\n const frameTypeId = world.get(frame, PrefabId)?.id;\n const canvas = typeof frameTypeId === \"string\" ? engineCatalogFor(world)?.canvasForContainer(frameTypeId) : undefined;\n return resolveFrameView(world, frame, canvas, isContainer === undefined ? {} : { isContainer }).camera;\n}\n\n/** The container's STATIC face: its body rect through its `portal` insets, parent-frame units (`resolvePortal`). */\nexport function staticFace(world: World, container: Entity): CanvasRect | undefined {\n const typeId = world.get(container, PrefabId)?.id;\n const binding = typeof typeId === \"string\" ? widgetTypeFor(world, typeId)?.container : undefined;\n return resolvePortal(world, container, binding)?.parent;\n}\n\n/** The gate the fallback measures presence by: the live settings', else the defaults'. */\nfunction gateOf(world: World): readonly [number, number] {\n const zt = world.getResource(ZoomThroughSettings);\n return zt === undefined ? ZOOM_THROUGH_DEFAULTS.gate : [zt.gate0, zt.gate1];\n}\n\n/**\n * A `NavFace` from the STATIC geometry — core's own word when no renderer has one: the face is\n * the portal rect, the arrival `defaultArrivalCamera`'s, the cover test sharp-cornered (the\n * desk's mini mat's face has square corners too — its face law's `radius` 0, K8a — so the two agree where both answer).\n */\nexport function fallbackNavFace(world: World, container: Entity, cam: CameraState, opts: { readonly face?: CanvasRect; readonly arrival?: CameraState; readonly isContainer?: (e: Entity) => boolean } = {}): NavFace | undefined {\n const face = opts.face ?? staticFace(world, container);\n if (face === undefined || !(face.width > 0) || !(face.height > 0)) return undefined;\n const vp = world.getResource(Viewport);\n const w = vp?.w ?? 0;\n const h = vp?.h ?? 0;\n const arrival = opts.arrival ?? defaultArrivalCamera(world, container, opts.isContainer);\n const affine = portalAffine(visibleRect(arrival, w, h), face);\n const [g0, g1] = gateOf(world);\n const short = Math.min(face.width, face.height) * cam.zoom;\n return {\n face,\n arrival,\n affine,\n camera: outgoingCamera(affine, cam),\n presence: smoothstep(g0, g1, short),\n covers(marginPx) {\n if (w <= 0 || h <= 0) return false;\n const x0 = (face.x - cam.x) * cam.zoom;\n const y0 = (face.y - cam.y) * cam.zoom;\n const x1 = x0 + face.width * cam.zoom;\n const y1 = y0 + face.height * cam.zoom;\n return x0 <= -marginPx && y0 <= -marginPx && x1 >= w + marginPx && y1 >= h + marginPx;\n },\n };\n}\n\n/**\n * THE one door core's nav reads a container's face through: the renderer's word when a source is\n * mounted and answers, else the fallback. `overrides` are an op's own numbers (`NavOpts.face` /\n * `.arrival`), which outrank both.\n */\nexport function resolveNavFace(world: World, container: Entity, cam: CameraState, slot: NavGeometrySlot | undefined, overrides: { readonly face?: CanvasRect; readonly arrival?: CameraState; readonly isContainer?: (e: Entity) => boolean } = {}): NavFace | undefined {\n const source = slot?.current ?? null;\n if (source !== null && overrides.face === undefined && overrides.arrival === undefined) {\n const drawn = source.face(container, cam);\n if (drawn !== undefined) return drawn;\n }\n return fallbackNavFace(world, container, cam, overrides);\n}\n\n/**\n * A nav op asked for from INSIDE the tick — by the double-tap gesture (`navTap`) or the\n * zoom-through — for the facade to apply once the tick is over. `epoch` bumps per request;\n * `transition` is the op's (a `\"cut\"` states `NavRedress` itself). `target` is the container to\n * enter (unused on exit).\n */\nexport const NavIntent = defineResource(\n \"NavIntent\",\n {\n kind: field(enumOf([\"enter\", \"exit\"]), { default: \"enter\" }),\n target: field(\"eid\", { default: 0 as Entity }),\n transition: field(enumOf([\"zoom\", \"none\", \"cut\"]), { default: \"zoom\" }),\n source: field(enumOf([\"tap\", \"through\"]), { default: \"tap\" }),\n epoch: field(\"u32\", { default: 0 }),\n },\n { durable: false },\n);\n\n/**\n * A zoom-through cut left a desk dressed for another zoom (design-015 §9): `in` — the desk\n * entered was dressed for its arrival (`from`) as a face and re-dresses to the camera's zoom;\n * `out` — the desk left, now the live inside of `frame`, was dressed for the camera it was cut\n * at (`from`) and re-dresses to its arrival. Stated by the nav ops on every `transition: \"cut\"`\n * (one writer); the renderer eases; `epoch` bumps per cut.\n */\nexport const NavRedress = defineResource(\n \"NavRedress\",\n {\n kind: field(enumOf([\"in\", \"out\"]), { default: \"in\" }),\n from: field(\"f64\", { default: 1 }),\n /** The container whose desk re-dresses: the one entered (`in`), the one left (`out`). */\n frame: field(\"eid\", { default: 0 as Entity }),\n epoch: field(\"u32\", { default: 0 }),\n },\n { durable: false },\n);\n","/**\n * Nested canvas (design-004 §7 rev 2 — \"the missing systems\"; design-001\n * §5.7/§5.8 catalog).\n *\n * - `Active` = derived membership tag: a widget is Active iff the FIRST\n * container ancestor on its `ChildOf` chain is the current nav frame\n * (at root: no container ancestor at all). Children of a deeper container\n * are that container's content — not Active until you enter it.\n * - `activeMembership` (derive tick, before cull): recomputes membership and\n * flips Active/Visible/Culled CHANGE-ONLY, gated per design-004 §7\n * (`runIf: nav-change ∨ ChildOf churn`) as a drain-and-early-return tick\n * body — the spatialSync shape (petition 7 ChangeCollector; a `runIf`\n * cannot drain, and this system declares no writes so an early-out\n * blanket-stamps nothing). Idle frames cost one drain + one nav compare.\n * Full resweeps run on seed / reset / coarse / NAV CHANGE / container\n * despawn; everything else is delta-driven: a journaled entity whose\n * membership INPUTS (ChildOf edge, Container-ness) are unchanged is\n * skipped (drag frames journal Position every tick — O(1) each), a real\n * reparent/container-flip reclassifies its re-anchored subtree.\n * MEMBERSHIP-CHURN SIGNAL (why Position is the reparent proxy): relations\n * are not collector-journalable (strata CollectOptions = components +\n * tags), but coordinates are FRAME-LOCAL (design-001 §5.1) — a reparent\n * that does not rewrite Position into the new frame's space is already a\n * bug, and every real path co-writes: the doc sink commits reparent +\n * Position in ONE tx (doc-commit-sink.ts), and undo/redo/remote imports\n * project both rows of that tx. A bare runtime `world.setRelation(e,\n * ChildOf, …)` with no Position write on a pre-existing entity is OUTSIDE\n * the contract and goes stale until the next resweep.\n * THE SELECTION IS SCOPED HERE (design-011 §6/§16 `Selected ⇒ Active`,\n * 2026-09-26): a widget classified OUT of the frame loses `Selected` in the\n * same flush — a drop into a mini mat, a peer's reparent, an undo or a redo\n * that carries it away. The collector journals `Selected` too, so a\n * selection written onto a standing non-member (the undo stack's selection\n * restore of a stale key, an app's raw write) is dropped the next tick.\n * Found at D4a's landing: a note dropped into a mini mat stayed selected\n * inside it — no marks, no menu, but reachable by every consumer that does\n * not filter by membership (the nudge, the tape, a drag of the rest).\n * - Nav stack = SESSION entities: `NavEntry` rows carry NavDepth + NavCamera\n * (the camera to restore on exit) + NavFrame(entry→container). Root =\n * empty stack. Current frame = deepest live entry's NavFrame target.\n * - `enterContainer`/`exitContainer` ops own the SPATIAL INDEX REBUILD:\n * membership flips don't move Transforms, so the incremental spatialSync\n * cache never fires on nav — the ops clear the index + caches and bump\n * `SpatialVersion`; spatialSync repopulates from the new Active set on the\n * next tick (its sweep-by-`seen` semantics make clear+repopulate exact).\n * - `navIntegrity` (react tick, before picking): if the current frame's\n * container died (undo/remote — NavFrame edge auto-cleared), pop to the\n * nearest LIVE ancestor entry (skipping dead ones) or root, restore that\n * camera, rebuild. The recognizer-integrity pattern applied to nav.\n * - Camera policy (design-006, amending design-004 §7; James 2026-07-15):\n * enter saves the live camera on the pushed entry (NavCamera) and ALWAYS\n * lands on the DEFAULT framing — zoom-to-fit over the frame's content, else\n * identity. The `ContainerCamera` rider is neither read nor written by the\n * engine anymore (per-canvas view memory made re-entry unpredictable); the\n * component stays in the catalog for userland. Exit restores the entry's\n * NavCamera — \"back where you came from\" is the nav stack, not view memory.\n * - Transitions (design-006 T1): with a live Viewport and `transition` not\n * \"none\", enter/exit CUT exactly as before and then FLY — the camera snaps\n * to the continuity-solved start and `navFlight` springs it to the arrival\n * (systems/nav-flight.ts). `exitTo(depth)` pops multi-level in ONE flight\n * through the composed portals (rebuilt from CURRENT container rects — a\n * collaborator may have moved a card). Headless (no Viewport) or opted-out\n * calls snap, preserving the pre-T1 behavior exactly.\n */\nimport type { ChangeCollector, Entity, TickSystem, World } from \"@vibecook/strata-ecs\";\nimport { defineQuery, defineTickSystem } from \"@vibecook/strata-ecs\";\nimport type { CameraState, PortalAffine, SpatialIndex } from \"@ice/kernel\";\nimport {\n composeAffine,\n invertAffine,\n outgoingCamera,\n portalAffine,\n solveFlightStart,\n visibleRect,\n} from \"@ice/kernel\";\nimport {\n Camera,\n ActiveTool,\n Container,\n Culled,\n NavCamera,\n NavDepth,\n NavFrame,\n NavTool,\n Position,\n Size,\n Viewport,\n Visible,\n Selected,\n} from \"../catalog\";\nimport {\n NavTransition,\n abortNavFlight,\n publishNavCut,\n startNavFlight,\n type NavTransitionIdentity,\n} from \"../systems/nav-flight\";\nimport { Active } from \"../catalog/camera-derived\";\nimport { Held, HeldIntent } from \"../catalog/desk\";\nimport { PrefabId } from \"../schema/prefab\";\nimport { SpatialVersion, bumpVersion } from \"../helpers/version-stamps\";\nimport { SelectionVersion } from \"../helpers/version-stamps\";\nimport { writeRuntimeResource } from \"../guards/resource-writer\";\nimport { ChildOf } from \"../catalog/scene\";\nimport { WidgetEquipped } from \"../widget/define-widget\";\nimport { engineCatalogFor, widgetTypeFor } from \"../canvas/engine-catalog\";\nimport type { CanvasRect } from \"../canvas/frame-view\";\nimport type {\n FrameSwitchRequest,\n PreparedFrameSwitch,\n PresentationReleaseReason,\n} from \"../canvas/presentation-transition\";\nimport { defaultArrivalCamera, type NavGeometrySlot, NavRedress, resolveNavFace, staticFace } from \"./nav-geometry\";\n\nconst navEntryQ = defineQuery([NavDepth, NavCamera]);\nconst selectedQ = defineQuery([Selected]);\n// Keyed on PrefabId (present AT SPAWN — same flush as equip's WidgetEquipped\n// stamp), so Active lands the same tick projection does and the M6 mount\n// timing is unchanged. Chrome/pointers lack PrefabId; wires lack Position.\nconst equippedQ = defineQuery([Position, Size, PrefabId]);\n\n/** Deepest live nav entry, or undefined at root. */\nexport function currentNavEntry(world: World): Entity | undefined {\n let best: Entity | undefined;\n let bestDepth = -1;\n world.query(navEntryQ).each((b) => {\n for (const r of b) {\n const e = b.entity(r);\n const d = world.read(e, NavDepth).d;\n if (d > bestDepth) {\n bestDepth = d;\n best = e;\n }\n }\n });\n return best;\n}\n\n/** The container the user is inside, or undefined at root. */\nexport function currentNavFrame(world: World): Entity | undefined {\n const entry = currentNavEntry(world);\n if (entry === undefined) return undefined;\n const frame = world.getRelation(entry, NavFrame);\n return frame !== undefined && world.isAlive(frame) ? frame : undefined;\n}\n\n/**\n * Container-ness for MEMBERSHIP decisions, with the equip-lag fallback: the\n * `Container` capability tag lands at the equip flush, ONE FRAME after a\n * widget projects — but membership classifies on the projection frame (the\n * M6 mount-timing invariant). Answering from the runtime tag alone during\n * that window mis-anchors fresh container CONTENT to the root for a frame;\n * cull then mass-Visible-tags it in the same flush membership corrects it\n * (change-only writes let the conflict through), and the zombies stay\n * mounted forever (measured: 6,440 phantom mounts on a 10k-board seed,\n * 2026-07-15). Pre-equip, the WIDGET REGISTRY answers from PrefabId.\n */\nfunction isContainerForMembership(world: World, e: Entity): boolean {\n if (world.hasTag(e, Container)) return true;\n if (world.hasTag(e, WidgetEquipped)) return false; // equipped: the tag is truth\n const id = world.get(e, PrefabId)?.id;\n if (typeof id !== \"string\") return false;\n return widgetTypeFor(world, id)?.capabilityTags.includes(Container) ?? false;\n}\n\n/** First container ancestor on the ChildOf chain (undefined = root-level). */\nfunction firstContainerAncestor(world: World, e: Entity): Entity | undefined {\n let cur = world.getRelation(e, ChildOf);\n let hops = 0;\n while (cur !== undefined && hops < 64) {\n if (isContainerForMembership(world, cur)) return cur;\n cur = world.getRelation(cur, ChildOf);\n hops += 1;\n }\n return undefined;\n}\n\n/**\n * Per-op transition choice (design-006 §3.1); default is the portal zoom. `\"none\"` snaps to\n * the arrival; `\"cut\"` (design-015 §9, the zoom-through — D2b) moves nothing either but lands\n * on the CONTINUITY camera — the one the destination was already rendering under through the\n * face (`c0`) — so the cut changes no pixel; the renderer then re-dresses.\n *\n * The three overrides are the renderer's word on the container's DRAWN geometry (the nav\n * geometry seam, nav-geometry.ts): the face `K` in the parent's units, the inside's `arrival`,\n * and the exact `c0`. Given, they outrank the seam and core's own computation; absent, the op\n * asks the seam, then computes.\n */\nexport interface NavOpts {\n readonly transition?: \"zoom\" | \"none\" | \"cut\";\n readonly face?: CanvasRect;\n readonly arrival?: CameraState;\n readonly c0?: CameraState;\n}\n\nexport interface NestedCanvas {\n readonly activeMembership: TickSystem;\n readonly navIntegrity: TickSystem;\n enterContainer(container: Entity, opts?: NavOpts): void;\n exitContainer(opts?: NavOpts): void;\n /** Pop to `targetDepth` in ONE transition (breadcrumb jumps; design-006 §5). */\n exitTo(targetDepth: number, opts?: NavOpts): void;\n /** Depth of the nav stack (0 = root). */\n depth(): number;\n}\n\nexport interface NestedCanvasOpts {\n /** THE spatial index (nav ops clear it; spatialSync repopulates). */\n readonly index: SpatialIndex<Entity>;\n /**\n * Clear spatialSync's private last-known cache alongside the index (the\n * install seam wires this; without it the compare-and-skip would believe\n * stale entries still exist).\n */\n readonly clearSpatialCaches: () => void;\n /** EngineCatalog-backed container validity; legacy rigs may omit it. */\n readonly isContainer?: (entity: Entity) => boolean;\n /** The nav geometry seam (design-015 §9; D2b): the renderer's word on a container's drawn face, arrival and exact `c0`. */\n readonly navGeometry?: NavGeometrySlot;\n /** Runs synchronously before an explicit enter/exit visibility cut. */\n readonly beforeSwitch?: () => void;\n /** Presentation gate: false forces an atomic cut (for example, cross-ground before T2). */\n readonly transitionAllowed?: (\n fromFrame: Entity | undefined,\n toFrame: Entity | undefined,\n ) => boolean;\n /** Trusted synchronous pre-cut presentation capture. It cannot veto the cut. */\n readonly prepareTransition?: (request: FrameSwitchRequest) => PreparedFrameSwitch;\n /** Integrity/doc recovery releases any adapter holds without animation. */\n readonly abortTransition?: (reason: PresentationReleaseReason) => void;\n /** Capture stable frame/type/document identity before the authority cut. */\n readonly transitionIdentity?: (\n fromFrame: Entity | undefined,\n toFrame: Entity | undefined,\n ) => NavTransitionIdentity;\n /** One publication per completed switch or integrity pop. */\n readonly onSwitch?: (\n frame: Entity | undefined,\n depth: number,\n restoreTool: string | undefined,\n ) => void;\n readonly maxDepth?: number;\n}\n\n/**\n * The membership stamper alone — installed by `installWidgetRuntime` (before\n * cull) so EVERY app partitions correctly, containers or not: a board with no\n * containers converges to all-Active on the first pass and never writes again.\n *\n * Gated per design-004 §7 (see the file header): the tick body drains a\n * petition-7 collector and early-returns on idle frames; membership work runs\n * only on nav change or membership-input churn. Baseline before this gate\n * (bench/membership-scale.test.ts, 2026-07-15): the full scan cost 19.0 ms\n * PER IDLE FRAME at 100k widgets nested 8 deep.\n */\nexport function createActiveMembership(world: World): TickSystem {\n const catalog = engineCatalogFor(world);\n // Created lazily on the FIRST run: both installWidgetRuntime and\n // createNestedCanvas construct an instance but rigs install only one — an\n // un-installed instance must never accumulate an undrained journal.\n let collector: ChangeCollector | undefined;\n let seeded = false;\n let lastFrame: Entity | undefined;\n let framePrimed = false;\n // Last-known membership INPUTS per equipped widget (the spatialSync `known`\n // pattern): ChildOf edge + Container-ness. A journaled entity whose inputs\n // are unchanged (Position-only churn — every drag frame) is skipped without\n // a chain walk. Rebuilt wholesale on every full resweep.\n let knownParent = new Map<Entity, Entity | undefined>();\n let knownContainer = new Set<Entity>();\n\n const isEquipped = (e: Entity): boolean =>\n world.has(e, PrefabId) && world.has(e, Position) && world.has(e, Size);\n\n return defineTickSystem(\n (ctx) => {\n if (collector === undefined) {\n // Position is the reparent proxy (frame-local co-write — file header);\n // PrefabId journals widget spawns/despawns; Container journals\n // container-ness flips (equip lands them one flush after spawn).\n // `coarse: false` is the same attestation spatialSync makes: every\n // writer of these components is store-visible (ctx/edit/projection).\n collector = world.changes.collect({\n components: [PrefabId, Position],\n tags: [Container, Selected],\n coarse: false,\n });\n }\n const delta = collector.drain();\n const frame = currentNavFrame(world);\n const navChanged = !framePrimed || frame !== lastFrame;\n framePrimed = true;\n lastFrame = frame;\n let deselected = false;\n\n const classify = (e: Entity): void => {\n // Retired rows remain durable, but never enter picking, drawing, or the active selection.\n // Membership is journal-driven: this does no work on idle frames.\n const type = world.get(e, PrefabId)?.id;\n const retired = typeof type === \"string\" && catalog?.retiredWidget(type) !== undefined;\n const member = !retired && 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 // …and out of the selection (the header's `Selected ⇒ Active`).\n if (ctx.hasTag(e, Selected)) {\n ctx.removeTag(e, Selected);\n deselected = true;\n }\n // …and out of the HAND (`Held ⇒ Active`, D7 #8): a peer's reparent carried the held object out of the frame —\n // left held, the desk behind stays inert and the hand keeps drawing a non-member. Held's writer is an op, and a\n // system runs no op mid-tick: the one-tick intent the facade applies after the step, as the hold's input does.\n if (ctx.hasTag(e, Held)) {\n const prev = world.getResource(HeldIntent);\n world.setResource(HeldIntent, { kind: \"putDown\", target: e, epoch: (prev?.epoch ?? 0) + 1 });\n }\n }\n };\n\n // Container-despawn insurance: a dead container's ex-CHILDREN changed\n // first-ancestor without any journaled write of their own (a remote tx\n // can delete just the folder row; engine-local deletes cascade, so this\n // stays rare). Resweep rather than reconstruct the orphan set.\n let containerRemoved = false;\n for (const e of delta.removed) {\n if (knownContainer.delete(e)) containerRemoved = true;\n knownParent.delete(e);\n }\n\n // Structural resweeps rebuild the input caches; a NAV-ONLY resweep keeps\n // them — nav moves the frame, not the tree, and the cache rebuild is the\n // expensive half at scale (measured +80 ms on a 100k-entity enter).\n const structural = !seeded || delta.reset || delta.coarse.length > 0 || containerRemoved;\n if (structural || navChanged) {\n seeded = true;\n if (structural) {\n const nextParent = new Map<Entity, Entity | undefined>();\n const nextContainer = new Set<Entity>();\n ctx.query(equippedQ).each((b) => {\n for (const r of b) {\n const e = b.entity(r);\n classify(e);\n nextParent.set(e, world.getRelation(e, ChildOf));\n if (isContainerForMembership(world, e)) nextContainer.add(e);\n }\n });\n knownParent = nextParent;\n knownContainer = nextContainer;\n } else {\n ctx.query(equippedQ).each((b) => {\n for (const r of b) classify(b.entity(r));\n });\n }\n if (deselected) bumpVersion(world, SelectionVersion);\n return;\n }\n\n if (delta.changed.length === 0) return; // the idle frame: one drain, one compare\n\n // Delta route: reclassify entities whose membership inputs changed plus\n // the subtree a reparent/container-flip re-anchors. The walk stops at\n // container CHILDREN (their content anchors to them — unaffected by a\n // move above), but the DFS ROOT recurses even when it is a container:\n // its container-ness may have just flipped, re-anchoring its children.\n const visited = new Set<Entity>();\n const reclassifySubtree = (root: Entity): void => {\n const stack: Entity[] = [root];\n while (stack.length > 0) {\n const e = stack.pop() as Entity;\n if (visited.has(e)) continue;\n visited.add(e);\n classify(e);\n if (e !== root && isContainerForMembership(world, e)) continue;\n for (const c of world.getReverse(e, ChildOf)) {\n if (isEquipped(c)) stack.push(c);\n }\n }\n };\n\n for (const e of delta.changed) {\n if (!world.isAlive(e) || !isEquipped(e)) continue;\n const parent = world.getRelation(e, ChildOf);\n const isCont = isContainerForMembership(world, e);\n if (knownParent.has(e) && knownParent.get(e) === parent && knownContainer.has(e) === isCont) {\n // Position-only churn — membership inputs unchanged. A standing\n // non-member that just gained `Selected` is the one exception.\n if (ctx.hasTag(e, Selected) && !ctx.hasTag(e, Active)) classify(e);\n continue;\n }\n knownParent.set(e, parent);\n if (isCont) knownContainer.add(e);\n else knownContainer.delete(e);\n reclassifySubtree(e);\n }\n if (deselected) bumpVersion(world, SelectionVersion);\n },\n { name: \"activeMembership\" },\n );\n}\n\nexport function createNestedCanvas(world: World, config: NestedCanvasOpts): NestedCanvas {\n const maxDepth = config.maxDepth ?? 64;\n const validContainer = (entity: Entity): boolean =>\n config.isContainer?.(entity) ?? world.hasTag(entity, Container);\n const rebuildIndex = (): void => {\n config.index.clear();\n config.clearSpatialCaches();\n bumpVersion(world, SpatialVersion);\n };\n\n /**\n * THE VISIBILITY CUT (field glitch 2026-07-17): the op snaps the camera to\n * the flight start SYNCHRONOUSLY, but membership → cull → mount hide the\n * departed frame's content one to two ticks later — a few frames of the old\n * scene squeezed under the new camera at the portal. Nav member sets are\n * DISJOINT across a cut, so the op stamps the canonical non-member state\n * (¬Active ∧ ¬Visible ∧ Culled) on EVERY equipped widget right now (ops run\n * outside the tick — the index-rebuild legality); the next tick's membership\n * resweep re-derives the new frame's members, and every renderer (DOM\n * mounts, GL island phases, ground wires, selection chrome) reads the same\n * canonical signal, so the old frame vanishes on the same reflect pass that\n * first applies the new camera.\n */\n const cutVisibility = (): void => {\n // Two-phase: world.* tag writes are IMMEDIATE (archetype moves) and\n // illegal mid-iteration — collect, then mutate.\n const all: Entity[] = [];\n world.query(equippedQ).each((b) => {\n for (const r of b) all.push(b.entity(r));\n });\n for (const e of all) {\n if (world.hasTag(e, Active)) world.removeTag(e, Active);\n if (world.hasTag(e, Visible)) world.removeTag(e, Visible);\n if (!world.hasTag(e, Culled)) world.addTag(e, Culled);\n }\n };\n\n /**\n * The DEFAULT framing for a frame: kernel `fitCamera` over its direct\n * content — zoom-to-fit (FIT_DEFAULTS.pad) capped into the NATURAL band\n * (FIT_DEFAULTS ∩ the session's CameraLimits: never past 100%, never\n * below 50% — 2026-07-18, James: \"should feel natural\"); identity when\n * empty/headless. Sizes are measured-when-real (the folder minis' rule —\n * arrival and portal preview must agree). The flight PATH may transit\n * outside the band; only the arrival honors it. No `ContainerCamera`\n * rider (design-006).\n */\n const resolveArrivalCamera = (frame: Entity): CameraState =>\n defaultArrivalCamera(world, frame, validContainer);\n\n const snapCamera = (c: CameraState): void => {\n writeRuntimeResource(world, Camera, { x: c.x, y: c.y, zoom: c.zoom, gesturing: false });\n };\n\n /** A `\"cut\"` states the re-dressing fact (design-015 §9, `NavRedress`): the renderer eases the desk's dressing from `from` on its own ramp. */\n const stateRedress = (kind: \"in\" | \"out\", from: number, frame: Entity): void => {\n const prev = world.getResource(NavRedress);\n writeRuntimeResource(world, NavRedress, { kind, from, frame, epoch: (prev?.epoch ?? 0) + 1 });\n };\n\n /** Flights need a real viewport and no opt-out; headless snaps (pre-T1 behavior). A `\"cut\"` never flies. */\n const flightable = (\n opts: NavOpts | undefined,\n fromFrame: Entity | undefined,\n toFrame: Entity | undefined,\n ): boolean => {\n const vp = world.getResource(Viewport);\n return (\n opts?.transition !== \"none\" &&\n opts?.transition !== \"cut\" &&\n (config.transitionAllowed?.(fromFrame, toFrame) ?? true) &&\n vp !== undefined &&\n vp.w > 0 &&\n vp.h > 0\n );\n };\n\n /** Container body rect in its parent frame's coords — the portal (§8.5: full body for now). */\n const containerRect = (c: Entity): CanvasRect | undefined => staticFace(world, c);\n\n /**\n * A container's face and its inside's arrival for an op (design-015 §9; D2b): the op's own\n * overrides first, then the renderer's drawn geometry through the seam, then the static rect\n * and the default framing. `cam` is the host camera the drawn answer is taken under.\n */\n const faceOf = (\n c: Entity,\n cam: CameraState,\n opts: NavOpts | undefined,\n ): { readonly K: CanvasRect | undefined; readonly arrival: CameraState; readonly c0: CameraState | undefined } => {\n const drawn = resolveNavFace(world, c, cam, config.navGeometry, {\n ...(opts?.face !== undefined ? { face: opts.face } : {}),\n ...(opts?.arrival !== undefined ? { arrival: opts.arrival } : {}),\n isContainer: validContainer,\n });\n return {\n K: opts?.face ?? drawn?.face ?? containerRect(c),\n arrival: opts?.arrival ?? drawn?.arrival ?? resolveArrivalCamera(c),\n c0: opts?.c0 ?? drawn?.camera,\n };\n };\n\n const prepareSwitch = (\n kind: \"enter\" | \"exit\",\n fromCamera: CameraState,\n toCamera: CameraState,\n A: PortalAffine | undefined,\n identity: NavTransitionIdentity | undefined,\n requestedMotion: boolean,\n ): PreparedFrameSwitch | undefined =>\n config.prepareTransition?.(\n Object.freeze({\n kind,\n documentEpoch: identity?.documentEpoch ?? 0,\n fromFrame: identity?.fromFrame ?? (0 as Entity),\n toFrame: identity?.toFrame ?? (0 as Entity),\n fromTypeId: identity?.fromTypeId ?? \"\",\n toTypeId: identity?.toTypeId ?? \"\",\n fromCamera,\n toCamera,\n affine: A ?? { s: 1, ox: 0, oy: 0 },\n requestedMotion,\n }),\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) || !validContainer(frame)) {\n deadAt = Math.min(deadAt, world.read(e, NavDepth).d);\n }\n }\n });\n if (!Number.isFinite(deadAt)) return;\n const fromFrame = currentNavFrame(world);\n const fromCamera = world.getResource(Camera) ?? {\n x: 0,\n y: 0,\n zoom: 1,\n gesturing: false,\n };\n abortNavFlight(world); // integrity is never blocked on animation (design-006 §4)\n config.abortTransition?.(\"interrupted\");\n let restore: { x: number; y: number; zoom: number } | undefined;\n let restoreTool: string | undefined;\n let targetFrame: Entity | undefined;\n let targetDepth = 0;\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) {\n if (d === deadAt) {\n const cam = world.read(e, NavCamera);\n restore = { x: cam.x, y: cam.y, zoom: cam.zoom };\n restoreTool = world.get(e, NavTool)?.id ?? undefined;\n }\n ctx.destroy(e);\n } else if (d > targetDepth) {\n const frame = world.getRelation(e, NavFrame);\n if (frame !== undefined && world.isAlive(frame) && validContainer(frame)) {\n targetDepth = d;\n targetFrame = frame;\n }\n }\n }\n });\n const arrival = restore ?? fromCamera;\n if (restore !== undefined) writeRuntimeResource(world, Camera, { ...restore, gesturing: false });\n // The same visibility cut the ops make (via ctx — this is a system):\n // an integrity pop swaps frames too, and stale content under the\n // restored camera is the same glitch.\n ctx.query(equippedQ).each((b) => {\n for (const r of b) {\n const e = b.entity(r);\n if (ctx.hasTag(e, Active)) ctx.removeTag(e, Active);\n if (ctx.hasTag(e, Visible)) ctx.removeTag(e, Visible);\n if (!ctx.hasTag(e, Culled)) ctx.addTag(e, Culled);\n }\n });\n let clearedSelection = false;\n ctx.query(selectedQ).each((b) => {\n for (const r of b) {\n ctx.removeTag(b.entity(r), Selected);\n clearedSelection = true;\n }\n });\n if (clearedSelection) bumpVersion(world, SelectionVersion);\n rebuildIndex();\n publishNavCut(\n world,\n \"exit\",\n fromCamera,\n arrival,\n config.transitionIdentity?.(fromFrame, targetFrame),\n );\n config.onSwitch?.(targetFrame, targetDepth, restoreTool);\n },\n {\n name: \"navIntegrity\",\n runIf: () => {\n // Cheap guard: any nav entry at all? (root sessions skip entirely)\n return world.firstOf(navEntryQ) !== undefined;\n },\n },\n );\n\n const exitTo = (targetDepth: number, opts?: NavOpts): void => {\n // Live entries, depth ascending; the deepest is the current frame.\n const entries: { e: Entity; d: number }[] = [];\n world.query(navEntryQ).each((b) => {\n for (const r of b) {\n const e = b.entity(r);\n entries.push({ e, d: world.read(e, NavDepth).d });\n }\n });\n entries.sort((a, b) => a.d - b.d);\n const deepest = entries[entries.length - 1];\n if (deepest === undefined || targetDepth < 0 || targetDepth >= deepest.d) return;\n const doomed = entries.filter((x) => x.d > targetDepth);\n const shallowest = doomed[0] as { e: Entity; d: number }; // non-empty by the guard\n // The shallowest doomed entry's saved camera is the restore point (the\n // camera as it was the moment that level was entered).\n const restore = world.read(shallowest.e, NavCamera);\n const restoreTool = world.get(shallowest.e, NavTool)?.id ?? undefined;\n const c1: CameraState = { x: restore.x, y: restore.y, zoom: restore.zoom };\n const camPre = world.getResource(Camera) ?? { x: 0, y: 0, zoom: 1, gesturing: false };\n const fromFrame = currentNavFrame(world);\n const targetEntry = entries.find((entry) => entry.d === targetDepth);\n const targetFrame =\n targetEntry === undefined ? undefined : world.getRelation(targetEntry.e, NavFrame);\n\n // Compose the portal chain from CURRENT rects (containers move), outermost\n // first: A maps the departed frame's coords into the TARGET frame's. Any\n // dead/rect-less link degrades the whole jump to a snap — never half-fly.\n let A: PortalAffine | undefined;\n const vp = world.getResource(Viewport);\n if (vp !== undefined && vp.w > 0 && vp.h > 0) {\n // the deepest link — the current frame's own container — takes the op's overrides; the seam\n // answers every link at rest (a container out of the frame is not drawn)\n const deepest = doomed[doomed.length - 1]?.e;\n for (const { e } of doomed) {\n const frame = world.getRelation(e, NavFrame);\n if (frame === undefined || !world.isAlive(frame)) {\n A = undefined;\n break;\n }\n const { K, arrival } = faceOf(frame, camPre, e === deepest ? opts : undefined);\n if (K === undefined) {\n A = undefined;\n break;\n }\n const M = portalAffine(visibleRect(arrival, vp.w, vp.h), K);\n A = A === undefined ? M : composeAffine(A, M);\n }\n }\n const identity = config.transitionIdentity?.(fromFrame, targetFrame);\n const requestedMotion = A !== undefined && flightable(opts, fromFrame, targetFrame);\n\n config.beforeSwitch?.();\n const prepared = prepareSwitch(\"exit\", camPre, c1, A, identity, requestedMotion);\n let authorityMutated = false;\n try {\n for (const { e } of doomed) {\n // ops run OUTSIDE the tick — structural world.* is legal here. Once\n // one entry is gone this attempt cannot be treated as a pre-cut\n // presentation rollback, even if a later operation faults.\n world.destroy(e);\n authorityMutated = true;\n }\n cutVisibility(); // BEFORE the camera write (see enterContainer)\n authorityMutated = true;\n if (A !== undefined && requestedMotion && (prepared?.allowFlight ?? true)) {\n startNavFlight(world, \"exit\", A, solveFlightStart(A, camPre), c1, identity);\n } else if (A !== undefined && opts?.transition === \"cut\") {\n // the zoom-through's cut OUT (design-015 §9): the parent camera under which the inside renders as it does now; the desk\n // left — the live inside of `fromFrame` now — stays dressed for the camera it was cut at and re-dresses to its arrival\n const c0 = opts.c0 ?? solveFlightStart(A, camPre);\n snapCamera(c0);\n publishNavCut(world, \"exit\", camPre, c0, identity, A);\n if (fromFrame !== undefined) stateRedress(\"out\", camPre.zoom, fromFrame);\n } else {\n snapCamera(c1);\n publishNavCut(world, \"exit\", camPre, c1, identity, A);\n }\n rebuildIndex();\n config.onSwitch?.(targetFrame, targetDepth, restoreTool);\n prepared?.commit();\n } catch (error) {\n prepared?.cancel(authorityMutated ? \"fault\" : \"cancelled\");\n throw error;\n }\n };\n\n return {\n activeMembership,\n navIntegrity,\n enterContainer(container, opts) {\n if (!world.isAlive(container) || !validContainer(container)) {\n throw new Error(\"ice: enterContainer target is not a live container.\");\n }\n const fromFrame = currentNavFrame(world);\n const cam = world.getResource(Camera) ?? { x: 0, y: 0, zoom: 1, gesturing: false };\n // §6.2 rev 2: the saved return pose is SETTLED — a driving flight saves its\n // arrival camera, never the mid-flight pose; an aborted flight's resting\n // pose is user truth and saves as-is.\n const flight = world.getResource(NavTransition);\n const returnCam = flight?.active\n ? { x: flight.c1x, y: flight.c1y, zoom: flight.c1z }\n : cam;\n const depth = (currentNavEntry(world) !== undefined ? world.read(currentNavEntry(world) as Entity, NavDepth).d : 0) + 1;\n if (depth > maxDepth) {\n throw new Error(`ice: enterContainer would exceed the maximum CanvasFrame depth ${maxDepth}.`);\n }\n // the face AS DRAWN, the arrival and the exact c0 — the op's, the renderer's (the seam), or core's own (design-015 §9)\n const camNow: CameraState = { x: cam.x, y: cam.y, zoom: cam.zoom };\n const face = faceOf(container, camNow, opts);\n const c1 = face.arrival;\n const K = face.K;\n const vp = world.getResource(Viewport);\n // M: the child's arrival view onto the container's face (the live portal's own affine); A = M⁻¹.\n const M =\n K !== undefined && vp !== undefined && vp.w > 0 && vp.h > 0\n ? portalAffine(visibleRect(c1, vp.w, vp.h), K)\n : undefined;\n const A = M === undefined ? undefined : invertAffine(M);\n // the camera the inside was already rendering under through the face: the renderer's word when it has one (the drawn face),\n // else `outgoingCamera(M, cam)` — the live portal's camera, not the continuity solve's ulp-off twin (design-013 §8 B7, D-B7.1)\n const c0 = M === undefined ? undefined : (face.c0 ?? outgoingCamera(M, camNow));\n const identity = config.transitionIdentity?.(fromFrame, container);\n const requestedMotion = A !== undefined && flightable(opts, fromFrame, container);\n config.beforeSwitch?.();\n const prepared = prepareSwitch(\"enter\", cam, c1, A, identity, requestedMotion);\n let authorityMutated = false;\n try {\n const entry = world.spawn({\n components: [\n [NavDepth, { d: depth }],\n [NavCamera, { x: returnCam.x, y: returnCam.y, zoom: returnCam.zoom }],\n [NavTool, { id: world.getResource(ActiveTool)?.id ?? \"select\" }],\n ],\n });\n authorityMutated = true;\n world.setRelation(entry, NavFrame, container);\n cutVisibility(); // BEFORE the camera write — no frame may render old content under the new camera\n if (A !== undefined && c0 !== undefined && requestedMotion && (prepared?.allowFlight ?? true)) {\n // A = M⁻¹: parent (departed) coords → child (destination) coords. The flight STARTS from the\n // live portal's exact camera (`c0` above), the camera the inside was already rendering under.\n startNavFlight(world, \"enter\", A, c0, c1, identity);\n } else if (A !== undefined && c0 !== undefined && opts?.transition === \"cut\") {\n // the zoom-through's cut IN (design-015 §9): the camera lands where the inside already rendered — no pixel changes; the\n // desk entered stays dressed for its arrival, as its face showed it, and re-dresses to the camera's zoom\n snapCamera(c0);\n publishNavCut(world, \"enter\", cam, c0, identity, A);\n stateRedress(\"in\", c1.zoom, container);\n } else {\n snapCamera(c1);\n publishNavCut(world, \"enter\", cam, c1, identity, A);\n }\n rebuildIndex();\n config.onSwitch?.(container, depth, undefined);\n prepared?.commit();\n } catch (error) {\n prepared?.cancel(authorityMutated ? \"fault\" : \"cancelled\");\n throw error;\n }\n },\n exitContainer(opts) {\n const entry = currentNavEntry(world);\n if (entry === undefined) return; // already at root\n exitTo(world.read(entry, NavDepth).d - 1, opts);\n },\n exitTo,\n depth() {\n const entry = currentNavEntry(world);\n return entry === undefined ? 0 : world.read(entry, NavDepth).d;\n },\n };\n}\n","/**\n * Sibling order — THE per-frame stacking source (petition 8; design-004 §1\n * amendment). Within a frame, paint/pick/drop order IS the frame parent's\n * ordered `ChildOf` sibling sequence: index 0 paints first (bottom), the tail\n * paints last (top). The frame parent is `currentNavFrame(world) ?? BoardRoot`\n * — every renderer/pick consumer shares this module so the orders can never\n * diverge (the point-pick lesson, extended to the comparator).\n *\n * THE DESK'S STRATA (design-015 §4.2, D2a-core, 2026-09-25) rank ABOVE the\n * sequence: `compareStackOrder` orders by `Stratum.band` first (pads · sheets ·\n * things; absent = things) and by sibling order within a band, so an object's\n * pick order is its paint order across kinds. No pre-desk widget carries a\n * `Stratum`, so every existing board is one band and orders as it always did.\n *\n * LEGACY FALLBACK (must keep working): when the `BoardRoot` resource is absent\n * (a pre-schema-2 doc opened read-only, or a doc-less runtime world) OR an\n * entity carries no `ChildOf` edge (bare runtime spawns), stacking falls back\n * to the legacy `(StackZ.z asc, entity asc)` comparator. This module is the\n * ONLY sanctioned StackZ reader outside the schema migration.\n *\n * Mixed frames — some entities ordinal-mapped, some fallback — are nominally\n * impossible (the 1→2 migration hangs an edge on every durable widget, and a\n * pre-schema-2 read-only doc has no BoardRoot at all, so it is all-fallback).\n * The comparator still totals them: ordinal-mapped entities sort BELOW the\n * fallback set (ordinals first in paint order), each group internally ordered\n * by its own rule — documented so a stray bare spawn lands somewhere stable\n * rather than somewhere random.\n *\n * Invalidation is PULL-ONLY, the strata 0.8.0 contract: `world.orderStamp\n * (parent, ChildOf)` is a monotonic per-parent version consumers poll after a\n * reactive wake; the wake itself is an `observeQuery` whose grammar names the\n * relation (`Related(ChildOf)` — pure reorders turn it over).\n */\nimport type { Component, Entity, World } from \"@vibecook/strata-ecs\";\nimport { Related, defineQuery } from \"@vibecook/strata-ecs\";\nimport { BoardRoot, ChildOf, Position, StackZ } from \"../catalog/scene\";\nimport { DEFAULT_STRATUM_BAND, Stratum } from \"../catalog/desk\";\nimport { currentNavFrame } from \"../nav/nested-canvas\";\n\n/** Structural read both `World` and `SystemCtx` provide — all the comparator needs. */\nexport interface StackOrderReader {\n get<S>(e: Entity, c: Component<S>): S | undefined;\n}\n\n/**\n * The frame parent — the entity whose `ChildOf` sibling sequence is the\n * current frame's stacking order: the nav frame when inside a container, else\n * the document's board root. `undefined` = a legacy world (pre-schema-2\n * read-only doc / doc-less runtime) — everything is fallback-ordered.\n */\nexport function frameParent(world: World): Entity | undefined {\n const frame = currentNavFrame(world);\n if (frame !== undefined) return frame;\n const root = world.getResource(BoardRoot)?.root;\n return root !== undefined && world.isAlive(root) ? root : undefined;\n}\n\n/** `parent`'s sibling sequence as entity → position (the renderers' sort key). */\nexport function buildOrdinals(world: World, parent: Entity): Map<Entity, number> {\n const seq = world.getReverse(parent, ChildOf);\n const map = new Map<Entity, number>();\n for (let i = 0; i < seq.length; i++) map.set(seq[i] as Entity, i);\n return map;\n}\n\n/**\n * THE stacking comparator (ascending = paint order; the pick tier takes the\n * max). The desk's STRATUM first (design-015 §4.2, D-D4 — D2a-core): pads\n * under sheets under things, whatever the sibling order says, so what the desk\n * paints on top is what a point picks; an entity with no `Stratum` is a thing,\n * which is every pre-desk widget — an all-dom board is one band and orders\n * exactly as before. Within a band: ordinal-mapped entities order by sibling\n * position; entities missing from the map use the legacy `(StackZ asc, entity\n * asc)` fallback among themselves and sort ABOVE the ordinal-mapped set (see\n * the header note on nominally-impossible mixed frames).\n */\nexport function compareStackOrder(\n reader: StackOrderReader,\n ordinals: ReadonlyMap<Entity, number>,\n a: Entity,\n b: Entity,\n): number {\n const ba = reader.get(a, Stratum)?.band ?? DEFAULT_STRATUM_BAND;\n const bb = reader.get(b, Stratum)?.band ?? DEFAULT_STRATUM_BAND;\n if (ba !== bb) return ba - bb;\n const oa = ordinals.get(a);\n const ob = ordinals.get(b);\n if (oa !== undefined && ob !== undefined) return oa - ob;\n if (oa !== undefined) return -1;\n if (ob !== undefined) return 1;\n const za = reader.get(a, StackZ)?.z ?? 0;\n const zb = reader.get(b, StackZ)?.z ?? 0;\n return za !== zb ? za - zb : Number(a) - Number(b);\n}\n\nexport interface SiblingOrderIndex {\n /** The frame parent backing the current ordinal map (undefined = legacy world). */\n parent(): Entity | undefined;\n /** The stamp-checked ordinal map — rebuilt only when the frame parent or its `orderStamp` moved. */\n ordinals(): ReadonlyMap<Entity, number>;\n /** True when the next `ordinals()` would rebuild (cheap pull; no rebuild). */\n stale(): boolean;\n /**\n * Arm the reorder wake: an `observeQuery` naming `ChildOf` (`Related`\n * grammar — pure reorders and edge turnover both fire it). Callers pair it\n * with `stale()`/`ordinals()` so other-frame churn stays a no-op.\n */\n observe(cb: () => void): () => void;\n}\n\n// Widgets all carry Position; naming ChildOf makes reorders (not just edge\n// membership) turn the watch over — the ordered-relations wake contract.\nconst orderWakeQ = defineQuery([Position, Related(ChildOf)]);\n\n/**\n * A pull-based ordinal cache over the CURRENT frame parent's sibling sequence.\n * Consumers each hold their own instance (the cache is a cheap `getReverse`\n * walk); correctness is shared through {@link compareStackOrder} and the\n * stamp, never through instance identity.\n */\nexport function createSiblingOrderIndex(world: World): SiblingOrderIndex {\n const empty: ReadonlyMap<Entity, number> = new Map();\n let built: ReadonlyMap<Entity, number> = empty;\n let builtParent: Entity | undefined;\n let builtStamp = 0;\n let hasBuilt = false;\n\n const stale = (): boolean => {\n const parent = frameParent(world);\n if (!hasBuilt || parent !== builtParent) return true;\n return parent !== undefined && world.orderStamp(parent, ChildOf) !== builtStamp;\n };\n\n return {\n parent: () => frameParent(world),\n ordinals() {\n if (!stale()) return built;\n const parent = frameParent(world);\n builtParent = parent;\n builtStamp = parent === undefined ? 0 : world.orderStamp(parent, ChildOf);\n built = parent === undefined ? empty : buildOrdinals(world, parent);\n hasBuilt = true;\n return built;\n },\n stale,\n observe: (cb) => world.reactive.observeQuery(orderWakeQ, cb),\n };\n}\n","/**\n * THE point-pick (Law 15: the spatial index is the only hit path; this\n * function is its only narrow-phase). Shared verbatim by the in-tick\n * `picking` system (L1, via SystemCtx) and the pointer router's synchronous\n * event-time pick (design-004 §4 GL path, via World — world reads outside\n * the tick are verified-unrestricted). One implementation so the two can\n * never disagree on ordering.\n *\n * Priority: HandleSpec chrome first (nearest edge), then widgets topmost by\n * SIBLING ORDER (petition 8: the frame parent's ChildOf sequence, legacy\n * (StackZ, entity) fallback for edge-less entities — compareStackOrder is the\n * ONE comparator paint and pick share). Deliberately NOT plane-stratified:\n * cross-plane z is stratified visually (P2 GL composites above P1 DOM), but\n * pick order is sibling order across all surfaces — design-004 §1 names the\n * mixed-overlap consequence and accepts it; do not \"fix\" it here. (The desk's\n * `Stratum` bands — design-015 §4.2 — are NOT that stratification: they are\n * the desk's PAINT order, read inside compareStackOrder, so pick still equals\n * paint. No pre-desk widget carries one.)\n */\nimport type { Component, Entity } from \"@vibecook/strata-ecs\";\nimport type { Cubic, SpatialIndex } from \"@ice/kernel\";\nimport { distanceToCubic } from \"@ice/kernel\";\nimport { HandleSpec, Port, Position, Wire } from \"../catalog\";\nimport { compareStackOrder } from \"./sibling-order\";\n\n/** Structural reads both `World` and `SystemCtx` provide. */\nexport interface PickReader {\n isAlive(e: Entity): boolean;\n has(e: Entity, c: Component): boolean;\n hasTag(e: Entity, t: import(\"@vibecook/strata-ecs\").Tag): boolean;\n get<S>(e: Entity, c: Component<S>): S | undefined;\n}\n\n/** Wire narrow-phase source: cached cubics from wireSync (M8). */\nexport interface WirePickSource {\n cubicOf(e: Entity): Cubic | undefined;\n /** Pick slop in WORLD units (screen slop / zoom, caller-converted). */\n readonly slopWorld: number;\n}\n\n/** Distance from a point to the nearest edge of an AABB (0 iff inside). */\nexport function distPointToBox(\n px: number,\n py: number,\n minX: number,\n minY: number,\n maxX: number,\n maxY: number,\n): number {\n const dx = Math.max(minX - px, 0, px - maxX);\n const dy = Math.max(minY - py, 0, py - maxY);\n return Math.hypot(dx, dy);\n}\n\n/** No frame parent (legacy world) — every widget compares by the fallback. */\nconst NO_ORDINALS: ReadonlyMap<Entity, number> = new Map();\n\n/**\n * Top pick under a world point within `rWorld` (point-in-box when 0).\n * Tier order (design-003 §3, amended for M8): HandleSpec chrome → PORT\n * entities (interaction affordances sit atop their widget edge) → widgets by\n * sibling order (topmost = compareStackOrder max; `ordinals` is the caller's\n * frame ordinal map — SiblingOrderIndex — so paint and pick share one order)\n * → WIRES (render in P0 under content; pick below widgets, above\n * canvas — render order and pick order agree). The canvas fallback stays the\n * caller's. Wires narrow-phase against their cached cubic (`wires` source;\n * without one, wire entries are skipped — coarse AABB hits would make fat\n * bounding boxes steal canvas taps).\n */\nexport function pickTopAt(\n reader: PickReader,\n index: SpatialIndex<Entity>,\n wx: number,\n wy: number,\n rWorld: number,\n wires?: WirePickSource,\n ordinals: ReadonlyMap<Entity, number> = NO_ORDINALS,\n): Entity | undefined {\n let bestHandle: Entity | undefined;\n let bestHandleD = Number.POSITIVE_INFINITY;\n let bestPort: Entity | undefined;\n let bestPortD = Number.POSITIVE_INFINITY;\n let bestWidget: Entity | undefined;\n let bestWire: Entity | undefined;\n let bestWireD = Number.POSITIVE_INFINITY;\n for (const entry of index.searchPoint(wx, wy, rWorld)) {\n const e = entry.id;\n if (!reader.isAlive(e)) continue;\n const d = distPointToBox(wx, wy, entry.minX, entry.minY, entry.maxX, entry.maxY);\n if (d > rWorld) continue; // narrow: disc-vs-box\n if (reader.has(e, HandleSpec)) {\n if (d < bestHandleD) {\n bestHandleD = d;\n bestHandle = e;\n }\n } else if (reader.has(e, Port)) {\n if (d < bestPortD) {\n bestPortD = d;\n bestPort = e;\n }\n } else if (reader.hasTag(e, Wire)) {\n if (wires === undefined) continue;\n const cubic = wires.cubicOf(e);\n if (cubic === undefined) continue;\n const wd = distanceToCubic(wx, wy, cubic);\n if (wd <= rWorld + wires.slopWorld && wd < bestWireD) {\n bestWireD = wd;\n bestWire = e;\n }\n } else if (reader.has(e, Position)) {\n if (bestWidget === undefined || compareStackOrder(reader, ordinals, e, bestWidget) > 0) {\n bestWidget = e;\n }\n }\n }\n return bestHandle ?? bestPort ?? bestWidget ?? bestWire;\n}\n","/**\n * Port-slot resolution: a widget's port DECLARATIONS (from the widget registry,\n * design-005 §2) → kernel `PortSlot`s (side + even-distribution index/count).\n *\n * The single source of a port's world anchor is the kernel's pure\n * `portAnchor(widgetRect, slot)` — geometry NEVER reads a port ENTITY (design-001\n * §5.3), so wires, the connect preview, and materialized-port anchors all agree\n * by construction and culled endpoints resolve for free. Ports sharing a side are\n * numbered by their declared `index` when given, else by declaration order; the\n * side's `count` drives the even spacing.\n */\nimport type { PortSide, PortSlot } from \"@ice/kernel\";\nimport type { WidgetPortDecl } from \"../widget/define-widget\";\n\n/** Map every declared port id → its `PortSlot` (side/index/count for even spacing). */\nexport function portSlots(decls: readonly WidgetPortDecl[]): Map<string, PortSlot> {\n const bySide = new Map<PortSide, WidgetPortDecl[]>();\n for (const d of decls) {\n let list = bySide.get(d.side);\n if (list === undefined) {\n list = [];\n bySide.set(d.side, list);\n }\n list.push(d);\n }\n const out = new Map<string, PortSlot>();\n for (const [side, list] of bySide) {\n for (let i = 0; i < list.length; i++) {\n const d = list[i];\n if (d === undefined) continue;\n out.set(d.id, { side, index: d.index ?? i, count: list.length });\n }\n }\n return out;\n}\n\n/** The `PortSlot` for one port id (undefined if the widget declares no such port). */\nexport function portSlotOf(decls: readonly WidgetPortDecl[], portId: string): PortSlot | undefined {\n return portSlots(decls).get(portId);\n}\n","/**\n * L1 — wire geometry sync (design-004 §6 ports & wires runtime; `react` phase,\n * AFTER `spatialSync`).\n *\n * A wire is a durable reified edge (Wire tag + WireFrom/WireTo → widgets +\n * WirePorts ids). Its RENDER + PICK geometry is a pure function of the two\n * endpoint widget rects and their port declarations (design-001 §5.3: geometry\n * never reads a port entity — culled endpoints resolve by construction). This\n * TICK system (strata 0.5.0) recomputes each wire's cubic once per frame and\n * keeps a private cache so the shared spatial index only churns on real\n * movement — exactly the `spatialSync` idiom, and the reason it must run every\n * frame: it is a `SpatialVersion` writer and cannot gate on the version it bumps.\n *\n * Per wire: resolve WireFrom/WireTo → endpoint Position+Size + the port slot\n * (PrefabId → widget registry → decl → kernel `portAnchor`) → `wireCubic` →\n * `cubicAABB`. Endpoint or declaration unresolvable (mid-projection, a despawned\n * widget, a removed port id) ⇒ the wire leaves the index (invisible to picking;\n * the renderer draws nothing for it). The cache also feeds the `WirePickSource`\n * the point-pick narrow-phases against (`ops/point-pick`), and exposes the\n * screen-constant pick slop as `slopWorld = wirePickSlopPx / zoom`.\n */\nimport type { Component, Entity, TickSystem, World } from \"@vibecook/strata-ecs\";\nimport { defineQuery, defineTickSystem } from \"@vibecook/strata-ecs\";\nimport { type AABB, type Cubic, type SpatialIndex, cubicAABB, portAnchor, wireCubic } from \"@ice/kernel\";\nimport { Camera, Position, Size, Wire, WireFrom, WirePorts, WireTo } from \"../catalog\";\nimport { widgetTypeFor } from \"../canvas/engine-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\";\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 world: World,\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\" ? widgetTypeFor(world, 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, world, ctx.getRelation(wire, WireFrom), ports.from ?? \"\");\n const to = endpointAnchor(ctx, world, 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","/** Generation-safe local CanvasSession resource and its engine-owned writer. */\nimport { enumOf, field, type Entity, type World } from \"@vibecook/strata-ecs\";\nimport { defineComponent, defineResource } from \"../schema/meta\";\n\nexport const CanvasSession = defineResource(\"CanvasSession\", {\n state: field(enumOf([\"detached\", \"attached\"]), { default: \"detached\" }),\n documentEpoch: field(\"u32\", { default: 0 }),\n epoch: field(\"u32\", { default: 0 }),\n /** Ignored while detached. Zero is a sentinel, never a retained entity API. */\n frame: field(\"eid\", { default: 0 as Entity }),\n typeId: field(\"string\", { default: \"\" }),\n depth: field(\"u8\", { default: 0 }),\n});\n\n/** Gesture-start latch used to reject commits after a document/nav switch. */\nexport const CanvasIntentScope = defineComponent(\"CanvasIntentScope\", {\n documentEpoch: field(\"u32\", { default: 0 }),\n canvasEpoch: field(\"u32\", { default: 0 }),\n frame: field(\"eid\", { default: 0 as Entity }),\n});\n\nexport type CanvasSessionValue = {\n readonly state: \"detached\" | \"attached\";\n readonly documentEpoch: number;\n readonly epoch: number;\n readonly frame: Entity;\n readonly typeId: string;\n readonly depth: number;\n};\n\nexport interface CanvasSessionController {\n current(): CanvasSessionValue;\n attach(frame: Entity, typeId: string): CanvasSessionValue;\n detach(): CanvasSessionValue;\n switchFrame(frame: Entity, typeId: string, depth: number): CanvasSessionValue;\n bumpCapabilities(): CanvasSessionValue;\n /** Re-publish closure state after world.reset() clears runtime resources. */\n republish(): void;\n}\n\nconst next = (value: number): number => (value + 1) >>> 0;\n\nexport function createCanvasSessionController(world: World): CanvasSessionController {\n let value: CanvasSessionValue = {\n state: \"detached\",\n documentEpoch: 0,\n epoch: 0,\n frame: 0 as Entity,\n typeId: \"\",\n depth: 0,\n };\n const publish = (): void => world.setResource(CanvasSession, value);\n publish();\n\n return {\n current: () => value,\n attach(frame, typeId) {\n value = {\n state: \"attached\",\n documentEpoch: next(value.documentEpoch),\n epoch: next(value.epoch),\n frame,\n typeId,\n depth: 0,\n };\n publish();\n return value;\n },\n detach() {\n value = {\n state: \"detached\",\n documentEpoch: next(value.documentEpoch),\n epoch: next(value.epoch),\n frame: 0 as Entity,\n typeId: \"\",\n depth: 0,\n };\n publish();\n return value;\n },\n switchFrame(frame, typeId, depth) {\n if (value.state !== \"attached\") {\n throw new Error(\"ice: cannot switch CanvasSession while no document is attached.\");\n }\n value = { ...value, epoch: next(value.epoch), frame, typeId, depth };\n publish();\n return value;\n },\n bumpCapabilities() {\n value = { ...value, epoch: next(value.epoch) };\n publish();\n return value;\n },\n republish: publish,\n };\n}\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`; a primary\n * press only — a secondary one is a point, a middle one its\n * pan's drag: petition I28, press-button.ts) →\n * recognizerIntegrity (requiredWatches counts, capture death,\n * suspension lift). Newborns are identity-only until the\n * ctl:spawn flush, so integrity naturally skips them until the\n * next frame — by which time their edges are placed.\n * `ctl:recognize` — per-kind systems. Transitions go through the PhaseSet via\n * `ctx` (visible at this phase's flush — arbitration reads them\n * the same frame); field updates are immediate `edit().set`\n * under declared `access.write`.\n *\n * All timing reads FrameInfo.CLOCK — the accumulated CLAMPED-dt gesture clock\n * (2026-07-17, supersedes both raw FrameInfo.now and the 2026-07-12\n * event-timestamp anchor): rAF `now` lags wall time by up to SECONDS under\n * throttling/headless/software rendering while event.timeStamp does not, so\n * any window mixing the two evaluates garbage; `clock` is monotonic, stalls\n * contribute ≤ dtClampMs (the stall-protection intent), and no event\n * timestamp ever enters window math. All thresholds read the GestureSettings\n * RESOURCE (live-tunable, design-005 §4) with the GESTURE_DEFAULTS constants\n * as the unset fallback. Gesture math is screen-space totals + zoom-at-claim\n * — never live PointerWorld (design-002 §2 staleness rule).\n */\nimport type { Entity, SystemCtx, World } from \"@vibecook/strata-ecs\";\nimport { Any, Not, defineQuery, defineSystem, type System, type Tag } from \"@vibecook/strata-ecs\";\nimport {\n Camera,\n CancelRequest,\n Captures,\n ClaimedBy,\n Down,\n DownPart,\n Drag,\n DragBounds,\n GesturePhases,\n GestureSuspended,\n HadCapture,\n InsertGhost,\n HadRequiresFail,\n HadSequence,\n HandledByWidget,\n LocalPointer,\n Keyboard,\n MovesSelection,\n PointerMods,\n LongPress,\n LongPressDrag,\n MultiTap,\n Pinch,\n Pointer,\n PointerButtons,\n PointerPart,\n PointerScreen,\n PointerWheel,\n RequiresFail,\n Sequence,\n SnapState,\n Simultaneous,\n Tap,\n TouchesExact,\n Watches,\n WentCancelled,\n WentDown,\n WentUp,\n WheelHandled,\n WheelPan,\n WheelZoom,\n} from \"../catalog\";\nimport { ActiveTool } from \"../catalog/camera-derived\";\nimport { resolveToolFor, toolTypeFor } from \"../canvas/engine-catalog\";\nimport { selectionDragAt } from \"../ops/selection-drag\";\nimport { CanvasIntentScope, CanvasSession } from \"../canvas/session\";\nimport { FrameInfo } from \"../engine/frame-info\";\nimport { GestureSettings } from \"../catalog/settings-resources\";\nimport { GESTURE_DEFAULTS } from \"../settings/defaults\";\nimport { middlePans, pressButton } from \"./press-button\";\n\nexport type SingleKindName = \"tap\" | \"longPress\" | \"drag\";\n\n/** Tool id → single-pointer recognizer set spawned per down (design-003 §4.1). */\nexport type SpawnProfiles = Readonly<Record<string, readonly SingleKindName[]>>;\n\nexport const DEFAULT_SPAWN_PROFILES: SpawnProfiles = {\n select: [\"tap\", \"longPress\", \"drag\"],\n pan: [\"drag\"],\n};\n\nconst anyKindQ = defineQuery([Any(Tap, LongPress, Drag, Pinch, WheelPan, WheelZoom)]);\nconst downQ = defineQuery([Pointer, WentDown, Not(HandledByWidget), LocalPointer]);\nconst heldTouchQ = defineQuery([Pointer, PointerButtons, LocalPointer]);\n// `Not(WheelHandled)` mirrors downQ's `Not(HandledByWidget)` one line up — the\n// wheel-specific opt-out (design-007 §3.5): a ceded tick spawns no recognizer,\n// while a same-tick canvas DOWN on the same pointer is untouched.\nconst wheelSourceQ = defineQuery([Pointer, PointerWheel, LocalPointer, Not(WheelHandled)]);\nconst tapQ = defineQuery([Tap, Not(GestureSuspended)]);\nconst longPressQ = defineQuery([LongPress, Not(GestureSuspended)]);\nconst dragQ = defineQuery([Drag, Not(GestureSuspended)]);\nconst pinchQ = defineQuery([Pinch]);\nconst wheelKindQ = defineQuery([Any(WheelPan, WheelZoom)]);\nconst pendingTapQ = defineQuery([Tap, GesturePhases.tags.Pending]);\nconst pendingQ = defineQuery([Any(Tap, LongPress, Drag, Pinch), GesturePhases.tags.Pending]);\n\nconst P = GesturePhases;\n\n/** Live-tunable gesture settings (design-005 §4): resource first, const fallback. Only the numeric thresholds; camera mode and curve are separate settings. */\nfunction gs(ctx: SystemCtx): Readonly<Record<Exclude<keyof typeof GESTURE_DEFAULTS, \"wheel\" | \"wheelZoomCurve\">, number>> {\n return ctx.getResource(GestureSettings) ?? GESTURE_DEFAULTS;\n}\n\n/** The gesture clock (see the header — NEVER FrameInfo.now for window math). */\nfunction clk(ctx: SystemCtx): number {\n return ctx.getResource(FrameInfo)?.clock ?? 0;\n}\n\n\n/** A recognizer is in a phase from which no further recognition can happen. */\nfunction isTerminal(ctx: SystemCtx | World, e: Entity): boolean {\n if (ctx.hasTag(e, P.tags.Failed) || ctx.hasTag(e, P.tags.Cancelled) || ctx.hasTag(e, P.tags.Ended)) {\n return true;\n }\n // Recognized is terminal for Tap only — LongPress keeps a continuous tail.\n return ctx.hasTag(e, P.tags.Recognized) && ctx.has(e, Tap);\n}\n\nfunction requiredWatches(ctx: SystemCtx | World, e: Entity): number {\n return ctx.has(e, Pinch) ? 2 : 1;\n}\n\nfunction dist(ax: number, ay: number, bx: number, by: number): number {\n return Math.hypot(bx - ax, by - ay);\n}\n\nexport interface L2Deps {\n readonly world: World;\n readonly profiles?: SpawnProfiles;\n}\n\nexport interface L2Systems {\n cancelSweep: System;\n recognizerSpawn: System;\n /** Same design slot as recognizerSpawn (design-002 §2) over the wheel-source query. */\n wheelSpawn: System;\n recognizerIntegrity: System;\n tapSystem: System;\n longPressSystem: System;\n dragSystem: System;\n pinchSystem: System;\n wheelSystem: System;\n /** Resolves Pending `Sequence`/`RequiresFail` edges; last in `ctl:recognize`. */\n dependencySystem: System;\n}\n\nexport function createL2Systems({ world, profiles = DEFAULT_SPAWN_PROFILES }: L2Deps): L2Systems {\n /** Non-terminal recognizers watching `pointer` (live reverse edges). */\n const watchersOf = (ctx: SystemCtx, pointer: Entity): Entity[] =>\n ctx.getReverse(pointer, Watches).filter((rec) => !isTerminal(ctx, rec));\n\n const cancelSweep = defineSystem(\n anyKindQ,\n (b, ctx) => {\n for (const r of b) {\n const e = b.entity(r);\n if (isTerminal(ctx, e)) continue;\n P.set(ctx, e, \"Cancelled\");\n }\n },\n {\n name: \"cancelSweep\",\n runIf: (ctx) => ctx.getResource(CancelRequest)?.active === true,\n },\n );\n\n const recognizerSpawn = defineSystem(\n downQ,\n (b, ctx) => {\n const now = clk(ctx);\n const tool = ctx.getResource(ActiveTool)?.id ?? \"select\";\n // Explicit profiles (test/app override) → tool registry (design-005 §3)\n // → select. Tools parameterize L2 spawn purely through config.\n const profile =\n profiles[tool] ??\n toolTypeFor(world, tool)?.spawnProfile ??\n toolTypeFor(world, \"select\")?.spawnProfile ??\n DEFAULT_SPAWN_PROFILES.select ??\n [];\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 // The button the press began with (petition I28, press-button.ts): only the primary's is a gesture. A secondary press is a\n // POINT — ingest and `picking` already moved its point, pick and hover — so nothing spawns: nothing selects, drags, enters\n // or works a part. A middle press is its pan's drag where `dragRoute` pans it, and nothing anywhere else.\n const button = pressButton(ctx.get(pointer, PointerButtons)?.buttons ?? 0);\n if (button === \"secondary\" || (button === \"middle\" && !middlePans(ctx, captureTarget))) continue;\n // The part under the down (design-014, B3b): copied onto every recognizer this down spawns.\n const downPart = ctx.get(pointer, PointerPart)?.part ?? \"\";\n // Latch group intent at the original press, before crossing the drag\n // threshold. A custom solo carry can yield immediately, without a jump.\n const movesSelection = button === \"primary\" && downPart === \"\" && profile.includes(\"drag\") &&\n ctx.read(pointer, Pointer).device !== \"touch\" && ctx.getResource(Keyboard)?.space !== true &&\n selectionDragAt(ctx, captureTarget, screen.x, screen.y, resolveToolFor(world, tool), ctx.get(pointer, PointerMods)?.shift === true);\n\n // Gesture timing anchors on the CLOCK at ingest. The 2026-07-12\n // event-timestamp anchor is retired (2026-07-17): event.timeStamp and\n // rAF now are DIFFERENT clocks under throttling (measured seconds of\n // skew), and the stall protection it bought is now the clock's own\n // property — a stalled frame contributes at most dtClampMs.\n const downMs = now;\n\n // Pinch rule: this down makes it TWO local touch pointers held — spawn a\n // Pinch watching both and suspend both pointers' single-pointer\n // recognizers (spawn this pointer's singles pre-suspended).\n let pinchPartner: Entity | undefined;\n if (ctx.read(pointer, Pointer).device === \"touch\") {\n world.query(heldTouchQ).each((pb) => {\n for (const pr of pb) {\n const other = pb.entity(pr);\n if (other === pointer) continue;\n if (world.read(other, Pointer).device !== \"touch\") continue;\n if (world.read(other, PointerButtons).buttons === 0) continue;\n // A partner already claimed by a live gesture never forms a pinch —\n // two touches dragging two widgets stay two independent gestures\n // (design-003 §9); pinch is for two FREE fingers.\n const partnerClaim = ctx.getRelation(other, ClaimedBy);\n if (partnerClaim !== undefined && !isTerminal(ctx, partnerClaim)) continue;\n pinchPartner = other;\n }\n });\n }\n const suspendedAtBirth = pinchPartner !== undefined;\n\n // iOS hold-to-lift (LongPressDrag capability, 2026-07-12): the widget's\n // Drag recognizer spawns PARKED (Pending + Sequence → this down's\n // LongPress). The dependency system hands off when the hold passes;\n // early movement fails the LongPress and the parked Drag dies with it\n // — taps and widget-internal interactions stay instant. Requires the\n // profile to spawn longPress BEFORE drag (the default select order).\n const holdToDrag =\n captureTarget !== undefined &&\n ctx.hasTag(captureTarget, LongPressDrag) &&\n profile.includes(\"longPress\");\n let lpRec: Entity | undefined;\n\n // Multi-tap REJOIN (v2 findPendingTap): a down on a MultiTap target near a\n // Pending tap's last down re-points that tap at the new pointer (count\n // preserved) instead of spawning fresh. Edge-parked Pendings never rejoin.\n let rejoined = false;\n if (button === \"primary\" && 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 // The heat's fact (design-013 §5, GLOW.md §3), on the same\n // discipline: dropSystem fills it from the post-move union.\n [DragBounds, { minX: 0, minY: 0, maxX: 0, maxY: 0 }],\n [Down, { x: screen.x, y: screen.y, ms: downMs }],\n ],\n tags: [...tags],\n });\n }\n if (kind === \"drag\" && movesSelection) ctx.addTag(rec, MovesSelection);\n ctx.addRelation(rec, Watches, pointer);\n if (downPart !== \"\") ctx.addComponent(rec, DownPart, { part: downPart });\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 (button === \"middle\" && kind !== \"drag\") continue; // the middle press is its pan's drag — never a tap, never a hold\n if (kind === \"tap\" && rejoined) continue; // the rejoined Pending tap IS this down's tap\n const rec = spawnSingle(kind);\n if (kind === \"longPress\") lpRec = rec;\n }\n\n if (pinchPartner !== undefined) {\n const partnerScreen = ctx.read(pinchPartner, PointerScreen);\n const spread = dist(screen.x, screen.y, partnerScreen.x, partnerScreen.y);\n const cx = (screen.x + partnerScreen.x) / 2;\n const cy = (screen.y + partnerScreen.y) / 2;\n const pinch = ctx.spawn({\n components: [\n [\n Pinch,\n {\n startDist: spread,\n startZoom: ctx.getResource(Camera)?.zoom ?? 1,\n cx,\n cy,\n zoomAtClaim: ctx.getResource(Camera)?.zoom ?? 1,\n },\n ],\n [Down, { x: cx, y: cy, ms: now }],\n ],\n tags: [P.tags.Possible],\n });\n ctx.addRelation(pinch, Watches, pointer);\n ctx.addRelation(pinch, Watches, pinchPartner);\n // Suspend the partner's existing singles (\"suspend, don't kill\").\n for (const rec of watchersOf(ctx, pinchPartner)) {\n if (!ctx.has(rec, Pinch)) ctx.addTag(rec, GestureSuspended);\n }\n }\n }\n },\n // The multi-tap REJOIN rebases a Pending tap's Down (edit().set above); spawns\n // are structural, not value writes. Sole declared Down writer in ctl:spawn\n // (cancelSweep/wheelSpawn/recognizerIntegrity write no cells) → no same-phase\n // co-writer, so no orderIndependent attestation.\n { name: \"recognizerSpawn\", access: { write: [Down] } },\n );\n\n // Wheel recognizer spawn rides the same ctl:spawn slot: wheel deltas landed\n // this tick (values — visible) and no live recognizer of that wheel kind watches the pointer.\n const wheelSpawn = defineSystem(\n wheelSourceQ,\n (b, ctx) => {\n const now = clk(ctx);\n for (const r of b) {\n const pointer = b.entity(r);\n const wheel = ctx.read(pointer, PointerWheel);\n const zooming = wheel.pinch !== 0;\n const panning = wheel.dx !== 0 || wheel.dy !== 0;\n if (!zooming && !panning) continue;\n // Pan and zoom have independent lifecycles. A pinch may follow a pan\n // before its silence timer expires, and both can land in one frame.\n let needZoom = zooming;\n let needPan = panning;\n for (const rec of ctx.getReverse(pointer, Watches)) {\n if (isTerminal(ctx, rec)) continue;\n if (needZoom && ctx.has(rec, WheelZoom)) needZoom = false;\n if (needPan && ctx.has(rec, WheelPan)) needPan = false;\n if (!needZoom && !needPan) break;\n }\n // An ongoing gesture needs neither a temporary list nor a screen read.\n if (!needZoom && !needPan) continue;\n const screen = ctx.read(pointer, PointerScreen);\n if (needZoom) {\n const rec = ctx.spawn({\n components: [\n [WheelZoom, { pinch: 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 if (needPan) {\n const rec = 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 },\n { name: \"wheelSpawn\" },\n );\n\n const recognizerIntegrity = defineSystem(\n anyKindQ,\n (b, ctx) => {\n for (const r of b) {\n const e = b.entity(r);\n if (isTerminal(ctx, e)) continue;\n\n // Suspension lift: no live non-terminal Pinch shares any watched pointer.\n if (ctx.hasTag(e, GestureSuspended) && !ctx.has(e, Pinch)) {\n const pointers = ctx.getRelations(e, Watches);\n const suspenderAlive = pointers.some((p) =>\n ctx.getReverse(p, Watches).some((rec) => ctx.has(rec, Pinch) && !isTerminal(ctx, rec)),\n );\n if (!suspenderAlive) ctx.removeTag(e, GestureSuspended);\n }\n\n // Required-watches count (edges to despawned pointers auto-clear). A\n // Pending recognizer is ALLOWED to outlive its watched pointer — a\n // multi-tap awaiting the next tap, or an edge-parked recognizer before\n // its source (v2 rule); only capture death cancels those (below).\n if (!ctx.hasTag(e, P.tags.Pending) && ctx.getRelations(e, Watches).length !== requiredWatches(ctx, e)) {\n P.set(ctx, e, \"Cancelled\");\n continue;\n }\n\n // Capture death — incl. remote despawns (edge auto-clears; HadCapture remembers).\n if (ctx.hasTag(e, HadCapture) && ctx.getRelation(e, Captures) === undefined) {\n P.set(ctx, e, \"Cancelled\");\n }\n }\n },\n { name: \"recognizerIntegrity\" },\n );\n\n // --- per-kind FSMs (ctl:recognize) ---\n\n const tapSystem = defineSystem(\n tapQ,\n (b, ctx) => {\n const now = clk(ctx);\n for (const r of b) {\n const e = b.entity(r);\n const pending = ctx.hasTag(e, P.tags.Pending);\n if (!ctx.hasTag(e, P.tags.Possible) && !pending) continue;\n\n if (pending) {\n // Edge-parked Pending (Sequence/RequiresFail) belongs to the dependency\n // system — never window-expire it here (v2 rule).\n if (ctx.hasTag(e, HadSequence) || ctx.hasTag(e, HadRequiresFail)) continue;\n // Multi-tap Pending: await a rejoin (recognizerSpawn) or the window closing.\n const down = ctx.read(e, Down);\n const cap = ctx.getRelation(e, Captures);\n const windowMs =\n cap !== undefined && ctx.has(cap, MultiTap)\n ? ctx.read(cap, MultiTap).windowMs\n : gs(ctx).multiTapWindowMs;\n if (now - down.ms > windowMs) P.set(ctx, e, \"Recognized\"); // window closed → final count stands\n continue;\n }\n\n const pointer = ctx.getRelations(e, Watches)[0];\n if (pointer === undefined) continue; // integrity cancels next frame\n if (ctx.hasTag(pointer, WentCancelled)) {\n P.set(ctx, e, \"Cancelled\");\n continue;\n }\n const down = ctx.read(e, Down);\n const screen = ctx.read(pointer, PointerScreen);\n const moved = dist(down.x, down.y, screen.x, screen.y);\n if (moved > gs(ctx).tapSlopPx) {\n P.set(ctx, e, \"Failed\");\n continue;\n }\n // Hold measured from Down.ms, not Tap.downAt: a rejoined multi-tap rebases\n // Down per tap while downAt keeps the FIRST down (the gesture's birth).\n const held = now - down.ms;\n if (ctx.hasTag(pointer, WentUp)) {\n if (held > gs(ctx).tapMaxMs) {\n P.set(ctx, e, \"Failed\");\n continue;\n }\n // Clean release — count it (v2): at the target count → Recognized now;\n // under it → park Pending (never reaped) until rejoin or window close.\n const tap = ctx.read(e, Tap);\n const cap = ctx.getRelation(e, Captures);\n const max = cap !== undefined && ctx.has(cap, MultiTap) ? ctx.read(cap, MultiTap).max : 1;\n const count = tap.count + 1;\n ctx.edit(e).set(Tap, { ...tap, count });\n if (count >= max) {\n P.set(ctx, e, \"Recognized\");\n } else {\n ctx.edit(e).set(Down, { ...down, ms: now }); // restart the inter-tap window from release\n P.set(ctx, e, \"Pending\");\n }\n } else if (held > gs(ctx).tapMaxMs) {\n P.set(ctx, e, \"Failed\");\n }\n }\n },\n // Down co-writers in ctl:recognize (tap park / wheel activity / dependency\n // rebase) touch DISJOINT rows — tap rows, wheel rows, edge-parked rows.\n { name: \"tapSystem\", access: { write: [Tap, Down], orderIndependent: [Down] } },\n );\n\n const longPressSystem = defineSystem(\n longPressQ,\n (b, ctx) => {\n const now = clk(ctx);\n for (const r of b) {\n const e = b.entity(r);\n const pointer = ctx.getRelations(e, Watches)[0];\n if (pointer === undefined) continue;\n const screen = ctx.read(pointer, PointerScreen);\n const lp = ctx.read(e, LongPress);\n\n if (ctx.hasTag(pointer, WentCancelled)) {\n P.set(ctx, e, \"Cancelled\");\n continue;\n }\n\n if (ctx.hasTag(e, P.tags.Possible)) {\n if (ctx.hasTag(pointer, WentUp)) {\n P.set(ctx, e, \"Failed\"); // released before the hold\n continue;\n }\n if (dist(lp.startX, lp.startY, screen.x, screen.y) > gs(ctx).longPressSlopPx) {\n P.set(ctx, e, \"Failed\");\n continue;\n }\n if (now - lp.downAt >= gs(ctx).longPressMs) {\n ctx.edit(e).set(LongPress, { ...lp, curX: screen.x, curY: screen.y });\n P.set(ctx, e, \"Recognized\"); // discrete claim; continuous tail follows\n }\n continue;\n }\n\n if (ctx.hasTag(e, P.tags.Recognized)) {\n ctx.edit(e).set(LongPress, { ...lp, curX: screen.x, curY: screen.y }); // the tail\n if (ctx.hasTag(pointer, WentUp)) P.set(ctx, e, \"Ended\");\n }\n }\n },\n { name: \"longPressSystem\", access: { write: [LongPress] } },\n );\n\n const dragSystem = defineSystem(\n dragQ,\n (b, ctx) => {\n const dtMs = ctx.getResource(FrameInfo)?.dt ?? 16;\n for (const r of b) {\n const e = b.entity(r);\n const pointer = ctx.getRelations(e, Watches)[0];\n if (pointer === undefined) continue;\n const screen = ctx.read(pointer, PointerScreen);\n const d = ctx.read(e, Drag);\n\n if (ctx.hasTag(pointer, WentCancelled)) {\n P.set(ctx, e, \"Cancelled\");\n continue;\n }\n\n if (ctx.hasTag(e, P.tags.Possible)) {\n // Released before it activated → Failed, inside the dead zone or past\n // it (2026-09-26): a drag activates only while its pointer is held.\n // Pressed travel can fold into the release's own tick (a flick, a\n // starved frame), and `WentUp` is one-tick — a drag promoted HERE\n // would never see its release and stay Active on a lifted pointer,\n // the object glued to the cursor until the next press.\n if (ctx.hasTag(pointer, WentUp)) {\n P.set(ctx, e, \"Failed\");\n continue;\n }\n const down = ctx.read(e, Down);\n // Adopted insert drags (tray ghosts, 2026-07-19) have NO tap-vs-drag\n // ambiguity — the user is already mid-drag when the synthetic down\n // lands, so the dead zone only adds anchor drift (the ghost sits\n // still while the pointer travels the slop). First move activates.\n const cap = ctx.getRelation(e, Captures);\n const ghostDrag = cap !== undefined && ctx.has(cap, InsertGhost);\n const slopPx = ghostDrag ? 0 : gs(ctx).dragSlopPx;\n if (dist(down.x, down.y, screen.x, screen.y) > slopPx) {\n // Origin measured FROM DEAD-ZONE EXIT (no jump on promote) —\n // EXCEPT ghost drags: the ghost spawned anchored AT the down, so\n // every pixel since the down belongs to it. PointerScreen is the\n // tick's FOLDED latest, so an exit-origin bakes in whatever\n // travel folded into the activation tick (46px at a starved\n // 2fps, 2–8px on a fast real-browser flick — the anchor-drift\n // field bug, 2026-07-19). The down IS the anchor; use it.\n ctx.edit(e).set(Drag, {\n startX: ghostDrag ? down.x : screen.x,\n startY: ghostDrag ? down.y : screen.y,\n totalX: 0,\n totalY: 0,\n velX: 0,\n velY: 0,\n zoomAtClaim: ctx.getResource(Camera)?.zoom ?? 1,\n });\n const canvas = ctx.getResource(CanvasSession);\n if (canvas?.state === \"attached\") {\n ctx.addComponent(e, CanvasIntentScope, {\n documentEpoch: canvas.documentEpoch,\n canvasEpoch: canvas.epoch,\n frame: canvas.frame,\n });\n }\n P.set(ctx, e, \"Active\");\n }\n continue;\n }\n\n if (ctx.hasTag(e, P.tags.Active)) {\n const totalX = screen.x - d.startX;\n const totalY = screen.y - d.startY;\n const frameDx = totalX - d.totalX;\n const frameDy = totalY - d.totalY;\n const dtS = Math.max(dtMs, 1) / 1000;\n const alpha = 0.3; // EMA release velocity (v2 constant)\n ctx.edit(e).set(Drag, {\n ...d,\n totalX,\n totalY,\n velX: d.velX + alpha * (frameDx / dtS - d.velX),\n velY: d.velY + alpha * (frameDy / dtS - d.velY),\n });\n if (ctx.hasTag(pointer, WentUp)) P.set(ctx, e, \"Ended\");\n }\n }\n },\n { name: \"dragSystem\", access: { write: [Drag] } },\n );\n\n const pinchSystem = defineSystem(\n pinchQ,\n (b, ctx) => {\n for (const r of b) {\n const e = b.entity(r);\n const pointers = ctx.getRelations(e, Watches);\n if (pointers.length !== 2) continue; // integrity cancels\n const [pa, pb] = pointers as [Entity, Entity];\n if (ctx.hasTag(pa, WentCancelled) || ctx.hasTag(pb, WentCancelled)) {\n P.set(ctx, e, \"Cancelled\");\n continue;\n }\n const sa = ctx.read(pa, PointerScreen);\n const sb = ctx.read(pb, PointerScreen);\n const spread = dist(sa.x, sa.y, sb.x, sb.y);\n const cx = (sa.x + sb.x) / 2;\n const cy = (sa.y + sb.y) / 2;\n const pin = ctx.read(e, Pinch);\n const anyUp = ctx.hasTag(pa, WentUp) || ctx.hasTag(pb, WentUp);\n\n if (ctx.hasTag(e, P.tags.Possible)) {\n if (anyUp) {\n P.set(ctx, e, \"Cancelled\"); // lost a finger pre-activation\n continue;\n }\n if (Math.abs(spread - pin.startDist) > gs(ctx).pinchSlopPx) {\n const zoom = ctx.getResource(Camera)?.zoom ?? 1;\n // Re-baseline at activation (v2): the dead-zone spread never zooms.\n ctx.edit(e).set(Pinch, { startDist: spread, startZoom: zoom, cx, cy, zoomAtClaim: zoom });\n P.set(ctx, e, \"Active\");\n }\n continue;\n }\n\n if (ctx.hasTag(e, P.tags.Active)) {\n ctx.edit(e).set(Pinch, { ...pin, cx, cy });\n if (anyUp) P.set(ctx, e, \"Ended\");\n }\n }\n },\n { name: \"pinchSystem\", access: { write: [Pinch] } },\n );\n\n const wheelSystem = defineSystem(\n wheelKindQ,\n (b, ctx) => {\n const now = clk(ctx);\n for (const r of b) {\n const e = b.entity(r);\n if (isTerminal(ctx, e)) continue;\n const pointer = ctx.getRelations(e, Watches)[0];\n if (pointer === undefined) continue;\n const wheel = ctx.read(pointer, PointerWheel);\n const screen = ctx.read(pointer, PointerScreen);\n const down = ctx.read(e, Down);\n const isZoom = ctx.has(e, WheelZoom);\n // A ceded tick (WheelHandled — native scroll consumed the deltas) is\n // wheel SILENCE to a live recognizer: don't feed the deltas into the\n // camera, zero the per-frame values, let the end-silence timer run.\n // The spawn gate alone can't cover this — a recognizer already live\n // within `wheelEndSilenceMs` would otherwise pan from ceded deltas.\n const ceded = ctx.hasTag(pointer, WheelHandled);\n const active = !ceded && (isZoom ? wheel.pinch !== 0 : wheel.dx !== 0 || wheel.dy !== 0);\n\n if (active) {\n if (isZoom) {\n ctx.edit(e).set(WheelZoom, { pinch: wheel.pinch, anchorX: screen.x, anchorY: screen.y });\n } else {\n ctx.edit(e).set(WheelPan, { dx: wheel.dx, dy: wheel.dy, anchorX: screen.x, anchorY: screen.y });\n }\n ctx.edit(e).set(Down, { x: screen.x, y: screen.y, ms: now }); // last-activity timer\n if (ctx.hasTag(e, P.tags.Possible)) P.set(ctx, e, \"Active\");\n } else {\n // Zero the per-frame deltas so cameraControl never re-applies stale ones.\n if (isZoom) {\n const z = ctx.read(e, WheelZoom);\n if (z.pinch !== 0) ctx.edit(e).set(WheelZoom, { ...z, pinch: 0 });\n } else {\n const p = ctx.read(e, WheelPan);\n if (p.dx !== 0 || p.dy !== 0) ctx.edit(e).set(WheelPan, { ...p, dx: 0, dy: 0 });\n }\n if (ctx.hasTag(e, P.tags.Active) && now - down.ms > gs(ctx).wheelEndSilenceMs) {\n P.set(ctx, e, \"Ended\");\n }\n }\n }\n },\n { name: \"wheelSystem\", access: { write: [WheelPan, WheelZoom, Down], orderIndependent: [Down] } },\n );\n\n // dependency (last in ctl:recognize; v2 dependencySystem) — resolve the Pending\n // EDGE cases. `RequiresFail` gates the EXIT (finish once `other` fails);\n // `Sequence` gates the ENTRANCE (wait for `after` to pass, then hand off,\n // rebasing Down). A multi-tap Pending has neither edge → untouched (tapSystem\n // owns its window). TIMING (differs from v2's immediate-write model): phase\n // flips flush at the ctl:recognize boundary, so this system observes a\n // target's SAME-GROUP transition one frame later via its persistent tag —\n // safe because reap waits terminal+1 (cleanup.ts), and this system's own\n // flips flush before ctl:arbitrate reads their Just* markers this frame.\n const dependencySystem = defineSystem(\n pendingQ,\n (b, ctx) => {\n const now = clk(ctx);\n for (const r of b) {\n const e = b.entity(r);\n if (ctx.hasTag(e, HadRequiresFail)) {\n const other = ctx.getRelation(e, RequiresFail);\n if (other === undefined) {\n P.set(ctx, e, \"Failed\"); // orphaned edge (target despawned; edge auto-cleared)\n } else if (ctx.hasTag(other, P.tags.Failed) || ctx.hasTag(other, P.tags.Cancelled)) {\n // `other` failed → this may finish: discrete (Tap) → Recognized, continuous → Active.\n P.set(ctx, e, ctx.has(e, Tap) ? \"Recognized\" : \"Active\");\n } else if (ctx.hasTag(other, P.tags.Recognized) || ctx.hasTag(other, P.tags.Active)) {\n P.set(ctx, e, \"Failed\"); // `other` won → this loses\n } // else still waiting (other Possible/Pending)\n continue;\n }\n if (ctx.hasTag(e, HadSequence)) {\n const after = ctx.getRelation(e, Sequence);\n if (after === undefined) {\n P.set(ctx, e, \"Failed\");\n } else if (ctx.hasTag(after, P.tags.Active) || ctx.hasTag(after, P.tags.Recognized)) {\n // Hand off: rebase Down to the current pointer, enter, and RETIRE the\n // source — else it keeps its pointer claimed and arbitration would\n // fail this freshly-handed-off recognizer (v2 rule).\n const p = ctx.getRelations(e, Watches)[0];\n if (p !== undefined) {\n const screen = ctx.read(p, PointerScreen);\n ctx.edit(e).set(Down, { x: screen.x, y: screen.y, ms: now });\n }\n P.set(ctx, e, \"Possible\");\n // v2 retired an ACTIVE source; v3 must retire any still-live one —\n // LongPress claims at Recognized and keeps a continuous tail, and\n // arbitration's claim is first-wins (a live source would hold the\n // pointer against the handed-off recognizer forever).\n if (!isTerminal(ctx, after)) P.set(ctx, after, \"Ended\");\n } else if (ctx.hasTag(after, P.tags.Failed) || ctx.hasTag(after, P.tags.Cancelled)) {\n P.set(ctx, e, \"Failed\");\n } // else still waiting\n }\n }\n },\n { name: \"dependencySystem\", access: { write: [Down], orderIndependent: [Down] } },\n );\n\n return {\n cancelSweep,\n recognizerSpawn,\n wheelSpawn,\n recognizerIntegrity,\n tapSystem,\n longPressSystem,\n dragSystem,\n pinchSystem,\n wheelSystem,\n dependencySystem,\n };\n}\n","import { defineQuery, type Entity, type SystemCtx } from \"@vibecook/strata-ecs\";\nimport { screenToWorld } from \"@ice/kernel\";\nimport { Active, Camera, CanvasSurface, Culled, HandleSpec, Locked, Movable, Port, Position, Selected, SelectionMovable, Size } from \"../catalog\";\nimport type { Tool } from \"../tools/define-tool\";\n\nconst selectionQ = defineQuery([Selected, Position, Size]);\n\n/**\n * Decide ONCE at pointer-down, never during hover or rendering. Empty space in\n * a multi-selection can carry the group; real objects, controls and handles\n * keep their pick priority. Shift on the canvas starts an additive marquee.\n */\nexport function selectionDragAt(ctx: SystemCtx, target: Entity | undefined, sx: number, sy: number, tool: Tool, shift: boolean): boolean {\n if (!tool.gates.movable || tool.route.widgetDrag !== \"move\") return false;\n const onCanvas = target === undefined || ctx.hasTag(target, CanvasSurface);\n if (onCanvas) {\n if (shift || tool.route.canvasDrag !== \"marquee\") return false;\n } else if (!ctx.hasTag(target, Selected) || ctx.has(target, HandleSpec) || ctx.has(target, Port) ||\n (!ctx.hasTag(target, Movable) && !ctx.hasTag(target, SelectionMovable))) return false;\n\n let count = 0;\n let movable = false;\n let minX = Number.POSITIVE_INFINITY;\n let minY = Number.POSITIVE_INFINITY;\n let maxX = Number.NEGATIVE_INFINITY;\n let maxY = Number.NEGATIVE_INFINITY;\n ctx.query(selectionQ).each(b => {\n for (const r of b) {\n const e = b.entity(r);\n if (ctx.hasTag(e, Culled) && !ctx.hasTag(e, Active)) continue;\n const p = ctx.read(e, Position);\n const s = ctx.read(e, Size);\n count++;\n if (!ctx.hasTag(e, Locked) && (ctx.hasTag(e, Movable) || ctx.hasTag(e, SelectionMovable))) movable = true;\n minX = Math.min(minX, p.x); minY = Math.min(minY, p.y);\n maxX = Math.max(maxX, p.x + s.w); maxY = Math.max(maxY, p.y + s.h);\n }\n });\n if (count < 2 || !movable) return false;\n if (!onCanvas) return true;\n const p = screenToWorld(sx, sy, ctx.getResource(Camera) ?? { x: 0, y: 0, zoom: 1 });\n return p.x >= minX && p.x <= maxX && p.y >= minY && p.y <= maxY;\n}\n","/**\n * The button a press began with (petition I28) — read off the pointer's `PointerButtons.buttons` on its `WentDown` tick, which is\n * the down fact's own PointerEvent `buttons` mask (ingest's fold ends at the transition, l0-input.ts). A pointerdown carries the\n * one button that pressed: a second button joining a held press arrives as a pointermove (the Pointer Events spec's chorded\n * buttons), never as a down.\n *\n * - PRIMARY — bit 1 (a mouse's left button, a touch, a pen's tip) or 32 (a pen's eraser end: the board's eraser reads it), or\n * no bit at all (a synthetic down that names no button — every press, as before I28). The recognizers take it, and the hand.\n * - MIDDLE — bit 4: a drag only where its drag pans — `dragRoute`'s device convention on the bare canvas (design-003 §4.4), the\n * hand's pan brought close (held.ts) — and never a tap, a long press, or a grab of what is under it.\n * - SECONDARY — anything else (2: the right button, a pen's barrel; 8/16: back and forward): a POINT. Its point, its pick and\n * its hover move with it (ingest, `picking`); nothing selects, drags, enters or works a part. Its `contextmenu` is the host's.\n *\n * Pure over the ctx: no writes.\n */\nimport type { Entity, SystemCtx } from \"@vibecook/strata-ecs\";\nimport { CanvasSurface, HandleSpec, Port, Position } from \"../catalog\";\n\nexport type PressButton = \"primary\" | \"middle\" | \"secondary\";\n\n/** The button a press began with, from the `buttons` mask its down carried. */\nexport function pressButton(buttons: number): PressButton {\n if (buttons === 0 || (buttons & (1 | 32)) !== 0) return \"primary\";\n return (buttons & 4) !== 0 ? \"middle\" : \"secondary\";\n}\n\n/**\n * Whether a MIDDLE press on `captured` is a drag: where `dragRoute` sends a drag to its CANVAS branch, whose device convention pans\n * — the bare canvas, or a capture that is no handle, no port and no object (a wire). Over a handle, a port or an object it is a\n * point: before I28 it resized, connected or MOVED what it landed on.\n */\nexport function middlePans(ctx: Pick<SystemCtx, \"has\" | \"hasTag\">, captured: Entity | undefined): boolean {\n if (captured === undefined || ctx.hasTag(captured, CanvasSurface)) return true;\n return !ctx.has(captured, HandleSpec) && !ctx.has(captured, Port) && !ctx.has(captured, Position);\n}\n","/**\n * Selection ops — bulk `Selected` tag flips from app handlers (design-003 §5.1).\n *\n * `Selected` is a runtime rider; toggling it via `world.addTag/removeTag` is a\n * legal free write from an app handler (design-001 §2 rule 4 — riders are not\n * doc cells). The engine bumps the `SelectionVersion` stamp (helpers/version-stamps.ts)\n * on every actual change, in addition to firing the optional `onChange` hook the\n * app wires for its own bookkeeping. Selection is committed ONCE per interaction,\n * never per frame (the v1 marquee lesson) — so change-only firing matters for both.\n */\nimport { defineQuery } from \"@vibecook/strata-ecs\";\nimport type { Entity, World } from \"@vibecook/strata-ecs\";\nimport { Selected } from \"../catalog/selection-presence\";\nimport { bumpVersion, SelectionVersion } from \"../helpers/version-stamps\";\n\nexport type SelectionMode = \"replace\" | \"toggle\" | \"add\";\n\nconst selectedQuery = defineQuery([Selected]);\n\n/** All entities currently carrying the `Selected` rider. */\nexport function selectedEntities(world: World): Entity[] {\n const out: Entity[] = [];\n world.query(selectedQuery).each((batch) => {\n for (const row of batch) out.push(batch.entity(row));\n });\n return out;\n}\n\n/**\n * Apply a selection.\n * - `replace`: exactly `entities` end up selected (others cleared).\n * - `toggle`: flip each of `entities`.\n * - `add`: union `entities` into the current selection.\n * `onChange` fires once, only if a tag actually flipped.\n */\nexport function setSelection(\n world: World,\n entities: Iterable<Entity>,\n mode: SelectionMode,\n onChange?: () => void,\n): void {\n const next = new Set(entities);\n let changed = false;\n\n if (mode === \"replace\") {\n for (const e of selectedEntities(world)) {\n if (!next.has(e)) {\n world.removeTag(e, Selected);\n changed = true;\n }\n }\n for (const e of next) {\n if (!world.hasTag(e, Selected)) {\n world.addTag(e, Selected);\n changed = true;\n }\n }\n } else if (mode === \"toggle\") {\n for (const e of next) {\n if (world.hasTag(e, Selected)) world.removeTag(e, Selected);\n else world.addTag(e, Selected);\n changed = true;\n }\n } else {\n for (const e of next) {\n if (!world.hasTag(e, Selected)) {\n world.addTag(e, Selected);\n changed = true;\n }\n }\n }\n\n if (changed) {\n bumpVersion(world, SelectionVersion);\n onChange?.();\n }\n}\n\n/** Clear the whole selection. `onChange` fires once, only if something was selected. */\nexport function clearSelection(world: World, onChange?: () => void): void {\n let changed = false;\n for (const e of selectedEntities(world)) {\n world.removeTag(e, Selected);\n changed = true;\n }\n if (changed) {\n bumpVersion(world, SelectionVersion);\n onChange?.();\n }\n}\n","/**\n * L3 — connect behavior (design-003 §5 item 8, §4.5 connectClaim; design-004 §6;\n * `ctl:claim` + `ctl:behave`). The node-editor core gesture: drag from a source\n * port to a compatible target port, commit ONE wire.\n *\n * `connectClaim` (JustActive × RoutedConnect): latch the source port — the\n * recognizer's `Captures` target must be a Port entity (dragRoute guarantees it,\n * or the connect tool started the drag). Recognizer field-sets are per-kind\n * (Drag), so per-gesture claim state lives in a closure Map keyed by recognizer\n * (the `tweenStart`/camera-sim precedent), holding the source WIDGET + port id +\n * world anchor + accepts-keys. The preview buffer arms here.\n *\n * `connectBehavior` (a TICK system, like marquee, so it can CLEAR the preview the\n * frame after the gesture ends): per Active frame it writes the out-of-ECS\n * `WirePreviewBuffer` (source anchor → pointer world, snapped to a COMPATIBLE\n * port anchor when the watched pointer `Targets` one; type check via the widgets'\n * port decls; self-wire never compatible). On `JustEnded` over a compatible port\n * it commits `{kind:\"connect\", wires:[{from,to,fromPort,toPort}]}` (the doc sink\n * spawns the wire); elsewhere it commits nothing.\n *\n * PREVIEW CONTINUITY — SIMPLIFICATION ACCEPTED (design-003 §5.8 / design-002 §8):\n * the preview clears on JustEnded+1 (one linger frame) rather than persisting\n * until the projected wire entity places (the promote-sweep analog). Full\n * continuity — hand the preview off to the freshly-synced wire with no blink —\n * is polish deferred; the one-frame gap is invisible in practice.\n */\nimport type { Entity, System, SystemCtx, TickSystem, World } from \"@vibecook/strata-ecs\";\nimport { defineQuery, defineSystem, defineTickSystem } from \"@vibecook/strata-ecs\";\nimport { type CameraState, type SpatialIndex, portAnchor, screenToWorld } from \"@ice/kernel\";\nimport {\n Camera,\n Captures,\n Drag,\n GesturePhases,\n Port,\n PortOf,\n PointerScreen,\n Position,\n RoutedConnect,\n Size,\n Targets,\n Watches,\n} from \"../catalog\";\nimport { widgetTypeFor } from \"../canvas/engine-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\";\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(world: World, ctx: SystemCtx, e: Entity) {\n const type = ctx.get(e, PrefabId)?.id;\n if (typeof type !== \"string\") return undefined;\n const decls = widgetTypeFor(world, 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(world: World, ctx: SystemCtx, widget: Entity, portId: string): { x: number; y: number } | undefined {\n const decls = declsOf(world, 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(world, ctx, widget, portId);\n if (anchor === undefined) continue;\n const decls = declsOf(world, 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(world, ctx, targetWidget);\n const accepts = decls?.find((d) => d.id === targetPortId)?.accepts ?? [];\n if (compatible(src.accepts, accepts)) {\n const a = anchorOf(world, 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 * precedent of the retired selection box). 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 { widgetTypeFor } from \"../canvas/engine-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\";\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(\n world: World,\n ctx: SystemCtx,\n e: Entity,\n): readonly WidgetPortDecl[] | undefined {\n const type = ctx.get(e, PrefabId)?.id;\n if (typeof type !== \"string\") return undefined;\n const decls = widgetTypeFor(world, 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(world, 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(world, 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(world, 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(world, 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(world, 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(world, ctx, widget) ?? []);\n for (const [portId, rec] of wp.ports) {\n const slot = slots.get(portId);\n if (slot === undefined || !ctx.isAlive(rec.entity)) continue;\n const a = portAnchor(rect, slot);\n if (a.x !== rec.ax || a.y !== rec.ay) {\n ctx.edit(rec.entity).set(PortAnchor, { x: a.x, y: a.y });\n index.upsert(rec.entity, portAabb(a.x, a.y));\n rec.ax = a.x;\n rec.ay = a.y;\n changed = true;\n }\n }\n }\n for (const w of reap) byWidget.delete(w);\n\n if (changed) bumpVersion(world, SpatialVersion);\n },\n { name: \"portMaterialize\", access: { write: [PortAnchor] } },\n );\n}\n","/**\n * Churn guard — the `runIf` half of the petition-7 gating pattern\n * (design-002 §4 \"guards live in runIf, never the body\" × strata 0.7.0\n * `world.changes`).\n *\n * `activeMembership` gates by draining a collector INSIDE its tick body\n * (legal there: it declares no writes, so an early-out stamps nothing).\n * Systems that DECLARE `access.write` cannot use that shape — strata\n * blanket-stamps declared writes for any system that RUNS, even one that\n * early-outs (see helpers/version-stamps.ts) — so their gate must be a real\n * `runIf`. But a naive collector-in-runIf would LOSE the drained delta when\n * the body runs: this guard drains in `runIf`, stashes the delta, and hands\n * it to the body via `take()` in the same frame.\n *\n * Contract:\n * - `runIf` drains the collector every frame (collector creation is lazy —\n * a guard whose system is never installed never journals) and evaluates\n * the optional `extra` trigger (a value-compare closure, e.g. \"camera\n * zoom changed\"; it is called every frame so it can keep its own cache\n * current). Returns true iff there is work.\n * - `take()` (body, same frame) returns the work: `full` means rebuild\n * everything (first run, `world.reset`, coarse writes, or `extra` fired);\n * otherwise `changed`/`removed` are the journaled entities. The arrays\n * alias the collector's internal buffers — valid until the next drain,\n * i.e. for the body that runs this frame; do not retain them.\n */\nimport type { CollectOptions, Entity, World } from \"@vibecook/strata-ecs\";\nimport type { ChangeCollector } from \"@vibecook/strata-ecs\";\n\nexport interface ChurnWork {\n /** Rebuild everything: first run, reset, coarse writes, or `extra` fired. */\n readonly full: boolean;\n readonly changed: readonly Entity[];\n readonly removed: readonly Entity[];\n}\n\nexport interface ChurnGuard {\n /** Drop into a system's `runIf`. */\n readonly runIf: () => boolean;\n /** The work stashed by this frame's `runIf` (undefined if it returned false). */\n take(): ChurnWork | undefined;\n}\n\nconst NO_ENTITIES: readonly Entity[] = [];\n\nexport function makeChurnGuard(\n world: World,\n collect: CollectOptions,\n extra?: () => boolean,\n): ChurnGuard {\n let collector: ChangeCollector | undefined;\n let seeded = false;\n let stash: ChurnWork | undefined;\n\n return {\n runIf: () => {\n if (collector === undefined) collector = world.changes.collect(collect);\n const delta = collector.drain();\n const extraFired = extra?.() ?? false;\n const full = !seeded || delta.reset || delta.coarse.length > 0 || extraFired;\n seeded = true;\n if (!full && delta.changed.length === 0 && delta.removed.length === 0) {\n stash = undefined;\n return false;\n }\n stash = full\n ? { full: true, changed: NO_ENTITIES, removed: delta.removed }\n : { full: false, changed: delta.changed, removed: delta.removed };\n return true;\n },\n take: () => {\n const s = stash;\n stash = undefined;\n return s;\n },\n };\n}\n","/**\n * Chrome derive systems (design-004 §5 chrome plane, §8 LOD; `derive` phase).\n *\n * Two systems, both derive-scheduled, both write change-only:\n *\n * `selectionChrome` — maintains the POOLED resize-handle entities mirroring the\n * current `Selected` set: 8 handles carrying Position + Size + `HandleSpec{anchor}`,\n * placed about the selection's union bbox. They exist only when EVERY selected\n * entity is Resizable and none is taped (Locked) — v1 parity; any other\n * selection gets no engine chrome (the desk's marks draw its look).\n *\n * HANDLE PICKING (the point of the design): handles carry a world AABB, so the\n * `react`-phase `spatialSync` indexes them automatically and `picking` resolves\n * a corner grab to the handle (HandleSpec has pick priority) → `dragRoute`\n * routes `RoutedResize` → `resizeBehavior` runs. Nothing here touches the index.\n *\n * HANDLES ARE SCREEN-CONSTANT: a handle's world size is `HANDLE_PICK_PX / zoom`\n * so its on-screen hit target stays ~constant across zoom. The tradeoff: the\n * handles must be recomputed whenever the camera zoom changes, so this system\n * runs every frame a selection exists and rewrites the 8 handles' Position/Size\n * change-only (a zoom change restamps 8 entities — small, bounded N).\n *\n * THE SELECTION BOX LEFT AT design-015 D7: the pooled box entity carried the\n * union bbox in a `SelectionBox` value (with a `VisualOf` edge from each handle)\n * for the P4 DOM chrome that drew it; that chrome was deleted at D5b, nothing read\n * the box, and it was rewritten every frame the union moved (every drag frame).\n * Only what picking reads stays.\n *\n * POOL LIFECYCLE: the handles spawn once via `ctx` (runtime prefab class) when a\n * resizable selection appears and are reaped via `ctx.destroy` when it empties.\n * On the spawn frame they 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 `Size`, width-thresholded into\n * 5 tiers with ±10% boundary hysteresis. Added lazily (on `WidgetEquipped`\n * widgets, once measured) and thereafter written ONLY when the tier changes —\n * the LOD signal must be stable within a tier so the measure→tier→content→\n * measure loop converges (§2). The stored w,h are the effective size at the\n * tier transition (what the tier \"was computed from\").\n */\nimport type { Entity, System, SystemCtx, TickSystem, World } from \"@vibecook/strata-ecs\";\nimport { defineQuery, defineSystem, defineTickSystem } from \"@vibecook/strata-ecs\";\nimport {\n Camera,\n ChromeSettings,\n Culled,\n Grab,\n HandleSpec,\n Locked,\n Position,\n Resizable,\n Selected,\n Size,\n WidgetBreakpoint,\n} from \"../catalog\";\nimport { selectedEntities } from \"../ops/selection\";\nimport { WidgetEquipped } from \"../widget/define-widget\";\nimport { Active } from \"../catalog/camera-derived\";\nimport { makeChurnGuard } from \"../helpers/churn-guard\";\nimport { navFlightActive } from \"./nav-flight\";\n\n// --- selection chrome ---------------------------------------------------------\n\n/** Handle world size = this / zoom → ~constant on-screen hit target across zoom. */\nconst HANDLE_PICK_PX = 10;\n\n/** The 8 handle anchors, in a fixed order the pool aligns to. */\nconst HANDLE_ANCHORS = [\"nw\", \"n\", \"ne\", \"e\", \"se\", \"s\", \"sw\", \"w\"] as const;\ntype HandleAnchor = (typeof HANDLE_ANCHORS)[number];\n\ninterface Rect {\n x: number;\n y: number;\n w: number;\n h: number;\n}\n\n/** The center point (world) of a handle for one anchor over the bbox. */\nfunction anchorPoint(anchor: HandleAnchor, b: Rect): { x: number; y: number } {\n const cx = b.x + b.w / 2;\n const cy = b.y + b.h / 2;\n const l = b.x;\n const r = b.x + b.w;\n const t = b.y;\n const bot = b.y + b.h;\n switch (anchor) {\n case \"nw\":\n return { x: l, y: t };\n case \"n\":\n return { x: cx, y: t };\n case \"ne\":\n return { x: r, y: t };\n case \"e\":\n return { x: r, y: cy };\n case \"se\":\n return { x: r, y: bot };\n case \"s\":\n return { x: cx, y: bot };\n case \"sw\":\n return { x: l, y: bot };\n default:\n return { x: l, y: cy }; // \"w\"\n }\n}\n\n/** A handle's world AABB (top-left + size), centered on its anchor point. */\nfunction handleRect(anchor: HandleAnchor, b: Rect, worldSize: number): Rect {\n const p = anchorPoint(anchor, b);\n return { x: p.x - worldSize / 2, y: p.y - worldSize / 2, w: worldSize, h: worldSize };\n}\n\nconst selectedQ = defineQuery([Selected]);\n\nexport function createSelectionChromeSystem(world: World): TickSystem {\n // Pool state (a derived cache, not world state): the 8 handles, aligned to\n // HANDLE_ANCHORS, plus the last-written geometry for change-only writes.\n let handleEntities: Entity[] = [];\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 spawnHandles = (ctx: SystemCtx, bbox: Rect, worldSize: number): 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 handleEntities.push(he);\n handleCache.set(he, hr);\n }\n };\n\n // Tick system (strata 0.5.0): exactly one pass per frame by construction\n // (spawn/destroy are NOT idempotent — cardinality is the scheduler's now).\n const sys = defineTickSystem(\n (ctx) => {\n // Union bbox over the selection's positioned entities.\n let minX = Number.POSITIVE_INFINITY;\n let minY = Number.POSITIVE_INFINITY;\n let maxX = Number.NEGATIVE_INFINITY;\n let maxY = Number.NEGATIVE_INFINITY;\n let count = 0;\n // Resize affordance gate (field report 2026-07-12, v1 parity): handles\n // exist only when EVERY selected entity is Resizable — a non-resizable\n // card gets no grips (mixed multi-select is conservatively grip-less too).\n let allResizable = true;\n // The tape (design-015 §5.1, D4a): a taped widget is never resized by a gesture (resizeClaim gives it no rider),\n // so a selection holding one shows no grips.\n let anyLocked = false;\n // Visual drag-lift factor (2026-07-17): a Grab-bed member is scaled about its center by\n // the app's lift; inflate its rect by the mirrored setting so the handles keep wrapping what\n // the user sees. 1 (default) ⇒ pure ECS union.\n const chrome = ctx.getResource(ChromeSettings);\n const liftScale = chrome?.liftScale ?? 1;\n for (const e of selectedEntities(world)) {\n if (!ctx.has(e, Position)) continue;\n // Scope filter (field bug 2026-07-17, the wires-collect rule): a\n // selection that rode a nav transition must not draw chrome for\n // OTHER frames' widgets — their coords are frame-local nonsense\n // here. Non-member signature: Culled ∧ ¬Active (viewport-culled\n // members stay Culled ∧ Active and keep their chrome; bare\n // membership-less worlds carry neither tag).\n if (ctx.hasTag(e, Culled) && !ctx.hasTag(e, Active)) continue;\n if (!ctx.hasTag(e, Resizable)) allResizable = false;\n if (ctx.hasTag(e, Locked)) anyLocked = true;\n const p = ctx.read(e, Position);\n const s = ctx.get(e, Size);\n let w = s?.w ?? 0;\n let h = s?.h ?? 0;\n let x = p.x;\n let y = p.y;\n if (ctx.has(e, Grab)) {\n if (liftScale !== 1) {\n x -= (w * (liftScale - 1)) / 2;\n y -= (h * (liftScale - 1)) / 2;\n w *= liftScale;\n h *= liftScale;\n }\n }\n minX = Math.min(minX, x);\n minY = Math.min(minY, y);\n maxX = Math.max(maxX, x + w);\n maxY = Math.max(maxY, y + h);\n count++;\n }\n\n if (!(count > 0 && allResizable && !anyLocked)) {\n if (handleEntities.length > 0) reapHandles(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 (handleEntities.length === 0) {\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 spawnHandles(ctx, bbox, worldSize);\n return;\n }\n // Pool exists (placed) — change-only value writes.\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 // orderIndependent (petition I34): its writes land on its OWN handle pool alone — rows disjoint from every other derive\n // writer of Position/Size (the tray's lay writes the tray's specimens alone)\n access: { write: [Position, Size], orderIndependent: [Position, Size] },\n // Run while there is a selection to mirror OR a pool still to reap.\n runIf: () => world.firstOf(selectedQ) !== undefined || handleEntities.length > 0,\n },\n );\n\n return sys;\n}\n\n// --- breakpoints --------------------------------------------------------------\n\n/** Tier width thresholds (px). Engine defaults pending design-005 facade config. */\nconst TIER_THRESHOLDS = [80, 160, 320, 560] as const;\nconst TIER_NAMES = [\"micro\", \"compact\", \"normal\", \"expanded\", \"detailed\"] as const;\ntype Tier = (typeof TIER_NAMES)[number];\n/** Boundary hysteresis: cross up at +10%, down at -10%, before the tier flips. */\nconst TIER_HYSTERESIS = 0.1;\n\n/** Raw tier index (no hysteresis) — the seed for a widget's first computation. */\nfunction rawTierIndex(w: number): number {\n let i = 0;\n while (i < TIER_THRESHOLDS.length) {\n const t = TIER_THRESHOLDS[i];\n if (t === undefined || w < t) break;\n i++;\n }\n return i;\n}\n\n/** Tier index from width, holding `cur` unless the ±10% band is crossed. */\nfunction hysteresisTierIndex(w: number, cur: number): number {\n let i = cur;\n while (i < TIER_THRESHOLDS.length) {\n const t = TIER_THRESHOLDS[i]; // upper boundary of tier i\n if (t === undefined || w < t * (1 + TIER_HYSTERESIS)) break;\n i++;\n }\n while (i > 0) {\n const t = TIER_THRESHOLDS[i - 1]; // lower boundary of tier i\n if (t === undefined || w >= t * (1 - TIER_HYSTERESIS)) break;\n i--;\n }\n return i;\n}\n\nfunction clampU16(v: number): number {\n return Math.max(0, Math.min(65535, Math.round(v)));\n}\n\n// ACTIVE-scoped (2026-07-15 gate): tiers drive RENDERED content; non-active\n// widgets (closed-container content) are frozen-while-hidden by design and\n// recompute on re-activation via the Active-tag journal below. This is what\n// bounds a zoom gesture's cost to the current frame's content.\nconst equippedWidgetQ = defineQuery([Size, WidgetEquipped, Active]);\n\n/** One entity's tier pass (shared by the full walk and the delta path). */\nfunction retier(ctx: SystemCtx, e: Entity, w: number, h: number, zoom: number): void {\n const ew = w;\n const eh = h;\n const cw = clampU16(ew);\n const ch = clampU16(eh);\n // Tier input is the ON-SCREEN width: effective size × zoom (design-004\n // §8 — a zoomed-out large card shows micro content). Stored w,h remain\n // the world-effective size the tier was computed from.\n const screenW = ew * zoom;\n\n const existing = ctx.get(e, WidgetBreakpoint);\n if (existing === undefined) {\n const idx = rawTierIndex(screenW);\n ctx.addComponent(e, WidgetBreakpoint, { tier: TIER_NAMES[idx] as Tier, w: cw, h: ch });\n return;\n }\n const curIdx = TIER_NAMES.indexOf(existing.tier as Tier);\n const idx = hysteresisTierIndex(screenW, curIdx < 0 ? rawTierIndex(screenW) : curIdx);\n // Write only on a tier change — the tier must be stable within a band so\n // the measure→tier→content→measure loop converges (w,h ride the change).\n if (idx !== curIdx) {\n ctx.edit(e).set(WidgetBreakpoint, { tier: TIER_NAMES[idx] as Tier, w: cw, h: ch });\n }\n}\n\nexport function createBreakpointSystem(world: World): TickSystem {\n // The gate (2026-07-15; the activeMembership playbook, but through a REAL\n // runIf — this system declares access.write, and a run-but-early-out would\n // blanket-stamp WidgetBreakpoint every frame). Zoom is the `extra` trigger:\n // its change re-tiers everything Active; Size churn and\n // Active flips re-tier only the journaled entities. Pan frames (zoom\n // unchanged) skip entirely — pre-gate they paid the full O(N) scan.\n // A TICK system (one body per frame — the batch form would re-run the\n // guard logic per chunk), so the full walk goes through ctx.query and the\n // column reads are declared explicitly (the spatialSync precedent).\n let lastZoom: number | undefined;\n const guard = makeChurnGuard(\n world,\n { components: [Size], tags: [Active], coarse: false },\n () => {\n // A nav flight sweeps the zoom across EVERY tier threshold in ~400 ms —\n // retier-ing per flight frame swaps widget CONTENT mid-flight (React\n // commits at the worst possible moment; James's field report,\n // 2026-07-16). Defer: lastZoom stays FROZEN at the pre-flight value\n // while flying, so the first post-flight frame compares arrival vs\n // pre-flight zoom and fires exactly ONE full retier at rest. The delta\n // path below still runs mid-flight — freshly mounted content gets its\n // first tier immediately (corrected at settle if the zoom moved on).\n if (navFlightActive(world)) return false;\n const zoom = world.getResource(Camera)?.zoom;\n const changed = zoom !== lastZoom;\n lastZoom = zoom;\n return changed;\n },\n );\n\n return defineTickSystem(\n (ctx) => {\n const work = guard.take();\n if (work === undefined) return; // runIf false — never happens with the guard wired\n const zoom = ctx.getResource(Camera)?.zoom ?? 1;\n if (work.full) {\n ctx.query(equippedWidgetQ).each((b) => {\n const sw = b.col(Size).w;\n const sh = b.col(Size).h;\n for (const r of b) {\n retier(ctx, b.entity(r), sw[r] as number, sh[r] as number, zoom);\n }\n });\n return;\n }\n // Delta path: only the journaled entities, re-read entity-wise.\n for (const e of work.changed) {\n if (!ctx.isAlive(e) || !ctx.has(e, Size) || !ctx.hasTag(e, Active)) continue;\n if (!world.hasTag(e, WidgetEquipped)) continue;\n const s = ctx.read(e, Size);\n retier(ctx, e, s.w, s.h, zoom);\n }\n },\n { name: \"breakpoint\", access: { read: [Size], write: [WidgetBreakpoint] }, runIf: guard.runIf },\n );\n}\n","/**\n * L3 — draw behavior (design-005 §3 `draw(widgetType)` tool; `ctl:behave`,\n * after connect, before camera — design-003 §5 order).\n *\n * A `RoutedDraw` drag creates ONE widget from the release rect: at\n * `JustEnded`, screen start+total → world rect (Camera at release), floored\n * at the widget's `minSize`; a sub-slop release (a click) places the\n * widget's DEFAULT size centered on the point. Commit is one `create`\n * intent through the sink — the doc sink spawns via the same override\n * builder as `ops.spawnWidget`, so the two paths can never diverge.\n * Cancel/fail commit nothing. The widget type comes from the ACTIVE tool's\n * `draw` config (latched per drag at claim would be stricter; tools switch\n * via `ops.setTool` which cancels active gestures first, so the active\n * tool is stable for a live drag by construction).\n *\n * Mid-drag rect preview is recorded polish (design-001 §3's full\n * draft→promote protocol is the vNext shape); v1 draws nothing until release.\n */\nimport type { System, World } from \"@vibecook/strata-ecs\";\nimport { defineQuery, defineSystem } from \"@vibecook/strata-ecs\";\nimport { screenToWorld, type CameraState } from \"@ice/kernel\";\nimport { Camera, Drag, GesturePhases, RoutedDraw } from \"../catalog\";\nimport { ActiveTool } from \"../catalog/camera-derived\";\nimport { resolveToolFor, widgetTypeFor } from \"../canvas/engine-catalog\";\nimport type { CommitSink } from \"../engine/commit-sink\";\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 = resolveToolFor(world, ctx.getResource(ActiveTool)?.id ?? \"select\");\n const type = tool.draw?.widgetType;\n const widget = type !== undefined ? widgetTypeFor(world, type) : undefined;\n if (type === undefined || widget === undefined) continue; // route without a draw tool: no-op\n\n const d = ctx.read(rec, Drag);\n const cam = ctx.getResource(Camera) ?? IDENTITY_CAM;\n const w0 = screenToWorld(d.startX, d.startY, cam);\n const w1 = screenToWorld(d.startX + d.totalX, d.startY + d.totalY, cam);\n\n let x: number;\n let y: number;\n let w: number;\n let h: number;\n if (Math.hypot(d.totalX, d.totalY) < DRAW_CLICK_SLOP_PX) {\n // Click: default size centered on the point.\n w = widget.defaultSize.w;\n h = widget.defaultSize.h;\n x = w0.x - w / 2;\n y = w0.y - h / 2;\n } else {\n x = Math.min(w0.x, w1.x);\n y = Math.min(w0.y, w1.y);\n w = Math.max(widget.minSize.w, Math.abs(w1.x - w0.x));\n h = Math.max(widget.minSize.h, Math.abs(w1.y - w0.y));\n }\n\n sink.commit({\n kind: \"create\",\n gesture: rec,\n writes: [],\n creates: [{ type, x, y, w, h }],\n });\n }\n },\n { name: \"drawBehavior\" },\n );\n}\n","/**\n * spawnWidget — the paved-road widget creation op (app handler, design-005 §2).\n *\n * One guardedTransaction: spawnPrefab with Position (+Size) overrides and any\n * prop overrides folded into their group components (whole-group values —\n * design-001 §5.2's conflict-group granularity). Validation runs through each\n * prop's Standard Schema before the write.\n */\nimport type { Component, Entity, OrderPlace, Relation, World } from \"@vibecook/strata-ecs\";\nimport type { DurableStore } from \"@vibecook/strata-ecs/durable\";\nimport { ChildOf, Position, Size } from \"../catalog\";\nimport { guardedTransaction, type GuardedTx } from \"../guards/guarded-tx\";\nimport type { AnyBehaviorDef } from \"../behavior/types\";\nimport { widgetTypeFor } from \"../canvas/engine-catalog\";\nimport { frameParent } from \"../ops/sibling-order\";\nimport { init, type ComponentInit } from \"../schema/prefab\";\nimport { widgets, type WidgetType } from \"./define-widget\";\nimport { defaultValueOf } from \"./props\";\n\nexport interface SpawnWidgetOpts {\n readonly x: number;\n readonly y: number;\n readonly w?: number;\n readonly h?: number;\n /**\n * Sibling placement in the spawn parent's `ChildOf` sequence (petition 8);\n * default \"last\" = painted last = on top. \"first\" spawns UNDER everything in\n * the frame (e.g. a comment box spawning behind its members).\n */\n readonly order?: OrderPlace;\n /** Explicit `ChildOf` parent; default = the frame parent (nav frame ?? board root). */\n readonly parent?: Entity;\n readonly props?: Readonly<Record<string, unknown>>;\n /** false ⇒ the spawn never enters the local undo stack (batch seeds). */\n readonly undoable?: boolean;\n}\n\n/**\n * Hang the spawn's `ChildOf` edge (petition 8) — shared by `spawnWidget` and\n * the doc sink's create-intent execution so frame placement can never diverge\n * between the two spawn paths. A legacy world (no BoardRoot, no nav frame,\n * no explicit parent) gets NO edge: the entity stays legacy-fallback-ordered.\n */\nexport function attachSpawnParent(\n tx: { setRelation(e: Entity, r: Relation, target: Entity, place?: OrderPlace): void },\n world: World,\n spawned: Entity,\n opts?: { readonly parent?: Entity; readonly order?: OrderPlace },\n): void {\n const parent = opts?.parent ?? frameParent(world);\n if (parent === undefined) return;\n tx.setRelation(spawned, ChildOf, parent, opts?.order ?? \"last\");\n}\n\n/**\n * The prefab-override list for a widget spawn (Position/Size + validated\n * whole-group prop values). Shared by `spawnWidget` and the doc sink's\n * create-intent execution (draw tool) so the two can never diverge.\n */\nexport function widgetSpawnInits(\n type: string,\n opts: SpawnWidgetOpts,\n resolvedWidget?: WidgetType,\n): { prefab: import(\"../schema/prefab\").Prefab; overrides: ComponentInit[] } {\n const widget = resolvedWidget ?? widgets.get(type);\n if (widget === undefined) throw new Error(`ice: spawnWidget — unknown widget type \"${type}\".`);\n\n // Fold prop overrides into whole-group values (defaults + overrides).\n const overrides: ComponentInit[] = [\n init(Position, { x: opts.x, y: opts.y }),\n init(Size, {\n w: opts.w ?? widget.defaultSize.w,\n h: opts.h ?? widget.defaultSize.h,\n }),\n ];\n const givenProps = opts.props ?? {};\n for (const [name, value] of Object.entries(givenProps)) {\n const group = widget.propToGroup[name];\n if (group === undefined) throw new Error(`ice: spawnWidget(\"${type}\") — unknown prop \"${name}\".`);\n }\n for (const g of widget.groups) {\n const touched = Object.keys(givenProps).some((name) => widget.propToGroup[name] === g.name);\n if (!touched) continue;\n const value: Record<string, string | number | boolean> = {};\n for (const [name, spec] of Object.entries(g.fields)) {\n const given = givenProps[name];\n if (given !== undefined) {\n const result = spec[\"~standard\"].validate(spec.kind === \"json\" ? given : given);\n if (\"issues\" in result) {\n throw new Error(\n `ice: spawnWidget(\"${type}\") prop \"${name}\" invalid — ${result.issues[0]?.message}`,\n );\n }\n value[name] = spec.kind === \"json\" ? JSON.stringify(given) : (given as string | number | boolean);\n } else {\n // group values are whole-component writes: fill from defaults\n value[name] = defaultValueOf(spec);\n }\n }\n overrides.push([g.component, value] as ComponentInit);\n }\n\n return { prefab: widget.prefab, overrides };\n}\n\n/**\n * Attach a widget type's DURABLE pre-attached behaviors (design-009 §6), as\n * post-spawn `addComponent` calls inside the spawn transaction.\n *\n * Post-spawn rather than spawn-init overrides: `instantiate` checks every\n * override against the prefab's eligible set, and a behavior is eligible on\n * every entity by definition (BF-D6) — it is not in any prefab's set and never\n * will be. Runtime pre-attachments are NOT here: they ride projection (the\n * equip system), which is the only path that also equips a widget arriving\n * from a peer or a restored file.\n */\nexport function attachSpawnBehaviors(tx: GuardedTx, widget: WidgetType, e: Entity): void {\n for (const entry of widget.behaviors) {\n if (entry.behavior.store !== \"durable\") continue;\n tx.addComponent(\n e,\n entry.behavior.component as Component<Record<string, unknown>>,\n behaviorCell(entry.behavior, entry.data),\n );\n }\n}\n\n/** Defaults ∪ the declared pre-attach data, serialized for the cell. */\nfunction behaviorCell(b: AnyBehaviorDef, data: Readonly<Record<string, unknown>>): Record<string, unknown> {\n const out: Record<string, unknown> = { ...(b.defaults as Record<string, unknown>) };\n for (const [k, v] of Object.entries(data)) {\n if (v === undefined) continue;\n const spec = b.schema[k];\n out[k] = spec?.kind === \"json\" ? JSON.stringify(v) : v;\n }\n return out;\n}\n\nexport function spawnWidget(\n store: DurableStore,\n world: World,\n type: string,\n opts: SpawnWidgetOpts,\n): Entity {\n const widget = widgetTypeFor(world, type);\n if (widget === undefined) throw new Error(`ice: spawnWidget — unknown widget type \"${type}\".`);\n const { prefab, overrides } = widgetSpawnInits(type, opts, widget);\n let spawned: Entity | undefined;\n guardedTransaction(\n store,\n world,\n (tx) => {\n spawned = tx.spawnPrefab(prefab, overrides);\n attachSpawnParent(tx, world, spawned, opts);\n attachSpawnBehaviors(tx, widget, spawned);\n },\n opts.undoable === false ? { undoable: false } : undefined,\n );\n if (spawned === undefined) throw new Error(\"ice: spawnWidget — transaction did not spawn.\");\n return spawned;\n}\n","/**\n * The doc-backed CommitSink — the M5 half of the commit seam (design-001 §3\n * step 3a; design-002 decision 4).\n *\n * One intent = ONE `guardedTransaction` = one undo step. Behaviors already\n * filtered their write sets to live `Drags` edges; the sink re-guards anyway —\n * the doc is the authority (design-001 §3: `keyOf(w) === undefined ⇒ skip` —\n * one dead widget must not roll back the gesture). Value writes go through\n * `tx.edit().set` on PRE-EXISTING cells (the synchronous agreement point);\n * consume's reparent is a relation write in the SAME transaction.\n *\n * Read-only sessions (version gate) swap in `createReadOnlyCommitSink`: the\n * gesture still runs (runtime feels live) but nothing commits — the runtime\n * cells reconverge with the baseline at the next remote sweep, exactly like a\n * cancel, and a DEV warn says why.\n */\nimport type { DurableStore } from \"@vibecook/strata-ecs/durable\";\nimport type { Entity, World } from \"@vibecook/strata-ecs\";\nimport { ChildOf } from \"../catalog\";\nimport type { CommitIntent, CommitSink } from \"../engine/commit-sink\";\nimport { init } from \"../schema/prefab\";\nimport { WireFrom, WirePorts, WirePrefab, WireTo } from \"../catalog/graph\";\nimport { attachSpawnParent, widgetSpawnInits } from \"../widget/spawn\";\nimport { widgetTypeFor } from \"../canvas/engine-catalog\";\nimport { type GuardedTx, guardedTransaction } from \"../guards/guarded-tx\";\n\n/**\n * Out-of-ECS hand-off for `CommitCreate.select` (the marquee-buffer precedent:\n * plain JS state written mid-tick, consumed by a system in a later phase —\n * never observed, never ECS). The sink appends the spawned twin here; the\n * insert-ghost reap system drains it and applies the selection ONE tick later,\n * when the twin's projection is alive. Keyed per world so parallel test\n * engines never cross-talk.\n */\nconst pendingSelects = new WeakMap<World, Entity[]>();\n\nexport function drainCreatedSelections(world: World): Entity[] {\n const list = pendingSelects.get(world);\n if (list === undefined || list.length === 0) return [];\n pendingSelects.set(world, []);\n return list;\n}\n\n/**\n * A layer's word on a gesture's LANDING (design-001 §3 step 3a, widened 2026-09-26 by the desk's D7 #2): called inside the\n * intent's transaction, after the intent's own writes, with the intent that made them — so what the layer adds (the desk's\n * pin when a note is let go on a calendar's day, and the note at the day's slot) is the gesture's own undo step: one gesture,\n * one transaction, one ⌘Z. A cancelled gesture never reaches a sink, so it never reaches an extender either. A throwing\n * extender is reported and what it wrote before the throw stays in the step — the user's gesture never rolls back for a\n * layer's fault.\n */\nexport type CommitExtender = (intent: CommitIntent, tx: GuardedTx) => void;\n\nexport interface DocCommitSinkOpts {\n /** Whole-intent final authority; undefined means reject without a transaction. */\n readonly guard?: (intent: CommitIntent) => CommitIntent | undefined;\n /** The layers' word on the landing, inside the same transaction (see {@link CommitExtender}). */\n readonly extend?: CommitExtender;\n}\n\nexport function createDocCommitSink(\n store: DurableStore,\n world: World,\n opts: DocCommitSinkOpts = {},\n): CommitSink {\n return {\n commit(input: CommitIntent): boolean {\n const intent = opts.guard?.(input) ?? (opts.guard === undefined ? input : undefined);\n if (intent === undefined) return false;\n const liveWrites = intent.writes.filter((w) => store.keyOf(w.entity) !== undefined);\n const liveReparents = (intent.reparents ?? []).filter(\n (r) => store.keyOf(r.entity) !== undefined && store.keyOf(r.container) !== undefined,\n );\n // Wires bind widgets + port ids (design-001 §5.3): both ENDPOINT widgets\n // must still be durable-live at commit (the same divergence-is-the-signal\n // re-guard as writes — a remote delete mid-gesture drops the spawn).\n const liveWires = (intent.wires ?? []).filter(\n (w) => store.keyOf(w.from) !== undefined && store.keyOf(w.to) !== undefined,\n );\n // Order ops (petition 8): both ends re-guarded — a dead parent must not\n // roll back the gesture any more than a dead widget does.\n const liveOrders = (intent.orders ?? []).filter(\n (o) => store.keyOf(o.entity) !== undefined && store.keyOf(o.parent) !== undefined,\n );\n // Creates re-guard their PARENT (a consume-insert whose folder a remote\n // deleted mid-gesture): the container-local x/y are meaningless without\n // the container, so the create is dropped whole — the same\n // divergence-is-the-signal posture as a dead reparent target. Unknown\n // types are dropped too (never a throw inside the gesture's tx).\n const creates = (intent.creates ?? []).filter(\n (c) =>\n widgetTypeFor(world, c.type) !== undefined &&\n (c.parent === undefined || store.keyOf(c.parent) !== undefined),\n );\n if (\n liveWrites.length === 0 &&\n liveReparents.length === 0 &&\n liveOrders.length === 0 &&\n liveWires.length === 0 &&\n creates.length === 0\n ) {\n return false;\n }\n\n guardedTransaction(store, world, (tx) => {\n for (const w of liveWrites) {\n tx.edit(w.entity).set(w.component, w.value);\n }\n for (const r of liveReparents) {\n // Placeless set on the ordered ChildOf appends \"last\" — a consumed\n // widget lands on top of the container's sequence (petition 8).\n tx.setRelation(r.entity, ChildOf, r.container);\n }\n // Sibling placements land in the SAME transaction as the gesture's\n // value writes — one gesture, one undo step (petition 8).\n for (const o of liveOrders) {\n tx.setRelation(o.entity, ChildOf, o.parent, o.place);\n }\n // Draw-tool / tray-insert creations: one prefab spawn per entry,\n // through the SAME override builder as ops.spawnWidget — and the same\n // frame-parent edge attach, so the spawn paths cannot diverge. An\n // explicit `parent` (consume-insert) hangs the edge on the container\n // instead — x/y are container-local by that convention.\n for (const c of creates) {\n const widget = widgetTypeFor(world, c.type);\n if (widget === undefined) continue;\n const { prefab, overrides } = widgetSpawnInits(c.type, {\n x: c.x,\n y: c.y,\n w: c.w,\n h: c.h,\n ...(c.props !== undefined ? { props: c.props } : {}),\n }, widget);\n const spawned = tx.spawnPrefab(prefab, overrides);\n attachSpawnParent(tx, world, spawned, c.parent !== undefined || c.order !== undefined ? { ...(c.parent !== undefined ? { parent: c.parent } : {}), ...(c.order !== undefined ? { order: c.order } : {}) } : undefined);\n if (c.select === true) {\n let list = pendingSelects.get(world);\n if (list === undefined) {\n list = [];\n pendingSelects.set(world, list);\n }\n list.push(spawned);\n }\n }\n for (const w of liveWires) {\n // The paved prefab path: PrefabId + Wire tag ride the prefab, and\n // WireFrom/WireTo pass its eligibility contract (raw spawn skipped\n // those checks entirely — 2026-07-13 review).\n const wire = tx.spawnPrefab(WirePrefab, [init(WirePorts, { from: w.fromPort, to: w.toPort })]);\n tx.setRelation(wire, WireFrom, w.from);\n tx.setRelation(wire, WireTo, w.to);\n }\n // The layers' word on the landing — in THIS transaction, so it is the gesture's own undo step.\n if (opts.extend !== undefined) {\n try {\n opts.extend(intent, tx);\n } catch (err) {\n console.error(\"ice: a commit extender threw inside a gesture's transaction — what it wrote before stays; the gesture lands\", err);\n }\n }\n });\n return true;\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 return false;\n },\n };\n}\n","/**\n * L4 — cursor projection (design-003 §7; `derive` phase).\n *\n * Memoryless: resolved fresh every run from live world state, priority order\n * (1) any LOCAL pointer with a live `ClaimedBy` — Drag+RoutedMove or a\n * LongPress in Recognized → \"grabbing\"; RoutedResize → directional resize by\n * the captured handle's `HandleSpec.anchor`; RoutedPan → \"grabbing\";\n * (2) `ActiveTool` override — pan tool → \"grab\"; (3) else the mouse pointer's\n * `Targets` kind — a `HandleSpec` → directional resize, an entity with\n * `Position` (widget) → \"default\", `CanvasSurface`/none → \"default\".\n * The pegboard tray (design-017 §4, K3): a specimen on its board a thing to take, \"grab\", its copy lifted \"grabbing\" (K9), over\n * everything but the hand's. (design-018 §5: the lip's \"pointer\" retired with its handle — the drawer's handle is the app's DOM bar.)\n * Above all of them (design-015 §8, D3t-a): with an object IN HAND, the mode in hand's own\n * `cursor` (its `HeldToolDef.cursor` — \"none\" where the tool draws itself: the board's marker) while\n * the mouse is over the object's drawing surface (`HeldPointer.part` \"content\") or presses the tool —\n * and (design-019 §5, M24 LT2) over one of the kind's NAMED parts, the KIND's cursor when it names one:\n * the pose seam's `cursor` (its `open.cursor` — a link's `pointer`, a text field's `text`), asked each\n * run while the mouse is over such a part; undefined there falls to the rest, as ever.\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 { resolveToolFor, widgetTypeFor } from \"../canvas/engine-catalog\";\nimport type { HeldPoseSlot } from \"./held\";\nimport {\n ActiveTool,\n CanvasSurface,\n Captures,\n ClaimedBy,\n Drag,\n GesturePhases,\n HandleSpec,\n Held,\n Tray,\n TrayPress,\n HeldPointer,\n HeldPress,\n HeldTool,\n LocalPointer,\n LongPress,\n Pointer,\n Position,\n RoutedMove,\n RoutedPan,\n RoutedResize,\n Targets,\n} from \"../catalog\";\nimport { PrefabId } from \"../schema/prefab\";\n\nconst P = GesturePhases;\n\nconst anchorQ = defineQuery([CanvasSurface]);\nconst localPointerQ = defineQuery([Pointer, LocalPointer]);\nconst heldQ = defineQuery([Held]);\nconst trayQ = defineQuery([Tray]);\n\n/** The mode in hand's cursor while a local mouse is over the held object's drawing surface or presses its tool (D3t-a); undefined otherwise. */\nfunction heldToolCursor(world: World): string | undefined {\n const held = world.firstOf(heldQ);\n if (held === undefined) return undefined;\n const id = world.get(held, HeldTool)?.id ?? \"\";\n const typeId = world.get(held, PrefabId)?.id;\n if (id === \"\" || typeof typeId !== \"string\") return undefined;\n const cursor = widgetTypeFor(world, typeId)?.heldTools.find((t) => t.id === id)?.cursor;\n if (cursor === undefined) return undefined;\n let over = false;\n world.query(localPointerQ).each((b) => {\n for (const r of b) {\n const p = b.entity(r);\n if (world.read(p, Pointer).device !== \"mouse\") continue;\n if (world.get(p, HeldPointer)?.part === \"content\" || world.get(p, HeldPress)?.kind === \"tool\") over = true;\n }\n });\n return over ? cursor : undefined;\n}\n\n/**\n * The KIND's cursor in hand (design-019 §5, M24 LT2): the mouse over one of the held object's NAMED parts (any but `content` and\n * `frame` — `HeldPointer.part`) asks the pose seam (`HeldPoseSource.cursor` — the kind's `open.cursor`); undefined — the kind names\n * none there, no seam, nothing held.\n */\nfunction heldKindCursor(world: World, pose: HeldPoseSlot | undefined): string | undefined {\n const source = pose?.current;\n if (source?.cursor === undefined) return undefined;\n const held = world.firstOf(heldQ);\n if (held === undefined) return undefined;\n let part = \"\";\n world.query(localPointerQ).each((b) => {\n for (const r of b) {\n const p = b.entity(r);\n if (world.read(p, Pointer).device === \"mouse\") part = world.get(p, HeldPointer)?.part ?? \"\";\n }\n });\n if (part === \"\" || part === \"content\" || part === \"frame\") return undefined;\n const c = source.cursor(held, part);\n return typeof c === \"string\" && c !== \"\" ? c : undefined;\n}\n\n/**\n * The pegboard tray under the mouse (design-017 §4, K3 — the tray input's facts): K9 (S12):\n * a specimen a thing to take (`Tray.hover`, the open hand), its copy lifted off the board (`Tray.take`) and, handed to the desk, carried\n * to its drop (the mouse's `TrayPress carry` — the ticks before the ghost's own drag is recognized included): the closed one.\n */\nfunction trayCursor(world: World): string | undefined {\n const tray = world.firstOf(trayQ);\n const t = tray === undefined ? undefined : world.get(tray, Tray);\n if (t === undefined) return undefined;\n if ((t.take ?? \"\") !== \"\") return \"grabbing\";\n let carried = false;\n world.query(localPointerQ).each((b) => {\n for (const r of b) {\n const p = b.entity(r);\n if (world.read(p, Pointer).device === \"mouse\" && world.get(p, TrayPress)?.kind === \"carry\") carried = true;\n }\n });\n if (carried) return \"grabbing\";\n return (t.hover ?? \"\") !== \"\" ? \"grab\" : undefined;\n}\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\n/** `pose`: the stack's held pose slot (`installInteractionStack`'s `heldPose`) — the kind's cursor in hand rides it (M24 LT2). */\nexport function createCursorSync(world: World, opts: { readonly pose?: HeldPoseSlot } = {}): System & { readCursor(): string } {\n let cursor = \"default\";\n\n const system = defineSystem(\n anchorQ,\n (_b, ctx) => {\n let resolved: string | undefined = heldKindCursor(world, opts.pose) ?? heldToolCursor(world) ?? trayCursor(world);\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 = resolveToolFor(world, 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 * HELD INPUT (design-015 §8; D4b) — while an object is in the hand, every pointer is the held\n * object's and the desk behind it is inert. The HEAD of the `react` phase: the ingest's one-tick\n * tags are flushed by then (a press is visible), and what this stamps flushes before `ctl`.\n *\n * The desk goes inert with the vocabulary the stack already honours: every local pointer gets the\n * one-tick `HandledByWidget` (picking and the recognizers skip it — no hit, no tap, no drag, no\n * selection change) and `WheelHandled` (both wheel consumers skip it — the camera never moves), the\n * cleanup phase clears them, this system stamps them again next tick. So \"no camera move\" is not a\n * rule the camera keeps; it is a fact the camera never hears about.\n *\n * What the pointer does instead is mapped through the SAME pose the renderer drew — the seam\n * `HeldPoseSlot` beside `framePick`: the renderer publishes the held object's screen frame each\n * frame (`HeldPoseSource.frame`), and a pointer's point becomes `HeldPointer` — the object's own\n * units, centred — and an inside/outside verdict. The routes (desk.js `heldDown`/`heldMove`/\n * `heldUp`/`heldZoomAt`/`heldPanBy`, number for number):\n * - a ⌘/ctrl-wheel or a pinch brings the object closer ABOUT THE POINTER (`HeldView.zoom`, up to 3×,\n * the pan following so the point under the pointer stays), never the mat; in past 0.72× it is put\n * down — and the rest of that gesture is MUTED (`HeldMute`: 400 ms, +250 per swallowed event), so\n * the wheel's tail never zooms the desk (the v2 lesson);\n * - once brought close (zoom > 1) a plain wheel moves the object under the eye, clamped so it never\n * leaves the middle of the view; a middle-button or Space drag pans the same way, as does a drag\n * that starts on the soft desk;\n * - a click on the soft desk — pressed and released outside the object, unmoved — puts it down; two\n * instant taps on the object do too (the notebook's case rule, generalised) — unless they land on its\n * drawing surface with a mode in hand (D3t-a): that press is the TOOL's (`HeldPress` `tool` — the\n * board's stroke; a double-click there is two dots, never a way back) — or on one of the kind's named\n * PARTS (D3t-b: any part but `content` and `frame`, the object itself): that press is the KIND's\n * (`HeldPress` `part`, with the part it began on — a notebook's turn: two clicks there turn two pages);\n * - every route above is the PRIMARY button's (petition I28, press-button.ts): a secondary press — and a middle one with nothing\n * to pan — is a point in the hand as on the desk: it keeps no `HeldPress`, so it puts nothing down, works no part, lays no stroke;\n * - (design-019 §5, M24 LT2) a primary press is COUNTED — `HeldPress.count`, 1, 2, 3… within the multi-tap window and slop of the\n * last (`HeldPressMemo`, by the down events' own times): the platform's `detail` is 0 on a pointerdown, so the desk counts; and a\n * kind that takes the wheel (`OpenBinding.wheel: \"kind\"` — its type's `heldWheel`) has a plain wheel written to `HeldWheel` for it\n * instead of panning the hand — ⌘/ctrl and the pinch zoom the hand as ever, and past 0.72× still put it down.\n * The ways back are OPS (`ops.putDown`, structural) and a system may not run them mid-tick: it writes\n * the one-tick `HeldIntent` and the facade applies it after the step (D2b's `NavIntent`, same shape).\n * Nothing here reads a kind: the seam gives a frame and (D3t-a) the part under a point; the tool in\n * hand is core's `HeldTool`, the wheel's owner the widget type's `heldWheel`. The kind is TOLD its input by the desk, which folds\n * `HeldPointer`, `HeldPress` and `HeldWheel` into its `held` events (desk/hold/told.ts) — never a second input path.\n */\nimport type { Entity, System, World } from \"@vibecook/strata-ecs\";\nimport { defineQuery, defineSystem } from \"@vibecook/strata-ecs\";\nimport { widgetTypeFor } from \"../canvas/engine-catalog\";\nimport { Held, HeldIntent, HeldMute, HeldPointer, HeldPress, HeldPressMemo, HeldTapMemo, HeldTool, HeldView, HeldWheel } from \"../catalog/desk\";\nimport {\n HandledByWidget,\n Keyboard,\n LocalPointer,\n Pointer,\n PointerButtons,\n PointerMods,\n PointerScreen,\n PointerWheel,\n WentCancelled,\n WentDown,\n WentUp,\n WheelHandled,\n} from \"../catalog/pointer\";\nimport { GestureSettings } from \"../catalog/settings-resources\";\nimport { FrameInfo } from \"../engine/frame-info\";\nimport { PrefabId } from \"../schema/prefab\";\nimport { GESTURE_DEFAULTS } from \"../settings/defaults\";\nimport type { HeldToolState } from \"../widget/held-tools\";\nimport { pressButton } from \"./press-button\";\n\n/** The held object's frame ON SCREEN as the renderer drew it this frame (CSS px): its centre, half extents, its scale (CSS px per object unit), and whether the pickup has settled (the wheel waits for it). */\nexport interface HeldScreenFrame {\n readonly cx: number;\n readonly cy: number;\n readonly hx: number;\n readonly hy: number;\n readonly s: number;\n readonly settled: boolean;\n}\n\n/**\n * The pose seam: the renderer's word on where the held object is — `undefined` before its first frame — and (D3t-a) which of\n * its kind's parts is under a point of the object's own frame (its `hit` on the geometry it drew: the board's melamine\n * `content`, its `frame`), null over nothing; absent = no parts (\"content\" inside the frame). `cursor` (design-019 §5, M24 LT2):\n * the kind's cursor over one of its NAMED parts (its `open.cursor`) — L4 shows it above its own; undefined: L4's. `toolState`\n * (petition I49): what the held object's kind says of its tool `id` NOW — the renderer reads the tool's `state` with the kind's state\n * on its desk; `ops.useHeldTool` asks it and does nothing for a tool it says is disabled. Undefined: the tool as declared.\n */\nexport interface HeldPoseSource {\n frame(entity: Entity): HeldScreenFrame | undefined;\n part?(entity: Entity, x: number, y: number): string | null;\n cursor?(entity: Entity, part: string): string | undefined;\n toolState?(entity: Entity, id: string): HeldToolState | undefined;\n}\n\n/** The stack's slot for the pose source — a mutable box, so the renderer can arrive after install (as `framePick`). */\nexport interface HeldPoseSlot { current: HeldPoseSource | null }\n\n/** The hand's numbers (desk.js `HOLD` and its wheel handler): the zoom's floor (put down below it) and ceiling, the wheel's rate, the mute, the press slop. */\nexport const HOLD_INPUT = { zoomMin: 0.72, zoomMax: 3, wheelRate: 0.0105, muteMs: 400, muteMoreMs: 250, slopPx: 3 } as const;\n\nconst heldQ = defineQuery([Held]);\nconst localPointerQ = defineQuery([Pointer, PointerScreen, LocalPointer]);\n\nconst clamp = (x: number, a: number, b: number): number => Math.min(Math.max(x, a), Math.max(a, b));\n\n/** The held object, or undefined. */\nexport function heldEntity(world: World): Entity | undefined {\n return world.firstOf(heldQ);\n}\n\nexport function createHeldInput(world: World, opts: { readonly pose: HeldPoseSlot }): System {\n const request = (kind: \"open\" | \"putDown\", target: Entity): void => {\n const prev = world.getResource(HeldIntent);\n world.setResource(HeldIntent, { kind, target, epoch: (prev?.epoch ?? 0) + 1 });\n };\n return defineSystem(\n localPointerQ,\n (b, ctx) => {\n const now = world.getResource(FrameInfo)?.now ?? 0;\n const held = world.firstOf(heldQ);\n if (held === undefined || !ctx.isAlive(held)) {\n // nothing in hand: the mute swallows the tail of the gesture that put the object down, and a pointer's held facts leave\n const mute = world.getResource(HeldMute);\n let muted = mute !== undefined && now < mute.until;\n // the hand's count starts again with the next hold (written once, never a stamp a tick)\n if ((world.getResource(HeldPressMemo)?.count ?? 0) !== 0) world.setResource(HeldPressMemo, { x: 0, y: 0, at: 0, count: 0 });\n for (const r of b) {\n const p = b.entity(r);\n if (ctx.has(p, HeldPointer)) ctx.removeComponent(p, HeldPointer);\n if (ctx.has(p, HeldPress)) ctx.removeComponent(p, HeldPress);\n if (ctx.has(p, HeldWheel)) ctx.removeComponent(p, HeldWheel);\n if (!muted) continue;\n const w = ctx.get(p, PointerWheel);\n if (w === undefined || (w.dx === 0 && w.dy === 0 && w.pinch === 0) || ctx.hasTag(p, WheelHandled)) continue;\n ctx.addTag(p, WheelHandled);\n // each swallowed event pushes the mute further — never nearer (the page's own `now + 250` could shorten its 400)\n world.setResource(HeldMute, { until: Math.max(mute?.until ?? 0, now + HOLD_INPUT.muteMoreMs) });\n muted = true;\n }\n return;\n }\n const view = world.get(held, HeldView) ?? { zoom: 1, panX: 0, panY: 0 };\n const frame = opts.pose.current?.frame(held);\n const gs = world.getResource(GestureSettings);\n const windowMs = gs?.multiTapWindowMs ?? GESTURE_DEFAULTS.multiTapWindowMs;\n const slopPx = gs?.multiTapSlopPx ?? GESTURE_DEFAULTS.multiTapSlopPx;\n const space = world.getResource(Keyboard)?.space === true;\n // the plain wheel's owner in hand (M24 LT2): the hand's (it pans the object brought close) unless the kind takes it\n const typeId = world.get(held, PrefabId)?.id;\n const wheelToKind = typeof typeId === \"string\" && widgetTypeFor(world, typeId)?.heldWheel === \"kind\";\n /** The pan clamp at a zoom: half the held extent on screen there (desk.js `heldPanBy`). */\n const clampPan = (x: number, y: number, zoom: number): readonly [number, number] => {\n if (frame === undefined) return [x, y];\n const hx = (frame.hx / Math.max(view.zoom, 1e-9)) * zoom;\n const hy = (frame.hy / Math.max(view.zoom, 1e-9)) * zoom;\n return [clamp(x, -hx, hx), clamp(y, -hy, hy)];\n };\n let next = { zoom: view.zoom, panX: view.panX, panY: view.panY };\n let putDown = false;\n for (const r of b) {\n const p = b.entity(r);\n // the desk is inert: picking, the recognizers and both wheel consumers skip this pointer this tick\n if (!ctx.hasTag(p, HandledByWidget)) ctx.addTag(p, HandledByWidget);\n if (!ctx.hasTag(p, WheelHandled)) ctx.addTag(p, WheelHandled);\n const s = ctx.read(p, PointerScreen);\n // the pointer in the object's own frame, through the pose the renderer drew — and the kind's part under it (D3t-a) — change-only\n let inside = false;\n let part = \"\";\n if (frame !== undefined) {\n const lx = (s.x - frame.cx) / Math.max(frame.s, 1e-9);\n const ly = (s.y - frame.cy) / Math.max(frame.s, 1e-9);\n inside = Math.abs(s.x - frame.cx) <= frame.hx && Math.abs(s.y - frame.cy) <= frame.hy;\n const source = opts.pose.current;\n part = source?.part !== undefined ? (source.part(held, lx, ly) ?? \"\") : inside ? \"content\" : \"\";\n const cur = ctx.get(p, HeldPointer);\n if (cur === undefined) ctx.addComponent(p, HeldPointer, { x: lx, y: ly, inside, part });\n else if (cur.x !== lx || cur.y !== ly || cur.inside !== inside || cur.part !== part) ctx.edit(p).set(HeldPointer, { x: lx, y: ly, inside, part });\n }\n // the wheel: ⌘/ctrl or a pinch brings it closer about the pointer; a plain wheel moves it once brought close (settled only)\n const w = ctx.get(p, PointerWheel);\n if (!putDown && frame !== undefined && frame.settled && w !== undefined && (w.dx !== 0 || w.dy !== 0 || w.pinch !== 0)) {\n const mods = ctx.get(p, PointerMods);\n const zooming = w.pinch !== 0 || mods?.meta === true || mods?.ctrl === true;\n if (zooming) {\n const d = w.pinch !== 0 ? w.pinch : w.dy;\n const z = next.zoom * Math.exp(-d * HOLD_INPUT.wheelRate);\n if (z < HOLD_INPUT.zoomMin) {\n // in past the floor: down it goes, and the rest of this gesture is nobody's\n putDown = true;\n world.setResource(HeldMute, { until: now + HOLD_INPUT.muteMs });\n } else {\n const zoom = Math.min(z, HOLD_INPUT.zoomMax);\n const ratio = zoom / next.zoom;\n // the point under the pointer stays: C' = p + (C − p)·r, so pan' = pan + (p − C)(1 − r); at the reading size and under, centred\n const cx = frame.cx + (next.panX - view.panX);\n const cy = frame.cy + (next.panY - view.panY);\n const [px, py] = zoom <= 1 ? [0, 0] : clampPan(next.panX + (s.x - cx) * (1 - ratio), next.panY + (s.y - cy) * (1 - ratio), zoom);\n next = { zoom, panX: px, panY: py };\n }\n } else if (wheelToKind) {\n // the kind's wheel (design-019 §5): this tick's deltas, told once by `seq` — the hand never pans for it\n const cur = ctx.get(p, HeldWheel);\n const wheel = { dx: w.dx, dy: w.dy, seq: (cur?.seq ?? 0) + 1 };\n if (cur === undefined) ctx.addComponent(p, HeldWheel, wheel);\n else ctx.edit(p).set(HeldWheel, wheel);\n } else if (next.zoom > 1.001) {\n const [px, py] = clampPan(next.panX - w.dx, next.panY - w.dy, next.zoom);\n next = { ...next, panX: px, panY: py };\n }\n }\n // the press: where it began decides what it is; its release, unmoved, is a way back. On the drawing surface with a mode\n // in hand it is the TOOL's (D3t-a — the board's stroke); on a named part the KIND's (D3t-b — a notebook's turn): never a\n // pan, never a tap that puts the object down\n if (ctx.hasTag(p, WentDown)) {\n // the button it began with (petition I28, press-button.ts): the primary's press is the hand's, a middle one only pans; a\n // secondary press — or a middle one with nothing to pan — is a POINT, and keeps no press\n const button = pressButton(ctx.get(p, PointerButtons)?.buttons ?? 0);\n const pan = (button === \"middle\" || (button === \"primary\" && space)) && next.zoom > 1.001;\n if (pan || button === \"primary\") {\n const tool = part === \"content\" && (world.get(held, HeldTool)?.id ?? \"\") !== \"\";\n const named = part !== \"\" && part !== \"content\" && part !== \"frame\";\n const kind = pan ? \"pan\" : tool ? \"tool\" : named ? \"part\" : inside ? \"object\" : \"desk\";\n // its click count (M24 LT2): on from the last primary press within the multi-tap window and slop, by the down events' own\n // times (as the taps below pair) — a pointerdown's `detail` is 0 in the browser, so the desk counts\n let count = 1;\n if (button === \"primary\") {\n const memo = world.getResource(HeldPressMemo);\n const downMs = ctx.get(p, PointerButtons)?.downMs ?? 0;\n const at = downMs !== 0 ? downMs : now;\n if (memo !== undefined && memo.count > 0 && at - memo.at <= windowMs && Math.hypot(s.x - memo.x, s.y - memo.y) <= slopPx) count = memo.count + 1;\n world.setResource(HeldPressMemo, { x: s.x, y: s.y, at, count });\n }\n const press = { kind, part, x: s.x, y: s.y, panX0: next.panX, panY0: next.panY, moved: false, count } as const;\n if (ctx.has(p, HeldPress)) ctx.edit(p).set(HeldPress, press);\n else ctx.addComponent(p, HeldPress, press);\n } else if (ctx.has(p, HeldPress)) ctx.removeComponent(p, HeldPress);\n } else if (ctx.has(p, HeldPress)) {\n const pr = ctx.read(p, HeldPress);\n const dx = s.x - pr.x;\n const dy = s.y - pr.y;\n const moved = pr.moved || Math.hypot(dx, dy) > HOLD_INPUT.slopPx;\n if (pr.kind === \"pan\" || (pr.kind === \"desk\" && next.zoom > 1.001)) {\n // brought close: the drag moves the object under the eye\n const [px, py] = clampPan(pr.panX0 + dx, pr.panY0 + dy, next.zoom);\n next = { ...next, panX: px, panY: py };\n }\n const up = ctx.hasTag(p, WentUp);\n if (up || ctx.hasTag(p, WentCancelled)) {\n if (up && !moved && !putDown) {\n if (pr.kind === \"desk\") putDown = true; // a click on the soft desk puts it down (the whiteboard's rule, now every held object's)\n else if (pr.kind === \"object\") {\n // two instant taps on the object: the notebook's case, generalised (its parts are D3t's)\n const memo = world.getResource(HeldTapMemo);\n // the tap's time is its down EVENT's own — `PointerButtons.downMs`, the adapter's timestamp, kept through the release\n // (K9 S6 — K-H's product call): a main-thread stall between two taps does not unpair them; the frame's `now` is the\n // fallback for an input with no time, and the frame CLOCK is never it (clamped dt; the loop sleeps between taps)\n const downMs = ctx.get(p, PointerButtons)?.downMs ?? 0;\n const at = downMs !== 0 ? downMs : now;\n const pairs = memo !== undefined && memo.seq > 0 && at - memo.at <= windowMs && Math.hypot(s.x - memo.x, s.y - memo.y) <= slopPx;\n if (pairs) { putDown = true; world.setResource(HeldTapMemo, { x: 0, y: 0, at: 0, seq: 0 }); }\n else world.setResource(HeldTapMemo, { x: s.x, y: s.y, at, seq: (memo?.seq ?? 0) + 1 });\n }\n }\n ctx.removeComponent(p, HeldPress);\n } else if (moved !== pr.moved) ctx.edit(p).set(HeldPress, { ...pr, moved });\n }\n }\n if (putDown) { request(\"putDown\", held); return; }\n if (next.zoom !== view.zoom || next.panX !== view.panX || next.panY !== view.panY) {\n if (ctx.has(held, HeldView)) ctx.edit(held).set(HeldView, next);\n else ctx.addComponent(held, HeldView, next);\n }\n },\n { name: \"heldInput\", access: { write: [HeldView, HeldPointer, HeldPress, HeldWheel] } },\n );\n}\n","/**\n * THE WHEEL OF A HOLDING PRESS (design-015 §6's photo; D3t-a — PHOTO.md: \"wheel while holding turns the print about the\n * finger\"). While a local pointer's press holds a widget that declares `interaction.wheelTurns` (its `WheelTurns`\n * capability — a recognizer of the press captures it), the wheel on that pointer is the WIDGET's: this system stamps the\n * one-tick `WheelHandled` (both wheel consumers skip it — the camera never zooms under a carried print) and adds the tick's\n * deltas to the pointer's `PressWheel`, a running sum a reflector can still read after the tick, when `PointerWheel` has been\n * zeroed. The sum starts at the press's first wheel and leaves with the press. The head of `react`, beside the held input:\n * the ingest's facts are flushed by then and what this stamps flushes before `ctl`.\n */\nimport type { System, World } from \"@vibecook/strata-ecs\";\nimport { defineQuery, defineSystem } from \"@vibecook/strata-ecs\";\nimport { Captures, LocalPointer, MovesSelection, RoutedMove, Pointer, PointerButtons, PointerWheel, PressWheel, Watches, WheelHandled, WheelTurns } from \"../catalog\";\n\nconst pointersQ = defineQuery([Pointer, LocalPointer, PointerButtons]);\n\nexport function createPressWheel(world: World): System {\n return defineSystem(\n pointersQ,\n (b, ctx) => {\n for (const r of b) {\n const p = b.entity(r);\n let turns = false;\n if ((ctx.read(p, PointerButtons).buttons & 1) !== 0) {\n const watchers = world.getReverse(p, Watches);\n // A group move preserves each member's angle. Its wheel belongs to\n // canvas navigation, even when the press began on a turning widget.\n if (!watchers.some(rec => ctx.hasTag(rec, MovesSelection) || ctx.hasTag(rec, RoutedMove))) {\n for (const rec of watchers) {\n const e = world.getRelation(rec, Captures);\n if (e !== undefined && ctx.isAlive(e) && ctx.hasTag(e, WheelTurns)) { turns = true; break; }\n }\n }\n }\n const cur = ctx.get(p, PressWheel);\n if (!turns) { if (cur !== undefined) ctx.removeComponent(p, PressWheel); continue; }\n const w = ctx.get(p, PointerWheel);\n const dx = w?.dx ?? 0;\n const dy = w?.dy ?? 0;\n if (w !== undefined && (dx !== 0 || dy !== 0 || w.pinch !== 0) && !ctx.hasTag(p, WheelHandled)) ctx.addTag(p, WheelHandled);\n if (cur === undefined) ctx.addComponent(p, PressWheel, { dx, dy });\n else if (dx !== 0 || dy !== 0) ctx.edit(p).set(PressWheel, { dx: cur.dx + dx, dy: cur.dy + dy });\n }\n },\n { name: \"pressWheel\", access: { write: [PressWheel] } },\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 * TRAY INPUT (design-016 §7; design-017 §4 — K3) — the pegboard drawer's share of the pointer, beside the hand's (systems/held.ts)\n * and in its vocabulary. Right after `heldInput` at the head of `react`: the ingest's one-tick tags are flushed by then (a press is\n * visible), and what this stamps flushes before `ctl`, so the recognizers and both wheel consumers never hear of what the tray\n * takes. PICKING does not hear it either way — it runs in this same phase, before the stamp lands (a tag is a structural write,\n * applied at the phase boundary) — so it reads `Tray.open` itself and answers the bare canvas for every local pointer while the\n * drawer is out (l1-pick; K9 law #1: without that, the DOM-at-event-time halves read a live hit THROUGH the drawer). While an\n * object is in hand the tray stands aside (the hand's frame never draws it).\n *\n * - CLOSED, the drawer takes no pointer (design-018 §5, R2 — the lip's handle, its hover and its press retired): a press at the\n * bottom centre is the desk's like any other. What opens the drawer is the app's — the `a` key, and the DOM bar (`<TrayBar>`,\n * @ice/react), whose down never reaches the canvas as a press. Only a wheel stream it took while out stays its own (below).\n * - OPEN, the desk is INERT: every local pointer gets the one-tick `HandledByWidget` and `WheelHandled`, each tick, as the hand's\n * do — so \"the wheel never moves the camera\" is not a rule the camera keeps; it is a fact the camera never hears about. Over the\n * drawer the wheel scrolls it (`dy`; the OS's momentum arrives as deltas and is applied as it comes — no inertia of ours; ⌘/ctrl\n * and a pinch are swallowed). Wheel scrolling stays within the content: excess deltas are discarded, so a reversal responds\n * immediately and an uneven momentum tail cannot restart an edge bounce. Only an intentional press-drag can pull the band's\n * `stretch`; its spring returns on release. A click on the dimmed desk — pressed and released there,\n * unmoved — closes it. Shut, the wheel stays the tray's until it has been quiet `letGoMs` (K9): a flick's momentum still\n * arriving as the drawer shuts never zooms the desk.\n * - K5b, TAKING ONE (design-017 §9): a press on a SPECIMEN is `TrayPress specimen` — its type, the grab point across the object as the\n * board draws it (kernel `specimenFit`), the specimen's centre on screen. Past the slop its COPY lifts (`Tray.take` and the pointer:\n * the renderer's flux draws it; the specimen stays hung); a press on a specimen never scrolls the board. Out of the drawer's open\n * rect the copy is HANDED to the desk: the drawer slides away (`open` false), `handed` bumps (that tick `take` still names it, where\n * it left — what the renderer's ghost grows out of — and it clears the tick after), and the one-tick `TrayIntent` asks the\n * facade for `ops.insertByDrag` after the step — the insert ghost under the same grab point, its synthetic down this pointer's, the\n * ordinary drag from there. The press becomes `carry`: released back over the drawer as drawn — still sliding away, its open rect\n * the desk's once it has shut (K9) — the ghost's gesture is CANCELLED\n * (`CancelRequest` — the ctl sweep reads it this tick, before the release can commit) and it flies home. Released inside the drawer,\n * or the drawer shut under it (Esc, the key), the take is put back: nothing was made, nothing enters undo.\n *\n * Where the drawer is comes through the SEAM `TrayPoseSlot` beside `heldPose`: the renderer's word on the drawer as it DREW it this\n * frame (its rect mid-slide, the scroll range its layout gives), so a hit and the clamp agree with the pixels. Nothing here reads a\n * kind or a pixel; opening a drawer cancels every gesture in flight (`CancelRequest`, read by the `ctl:spawn` sweep this tick).\n */\nimport type { Component, Entity, System, SystemCtx, TickSystem, World } from \"@vibecook/strata-ecs\";\nimport { defineQuery, defineSystem, defineTickSystem } from \"@vibecook/strata-ecs\";\nimport { layTray, specimenFit, type TrayItem, trayOrder, trayScrollMax } from \"@ice/kernel\";\nimport { Specimen, Tray, TrayContent, TrayIntent, TrayPress } from \"../catalog/desk\";\nimport { HandledByWidget, LocalPointer, Pointer, PointerButtons, PointerMods, PointerScreen, PointerWheel, WentCancelled, WentDown, WentUp, WheelHandled } from \"../catalog/pointer\";\nimport { BoardRoot, ChildOf, Position, Size } from \"../catalog/scene\";\nimport { currentNavFrame } from \"../nav/nested-canvas\";\nimport type { DropPlacementPolicy } from \"./l3-drop\";\nimport { engineCatalogFor, widgetTypeFor } from \"../canvas/engine-catalog\";\nimport { Viewport } from \"../catalog/camera-derived\";\nimport { FrameInfo } from \"../engine/frame-info\";\nimport { cancelActiveGestures } from \"../ops/gestures\";\nimport { type ComponentInit, type FieldWrite, PrefabId } from \"../schema/prefab\";\nimport { WidgetEquipped, type WidgetType, widgets } from \"../widget/define-widget\";\nimport { widgetSpawnInits } from \"../widget/spawn\";\nimport { heldEntity } from \"./held\";\n\n/**\n * The drawer ON SCREEN as the renderer drew it this frame, CSS px: its outline box (top-left, width, full height — the part below\n * the view included), the slide `p` (0 closed … 1 open), the scroll range `max` the laid content gives, the board's `pitch`, and\n * the `scroll` as DRAWN — the fact's plus the band's shown pull — so a board point under the pointer is the one on screen. K9: the\n * `face`, the board's height the drawer shows inside its rim — the range is the content's foot plus a pitch less it (kernel\n * `trayScrollMax`), so the lay can clamp the scroll in the tick a new foot or face moves the range; absent, nothing clamps it.\n * design-018 R4: the `head`, how far under its top nothing of the board's content shows (the renderer's clear HEADER, where a host lays\n * the category chips) — a specimen scrolled under it is never hovered or taken there: a press there is the board's; absent, 0.\n * Petition I21: the `foot`, how far above its bottom edge nothing of the content shows (a host's foot inset — its line floats over the\n * board there): the same at the foot, and the range is the content's foot plus a pitch less the face ABOVE it; absent, 0.\n */\nexport interface TrayScreenFrame {\n readonly x: number;\n readonly y: number;\n readonly w: number;\n readonly h: number;\n readonly p: number;\n readonly max: number;\n readonly pitch: number;\n readonly scroll: number;\n readonly face?: number;\n readonly head?: number;\n readonly foot?: number;\n}\n\n/** The pose seam: the renderer's word on where the drawer is — `undefined` before its first frame. */\nexport interface TrayPoseSource {\n frame(): TrayScreenFrame | undefined;\n /**\n * Petition I38 — the renderer's word on what it can DRAW on the board: a hung type it answers `false` of (a kind the desk was not\n * mounted with — `@ice/desk` answers by the kind set it compiled) is not laid, so it hangs nothing, offers no category it would\n * leave empty and takes no press. Absent, every hung type (as before).\n */\n draws?(type: string): boolean;\n}\n\n/** The stack's slot for the pose source — a mutable box, so the renderer can arrive after install (as `heldPose`). */\nexport interface TrayPoseSlot { current: TrayPoseSource | null }\n\n/** The tray's input numbers: a click's slop and the quiet period for a drag's band and the wheel latch after closing. */\nexport const TRAY_INPUT = {\n slopPx: 4,\n letGoMs: 120,\n /** @deprecated Wheel input no longer estimates momentum from shrinking deltas. Kept for source compatibility. */\n fadeDeltas: 3,\n} as const;\n\nconst trayQ = defineQuery([Tray]);\n/** A tray press on no specimen (K5b): its take fields at rest. */\nconst NO_TAKE = { type: \"\", u: 0.5, v: 0.5, homeX: 0, homeY: 0 } as const;\nconst localPointerQ = defineQuery([Pointer, PointerScreen, LocalPointer]);\n\n/** The tray's specimens (K5a): the tray entity's children tagged `Specimen`, in sibling order. */\nexport function specimensOf(world: World, tray: Entity): Entity[] {\n const out: Entity[] = [];\n for (const c of world.getReverse(tray, ChildOf)) if (world.isAlive(c) && world.hasTag(c, Specimen)) out.push(c);\n return out;\n}\n\n/** The specimen at a board point (board px — x from the drawer's left edge, y down from the board's top at scroll 0): its type and where it hangs, or undefined. */\nfunction specimenAt(world: World, tray: Entity, bx: number, by: number): { readonly type: string; readonly x: number; readonly y: number; readonly w: number; readonly h: number } | undefined {\n let hit: { type: string; x: number; y: number; w: number; h: number } | undefined;\n for (const e of specimensOf(world, tray)) {\n const p = world.get(e, Position);\n const z = world.get(e, Size);\n const id = world.get(e, PrefabId)?.id;\n if (p === undefined || z === undefined || typeof id !== \"string\") continue;\n if (bx >= p.x && bx <= p.x + z.w && by >= p.y && by <= p.y + z.h) hit = { type: id, x: p.x, y: p.y, w: z.w, h: z.h };\n }\n return hit;\n}\n\n/** A delta down the board into scroll ∈ [0, max], the rest into the band; a delta back unwinds the band first. */\nexport function scrollBy(scroll: number, stretch: number, d: number, max: number): { readonly scroll: number; readonly stretch: number } {\n let s = scroll;\n let b = stretch;\n let rest = d;\n if (b !== 0 && Math.sign(rest) !== Math.sign(b)) {\n const back = Math.sign(b) * Math.min(Math.abs(b), Math.abs(rest));\n b -= back;\n rest += back;\n }\n if (b === 0 && rest !== 0) {\n const next = Math.min(Math.max(s + rest, 0), Math.max(max, 0));\n const took = next - s;\n s = next;\n rest -= took;\n }\n return { scroll: s, stretch: b + rest };\n}\n\nexport function createTrayInput(world: World, opts: { readonly pose: TrayPoseSlot }): System {\n /** The one-tick ask to hand a take to the desk (the facade applies it after the step — `HeldIntent`'s way). */\n const hand = (i: { readonly type: string; readonly x: number; readonly y: number; readonly pointerId: string; readonly device: \"mouse\" | \"touch\" | \"pen\"; readonly buttons: number; readonly u: number; readonly v: number; readonly homeX: number; readonly homeY: number }): void => {\n const prev = world.getResource(TrayIntent);\n world.setResource(TrayIntent, { ...i, epoch: (prev?.epoch ?? 0) + 1 });\n };\n return defineSystem(\n localPointerQ,\n (b, ctx) => {\n const tray: Entity | undefined = world.firstOf(trayQ);\n if (tray === undefined || !ctx.isAlive(tray)) return;\n const t = ctx.read(tray, Tray);\n if (heldEntity(world) !== undefined) {\n // the hand's focus: the tray stands aside, its presses let go (a take among them — put back)\n for (const r of b) { const p = b.entity(r); if (ctx.has(p, TrayPress)) ctx.removeComponent(p, TrayPress); }\n if ((t.hover ?? \"\") !== \"\" || (t.take ?? \"\") !== \"\") ctx.edit(tray).set(Tray, { ...t, hover: \"\", take: \"\" });\n return;\n }\n const frame = opts.pose.current?.frame();\n const now = world.getResource(FrameInfo)?.now ?? 0;\n const max = Math.max(0, frame?.max ?? 0);\n let open = t.open;\n let scroll = t.scroll;\n let stretch = t.stretch;\n let wheelAt = t.wheelAt;\n let hover = \"\";\n let dragging = false;\n let take = t.take ?? \"\";\n let takeU = t.takeU;\n let takeV = t.takeV;\n let takeX = t.takeX;\n let takeY = t.takeY;\n let handed = t.handed;\n const over = (x: number, y: number, pad: number): boolean =>\n frame !== undefined && x >= frame.x && x <= frame.x + frame.w && y >= frame.y - pad;\n // design-018 R4: what hangs on the board shows only under its header — there a specimen scrolled beneath is bare board; and (I21)\n // only above a host's foot inset\n const shows = (y: number): boolean => frame !== undefined && y >= frame.y + (frame.head ?? 0) && (frame.foot === undefined || y < frame.y + frame.h - frame.foot);\n // the drawer's OPEN rect (K5b): its outline at the full slide — the pose's box with its top the view's foot less its height\n const vh = world.getResource(Viewport)?.h ?? 0;\n const inOpen = (x: number, y: number): boolean => frame !== undefined && x >= frame.x && x <= frame.x + frame.w && y >= vh - frame.h;\n for (const r of b) {\n const p = b.entity(r);\n const s = ctx.read(p, PointerScreen);\n // a down the ingest already flagged is DOM chrome's (design-002 §8): it stays the chrome's — the drawer never takes it\n const chrome = ctx.hasTag(p, HandledByWidget);\n const down = ctx.hasTag(p, WentDown) && !chrome && ((ctx.get(p, PointerButtons)?.buttons ?? 0) & 1) !== 0;\n const press = ctx.get(p, TrayPress);\n if (!open) {\n // K9 (S7): the wheel stays the tray's until it goes quiet — the rest of a stream it took while out (a trackpad's momentum\n // still arriving as the drawer shut: Esc, the key, a take handed out) would zoom the desk; swallowed, each keeping the latch\n const lw = ctx.get(p, PointerWheel);\n if (lw !== undefined && (lw.dy !== 0 || lw.dx !== 0 || lw.pinch !== 0) && wheelAt > 0 && now - wheelAt < TRAY_INPUT.letGoMs) {\n if (!ctx.hasTag(p, WheelHandled)) ctx.addTag(p, WheelHandled);\n wheelAt = now;\n }\n if (press?.kind === \"carry\") {\n // K5b: the take handed to the desk — the insert ghost's drag is this pointer's (its synthetic down included: never the\n // lip's). Released back over the drawer AS DRAWN this frame — still sliding away — the gesture is cancelled — this tick's\n // ctl sweep, before the release can commit — and the ghost flies home; anywhere else the ordinary drag ends it. Once it\n // has slid shut its open rect is the desk's again (K9 S2), and so is the lip's strip (D-K9-c.1, as D-K3.10 gave it back).\n const ended = ctx.hasTag(p, WentUp) || ctx.hasTag(p, WentCancelled);\n if (ctx.hasTag(p, WentUp) && frame !== undefined && frame.p > 0 && over(s.x, s.y, 0)) cancelActiveGestures(world);\n if (ended) ctx.removeComponent(p, TrayPress);\n continue;\n }\n if (press?.kind === \"specimen\") {\n // K5b: the drawer shut under a take (Esc, the key, a peer's op) — the copy goes back on its peg; nothing was made\n take = \"\";\n ctx.removeComponent(p, TrayPress);\n continue;\n }\n // a press the open drawer took (its board, the dimmed desk), shut under it — Esc, the key, a peer's op: let go. A closed\n // drawer takes no press (design-018 §5: the lip's handle retired — the bottom centre is the desk's like anywhere else)\n if (press !== undefined) ctx.removeComponent(p, TrayPress);\n continue;\n }\n // OPEN: the desk is inert — picking, the recognizers and both wheel consumers skip this pointer this tick\n if (!ctx.hasTag(p, HandledByWidget)) ctx.addTag(p, HandledByWidget);\n if (!ctx.hasTag(p, WheelHandled)) ctx.addTag(p, WheelHandled);\n // the specimen under the mouse (K5a): the board point as DRAWN — the pose's shown scroll, the band's pull in it\n if (frame !== undefined && over(s.x, s.y, 0) && shows(s.y) && ctx.read(p, Pointer).device === \"mouse\") hover = specimenAt(world, tray, s.x - frame.x, s.y - frame.y + frame.scroll)?.type ?? \"\";\n const w = ctx.get(p, PointerWheel);\n if (w !== undefined && (w.dy !== 0 || w.dx !== 0 || w.pinch !== 0)) {\n // Every wheel is the tray's while it is out; keep its momentum latched here after a close.\n wheelAt = now;\n const mods = ctx.get(p, PointerMods);\n if (over(s.x, s.y, 0) && w.pinch === 0 && mods?.ctrl !== true && mods?.meta !== true && w.dy !== 0) {\n // macOS already sends the eased momentum tail as wheel deltas. Apply it once, in CSS px,\n // without guessing gesture phases or adding another spring. Discard overscroll instead of\n // banking it: even a small reversal must move immediately, including on a non-scrolling tray.\n scroll = Math.min(Math.max(Math.min(Math.max(scroll, 0), max) + w.dy, 0), max);\n stretch = 0;\n }\n }\n if (down) {\n const onBoard = over(s.x, s.y, 0);\n // K5b: a press on a specimen takes it (past the slop) — the grab point across the object as the board draws it\n const hit = onBoard && shows(s.y) && frame !== undefined ? specimenAt(world, tray, s.x - frame.x, s.y - frame.y + frame.scroll) : undefined;\n const natural = hit === undefined ? undefined : widgetTypeFor(world, hit.type)?.defaultSize;\n const fit = hit !== undefined && natural !== undefined && natural.w > 0 && natural.h > 0 ? specimenFit(hit, natural) : undefined;\n const at = { x: s.x, y: s.y, scroll0: scroll + stretch, moved: false };\n const next = hit !== undefined && fit !== undefined && frame !== undefined\n ? {\n ...at, kind: \"specimen\" as const, type: hit.type,\n u: Math.min(Math.max((s.x - frame.x - fit.x) / fit.w, 0), 1),\n v: Math.min(Math.max((s.y - frame.y + frame.scroll - fit.y) / fit.h, 0), 1),\n homeX: frame.x + fit.x + fit.w / 2, homeY: frame.y + fit.y + fit.h / 2 - frame.scroll,\n }\n : { ...at, kind: onBoard ? (\"board\" as const) : (\"desk\" as const), ...NO_TAKE };\n if (press !== undefined) ctx.edit(p).set(TrayPress, next);\n else ctx.addComponent(p, TrayPress, next);\n if (next.kind === \"board\") dragging = true;\n continue;\n }\n if (press === undefined) continue;\n const moved = press.moved || Math.hypot(s.x - press.x, s.y - press.y) > TRAY_INPUT.slopPx;\n const ended = ctx.hasTag(p, WentUp) || ctx.hasTag(p, WentCancelled);\n if (press.kind === \"specimen\") {\n // K5b — TAKING ONE. Released (or cancelled) inside the drawer: the copy goes back on its peg — nothing was made.\n if (ended) { take = \"\"; ctx.removeComponent(p, TrayPress); continue; }\n if (!moved) continue;\n if (!inOpen(s.x, s.y)) {\n // out of the drawer: it slides away, and the desk takes the copy — the insert ghost under the same grab point, after the step.\n // This tick the take still names it, where it was handed (a flick lifts and hands in one event): the renderer's word on\n // what the ghost grows out of; it clears the tick after, the drawer shut\n open = false;\n take = press.type ?? \"\";\n takeU = press.u;\n takeV = press.v;\n takeX = s.x;\n takeY = s.y;\n handed += 1;\n const pt = ctx.read(p, Pointer);\n hand({ type: press.type ?? \"\", x: s.x, y: s.y, pointerId: pt.id ?? \"mouse\", device: pt.device, buttons: ctx.get(p, PointerButtons)?.buttons ?? 1, u: press.u, v: press.v, homeX: press.homeX, homeY: press.homeY });\n ctx.edit(p).set(TrayPress, { ...press, kind: \"carry\", moved: true });\n continue;\n }\n // past the slop, in the drawer: the copy is lifted and follows the pointer (the specimen stays hung)\n take = press.type ?? \"\";\n takeU = press.u;\n takeV = press.v;\n takeX = s.x;\n takeY = s.y;\n if (moved !== press.moved) ctx.edit(p).set(TrayPress, { ...press, moved });\n continue;\n }\n if (press.kind === \"board\" && !ended) {\n // the board under the finger: where it began, less how far the pointer travelled — past an end, the band\n if (moved) {\n const target = press.scroll0 - (s.y - press.y);\n scroll = Math.min(Math.max(target, 0), max);\n stretch = target - scroll;\n wheelAt = now;\n }\n dragging = true;\n }\n if (ended) {\n if (press.kind === \"desk\" && ctx.hasTag(p, WentUp) && !moved) open = false;\n ctx.removeComponent(p, TrayPress);\n } else if (moved !== press.moved) ctx.edit(p).set(TrayPress, { ...press, moved });\n }\n // the band lets go once the scroll input is quiet — never under a finger still dragging the board — and as the drawer closes\n if (stretch !== 0 && ((!dragging && now - wheelAt > TRAY_INPUT.letGoMs) || !open)) stretch = 0;\n if (!open) { hover = \"\"; if (handed === t.handed) take = \"\"; }\n if (open !== t.open || scroll !== t.scroll || stretch !== t.stretch || wheelAt !== t.wheelAt || hover !== t.hover\n || take !== t.take || takeU !== t.takeU || takeV !== t.takeV || takeX !== t.takeX || takeY !== t.takeY || handed !== t.handed) {\n ctx.edit(tray).set(Tray, { ...t, open, scroll, stretch, wheelAt, hover, take, takeU, takeV, takeX, takeY, handed });\n }\n },\n { name: \"trayInput\", access: { write: [Tray, TrayPress] } },\n );\n}\n\n/** The catalog's object types that carry a tray entry — the tray's contents (K-L2: no list here names a kind); the registry's in an unbound world. The lay hangs those the current frame takes (K9). */\nexport function hungTypes(world: World): WidgetType[] {\n const all = engineCatalogFor(world)?.widgetTypes() ?? widgets.all();\n return all.filter((t) => t.tray !== undefined && t.object !== undefined);\n}\n\n/** A hung type's tray entry as the lattice law takes it: its type, its hang, its place in the order. */\nconst itemOf = (t: WidgetType): TrayItem => {\n const e = t.tray as NonNullable<WidgetType[\"tray\"]>;\n return { type: t.type, hang: e.hang, ...(e.category !== undefined ? { category: e.category } : {}), ...(e.order !== undefined ? { order: e.order } : {}) };\n};\n/** A hung type's tray category (\"\" — its entry names none). */\nconst categoryOf = (t: WidgetType): string => t.tray?.category ?? \"\";\n/** The categories among `types` in the lay's order (category, order, type), each with how many of them it holds (design-018 §6). */\nfunction presentOf(types: readonly WidgetType[]): [string, number][] {\n const out: [string, number][] = [];\n for (const item of types.map(itemOf).sort(trayOrder)) {\n const id = item.category ?? \"\";\n const last = out[out.length - 1];\n if (last !== undefined && last[0] === id) last[1] += 1;\n else out.push([id, 1]);\n }\n return out;\n}\n\n/**\n * THE TRAY'S LAY (design-017 §8; K5a) — the specimens in the world: one RUNTIME entity per object type whose widget carries a tray\n * entry (`hungTypes`), `ChildOf` the tray entity (the root of its runtime canvas), `PrefabId` its type, `Position`/`Size` where the\n * lattice law lays it (kernel `layTray`) across the drawer AS THE RENDERER DREW IT (the pose seam's width and pitch), its entry's\n * props over the widget's defaults, spawned `Specimen` and already `WidgetEquipped` (nothing stamps it; the spatial index never\n * takes it). Laid once the renderer has said how wide the drawer is; re-laid when that width, the pitch or the entries change (a\n * kind registered), a specimen whose kind left destroyed; after a reset the new tray entity is laid afresh. `TrayContent` records\n * what was laid — the content's foot is the renderer's scroll range. A tick system: its spawns are the scheduler's, once a frame —\n * at the head of `derive` (petition I34): it reads back the facts `trayInput` wrote in `react` this tick, so the phase orders them.\n * K9 (S10, D-K9-c.2): when that range MOVES — a lay (the width, the kinds) or the drawer's face (the view's height) — a scroll past its\n * new end with nothing stretching is clamped to it in the same tick, so no frame draws blank board past the content and the next wheel\n * starts from the end; only on a move, so the rig's door (`scrollTray`) still takes any value until the range next moves.\n * K9 (S13, D-K9-c.4): it hangs what the CURRENT frame takes — inside an entered container its ingress, at the root its canvas's\n * placement, the authority a drop's commit asks (`placement`) — so no specimen offers a take the frame would refuse; entering or\n * leaving re-lays it (the drawer is shut then: the desk is inert while it is out). Without a policy, every hung type.\n * Petition I38: and only what the renderer can DRAW (the pose seam's `draws`) — a kind the desk was not mounted with hangs nothing: no\n * specimen (so no hover, no press, no take), no count, no category; a change of that word (a remount on another kind set) re-lays.\n * design-018 §6 (R2) — THE FILTER: of those it lays only the entries of the category the drawer shows (`Tray.category`, \"\" all); a\n * change of it re-lays, and the board starts again at its top — the scroll and the band zeroed. A category the frame hangs none of\n * (its last entry gone with the frame, or an id no entry names) falls back to all. What the frame could hang before the filter — its\n * categories in the lay's order and their counts — is recorded in `TrayContent.present` (the ops' `trayCategories`: a host's chips).\n * Petition I37 — THE KEYBOARD FOCUS (`Tray.focus`, the op `focusTray`): when it moves to a specimen, the board scrolls the least that\n * shows that specimen whole between the header and the foot (once — a wheel may then take it out of view again); a focus on a type\n * the board no longer lays is let go.\n */\nexport function createTrayLay(world: World, opts: { readonly pose: TrayPoseSlot; readonly placement?: DropPlacementPolicy | undefined }): TickSystem {\n let laidKey = \"\";\n let rangeKey = \"\";\n // the category the last lay showed, and on which tray entity (R2): a move of it starts the board again at its top\n let laidTray: Entity | undefined;\n let laidCategory = \"\";\n // the focus the board last scrolled to (I37): a move of it scrolls once; and the types the last lay laid, in its order\n let focusedFor = \"\";\n let laidTypes: readonly string[] = [];\n const clampToRange = (ctx: SystemCtx, tray: Entity, frame: TrayScreenFrame, bottom: number): void => {\n if (frame.face === undefined) return;\n const range = trayScrollMax(bottom, frame.face - (frame.foot ?? 0), frame.pitch);\n const key = `${tray}|${range}`;\n if (key === rangeKey) return;\n const t = ctx.read(tray, Tray);\n if (t.stretch !== 0) return; // the band's pull (a wheel's, a finger's) is its own: judged once it lets go\n rangeKey = key;\n if (t.scroll > range) ctx.edit(tray).set(Tray, { ...t, scroll: range });\n };\n // THE KEYBOARD FOCUS (I37): moved to a specimen, the least scroll that shows it whole between the header and the foot; on a type the\n // board lays no more (this tick's lay removed it), let go. Specimens spawned this tick are not readable yet: a focus on one waits a tick.\n const focusInView = (ctx: SystemCtx, tray: Entity, frame: TrayScreenFrame, bottom: number): void => {\n const t = ctx.read(tray, Tray);\n const focus = t.focus ?? \"\";\n if (focus !== \"\" && !laidTypes.includes(focus)) {\n focusedFor = \"\";\n ctx.edit(tray).set(Tray, { ...t, focus: \"\" });\n return;\n }\n if (focus === focusedFor) return;\n if (focus === \"\") { focusedFor = \"\"; return; }\n const hung = specimensOf(world, tray).find((e) => world.get(e, PrefabId)?.id === focus);\n if (hung === undefined) return;\n const at = ctx.get(hung, Position);\n const size = ctx.get(hung, Size);\n if (at === undefined || size === undefined) return;\n focusedFor = focus;\n if (frame.face === undefined) return;\n const top = frame.head ?? 0;\n const showing = frame.face - (frame.foot ?? 0) - top;\n let scroll = t.scroll;\n if (at.y < scroll + top || size.h > showing) scroll = at.y - top;\n else if (at.y + size.h > scroll + top + showing) scroll = at.y + size.h - top - showing;\n scroll = Math.min(Math.max(scroll, 0), trayScrollMax(bottom, frame.face - (frame.foot ?? 0), frame.pitch));\n if (scroll !== t.scroll || t.stretch !== 0) ctx.edit(tray).set(Tray, { ...t, scroll, stretch: 0 });\n };\n return defineTickSystem(\n (ctx) => {\n const tray: Entity | undefined = world.firstOf(trayQ);\n if (tray === undefined || !ctx.isAlive(tray)) return;\n const source = opts.pose.current;\n const frame = source?.frame();\n if (source === null || source === undefined || frame === undefined || !(frame.w > 0) || !(frame.pitch > 0)) return;\n const content = ctx.get(tray, TrayContent);\n const policy = opts.placement;\n const inside = policy === undefined ? undefined : currentNavFrame(world);\n const root = world.getResource(BoardRoot)?.root;\n const takes = (type: string): boolean =>\n policy === undefined ? true : inside !== undefined ? policy.canIngress(type, inside) : root === undefined || policy.canPlace === undefined || policy.canPlace(type, root);\n // …of the types the renderer can draw (I38): a kind the desk was not mounted with is not laid — every hung type when it says nothing\n const draws = (type: string): boolean => source.draws === undefined || source.draws(type);\n const types = hungTypes(world).filter((t) => takes(t.type) && draws(t.type));\n // THE FILTER (design-018 §6): the category asked, or all when the frame hangs none of it — written back, so the fact says\n // what is shown; a move of what is shown zeroes the scroll and the band (the board starts again at its top)\n const t = ctx.read(tray, Tray);\n const asked = t.category ?? \"\";\n const category = asked !== \"\" && !types.some((q) => categoryOf(q) === asked) ? \"\" : asked;\n const moved = laidTray === tray && category !== laidCategory;\n if (category !== asked || (moved && (t.scroll !== 0 || t.stretch !== 0))) ctx.edit(tray).set(Tray, { ...t, category, ...(moved ? { scroll: 0, stretch: 0 } : {}) });\n const key = `${tray}|${content?.laid ?? 0}|${frame.w}|${frame.pitch}|${types.map((q) => q.type).join(\",\")}|${category}`;\n if (key === laidKey) { clampToRange(ctx, tray, frame, content?.bottom ?? 0); focusInView(ctx, tray, frame, content?.bottom ?? 0); return; }\n const shown = category === \"\" ? types : types.filter((q) => categoryOf(q) === category);\n const items: TrayItem[] = shown.map(itemOf);\n const layout = layTray(items, frame.w, frame.pitch);\n const have = new Map<string, Entity>();\n for (const e of specimensOf(world, tray)) { const id = world.get(e, PrefabId)?.id; if (typeof id === \"string\") have.set(id, e); }\n for (const p of layout.placed) {\n const w = shown.find((q) => q.type === p.type) as WidgetType;\n const e = have.get(p.type);\n if (e !== undefined) {\n have.delete(p.type);\n const at = ctx.get(e, Position);\n const size = ctx.get(e, Size);\n if (at?.x !== p.x || at?.y !== p.y) ctx.edit(e).set(Position, { x: p.x, y: p.y });\n if (size?.w !== p.w || size?.h !== p.h) ctx.edit(e).set(Size, { w: p.w, h: p.h });\n continue;\n }\n // the widget's own spawn inits (Position, Size, the entry's props folded into their groups), the untouched groups at their defaults\n const cells = new Map<Component, Record<string, FieldWrite>>();\n for (const [c, v] of w.prefab.components) cells.set(c, v);\n for (const [c, v] of widgetSpawnInits(w.type, { x: p.x, y: p.y, w: p.w, h: p.h, props: w.tray?.props ?? {} }, w).overrides) cells.set(c, v);\n cells.set(PrefabId, { id: w.type });\n const spawned = ctx.spawn({ components: [...cells] as ComponentInit[], tags: [Specimen, WidgetEquipped] });\n ctx.setRelation(spawned, ChildOf, tray, \"last\");\n }\n for (const e of have.values()) ctx.destroy(e);\n const next = { width: frame.w, bottom: layout.bottom, laid: (content?.laid ?? 0) + 1, present: JSON.stringify(presentOf(types)), order: JSON.stringify(layout.placed.map((q) => q.type)) };\n if (content === undefined) ctx.addComponent(tray, TrayContent, next);\n else ctx.edit(tray).set(TrayContent, next);\n laidKey = `${tray}|${next.laid}|${frame.w}|${frame.pitch}|${types.map((q) => q.type).join(\",\")}|${category}`;\n laidTray = tray;\n laidCategory = category;\n laidTypes = layout.placed.map((q) => q.type);\n clampToRange(ctx, tray, frame, layout.bottom);\n focusInView(ctx, tray, frame, layout.bottom);\n },\n // Petition I34: in derive, after `trayInput` (react) by the phase — the lay reads back what the input wrote this tick, so the two\n // `Tray` writers are ORDERED, never attested. `Position`/`Size` it writes on the tray's specimens alone, rows disjoint from the\n // selection chrome's handle pool (its derive co-writer) — that, and only that, is attested.\n { name: \"trayLay\", access: { write: [Position, Size, TrayContent, Tray], orderIndependent: [Position, Size] } },\n );\n}\n","/**\n * THE TRAY'S OPS (design-017 §2; K3) — the ways a host, the keymap and a rig move the pegboard drawer's facts (`Tray`, runtime, one\n * per view). Outside the tick, world-taking like `cancelActiveGestures`; the tray's input system (systems/tray.ts) is their one\n * in-tick peer. Opening is refused while an object is in hand (the hand is a focus of its own — put it down first) and cancels every\n * gesture in flight (widgetlab's hygiene: nothing freezes mid-drag under the drawer); closing lets the band go. design-018 §6 (R2):\n * the drawer's CATEGORY — which of the entries it lays (\"\" all), and the categories the frame hangs, for a host's chips. Petition\n * I37: the board's KEYBOARD FOCUS — which specimen a host's arrows are on (`focusTray`), the one its ⏎ lays (the facade's\n * `ops.layFromTray`).\n */\nimport type { Entity, World } from \"@vibecook/strata-ecs\";\nimport { defineQuery } from \"@vibecook/strata-ecs\";\nimport { Tray, TrayContent } from \"../catalog/desk\";\nimport { Container } from \"../catalog/graph\";\nimport { heldEntity } from \"../systems/held\";\nimport { cancelActiveGestures } from \"./gestures\";\n\nconst trayQ = defineQuery([Tray]);\n\n/**\n * The view's tray entity, spawned (runtime, closed) if the world has none — at install, and after a reset. It ROOTS the tray's\n * runtime canvas (K5a — a `Container`, so its specimens' first container is it, never a frame: none is ever `Active`), its\n * content not yet laid.\n */\nexport function ensureTray(world: World): Entity {\n const existing = world.firstOf(trayQ);\n if (existing !== undefined) return existing;\n return world.spawn({\n components: [[Tray, { open: false, scroll: 0, stretch: 0, wheelAt: 0, hover: \"\" }], [TrayContent, { width: 0, bottom: 0, laid: 0 }]],\n tags: [Container],\n });\n}\n\n/** The view's tray entity, if there is one. */\nexport function trayEntity(world: World): Entity | undefined {\n return world.firstOf(trayQ);\n}\n\n/** Is the drawer out? */\nexport function trayOpen(world: World): boolean {\n const e = world.firstOf(trayQ);\n return e !== undefined && world.get(e, Tray)?.open === true;\n}\n\nconst write = (world: World, patch: Partial<{ open: boolean; scroll: number; stretch: number; hover: string; category: string; focus: string }>): void => {\n const e = ensureTray(world);\n const cur = world.read(e, Tray);\n const next = { ...cur, ...patch };\n if (next.open !== cur.open || next.scroll !== cur.scroll || next.stretch !== cur.stretch || next.hover !== cur.hover || next.category !== cur.category || next.focus !== cur.focus) world.edit(e).set(Tray, next);\n};\n\n/** Open the drawer: refused (false) while an object is in hand; every gesture in flight is cancelled. */\nexport function openTray(world: World): boolean {\n if (heldEntity(world) !== undefined) return false;\n if (!trayOpen(world)) cancelActiveGestures(world);\n write(world, { open: true });\n return true;\n}\n\n/** Close the drawer; the band lets go. */\nexport function closeTray(world: World): void {\n write(world, { open: false, stretch: 0, hover: \"\" });\n}\n\n/** Open a closed drawer, close an open one; returns whether it is open now. */\nexport function toggleTray(world: World): boolean {\n if (trayOpen(world)) { closeTray(world); return false; }\n return openTray(world);\n}\n\n/** Set the board's scroll (CSS px past its top) — a host's or a rig's door; any value (the input clamps what it moves). */\nexport function scrollTray(world: World, scroll: number): void {\n write(world, { scroll, stretch: 0 });\n}\n\n/**\n * The types the board hangs now, in the LAY'S order — row by row, and across the categories when the drawer shows all (`TrayContent.\n * order`, the lay's record) — what the keyboard focus walks (petition I37). Empty until the lay has run (the renderer's first frame).\n */\nexport function trayHung(world: World): string[] {\n const e = world.firstOf(trayQ);\n const raw = e === undefined ? undefined : world.get(e, TrayContent)?.order;\n if (raw === undefined || raw === null || raw === \"\") return [];\n const list: unknown = JSON.parse(raw);\n return Array.isArray(list) ? list.filter((q): q is string => typeof q === \"string\") : [];\n}\n\n/** Where the board's keyboard focus moves (petition I37): along the lay's order, or to its ends. */\nexport type TrayFocusMove = \"next\" | \"prev\" | \"first\" | \"last\";\n\n/** The specimen the board's keyboard focus is on — its object type (\"\" — none). */\nexport function trayFocus(world: World): string {\n const e = world.firstOf(trayQ);\n return e === undefined ? \"\" : (world.get(e, Tray)?.focus ?? \"\");\n}\n\n/**\n * Move the board's KEYBOARD FOCUS (petition I37): `next`/`prev` along the specimens the lay hangs, in its order (row by row, and\n * across the categories when the drawer shows all) — from none, `next` is the first and `prev` the last; at an end it stays —\n * `first`/`last`, or a type by its id (one the board does not hang: the focus stays where it was). The lay scrolls the specimen it\n * moves to into the board's face (`createTrayLay`); nothing is drawn for it (a host rings `TrayAnchor.focused`). Open or shut, the\n * board is laid alike. Returns the focused type (\"\" — the board hangs nothing).\n */\nexport function focusTray(world: World, to: TrayFocusMove | string): string {\n const order = trayHung(world);\n const cur = trayFocus(world);\n const i = order.indexOf(cur);\n const last = order.length - 1;\n let next: string;\n if (to === \"first\") next = order[0] ?? \"\";\n else if (to === \"last\") next = order[last] ?? \"\";\n else if (to === \"next\") next = order[i < 0 ? 0 : Math.min(i + 1, last)] ?? \"\";\n else if (to === \"prev\") next = order[i < 0 ? last : Math.max(i - 1, 0)] ?? \"\";\n else next = order.includes(to) ? to : cur;\n write(world, { focus: next });\n return next;\n}\n\n/** A tray category as a host's chip shows it (design-018 §6): its id (an entry's `category`), its label, how many entries the frame hangs in it. */\nexport interface TrayCategory {\n readonly id: string;\n /** The id with its first letter capitalized (\"surfaces\" → \"Surfaces\"). */\n readonly label: string;\n readonly count: number;\n}\n\n/** The category the drawer shows (\"\" — all). */\nexport function trayCategory(world: World): string {\n const e = world.firstOf(trayQ);\n return e === undefined ? \"\" : (world.get(e, Tray)?.category ?? \"\");\n}\n\n/**\n * Show one category of the tray's entries (\"\" — all): the lay (systems/tray.ts `createTrayLay`) hangs only its entries, zeroes the\n * scroll and the band on the change, and falls back to all when the frame hangs none of it (an id no entry names included).\n */\nexport function setTrayCategory(world: World, id: string): void {\n write(world, { category: id });\n}\n\n/**\n * The categories PRESENT among the entries the drawer's frame hangs (design-018 §6) — the catalog's tray entries the current frame\n * takes (K9 S13), before the category's filter — in the lay's order, each with its label and count: a host's chips. An entry that\n * names no category is laid under all alone (it has no chip). Empty until the lay has run (the renderer's first frame).\n */\nexport function trayCategories(world: World): TrayCategory[] {\n return presentOf(world).filter(([id]) => id !== \"\").map(([id, count]) => ({ id, label: id.charAt(0).toUpperCase() + id.slice(1), count }));\n}\n\n/** How many entries the drawer's frame hangs, every category (before the filter) — 0: the tray has nothing to offer here. */\nexport function trayEntryCount(world: World): number {\n return presentOf(world).reduce((n, [, count]) => n + count, 0);\n}\n\n/** The lay's record of what the frame could hang (`TrayContent.present`), read back. */\nfunction presentOf(world: World): (readonly [string, number])[] {\n const e = world.firstOf(trayQ);\n const raw = e === undefined ? undefined : world.get(e, TrayContent)?.present;\n if (raw === undefined || raw === null || raw === \"\") return [];\n const list: unknown = JSON.parse(raw);\n return Array.isArray(list) ? list.filter((q): q is [string, number] => Array.isArray(q) && typeof q[0] === \"string\" && typeof q[1] === \"number\") : [];\n}\n","/**\n * The ENTER GESTURE (design-015 §9; D2b) — a double-tap on a `Container` asks to enter it, a\n * double-tap on the bare frame asks to leave. `ctl:behave`, after `selectBehavior`: the first\n * tap SELECTS at once (the prototype's click), the second — the same target, within\n * `multiTapWindowMs`, within `multiTapSlopPx` — is the gesture. Detected from two INSTANT\n * taps (each Recognized at count 1) held in `NavTapMemo`, not from a `MultiTap(2)` opt-in on\n * the target: that machinery parks the first tap Pending for the whole window, so a plain\n * click on a container would select 280 ms late — a latency the prototype never had (its\n * first click selected, its dblclick entered). `MultiTap` stays what it is for widgets that\n * want a counted tap.\n *\n * The op itself is NOT run here: `enterContainer` spawns, writes tags and rebuilds the index —\n * structural writes, illegal mid-tick. The gesture writes the one-tick `NavIntent` fact and the\n * facade applies it once `engine.step` returns (nav-geometry.ts). A tap on a PART (`DownPart`)\n * is the app's and never counts; a tap while a flight drives is not a double-tap's first half\n * (the flight yields to nothing but a camera gesture).\n */\nimport type { Entity, System, World } from \"@vibecook/strata-ecs\";\nimport { defineQuery, defineSystem, field } from \"@vibecook/strata-ecs\";\nimport { CanvasSurface } from \"../catalog/camera-derived\";\nimport { HeldIntent } from \"../catalog/desk\";\nimport { Captures, Down, DownPart, GesturePhases as P, Tap, Watches } from \"../catalog/gesture\";\nimport { Container } from \"../catalog/graph\";\nimport { PointerButtons } from \"../catalog/pointer\";\nimport { GestureSettings } from \"../catalog/settings-resources\";\nimport { FrameInfo } from \"../engine/frame-info\";\nimport { currentNavEntry } from \"../nav/nested-canvas\";\nimport { NavIntent } from \"../nav/nav-geometry\";\nimport { NavTransition } from \"./nav-flight\";\nimport { defineResource } from \"../schema/meta\";\nimport { GESTURE_DEFAULTS } from \"../settings/defaults\";\n\n/** The last instant tap: its target (0 = the bare frame), where and when — the double-tap's first half. */\nexport const NavTapMemo = defineResource(\n \"NavTapMemo\",\n {\n target: field(\"eid\", { default: 0 as Entity }),\n x: field(\"f64\", { default: 0 }),\n y: field(\"f64\", { default: 0 }),\n at: field(\"f64\", { default: 0 }),\n /** Bumps per tap seen; 0 = no memo. */\n seq: field(\"u32\", { default: 0 }),\n },\n { durable: false },\n);\n\nconst tapRecognizedQ = defineQuery([Tap, P.justTags.Recognized]);\n\nexport interface NavTapOpts {\n /** Is this entity a container the engine may enter (the facade's catalog-backed test)? Default: the `Container` tag. */\n readonly isContainer?: (entity: Entity) => boolean;\n /**\n * Is this entity an object that OPENS (design-015 §8, D4b — the facade's catalog-backed test: its widget type\n * declares `openable`)? A double-tap on one asks to pick it up (`HeldIntent`), not to enter it. Default: nothing opens.\n */\n readonly isOpenable?: (entity: Entity) => boolean;\n}\n\nexport function createNavTap(world: World, opts: NavTapOpts = {}): System {\n const isContainer = opts.isContainer ?? ((e: Entity): boolean => world.hasTag(e, Container));\n const isOpenable = opts.isOpenable ?? ((): boolean => false);\n return defineSystem(\n tapRecognizedQ,\n (b, ctx) => {\n for (const r of b) {\n const rec = b.entity(r);\n // a tap on a part is the app's (design-014 B3b) — it neither counts nor clears the memo\n if ((ctx.get(rec, DownPart)?.part ?? \"\") !== \"\") continue;\n // a tap while a flight drives is not a double-tap's first half (the header; D7 #12): the arriving desk is not yet\n // where the eye has it, so it neither counts nor pairs — the memo is spent, a tap after the landing starts afresh\n if (world.getResource(NavTransition)?.active === true) {\n world.setResource(NavTapMemo, { target: 0 as Entity, x: 0, y: 0, at: 0, seq: 0 });\n continue;\n }\n const down = ctx.read(rec, Down);\n const captured = ctx.getRelation(rec, Captures);\n // the bare frame: no target, or the canvas surface entity picking falls back to\n const bare = captured === undefined || ctx.hasTag(captured, CanvasSurface);\n const target = bare ? (0 as Entity) : captured;\n const gs = world.getResource(GestureSettings);\n const windowMs = gs?.multiTapWindowMs ?? GESTURE_DEFAULTS.multiTapWindowMs;\n const slopPx = gs?.multiTapSlopPx ?? GESTURE_DEFAULTS.multiTapSlopPx;\n // The tap's time is its down EVENT's own (K9 S6 — K-H's product call): the pointer this recognizer watches carries\n // `PointerButtons.downMs` = the adapter's `e.timeStamp` (l0-input), kept through the release — so a main-thread stall\n // between two taps (their frames 400 ms apart, their events 110) still pairs them, and two events 400 ms apart on adjacent\n // frames do not. 0 (a synthetic input with no time) falls back to the frame's `now`; never the frame CLOCK (its dt is\n // clamped, and the loop sleeps between taps — taps seconds apart could pair).\n const watched = ctx.getRelations(rec, Watches)[0];\n const downMs = watched !== undefined && ctx.isAlive(watched) ? (ctx.get(watched, PointerButtons)?.downMs ?? 0) : 0;\n const now = downMs !== 0 ? downMs : (world.getResource(FrameInfo)?.now ?? down.ms);\n const memo = world.getResource(NavTapMemo);\n const seq = (memo?.seq ?? 0) + 1;\n const pairs =\n memo !== undefined &&\n memo.seq > 0 &&\n memo.target === target &&\n now - memo.at <= windowMs &&\n Math.hypot(down.x - memo.x, down.y - memo.y) <= slopPx;\n if (!pairs) {\n world.setResource(NavTapMemo, { target, x: down.x, y: down.y, at: now, seq });\n continue;\n }\n // the second tap: the gesture. The memo is spent either way (a third tap starts afresh).\n world.setResource(NavTapMemo, { target: 0 as Entity, x: 0, y: 0, at: 0, seq: 0 });\n const prev = world.getResource(NavIntent);\n const epoch = (prev?.epoch ?? 0) + 1;\n if (!bare) {\n if (!ctx.isAlive(target)) continue;\n // an OPENABLE object is picked up (design-015 §8): its kind declared an opening, the more specific word\n if (isOpenable(target)) {\n const held = world.getResource(HeldIntent);\n world.setResource(HeldIntent, { kind: \"open\", target, epoch: (held?.epoch ?? 0) + 1 });\n continue;\n }\n if (!isContainer(target)) continue;\n world.setResource(NavIntent, { kind: \"enter\", target, transition: \"zoom\", source: \"tap\", epoch });\n } else if (currentNavEntry(world) !== undefined) {\n world.setResource(NavIntent, { kind: \"exit\", target: 0 as Entity, transition: \"zoom\", source: \"tap\", epoch });\n }\n }\n },\n { name: \"navTap\" },\n );\n}\n","/**\n * The ZOOM-THROUGH (design-015 §9, design-013 Q13 → ON; PORTAL.md §8 — D2b). `ctl:behave`,\n * after `cameraControl`: on a frame whose wheel zoomed (`WheelZoomStep`, D2a-core's one-tick\n * fact — pans never cut, and the touch pinch is not recorded there, D-D2a.6), when no flight\n * drives and the settings say so —\n *\n * - a zoom IN: the topmost Active container (paint order) whose face has come in whole\n * (presence 1) AND covers the whole viewport by `in` CSS px is entered as a CUT nobody can\n * see: the view already IS its inside, and the cut lands on the camera the inside was\n * rendering under (`transition: \"cut\"`).\n * - a zoom OUT: when the current frame's own face — under the parent camera the inside\n * renders as it does now, the continuity solve — no longer covers the view by `out` px, the\n * frame is left as a cut onto that parent camera.\n *\n * Both are asked through the one-tick `NavIntent` fact (ops are structural — illegal mid-tick;\n * the facade applies it right after the step) with `redress` set: the entered desk was DRESSED\n * for its arrival as a face (`from` = the arrival's zoom), the left desk for the camera it was\n * cut at (`from` = the camera's zoom) — the renderer re-dresses over its own ramp and hands the\n * lamp over on it (`NavRedress`, written by the applier). The faces come through the nav\n * geometry seam (the drawn face, the gate's answer, the cover test), else core's static rect.\n */\nimport type { Entity, TickSystem, World } from \"@vibecook/strata-ecs\";\nimport { defineQuery, defineTickSystem } from \"@vibecook/strata-ecs\";\nimport { type CameraState, solveFlightStart } from \"@ice/kernel\";\nimport { Active, Camera } from \"../catalog/camera-derived\";\nimport { Container } from \"../catalog/graph\";\nimport { Position, Size } from \"../catalog/scene\";\nimport { ZoomThroughSettings } from \"../catalog/settings-resources\";\nimport { FrameInfo } from \"../engine/frame-info\";\nimport { type NavGeometrySlot, NavIntent, resolveNavFace } from \"../nav/nav-geometry\";\nimport { currentNavFrame } from \"../nav/nested-canvas\";\nimport { compareStackOrder, createSiblingOrderIndex } from \"../ops/sibling-order\";\nimport { PrefabId } from \"../schema/prefab\";\nimport { NavTransition } from \"./nav-flight\";\nimport { WheelZoomStep } from \"./camera-sim\";\n\nconst activeContainersQ = defineQuery([Container, Active, Position, Size, PrefabId]);\n\nexport interface ZoomThroughOpts {\n /** The nav geometry seam the faces are read through (the interaction stack's slot). */\n readonly navGeometry?: NavGeometrySlot;\n /** Is this entity a container the engine may enter (the facade's catalog-backed test)? Default: any `Container`. */\n readonly isContainer?: (entity: Entity) => boolean;\n}\n\nexport function createZoomThrough(world: World, opts: ZoomThroughOpts = {}): TickSystem {\n const order = createSiblingOrderIndex(world);\n const isContainer = opts.isContainer ?? (() => true);\n const wheeledThisTick = (): boolean => {\n const step = world.getResource(WheelZoomStep);\n if (step === undefined || step.ratio === 1) return false;\n return step.tick === (world.getResource(FrameInfo)?.tick ?? -1);\n };\n return defineTickSystem(\n (ctx) => {\n const zt = world.getResource(ZoomThroughSettings);\n if (zt === undefined || !zt.enabled || !wheeledThisTick()) return;\n if (world.getResource(NavTransition)?.active === true) return; // no cut while a flight drives\n const step = world.getResource(WheelZoomStep);\n const camRes = world.getResource(Camera);\n if (step === undefined || camRes === undefined) return;\n const cam: CameraState = { x: camRes.x, y: camRes.y, zoom: camRes.zoom };\n const prev = world.getResource(NavIntent);\n const epoch = (prev?.epoch ?? 0) + 1;\n if (step.ratio > 1) {\n // IN: the topmost Active container first — paint order, the same comparator pick and paint use\n const conts: Entity[] = [];\n ctx.query(activeContainersQ).each((b) => { for (const r of b) conts.push(b.entity(r)); });\n if (conts.length === 0) return;\n const ordinals = order.ordinals();\n conts.sort((a, b) => compareStackOrder(ctx, ordinals, b, a));\n for (const c of conts) {\n if (!isContainer(c)) continue;\n const f = resolveNavFace(world, c, cam, opts.navGeometry);\n if (f === undefined || f.presence < 1 || !f.covers(zt.in)) continue;\n world.setResource(NavIntent, { kind: \"enter\", target: c, transition: \"cut\", source: \"through\", epoch });\n return;\n }\n } else {\n // OUT: the current frame's own face under the parent camera the inside renders as it does now\n const frame = currentNavFrame(world);\n if (frame === undefined || !world.isAlive(frame)) return;\n const rest = resolveNavFace(world, frame, cam, opts.navGeometry);\n if (rest === undefined) return;\n const hostCam = solveFlightStart(rest.affine, cam);\n const f = resolveNavFace(world, frame, hostCam, opts.navGeometry);\n if (f === undefined || f.covers(-zt.out)) return;\n world.setResource(NavIntent, { kind: \"exit\", target: frame, transition: \"cut\", source: \"through\", epoch });\n }\n },\n {\n name: \"zoomThrough\",\n runIf: () => world.getResource(ZoomThroughSettings)?.enabled === true && wheeledThisTick(),\n },\n );\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 { interactionDue, wakefulQueue } from \"./wakes\";\nimport { createCameraSystems } from \"../systems/camera-sim\";\nimport { createCleanupSystems } from \"../systems/cleanup\";\nimport { createL0Systems } from \"../systems/l0-input\";\nimport { createNavFlight } from \"../systems/nav-flight\";\nimport { createPickingSystems, type FramePickSlot, type PointPick } 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, type DropPlacementPolicy } from \"../systems/l3-drop\";\nimport { createMarqueeBehavior, type MarqueeBuffer } from \"../systems/l3-marquee\";\nimport { createPortMaterialize } from \"../systems/l3-ports\";\nimport { createResizeBehavior } from \"../systems/l3-resize\";\nimport { createSnapSystem } from \"../systems/l3-snap\";\nimport { createSelectionChromeSystem } from \"../systems/chrome\";\nimport { createDrawBehavior } from \"../systems/l3-draw\";\nimport { createInsertGhostReap } from \"../systems/insert-ghost\";\nimport { createCursorSync } from \"../systems/l4-cursor\";\nimport { createHeldInput, type HeldPoseSlot } from \"../systems/held\";\nimport { createPressWheel } from \"../systems/press-wheel\";\nimport { createTrayInput, createTrayLay, type TrayPoseSlot } from \"../systems/tray\";\nimport { ensureTray } from \"../ops/tray\";\nimport { createNavTap } from \"../systems/nav-tap\";\nimport { createZoomThrough } from \"../systems/zoom-through\";\nimport type { NavGeometrySlot } from \"../nav/nav-geometry\";\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 /** Typed Canvas SDK placement truth; omission retains compatibility cells. */\n readonly placement?: DropPlacementPolicy;\n /** Is this entity a container the engine may ENTER (the facade's catalog-backed test; design-015 §9's gesture and zoom-through)? Default: the `Container` tag. */\n readonly isContainer?: (entity: Entity) => boolean;\n /** Is this entity an object that OPENS (design-015 §8's double-tap; the facade's catalog-backed test — its type declares `openable`)? Default: nothing opens. */\n readonly isOpenable?: (entity: Entity) => boolean;\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 // the adapters' one door wakes a sleeping loop (K7a, engine/frame-control.ts)\n const queue = wakefulQueue(opts.queue ?? createInputQueue(), () => engine.frame.wake(\"input\"));\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(world);\n const claims = createClaimSystems(world);\n const behaviors = createSelectMoveBehaviors(world, sink);\n const cleanup = createCleanupSystems(world);\n\n const removers = [\n // the stack's registered wake (K7a, interaction/wakes.ts): due every frame while its time-driven work is pending\n engine.frame.wakeWhen(\"interaction\", interactionDue(world, queue)),\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 /** The frame pick source's slot (design-014, B3b): the ground layer sets `current` at mount, clears it at dispose. */\n readonly framePick: FramePickSlot;\n /**\n * The exact pick OUT of the tick (petition I27; l1-pick `pickAt`): what a press at a SCREEN point (CSS px of the view) would touch\n * now — `picking`'s own `TouchesExact` body on the world as the last tick left it, through the frame source above; `undefined` over\n * the bare canvas and while the pegboard drawer is out. Read-only. The desk's `handle.pick` reaches it through its mount context.\n */\n pickAt(sx: number, sy: number): PointPick | undefined;\n /**\n * The nav geometry seam (design-015 §9; D2b) beside `framePick`: the renderer's word on a\n * container's DRAWN face, the inside's arrival and the exact cut camera — core's nav, the\n * zoom-through and the drop-into read it when set; the renderer sets it at mount, clears it at dispose.\n */\n readonly navGeometry: NavGeometrySlot;\n /**\n * The held pose seam (design-015 §8; D4b) beside the two above: the renderer's word on where the object in\n * hand is ON SCREEN this frame, through which every pointer is mapped while something is held; the renderer\n * sets it at mount, clears it at dispose.\n */\n readonly heldPose: HeldPoseSlot;\n /**\n * The tray pose seam (design-017 §4; K3) beside `heldPose`: the renderer's word on where the pegboard drawer is ON SCREEN this\n * frame (its rect mid-slide, its scroll range), which the tray's input hit-tests and clamps by; set at mount, cleared at dispose.\n */\n readonly trayPose: TrayPoseSlot;\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 // the adapters' one door wakes a sleeping loop (K7a, engine/frame-control.ts)\n const queue = wakefulQueue(opts.queue ?? createInputQueue(), () => engine.frame.wake(\"input\"));\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 // The frame pick source's slot (design-014, B3b): the ground layer fills it at mount.\n const framePick: FramePickSlot = { current: null };\n const pick = createPickingSystems(world, index, wires, framePick);\n // The nav geometry seam (design-015 §9; D2b): the renderer fills it at mount.\n const navGeometry: NavGeometrySlot = { current: null };\n const navOpts = { navGeometry, ...(opts.isContainer !== undefined ? { isContainer: opts.isContainer } : {}), ...(opts.isOpenable !== undefined ? { isOpenable: opts.isOpenable } : {}) };\n // The held pose seam (design-015 §8; D4b): the renderer fills it at mount; the held input maps every pointer through it.\n const heldPose: HeldPoseSlot = { current: null };\n // The tray pose seam (design-017 §4; K3): the renderer fills it at mount; the tray's input hit-tests through it. Its facts' entity, one per view.\n const trayPose: TrayPoseSlot = { current: null };\n ensureTray(world);\n const l2 = createL2Systems({ world, ...(opts.profiles ? { profiles: opts.profiles } : {}) });\n const arb = createArbitrationSystems(world);\n const claims = createClaimSystems(world);\n const behaviors = createSelectMoveBehaviors(world, sink, { navGeometry });\n const snap = createSnapSystem(world, index);\n const drop = createDropSystem(world, index, opts.placement, navGeometry);\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, { pose: heldPose });\n const cleanup = createCleanupSystems(world);\n\n const removers = [\n // the stack's registered wake (K7a, interaction/wakes.ts): due every frame while its time-driven work is pending\n engine.frame.wakeWhen(\"interaction\", interactionDue(world, queue)),\n engine.addSystems(\"input\", l0.pointerLifecycle, l0.pointerIngest, l0.pointerWorldSync),\n // heldInput at the HEAD of react (design-015 §8, D4b): the ingest's one-tick tags (WentDown/WentUp) are flushed at the\n // phase boundary, so here it sees the press; its own `HandledByWidget`/`WheelHandled` flush before ctl — the recognizers\n // and both wheel consumers never see a pointer while an object is in hand. Picking still runs (the hover relations), harmless.\n // wireSync AFTER spatialSync (both SpatialVersion writers), BEFORE picking —\n // which now narrow-phases wire entries against wireSync's cached cubics.\n // pressWheel beside it (D3t-a): a press holding a `WheelTurns` widget takes its pointer's wheel from both wheel consumers too.\n // trayInput right after the hand's (design-017 §4, K3): the pegboard drawer's wheel, its board and its inert desk, in the same vocabulary\n // (its lay is derived from what it writes — at the head of derive, below)\n engine.addSystems(\"react\", createHeldInput(world, { pose: heldPose }), createTrayInput(world, { pose: trayPose }), createPressWheel(world), 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 // design-015 §9 (D2b): the enter GESTURE after the select (the first tap selects, the\n // second asks to enter) and the zoom-through after the camera (it reads this frame's\n // wheel zoom). Both ask through `NavIntent`; the facade applies it after the tick.\n createNavTap(world, navOpts),\n createZoomThrough(world, navOpts),\n ),\n // navFlight AFTER cameraControl's group (ctl:behave): a gesture going\n // Active stamps Camera.gesturing THIS frame, so the flight yields\n // same-frame (design-006 §4 \"touch always wins\").\n engine.addSystems(\"simulate\", camera.cameraInertia, camera.tweenSystem, createNavFlight(world)),\n // derive order: portMaterialize BEFORE selectionChrome (both touch the index\n // in derive; ports must be indexed before chrome/next-frame picking read it),\n // selectionChrome BEFORE cursor (handles spawn at the derive flush so cursor\n // + next frame's spatialSync see them).\n // trayLay at the HEAD of derive (petition I34): it reads back the drawer's facts trayInput wrote in react this tick — its clamp\n // judges this tick's band, a category move starts the board at its top over this tick's wheel — so it is ORDERED after the input\n // by the phase, never attested (both wrote `Tray` in react, and strata's dev build warned on every engine). Its specimens are\n // derived state, spawned at the derive flush for the renderer; the selection chrome, the other Position/Size writer here,\n // writes rows disjoint from them, and both attest it.\n engine.addSystems(\"derive\", createTrayLay(world, { pose: trayPose, placement: opts.placement }), ports, createSelectionChromeSystem(world), cursor),\n // insertGhostReap AFTER recognizerReap: it reads terminal phase tags on\n // capturing recognizers pre-flush (deferred destroys land at the group\n // boundary), and its own despawns must not race the marker sweep.\n engine.addSystems(\"cleanup\", cleanup.recognizerReap, cleanup.oneTickClear, createInsertGhostReap(world)),\n ];\n\n return {\n queue,\n sink,\n canvasSurface,\n index,\n marqueeBuffer: marquee.buffer,\n wirePreview: connect.previewBuffer,\n framePick,\n pickAt: (sx, sy) => pick.pickAt(sx, sy),\n navGeometry,\n heldPose,\n trayPose,\n clearCaches: () => pick.clearCaches(),\n readCursor: cursor.readCursor,\n uninstall() {\n for (const remove of removers) remove();\n },\n };\n}\n","/**\n * cleanup phase — nothing transient crosses frames (design-002 §2; design-003\n * §4.1 reap, §8 CancelRequest one-tick rule).\n *\n * `recognizerReap` destroys terminal recognizers at terminal +1 frame: a Just*\n * marker means the transition happened THIS tick (markers clear later this\n * phase, but ctx reads are pre-flush) — no marker means the tag has lingered a\n * full frame and every edge-triggered consumer has run. `ClaimedBy`/`Watches`/\n * `Captures`/`Drags` edges auto-clear with the despawn.\n *\n * `oneTickClear` then clears pointer transition tags, zeroes wheel deltas,\n * clears all Just* markers, and consumes CancelRequest (a latched cancel would\n * kill every future gesture forever).\n */\nimport { Any, defineQuery, defineSystem, type System, type World } from \"@vibecook/strata-ecs\";\nimport {\n CancelRequest,\n Drag,\n GesturePhases,\n HandledByWidget,\n LongPress,\n Pinch,\n Pointer,\n PointerWheel,\n Tap,\n WentCancelled,\n WentDown,\n WentUp,\n WheelHandled,\n WheelPan,\n WheelZoom,\n} from \"../catalog\";\n\nconst P = GesturePhases;\n\nconst anyKindQ = defineQuery([Any(Tap, LongPress, Drag, Pinch, WheelPan, WheelZoom)]);\nconst pointerQ = defineQuery([Pointer, PointerWheel]);\n\nexport function createCleanupSystems(world: World): { recognizerReap: System; oneTickClear: System } {\n const recognizerReap = defineSystem(\n anyKindQ,\n (b, ctx) => {\n for (const r of b) {\n const e = b.entity(r);\n const terminal =\n ctx.hasTag(e, P.tags.Failed) ||\n ctx.hasTag(e, P.tags.Cancelled) ||\n ctx.hasTag(e, P.tags.Ended) ||\n (ctx.hasTag(e, P.tags.Recognized) && ctx.has(e, Tap)); // Recognized is terminal for Tap only\n if (!terminal) continue;\n const transitionedThisTick =\n ctx.hasTag(e, P.justTags.Failed) ||\n ctx.hasTag(e, P.justTags.Cancelled) ||\n ctx.hasTag(e, P.justTags.Ended) ||\n ctx.hasTag(e, P.justTags.Recognized);\n if (!transitionedThisTick) ctx.destroy(e); // terminal + 1 frame\n }\n },\n { name: \"recognizerReap\" },\n );\n\n const oneTickClear = defineSystem(\n pointerQ,\n (b, ctx) => {\n for (const r of b) {\n const e = b.entity(r);\n if (ctx.hasTag(e, WentDown)) ctx.removeTag(e, WentDown);\n if (ctx.hasTag(e, WentUp)) ctx.removeTag(e, WentUp);\n if (ctx.hasTag(e, WentCancelled)) ctx.removeTag(e, WentCancelled);\n if (ctx.hasTag(e, HandledByWidget)) ctx.removeTag(e, HandledByWidget);\n if (ctx.hasTag(e, WheelHandled)) ctx.removeTag(e, WheelHandled);\n const w = ctx.read(e, PointerWheel);\n if (w.dx !== 0 || w.dy !== 0 || w.pinch !== 0) {\n ctx.edit(e).set(PointerWheel, { dx: 0, dy: 0, pinch: 0 });\n }\n }\n // Recognizer markers (reap above already consumed them pre-flush).\n world.query(anyKindQ).each((rb) => {\n for (const rr of rb) P.clearMarkers(ctx, rb.entity(rr));\n });\n // Consume the one-tick cancel request.\n if (ctx.getResource(CancelRequest)?.active === true) {\n world.setResource(CancelRequest, { active: false });\n }\n },\n { name: \"oneTickClear\", access: { write: [PointerWheel] } },\n );\n\n return { recognizerReap, oneTickClear };\n}\n","/**\n * L0 — pointers & ingest (design-003 §2; `input` phase).\n *\n * Order inside the phase is load-bearing:\n *\n * `pointerLifecycle` runs BEFORE `pointerIngest` and reads only immediate\n * values: a touch pointer whose buttons are still 0 at the top of a frame has\n * been idle-up for a full frame (ingest zeroed buttons on the up frame), so its\n * `ctx.destroy` lands at the input flush of frame up+1 — recognizers saw the up\n * frame's `WentUp` in full. Tag-based detection cannot work in-phase (ingest's\n * one-tick tags are deferred to the flush), hence values.\n *\n * `pointerIngest` is scheduled on the CANVAS-SURFACE anchor query (exactly one\n * such entity, guaranteed by install) because a system body only runs when its\n * query matches — and ingest must run on frames where no pointer entity exists\n * yet (the first down CREATES the pointer). It drains the queue once per tick\n * in two passes: fold events into per-pointer samples, then apply — existing\n * pointers get immediate value writes + deferred one-tick tags; NEW pointers\n * spawn once with their folded final state (an identity-only `ctx.spawn` handle\n * cannot take `edit().set`). Facts are always true: `surfaceHandled` events\n * still land, but carry the one-tick `HandledByWidget` tag L1/L2 read (the\n * pinned widget-event contract, design-002 §8).\n *\n * THE CUT (2026-09-26): a pointer's fold ENDS at its transition (down / up /\n * cancel), so a tick that carries `WentDown`/`WentUp` carries the pointer AT\n * the press or the release — picking hits what was pressed, recognizers judge\n * the release where it happened. The first event past a closed fold ends the\n * tick's drain: it and everything behind it (every pointer, every key — the\n * processed events stay a PREFIX of arrival order) are the next tick's facts.\n * Before the cut, a click whose release coalesced with a far move into one\n * frame published `WentUp` at the MOVE's point: the tap failed its slop, the\n * drag measured its dead zone to a point reached after the release and went\n * Active on the clicked object — which then followed the cursor (a ghost\n * drag; found under CDP input in apps/desk, reachable by a quick tap and\n * flick). Between transitions moves and wheel deltas still fold: every\n * consumer reads the latest position or the tick's accumulated deltas.\n */\nimport type { Entity, System, TickSystem, World } from \"@vibecook/strata-ecs\";\nimport { defineQuery, defineSystem, defineTickSystem } from \"@vibecook/strata-ecs\";\nimport { screenToWorld } from \"@ice/kernel\";\nimport {\n Camera,\n HandledByWidget,\n Keyboard,\n LocalPointer,\n OverInteractive,\n Pointer,\n PointerButtons,\n PointerMods,\n PointerOutside,\n PointerRadius,\n PointerScreen,\n PointerWheel,\n PointerWorld,\n WentCancelled,\n WentDown,\n WentUp,\n WheelHandled,\n} from \"../catalog\";\nimport { PointerVersion, bumpVersion } from \"../helpers/version-stamps\";\nimport type { InputEvent, InputQueue } from \"../input/queue\";\nimport { PointerSettings } from \"../catalog/settings-resources\";\nimport { POINTER_DEFAULTS } from \"../settings/defaults\";\n\nconst pointerQ = defineQuery([Pointer, PointerScreen]);\nconst touchLifecycleQ = defineQuery([Pointer, PointerButtons]);\n\nfunction radiusFor(device: InputEvent[\"device\"], ps?: { radiusTouchPx: number; radiusPenPx: number; radiusMousePx: number }): number {\n if (device === \"touch\") return (ps ?? POINTER_DEFAULTS).radiusTouchPx;\n if (device === \"pen\") return (ps ?? POINTER_DEFAULTS).radiusPenPx;\n return (ps ?? POINTER_DEFAULTS).radiusMousePx;\n}\n\n/** Per-pointer fold of one tick's drained events. */\ninterface Sample {\n device: InputEvent[\"device\"];\n x: number;\n y: number;\n buttons: number;\n downX: number;\n downY: number;\n downMs: number;\n wentDown: boolean;\n wentUp: boolean;\n wentCancelled: boolean;\n handled: boolean;\n /** Last hover-bearing fact's verdict; undefined = no hover info this tick (tag holds). */\n overInteractive: boolean | undefined;\n /** Left the host (the tick's last fact a `leave`, petition I42) or back over it (any other fact after one) — `PointerOutside`. */\n outside: boolean;\n mods: { shift: boolean; ctrl: boolean; alt: boolean; meta: boolean };\n wheelDx: number;\n wheelDy: number;\n wheelPinch: number;\n hasWheel: boolean;\n /** Any wheel fact this tick was ceded to widget scroll (design-007 §3.5). */\n wheelHandled: boolean;\n}\n\nexport interface L0Systems {\n pointerLifecycle: System;\n pointerIngest: TickSystem;\n pointerWorldSync: System;\n}\n\nexport function createL0Systems(world: World, queue: InputQueue): L0Systems {\n // pointerId → entity lookup. Derived index only (the fact is Pointer.id in\n // the world); entries validate with isAlive and rebuild on miss.\n const byId = new Map<string, Entity>();\n\n const resolve = (id: string): Entity | undefined => {\n const cached = byId.get(id);\n if (cached !== undefined && world.isAlive(cached)) return cached;\n byId.delete(id);\n let found: Entity | undefined;\n world.query(pointerQ).each((b) => {\n for (const r of b) {\n const e = b.entity(r);\n if (world.read(e, Pointer).id === id) {\n found = e;\n return;\n }\n }\n });\n if (found !== undefined) byId.set(id, found);\n return found;\n };\n\n const pointerLifecycle = defineSystem(\n touchLifecycleQ,\n (b, ctx) => {\n for (const r of b) {\n const e = b.entity(r);\n if (ctx.read(e, Pointer).device !== \"touch\") continue;\n if (ctx.read(e, PointerButtons).buttons === 0) ctx.destroy(e); // idle-up a full frame\n }\n },\n {\n name: \"pointerLifecycle\",\n // The STALE read is the mechanism: last frame's buttons==0 ⇒ up+1 destroy\n // (module doc). Declare no reads so strata's advisory \"reads before\n // ingest writes\" ordering hint doesn't flag the intentional dependency.\n access: { read: [] },\n },\n );\n\n // Tick system (strata 0.5.0): the drain runs exactly once per frame by\n // construction — the scheduler owns cardinality, no anchor query needed.\n const pointerIngest = defineTickSystem(\n (ctx) => {\n const events = queue.drain();\n if (events.length === 0) return;\n // Live-tunable pick radii (design-005 §4): resource first, const fallback.\n const pointerSettings = ctx.getResource(PointerSettings);\n\n // --- pass 1: fold ---\n const samples = new Map<string, Sample>();\n let keyboard: { shift: boolean; ctrl: boolean; alt: boolean; meta: boolean; space: boolean } | null =\n null;\n for (const [i, ev] of events.entries()) {\n if (ev.kind === \"key\") {\n keyboard = { ...ev.mods };\n continue;\n }\n let s = samples.get(ev.pointerId);\n if (s !== undefined && (s.wentDown || s.wentUp || s.wentCancelled)) {\n // The cut (module doc): this pointer's fold closed at its transition.\n // The drain above emptied the queue, so re-enqueueing puts the tail\n // back at its HEAD, in order, ahead of anything a later handler adds.\n for (const rest of events.slice(i)) queue.enqueue(rest);\n break;\n }\n if (s === undefined) {\n s = {\n device: ev.device,\n x: ev.screenX,\n y: ev.screenY,\n buttons: ev.buttons,\n downX: 0,\n downY: 0,\n downMs: 0,\n wentDown: false,\n wentUp: false,\n wentCancelled: false,\n handled: false,\n overInteractive: undefined,\n outside: 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 wheelHandled: false,\n };\n samples.set(ev.pointerId, s);\n }\n s.x = ev.screenX;\n s.y = ev.screenY;\n s.buttons = ev.buttons;\n s.mods = { shift: ev.mods.shift, ctrl: ev.mods.ctrl, alt: ev.mods.alt, meta: ev.mods.meta };\n if (ev.kind === \"down\") {\n s.wentDown = true;\n s.downX = ev.screenX;\n s.downY = ev.screenY;\n s.downMs = ev.tMs ?? 0; // event-time anchor (0 ⇒ consumers use frame now)\n } else if (ev.kind === \"up\") {\n s.wentUp = true;\n } else if (ev.kind === \"cancel\") {\n s.wentCancelled = true;\n } else if (ev.kind === \"wheel\" && ev.wheel !== undefined) {\n s.wheelDx += ev.wheel.dx;\n s.wheelDy += ev.wheel.dy;\n s.wheelPinch += ev.wheel.pinch;\n s.hasWheel = true;\n if (ev.wheelHandled === true) s.wheelHandled = true;\n }\n // Out of the host (I42): a `leave` at its last point; any other fact of the pointer's is the pointer over the host again.\n s.outside = ev.kind === \"leave\";\n if (ev.surfaceHandled === true) s.handled = true;\n // Hover truth: last stamped fact wins; unstamped facts (wheel, blur\n // cancel, test drivers that don't track hover) leave it undefined.\n if (ev.overInteractive !== undefined) s.overInteractive = ev.overInteractive;\n }\n\n // --- pass 2: apply ---\n if (keyboard !== null) world.setResource(Keyboard, keyboard);\n\n for (const [id, s] of samples) {\n const existing = resolve(id);\n if (existing === undefined) {\n // Its world point is its own from the spawn (petition I45): what `pointerWorldSync` writes from the next frame — the sync\n // cannot see a pointer spawned in this phase, and the cell's (0, 0) for that frame was the first cursor presence published.\n const cam = ctx.getResource(Camera);\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, cam === undefined ? { x: 0, y: 0 } : screenToWorld(s.x, s.y, cam)],\n ],\n tags: [LocalPointer],\n });\n if (s.wentDown) ctx.addTag(spawned, WentDown);\n if (s.wentUp) ctx.addTag(spawned, WentUp);\n if (s.wentCancelled) ctx.addTag(spawned, WentCancelled);\n if (s.handled) ctx.addTag(spawned, HandledByWidget);\n if (s.wheelHandled) ctx.addTag(spawned, WheelHandled);\n if (s.overInteractive === true) ctx.addTag(spawned, OverInteractive);\n if (s.outside) ctx.addTag(spawned, PointerOutside);\n byId.set(id, spawned);\n continue;\n }\n\n ctx.edit(existing).set(PointerScreen, { x: s.x, y: s.y });\n const prev = ctx.read(existing, PointerButtons);\n ctx.edit(existing).set(PointerButtons, {\n buttons: s.buttons,\n downX: s.wentDown ? s.downX : prev.downX,\n downY: s.wentDown ? s.downY : prev.downY,\n downMs: s.wentDown ? s.downMs : prev.downMs,\n });\n ctx.edit(existing).set(PointerMods, s.mods);\n if (s.hasWheel) {\n const w = ctx.read(existing, PointerWheel);\n ctx.edit(existing).set(PointerWheel, {\n dx: w.dx + s.wheelDx,\n dy: w.dy + s.wheelDy,\n pinch: w.pinch + s.wheelPinch,\n });\n }\n if (s.wentDown) ctx.addTag(existing, WentDown);\n if (s.wentUp) ctx.addTag(existing, WentUp);\n if (s.wentCancelled) ctx.addTag(existing, WentCancelled);\n if (s.handled) ctx.addTag(existing, HandledByWidget);\n if (s.wheelHandled) ctx.addTag(existing, WheelHandled);\n // Persistent hover-boundary tag, change-only (interaction-rate law):\n // written only when a hover-bearing fact arrived AND the state flipped.\n if (s.overInteractive !== undefined && s.overInteractive !== ctx.hasTag(existing, OverInteractive)) {\n if (s.overInteractive) ctx.addTag(existing, OverInteractive);\n else ctx.removeTag(existing, OverInteractive);\n }\n // Persistent and change-only too (I42): every fact says whether the pointer is out of the host.\n if (s.outside !== ctx.hasTag(existing, PointerOutside)) {\n if (s.outside) ctx.addTag(existing, PointerOutside);\n else ctx.removeTag(existing, PointerOutside);\n }\n }\n\n bumpVersion(world, PointerVersion);\n },\n {\n name: \"pointerIngest\",\n // Design-003 §10 table. Runs only when input arrived (runIf on the queue),\n // so idle frames stamp nothing.\n access: { write: [Pointer, PointerScreen, PointerButtons, PointerMods, PointerWheel] },\n runIf: () => queue.size() > 0,\n },\n );\n\n const pointerWorldSync = defineSystem(\n defineQuery([Pointer, PointerScreen, PointerWorld]),\n (b, ctx) => {\n const cam = ctx.getResource(Camera);\n if (cam === undefined) return;\n for (const r of b) {\n const e = b.entity(r);\n const s = ctx.read(e, PointerScreen);\n const w = screenToWorld(s.x, s.y, cam);\n ctx.edit(e).set(PointerWorld, { x: w.x, y: w.y });\n }\n },\n { name: \"pointerWorldSync\", access: { write: [PointerWorld] } },\n );\n\n return { pointerLifecycle, pointerIngest, pointerWorldSync };\n}\n","/**\n * L1 — spatial sync + targeting (design-003 §3; `react` phase).\n *\n * Two systems, run in this order:\n *\n * `spatialSync` maintains the kernel `SpatialIndex` over every Position+Size\n * entity (widgets AND HandleSpec chrome — both carry a world AABB). It is a\n * TICK system so the body runs every frame — it is the writer that bumps\n * `SpatialVersion` — but as of strata 0.7.0 (petition 7 LANDED) the body is\n * O(delta), not O(N): a `world.changes` collector journals exactly which\n * entities were touched (Position/Size writes, Active/WidgetEquipped flips,\n * spawns, destroys — same-frame, drained INSIDE the pipeline), and each is\n * re-checked against `isIndexable` → upsert or remove. The 2026-07-13 walk\n * machinery (last-known AABB cache, compare-and-skip, generation sweep) is\n * RETIRED — the collector knows; the system no longer has to discover.\n *\n * The FULL WALK survives as exactly what petition 7 said it should be:\n * - the SEED (a collector only journals writes made after its creation);\n * - the `reset` route (world.reset / replace import / nav `clearCaches`);\n * - the `coarse` fallback (some declared-raw-write system touched\n * Position/Size rows the journal cannot attribute — rescan, never miss).\n * Nav gating rides the walk QUERIES at archetype level: widgets match\n * `[Position, Size, WidgetEquipped, Active]`, chrome matches\n * `[Position, Size, Not(WidgetEquipped)]` — the union is exactly\n * `Position+Size ∧ (¬WidgetEquipped ∨ Active)`, and `isIndexable` is the\n * same predicate entity-wise for the delta path. Materialized ports are M8 —\n * skipped.\n *\n * `picking` runs the dual pick (design-003 §3), gated by a version guard over\n * `PointerVersion ∨ SpatialVersion`. `CameraVersion` does not exist — camera\n * motion alone does not re-pick, an accepted staleness (design-002 §2). Pointer\n * world position is derived from PointerScreen × Camera rather than read from\n * the PointerWorld cell. The cell no longer lags on the pointer's spawn: ingest\n * spawns it at screen×camera, what the pointerWorldSync writer (which cannot see\n * a pointer spawned in the same input phase) writes from the next frame\n * (petition I45 — before, (0, 0) for that frame, which would have mis-captured\n * on the down frame). The pick keeps its own derivation: screen×camera, at the\n * camera it reads, is exact here whoever wrote the cell.\n * - `Targets` = radiused disc-vs-box pick with a screen-px release\n * dead-band (hover is forgiving; hold the current target\n * while the pointer stays within its expanded bounds).\n * - `TouchesExact` = r=0 point pick (grab is precise; no dead-band).\n * Pick priority is plane priority: HandleSpec chrome first, then widgets\n * topmost by sibling order (petition 8 — the shared SiblingOrderIndex feeds\n * pickTopAt, so pick can never diverge from paint), then the CanvasSurface\n * entity as the guaranteed fallback (design-001 §4). Relations are written\n * change-only (design-002 §4 hygiene). Wires/ports are M8 — skipped.\n *\n * `pickAt` is the exact pick OUT of the tick (petition I27 — the desk's\n * `handle.pick`, a host's right-click): the `TouchesExact` body above run on\n * the world as the last tick left it, read-only — one body, so a host's pick\n * and a press can never disagree.\n */\nimport type { Batch, Entity, System, 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 PointerPart,\n PointerRadius,\n PointerScreen,\n Position,\n Size,\n Targets,\n TouchesExact,\n Tray,\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, type PickReader, pickTopAt, type WirePickSource } from \"../ops/point-pick\";\nimport { compareStackOrder, createSiblingOrderIndex } from \"../ops/sibling-order\";\nimport { PointerSettings } from \"../catalog/settings-resources\";\nimport { POINTER_DEFAULTS } from \"../settings/defaults\";\n\nconst IDENTITY_CAM: CameraState = { x: 0, y: 0, zoom: 1 };\n\nconst canvasSurfaceQ = defineQuery([CanvasSurface]);\n// The pegboard drawer's fact (design-017 §2): while it is out the desk is INERT to the pointer, and the pick reads that itself — see `picking`.\nconst trayQ = defineQuery([Tray]);\n// Nav gating at ARCHETYPE level (design-004 §7): the union of these two is\n// exactly `Position+Size ∧ (¬WidgetEquipped ∨ Active)` — equipped widgets are\n// hittable only while Active (in-frame); chrome/pre-equip entities always.\n// Tags in the query beat per-row `hasTag` calls (2026-07-13 perf audit).\nconst widgetAabbQ = defineQuery([Position, Size, WidgetEquipped, Active]);\nconst chromeAabbQ = defineQuery([Position, Size, Not(WidgetEquipped)]);\nconst pointerQ = defineQuery([Pointer, PointerScreen, PointerRadius, LocalPointer, Not(HandledByWidget)]);\n\n/**\n * The FRAME pick source (design-014, B3b): the ground's answer to \"what is\n * under this world point on card `e`\" — `content`, `frame` (the chrome band\n * outside the content rect), `outside`, or a PART the registered card program\n * names (`close`, `lock` …) — or `undefined`: the source has NO GEOMETRY for the card\n * (the ground's pipelines are still compiling, the card has not been drawn yet, or\n * creation failed), and the box tier's answer stands. `undefined` is not `outside`: a\n * card the ground cannot see is still a card (B9 review blocker 1 — a source that\n * answered `outside` there made every card unclickable until the first build, and for\n * good when `Ground.create` rejected). `pad()` is how far the chrome reaches past the\n * content rect, world units: the spatial index holds content rects, so\n * `picking` widens its search by it and asks the source about candidates the\n * boxes missed. Set on the interaction stack by the ground layer at mount;\n * `null` = every hit is the box's (the stratified profile).\n */\nexport interface FramePickSource {\n pad(): number;\n hit(e: Entity, wx: number, wy: number): string | undefined;\n /**\n * The source's geometry is MOVING under a still pointer (a reveal growing a control, a lift): `picking` runs\n * every frame this answers true, so the part under a motionless pointer is the part that is there now. Absent\n * = never; the pointer and the spatial index are then the only wakes (B9 review).\n */\n live?(): boolean;\n /**\n * The widgets the source draws LIFTED this frame — above the frame's own order and away from their facts (design-015 §6's\n * print in a hand, flicked or gliding; D3t-a): the spatial index still holds their fact rects, so the frame tier asks\n * these FIRST, wherever they are drawn, and the topmost that answers is the hit — a press catches a gliding print where\n * it is, and its old rect no longer does (its geometry says `outside` there). Absent = none.\n */\n lifted?(): Iterable<Entity>;\n}\n\n/** The stack's slot for the frame pick source — a mutable box, so the ground can arrive after install. */\nexport interface FramePickSlot { current: FramePickSource | null }\n\n/** What a press at a point would touch (`TouchesExact`): the entity, and the PART under it (`\"\"` the thing itself — design-014). */\nexport interface PointPick {\n readonly entity: Entity;\n readonly part: string;\n}\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 /**\n * The exact pick OUT of the tick (petition I27): what a press at a SCREEN point (CSS px of the view) would touch now — the\n * `TouchesExact` body `picking` runs, on the world as the last tick left it and the camera as it stands; `undefined` over the bare\n * canvas, and everywhere while the pegboard drawer is out (the desk inert, design-017 §4). Read-only: no relation, no tag, no stamp.\n */\n pickAt(sx: number, sy: number): PointPick | undefined;\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 frames: FramePickSlot = { current: null },\n): PickingSystems {\n // The change journal (petition 7 / strata 0.7.0). Subscribing here is the\n // whole trick: Position/Size writes, Active/WidgetEquipped flips, spawns\n // and destroys journal the ENTITY at the write chokepoints — no walk needed\n // to discover them. `seeded` gates the initial full walk (pre-collector\n // entities) and is re-armed by nav `clearCaches` (design-004 §7).\n //\n // `coarse: false` is the engine's ATTESTATION (the strata option's exact\n // contract): every Position/Size writer here uses store-visible writes —\n // absolute writes via `ctx.*`/`world.edit`/doc projection are engine LAW.\n // Without it, the declared-`access.write` blanket from exact-path systems\n // (move/resize/snap declare for enforcement) would mark coarse every\n // gesture frame and force the full rescan collectors exist to retire.\n const collector = world.changes.collect({\n components: [Position, Size],\n tags: [Active, WidgetEquipped],\n coarse: false,\n });\n let seeded = false;\n // Entities THIS system put in the index. The index is SHARED and\n // multi-writer (ports + wires maintain their own entries) — rebuilds must\n // remove only our own stale entries, never `index.clear()`.\n let known = new Set<Entity>();\n\n /**\n * The delta path's entity-wise twin of the walk queries' union: upserts and\n * reports true when `e` belongs in the index, false (no write) otherwise.\n */\n const upsertIfIndexable = (e: Entity): boolean => {\n if (!world.isAlive(e)) return false;\n const p = world.get(e, Position);\n const s = world.get(e, Size);\n if (p === undefined || s === undefined) return false;\n if (world.hasTag(e, WidgetEquipped) && !world.hasTag(e, Active)) return false;\n index.upsert(e, { minX: p.x, minY: p.y, maxX: p.x + s.w, maxY: p.y + s.h });\n return true;\n };\n\n const spatialSync = defineTickSystem(\n (ctx) => {\n const delta = collector.drain();\n // Full-walk routes: seed, reset (world.reset / nav), coarse raw writes.\n if (!seeded || delta.reset || delta.coarse.length > 0) {\n seeded = true;\n const next = new Set<Entity>();\n const visit = (batch: Batch): void => {\n const px = batch.col(Position).x;\n const py = batch.col(Position).y;\n const sw = batch.col(Size).w;\n const sh = batch.col(Size).h;\n for (const row of batch) {\n const x = px[row] as number;\n const y = py[row] as number;\n const e = batch.entity(row);\n index.upsert(e, {\n minX: x,\n minY: y,\n maxX: x + (sw[row] as number),\n maxY: y + (sh[row] as number),\n });\n next.add(e);\n }\n };\n ctx.query(widgetAabbQ).each(visit);\n ctx.query(chromeAabbQ).each(visit);\n for (const e of known) {\n if (!next.has(e)) index.remove(e); // only OUR stale entries — never index.clear()\n }\n known = next;\n bumpVersion(world, SpatialVersion);\n return;\n }\n // Delta path — O(changed), ~0 on still frames.\n if (delta.changed.length === 0 && delta.removed.length === 0) return;\n for (const e of delta.removed) {\n if (known.delete(e)) index.remove(e); // destroyed — drop by our cached key\n }\n for (const e of delta.changed) {\n if (upsertIfIndexable(e)) {\n known.add(e);\n } else if (known.delete(e)) {\n index.remove(e);\n }\n }\n bumpVersion(world, SpatialVersion);\n },\n {\n name: \"spatialSync\",\n // The inner ctx.query col() reads are charged to THIS system by access\n // enforcement — a tick system has no query, so the default read set is\n // empty and the columns must be declared explicitly.\n access: { read: [Position, Size] },\n },\n );\n\n // The pull-based frame ordinal map (petition 8): pickTopAt's widget tier\n // takes the compareStackOrder max over it — the same map every renderer\n // sorts by. Stamp-checked per read; ~free while order is quiet.\n const order = createSiblingOrderIndex(world);\n\n /** THE narrow-phase, shared with the router's event-time pick (ops/point-pick).\n * `wires` (M8) narrow-phases wire entries against their cached cubic; undefined\n * before the wire slice installs ⇒ wire index entries are skipped by pickTopAt. */\n const pickTop = (reader: PickReader, wx: number, wy: number, rWorld: number): Entity | undefined =>\n pickTopAt(reader, index, wx, wy, rWorld, wires, order.ordinals());\n /**\n * The frame tier (design-014, B3b): with a source registered, a widget hit by\n * its content box is asked what is under the point — a rounded corner's\n * void is `outside` and falls through; and when the boxes miss, the topmost\n * widget whose CHROME the source says is under the point (within `pad`) is\n * the hit. Returns the entity and the part (`\"\"` for content and frame).\n */\n const pickFrame = (ctx: PickReader, wx: number, wy: number, rWorld: number, boxHit: Entity | undefined): { e: Entity | undefined; part: string } => {\n const src = frames.current;\n if (src === null) return { e: boxHit, part: \"\" };\n const isWidget = (e: Entity): boolean => ctx.hasTag(e, WidgetEquipped) && ctx.hasTag(e, Active);\n const partOf = (h: string): string => (h === \"content\" || h === \"frame\" || h === \"outside\" ? \"\" : h);\n // the LIFTED first (D3t-a): drawn above the frame's order, wherever their facts are — the topmost that answers wins\n const lifted = src.lifted?.();\n if (lifted !== undefined) {\n const ordinals = order.ordinals();\n let top: Entity | undefined;\n let topPart = \"\";\n for (const e of lifted) {\n if (!ctx.isAlive(e) || !isWidget(e)) continue;\n if (top !== undefined && compareStackOrder(ctx, ordinals, e, top) < 0) continue;\n const h = src.hit(e, wx, wy);\n if (h === undefined || h === \"outside\") continue;\n top = e;\n topPart = partOf(h);\n }\n if (top !== undefined) return { e: top, part: topPart };\n }\n if (boxHit !== undefined && isWidget(boxHit)) {\n const h = src.hit(boxHit, wx, wy);\n if (h === undefined) return { e: boxHit, part: \"\" }; // no geometry for it yet: the box tier stands\n if (h !== \"outside\") return { e: boxHit, part: partOf(h) };\n } else if (boxHit !== undefined) {\n return { e: boxHit, part: \"\" }; // chrome, a port, a wire: the box tier's answer stands\n }\n // the boxes missed (or the box hit was a corner's void): the chrome band of the topmost widget within reach\n const ordinals = order.ordinals();\n let best: Entity | undefined;\n let bestPart = \"\";\n for (const entry of index.searchPoint(wx, wy, rWorld + src.pad())) {\n const e = entry.id;\n if (!ctx.isAlive(e) || !isWidget(e) || e === boxHit) continue;\n if (best !== undefined && compareStackOrder(ctx, ordinals, e, best) < 0) continue;\n const h = src.hit(e, wx, wy);\n if (h === undefined || h === \"outside\") continue; // no geometry: no chrome band to reach\n best = e;\n bestPart = partOf(h);\n }\n return { e: best, part: bestPart };\n };\n /** The EXACT pick (`TouchesExact` and its part — \"grab is precise\"): the r = 0 point pick through the frame tier. */\n const pickExact = (reader: PickReader, wx: number, wy: number): { e: Entity | undefined; part: string } =>\n pickFrame(reader, wx, wy, 0, pickTop(reader, wx, wy, 0));\n\n const versions = makeVersionGuard(world, [PointerVersion, SpatialVersion]);\n // The drawer out = the desk inert to the pointer (design-017 §4). `trayInput` stamps every local pointer `HandledByWidget` for\n // that, but it runs in THIS phase and a tag is a structural write — it lands at the phase boundary, after this has picked — so\n // the query's `Not(HandledByWidget)` never sees it (the hand's stamp the same: \"picking still runs\", install.ts) and the\n // DOM-at-event-time halves (the editor's tap, the calendar's days) read a LIVE hit through the drawer (K9 law #1). So the pick\n // reads the fact itself: while `Tray.open`, every local pointer touches the bare canvas and names no part — what rose under\n // it settles, and nothing under the drawer can be lent, selected or written on. `trayWasOpen` runs it once on each flip of the\n // fact (a drawer opened by key, the pointer still: the hovered note must still let go; shut again: the hit must come back).\n const trayIsOpen = (): boolean => { const t = world.firstOf(trayQ); return t !== undefined && world.read(t, Tray).open; };\n let trayWasOpen = false;\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 const inert = trayIsOpen();\n trayWasOpen = inert;\n\n for (const r of b) {\n const p = b.entity(r);\n if (inert) {\n // the desk under the drawer is bare to this pointer: the canvas surface is its exact hit and its target (as on the empty\n // desk), its part none — the same answers the pointer gets off every object, so every consumer reads \"nothing here\"\n if (canvas !== undefined) {\n if (ctx.getRelation(p, TouchesExact) !== canvas) ctx.setRelation(p, TouchesExact, canvas);\n if (ctx.getRelation(p, Targets) !== canvas) ctx.setRelation(p, Targets, canvas);\n }\n if (frames.current !== null) {\n const cur = ctx.get(p, PointerPart);\n if (cur === undefined) ctx.addComponent(p, PointerPart, { part: \"\" });\n else if (cur.part !== \"\") ctx.edit(p).set(PointerPart, { part: \"\" });\n }\n continue;\n }\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 exactFrame = pickExact(ctx, w.x, w.y);\n const exact = exactFrame.e ?? canvas;\n if (exact !== undefined && ctx.getRelation(p, TouchesExact) !== exact) {\n ctx.setRelation(p, TouchesExact, exact);\n }\n // The part under the exact hit (design-014, B3b) — change-only, present only with a source.\n if (frames.current !== null) {\n const cur = ctx.get(p, PointerPart);\n if (cur === undefined) ctx.addComponent(p, PointerPart, { part: exactFrame.part });\n else if (cur.part !== exactFrame.part) ctx.edit(p).set(PointerPart, { part: exactFrame.part });\n }\n\n // Targets — radiused pick with a dead-band hysteresis (\"hover is forgiving\").\n let target = pickFrame(ctx, w.x, w.y, rWorld, pickTop(ctx, w.x, w.y, rWorld)).e;\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 // `PointerPart` is this system's to write (change-only, through `edit().set` after the first `addComponent`): declared, or\n // strata's dev build throws on the first hover that crosses from content onto a control (B9 — found by the re-pick test).\n //\n // WHAT THAT DECLARATION COSTS A CONSUMER (Phase C review; no fix owed here).\n // A declared write is a COLUMN-WIDE stamp, taken whenever the system runs\n // rather than when a value changes — and `live()` runs this every frame a\n // spring is moving. A Tier-1 observer of `PointerPart` would therefore wake\n // on every one of those frames, for a hover that never moved. Nothing\n // inside ICE observes the column that way (the overlay collector and\n // `world.get` both PULL), so idle-zero holds here; a consumer that\n // subscribes Tier-1 to `PointerPart` is the one who pays, and wants a\n // `{ coarse: false }` collector instead — the same shape as the `Position`\n // finding against `cursorVisualPoles` (D-C4.9).\n { name: \"picking\", access: { write: [PointerPart] }, runIf: () => versions() || frames.current?.live?.() === true || trayIsOpen() !== trayWasOpen },\n );\n\n // clearCaches (nav seam, design-004 §7): re-arm the seed — the next tick\n // rebuilds the cleared index from the new Active set via the full walk.\n return {\n spatialSync,\n picking,\n index,\n pickAt(sx, sy) {\n // the drawer out: every press touches the bare canvas, as `picking` answers it\n if (trayIsOpen()) return undefined;\n const w = screenToWorld(sx, sy, world.getResource(Camera) ?? IDENTITY_CAM);\n const hit = pickExact(world, w.x, w.y);\n return hit.e === undefined ? undefined : { entity: hit.e, part: hit.part };\n },\n clearCaches: () => {\n seeded = false;\n },\n };\n}\n","/**\n * L2 — arbitration + routing (design-003 §4.3–§4.4; `ctl:arbitrate`).\n *\n * Arbitration rule (v2-proven, generalized): the first recognizer to enter a\n * claiming phase (`Active` for continuous, `Recognized` for discrete) claims\n * every pointer it watches; same-frame ties resolve by priority\n * Pinch > Drag > LongPress > Tap; every other non-terminal, non-`Simultaneous`,\n * non-suspended recognizer watching a claimed pointer → `Failed`. The claim is\n * world state: `ClaimedBy(pointer → recognizer)` (Law 4). DEV asserts at most\n * one ClaimedBy write per pointer per pass (`setRelation` is silent last-wins —\n * a mis-ordered arbitration would otherwise be undetectable).\n *\n * ONE PASS PER TICK (2026-09-26): a strata system body runs once per matching\n * CHUNK, and the recognizer kinds live in different archetypes — so while\n * arbitration was a chunk system, the tie rule compared claimants only within\n * one batch. The first batch's claimant won and failed the rest; a later batch,\n * reading `ClaimedBy` before the flush, claimed as well and failed back (a\n * pointer could end claimed by a Failed recognizer, both claimants dead). It is\n * a tick system now: it collects EVERY claimant of the tick, then decides once\n * per pointer. A claimant that lost this tick's tie fails even from a terminal\n * phase — a Tap's `Recognized` — so a pointer gets one outcome, never a drag\n * AND the tap it beat (as when the drag claims first: tap-then-drag fails the\n * pending tap).\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). A\n * canvas drag reads the pointer's latched shift to choose between the tool's\n * `canvasDrag` and `canvasDragShift` (design-015 §9, D2a-core).\n */\nimport type { Entity, System, SystemCtx, Tag, TickSystem, World } from \"@vibecook/strata-ecs\";\nimport { Any, Not, defineQuery, defineSystem, defineTickSystem } from \"@vibecook/strata-ecs\";\nimport {\n CanvasSurface,\n Captures,\n ClaimedBy,\n DownPart,\n Drag,\n GesturePhases,\n GestureSuspended,\n HadRequiresFail,\n HadSequence,\n HandleSpec,\n Keyboard,\n LongPress,\n Movable,\n MovesSelection,\n Pinch,\n Pointer,\n PointerButtons,\n PointerMods,\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 { resolveToolFor } from \"../canvas/engine-catalog\";\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/** Anything that entered a claiming phase this tick (the arbitration's gate). */\nconst justClaimQ = defineQuery([Any(P.justTags.Active, P.justTags.Recognized)]);\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(world?: World): { arbitration: TickSystem; dragRoute: System } {\n const arbitration = defineTickSystem(\n (ctx) => {\n // Collect this tick's claimants — recognizers that JUST entered a claiming\n // phase — from EVERY batch before deciding anything (the header).\n const bestByPointer = new Map<Entity, Entity>();\n const claimantsOf = new Map<Entity, Entity[]>();\n ctx.query(claimCandidateQ).each((b) => {\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 claimants = claimantsOf.get(pointer);\n if (claimants === undefined) claimantsOf.set(pointer, [e]);\n else claimants.push(e);\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\n const winners = new Set(bestByPointer.values());\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 — and this\n // tick's losing claimants even from a terminal phase (a Tap's\n // Recognized): one decision, one outcome. A winner elsewhere (a Pinch\n // holds two pointers) is never failed here.\n const lost = claimantsOf.get(pointer) ?? [];\n for (const rec of ctx.getReverse(pointer, Watches)) {\n if (rec === winner || winners.has(rec)) continue;\n if (isTerminal(ctx, rec) && !lost.includes(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 // Idle and mid-gesture ticks with no claim to settle skip the walk.\n { name: \"arbitration\", runIf: (ctx) => ctx.firstOf(justClaimQ) !== undefined },\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 toolId = ctx.getResource(ActiveTool)?.id ?? \"select\";\n const tool = world === undefined ? tools.resolve(toolId) : resolveToolFor(world, toolId);\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 // A press on a card program's PART (design-014, B3b) is a click on a control, never a move.\n const onPart = (ctx.get(e, DownPart)?.part ?? \"\") !== \"\";\n if (route === \"move\") {\n if (!onPart && tool.gates.movable && (ctx.hasTag(captured, Movable) || ctx.hasTag(e, MovesSelection))) ctx.addTag(e, RoutedMove);\n } else if (!onPart) {\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 // Shift takes the tool's shift route. It is the tool's own canvasDrag\n // unless declared, so a selection tool still marquees while Shift adds\n // to its selection; custom tools may choose a different route\n // (`??` for a Tool assembled outside defineTool).\n const shift = pointer !== undefined && ctx.get(pointer, PointerMods)?.shift === true;\n const route = shift ? (tool.route.canvasDragShift ?? tool.route.canvasDrag) : tool.route.canvasDrag;\n const t = ctx.hasTag(e, MovesSelection) && tool.gates.movable && tool.route.widgetDrag === \"move\" && route === \"marquee\"\n ? RoutedMove : routeTag(route);\n if (t !== undefined) ctx.addTag(e, t);\n }\n }\n },\n { name: \"dragRoute\" },\n );\n\n return { arbitration, dragRoute };\n}\n\n/** Wheel recognizers never claim; exported so tests can assert the invariant set. */\nexport const NEVER_CLAIMS = [WheelPan, WheelZoom] as const;\n","/**\n * L3 — select + move behaviors (design-003 §5 items 1, 3, 5; `ctl:behave`).\n *\n * The behavior contract (design-003 §5): read riders/edges attached at\n * ctl:claim; per frame (persistent `Active`) apply ABSOLUTE live writes from\n * rider origins + gesture totals; on `JustEnded` emit ONE commit (through the\n * CommitSink seam — M5 swaps in the doc transaction); on `JustCancelled`\n * restore from riders — Position AND sibling order (petition 8: a forgotten\n * order restore leaves the sequence diverged forever, the old StackZ law);\n * remove riders and gesture-scoped edges on every terminal path. Discrete\n * actions edge-trigger on `Just*` markers only.\n *\n * Move outcome tree (design-003 §5.5, three-way via dropSystem's signals):\n * DropTarget + OverlapCandidate on the container → CONSUME (reparent intent);\n * DropTarget without OverlapCandidate → FLY-BACK (no commit; TransformTween\n * rider per widget — the tween HOLDS the claim, design-001 §3 amended);\n * no DropTarget → COMMIT (final Position per live Drags edge + the sibling\n * placement as ORDER ops, so one gesture stays one transaction).\n * Without dropSystem installed no DropTarget ever exists ⇒ plain commits.\n */\nimport type { Entity, OrderPlace, System, SystemCtx, World } from \"@vibecook/strata-ecs\";\nimport { defineQuery, defineSystem } from \"@vibecook/strata-ecs\";\nimport { insertSlot, screenToWorld, type CameraState, type LayoutRect } from \"@ice/kernel\";\nimport {\n Camera,\n Captures,\n ChildOf,\n DownPart,\n Drag,\n Drags,\n DropTarget,\n GesturePhases,\n GhostCommitted,\n GhostRetiring,\n Grab,\n InsertGhost,\n LeavesCopy,\n NO_ENTITY,\n OverlapCandidate,\n OverlapRejected,\n PartTap,\n PointerMods,\n Position,\n RoutedMove,\n Selectable,\n Size,\n Selected,\n SnapState,\n Tap,\n TransformTween,\n Watches,\n Wire,\n} from \"../catalog\";\nimport type { CommitCreate, CommitOrder, CommitSink, CommitWrite } from \"../engine/commit-sink\";\nimport { SelectionVersion, bumpVersion } from \"../helpers/version-stamps\";\nimport type { NavGeometrySlot } from \"../nav/nav-geometry\";\nimport { selectedEntities } from \"../ops/selection\";\nimport { dropFaceOf, insideRect, objectsOnly } from \"./l3-drop\";\nimport { widgetTypeFor } from \"../canvas/engine-catalog\";\nimport { PrefabId } from \"../schema/prefab\";\nimport { moveDelta } from \"./drag-mods\";\n\nconst P = GesturePhases;\n\nconst tapRecognizedQ = defineQuery([Tap, P.justTags.Recognized]);\nconst moveDragQ = defineQuery([Drag, RoutedMove]);\n\nconst FLY_BACK_MS = 200;\n\n/** Min separation for consume free-slot placement (kernel insertSlot). */\nconst CONSUME_GUTTER = 16;\n\nconst IDENTITY_CAM: CameraState = { x: 0, y: 0, zoom: 1 };\n\n/** InsertGhost.props (JSON) → CommitCreate.props; empty/malformed ⇒ absent. */\nfunction parseGhostProps(raw: string): Record<string, unknown> | undefined {\n if (raw === \"\" || raw === \"{}\") return undefined;\n try {\n const v: unknown = JSON.parse(raw);\n return typeof v === \"object\" && v !== null && Object.keys(v).length > 0\n ? (v as Record<string, unknown>)\n : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Fly a tray-insert ghost HOME (cancel / rejected drop): the tween target is\n * the tray press point re-projected through the CURRENT camera — the ghost\n * returns to the tray ON SCREEN even after a mid-drag zoom (wheel gestures are\n * Simultaneous). `GhostRetiring` hands it to the reap system, which despawns\n * it when the tween lands. No Position restore, no commit — the ghost never\n * had a document row to diverge from.\n */\nfunction ghostFlyBack(ctx: SystemCtx, ghost: Entity): void {\n const gh = ctx.read(ghost, InsertGhost);\n const cam = ctx.getResource(Camera) ?? IDENTITY_CAM;\n const home = screenToWorld(gh.screenX, gh.screenY, cam);\n const size = ctx.get(ghost, Size) ?? { w: 0, h: 0 };\n ctx.addComponent(ghost, TransformTween, {\n toX: home.x - size.w / 2,\n toY: home.y - size.h / 2,\n durationMs: FLY_BACK_MS,\n elapsedMs: 0,\n });\n ctx.addTag(ghost, GhostRetiring);\n}\n\n/** ctx-side selection flip (setSelection is the app-handler/world variant). */\nfunction applySelection(\n world: World,\n ctx: SystemCtx,\n target: Entity | undefined,\n toggle: boolean,\n): void {\n const current = selectedEntities(world);\n if (target === undefined) {\n if (current.length === 0) return;\n for (const s of current) ctx.removeTag(s, Selected);\n bumpVersion(world, SelectionVersion);\n return;\n }\n if (toggle) {\n if (ctx.hasTag(target, Selected)) ctx.removeTag(target, Selected);\n else ctx.addTag(target, Selected);\n bumpVersion(world, SelectionVersion);\n return;\n }\n const alreadySole = current.length === 1 && current[0] === target;\n if (alreadySole) return;\n for (const s of current) if (s !== target) ctx.removeTag(s, Selected);\n if (!ctx.hasTag(target, Selected)) ctx.addTag(target, Selected);\n bumpVersion(world, SelectionVersion);\n}\n\n/**\n * Reinsert the dragged set at its remembered sibling positions (petition 8 —\n * the cancel/fly-back twin of the claim elevate). Members walk in ORIGINAL\n * relative order (`Grab.ord`), each `{after: resolved anchor}`:\n * - same-`prev` run → ride the previously-reinserted member (a contiguous\n * block re-forms in claim order);\n * - the original `prev` anchor, when it survived UNDER THE SAME PARENT;\n * - else the nearest surviving earlier sibling we know — the last member\n * already reinserted into this parent;\n * - else \"first\" — NEVER \"last\": a mid-stack cancel must not jump to top.\n * Edge-less members (memo parent NO_ENTITY) were never elevated — skipped; a\n * parent that died mid-gesture took the whole sequence with it — skipped.\n * ctx placements apply at the flush IN ORDER, so each anchor is already\n * placed when consulted.\n */\nfunction restoreOrder(ctx: SystemCtx, dragged: readonly Entity[]): void {\n const members: { e: Entity; parent: Entity; prev: Entity; ord: number }[] = [];\n for (const w of dragged) {\n if (!ctx.isAlive(w) || !ctx.has(w, Grab)) continue;\n const g = ctx.read(w, Grab);\n if (g.parent === NO_ENTITY || !ctx.isAlive(g.parent)) continue;\n // FOREIGN-REPARENT GUARD (rev-ice-flip finding 2): the gesture itself never changes a\n // member's parent mid-flight (elevate is same-parent; consume runs only at end), so a\n // current parent that differs from the memo means a REMOTE edit won that edge. Restoring\n // the memo parent would revert the foreign reparent in the runtime only — cancel commits\n // nothing, so runtime structure forks from the doc until some later remote op happens to\n // rewrite the row. Skip: order restore is a courtesy; membership truth is the doc's.\n if (ctx.getRelation(w, ChildOf) !== g.parent) continue;\n members.push({ e: w, parent: g.parent, prev: g.prev, ord: g.ord });\n }\n members.sort((a, b) => a.ord - b.ord);\n const lastByParent = new Map<Entity, { e: Entity; prev: Entity }>();\n for (const m of members) {\n const last = lastByParent.get(m.parent);\n let place: OrderPlace;\n if (last !== undefined && last.prev === m.prev) {\n place = { after: last.e };\n } else if (m.prev !== NO_ENTITY && ctx.isAlive(m.prev) && ctx.getRelation(m.prev, ChildOf) === m.parent) {\n place = { after: m.prev };\n } else if (last !== undefined) {\n place = { after: last.e };\n } else {\n place = \"first\";\n }\n ctx.setRelation(m.e, ChildOf, m.parent, place);\n lastByParent.set(m.parent, { e: m.e, prev: m.prev });\n }\n}\n\n/**\n * The plain-move commit's ORDER ops (petition 8): re-assert each member's\n * elevated placement — `{parent, \"last\"}` in CURRENT sibling order, so the\n * doc transaction lands exactly the runtime sequence the elevate built.\n * Edge-less members carry no placement.\n */\nfunction commitOrders(ctx: SystemCtx, dragged: readonly Entity[]): CommitOrder[] {\n const byParent = new Map<Entity, Set<Entity>>();\n for (const w of dragged) {\n if (!ctx.isAlive(w) || !ctx.has(w, Grab)) continue;\n const parent = ctx.getRelation(w, ChildOf);\n if (parent === undefined) continue;\n let set = byParent.get(parent);\n if (set === undefined) {\n set = new Set();\n byParent.set(parent, set);\n }\n set.add(w);\n }\n const orders: CommitOrder[] = [];\n for (const [parent, set] of byParent) {\n for (const sib of ctx.getReverse(parent, ChildOf)) {\n if (set.has(sib)) orders.push({ entity: sib, parent, place: \"last\" });\n }\n }\n return orders;\n}\n\nexport function createSelectMoveBehaviors(\n world: World,\n sink: CommitSink,\n opts: { readonly navGeometry?: NavGeometrySlot } = {},\n): { selectBehavior: System; moveBehavior: System } {\n const navGeometry = opts.navGeometry;\n /** An ⌥-drag's copy of `w`: its type and every prop group as they are, at its origin (`Grab`), untaped, just under it. */\n const copyOf = (ctx: SystemCtx, w: Entity, g: { readonly x: number; readonly y: number; readonly w: number; readonly h: number }): CommitCreate | undefined => {\n const id = ctx.get(w, PrefabId)?.id;\n const widget = typeof id === \"string\" ? widgetTypeFor(world, id) : undefined;\n if (widget === undefined || typeof id !== \"string\") return undefined;\n const props: Record<string, unknown> = {};\n for (const group of widget.groups) {\n const v = ctx.get(w, group.component) as Record<string, unknown> | undefined;\n if (v !== undefined) for (const name of Object.keys(group.fields)) props[name] = v[name];\n }\n return { type: id, x: g.x, y: g.y, w: g.w, h: g.h, props, order: { before: w } };\n };\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 // A tap on a card program's PART (design-014, B3b) is the app's: hand it over, select nothing.\n const part = ctx.get(rec, DownPart)?.part ?? \"\";\n if (part !== \"\" && captured !== undefined) {\n const prev = world.getResource(PartTap);\n world.setResource(PartTap, { seq: (prev?.seq ?? 0) + 1, target: captured, part });\n continue;\n }\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 rejectCommit = (ctx: SystemCtx, dragged: readonly Entity[]): void => {\n for (const w of dragged) {\n if (!ctx.isAlive(w) || !ctx.has(w, Grab)) continue;\n if (ctx.has(w, InsertGhost)) {\n ghostFlyBack(ctx, w);\n continue;\n }\n const g = ctx.read(w, Grab);\n ctx.addComponent(w, TransformTween, {\n toX: g.x,\n toY: g.y,\n durationMs: FLY_BACK_MS,\n elapsedMs: 0,\n });\n }\n restoreOrder(ctx, dragged);\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 + the drag's delta (screen totals / zoom-at-claim, ⇧'s axis lock — drag-mods.ts) + snap.\n const delta = moveDelta(ctx, rec);\n const snap = ctx.get(rec, SnapState) ?? { dx: 0, dy: 0 };\n const wx = delta.x + snap.dx;\n const wy = delta.y + 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 delta = moveDelta(ctx, rec);\n const snap = ctx.get(rec, SnapState) ?? { dx: 0, dy: 0 };\n const wx = delta.x + snap.dx;\n const wy = delta.y + snap.dy;\n let container = ctx.getRelation(rec, DropTarget);\n // The desk's rules for an all-OBJECT set (design-015 §9, D2b): ⌥ held at the release\n // keeps the object on this desk; the centre of the FINAL bounds over the container's\n // FACE decides; the landing goes through the inside's embedding (below).\n const objects = objectsOnly(world, dragged);\n const pointer = ctx.getRelations(rec, Watches)[0];\n const alt = pointer !== undefined && ctx.get(pointer, PointerMods)?.alt === true;\n if (objects && alt) container = undefined;\n let drop: ReturnType<typeof dropFaceOf> | undefined;\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) && objects) {\n drop = dropFaceOf(world, container, navGeometry);\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 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 minX = Math.min(minX, g.x + wx);\n minY = Math.min(minY, g.y + wy);\n maxX = Math.max(maxX, g.x + wx + ws.w);\n maxY = Math.max(maxY, g.y + wy + ws.h);\n }\n const over = drop !== undefined && Number.isFinite(minX) && insideRect(drop.face, (minX + maxX) / 2, (minY + maxY) / 2);\n if (!over) container = undefined; // the centre left the face → plain commit\n } else if (container !== undefined && ctx.isAlive(container)) {\n const cp = ctx.get(container, Position);\n const cs = ctx.get(container, Size);\n let overlaps = false;\n if (cp !== undefined && cs !== undefined) {\n for (const w of dragged) {\n if (!ctx.isAlive(w) || !ctx.has(w, Grab) || !ctx.has(w, Size)) continue;\n const g = ctx.read(w, Grab);\n const ws = ctx.read(w, Size);\n const x = g.x + wx;\n const y = g.y + wy;\n if (x < cp.x + cs.w && x + ws.w > cp.x && y < cp.y + cs.h && y + ws.h > cp.y) {\n overlaps = true;\n break;\n }\n }\n }\n if (!overlaps) container = undefined; // stale → plain commit\n }\n\n if (container !== undefined && !ctx.hasTag(container, OverlapCandidate)) {\n // Rejected drop → fly-back, NO commit. The tween holds the claim\n // (design-001 §3 amended); cells reconverge when it lands. A\n // tray-insert ghost flies HOME (the tray press point) instead of\n // to a Grab origin it only ever had under the tray — and retires.\n for (const w of dragged) {\n if (!ctx.isAlive(w) || !ctx.has(w, Grab)) continue;\n if (ctx.has(w, InsertGhost)) {\n ghostFlyBack(ctx, w);\n continue;\n }\n const g = ctx.read(w, Grab);\n ctx.addComponent(w, TransformTween, {\n toX: g.x,\n toY: g.y,\n durationMs: FLY_BACK_MS,\n elapsedMs: 0,\n });\n }\n // Restore sibling ORDER now (it is not animated): fly-back commits\n // nothing, so an elevated sequence left in place would keep the\n // runtime diverged forever and hold remote reorders indefinitely —\n // the same law as the cancel path (design-003 §5.3).\n restoreOrder(ctx, dragged);\n } else if (container !== undefined) {\n // Consume: reparent + final position, one intent (one tx at M5).\n // A tray-insert ghost becomes a CREATE-inside-container instead of\n // a reparent (it has no document row to reparent): same free-slot\n // placement, container-local coords, promoted in the same single\n // transaction. `GhostCommitted` hands it to the reap swap.\n const writes: CommitWrite[] = [];\n const reparents: { entity: Entity; container: Entity }[] = [];\n const creates: CommitCreate[] = [];\n const promotingGhosts: Entity[] = [];\n const containerPos = ctx.get(container, Position) ?? { x: 0, y: 0 };\n // Free-slot placement (2026-07-17, James: folder drops \"pile up on\n // each other\"): the raw drop point maps everyone who aimed at the\n // folder's center onto the same container-local spot. Newcomers\n // get the nearest free slot instead; incumbents NEVER move (the\n // kernel insertSlot contract). Sizes are the declared ones.\n const incumbents: LayoutRect[] = [];\n for (const c of ctx.getReverse(container, ChildOf)) {\n const cp = ctx.get(c, Position);\n const cs = ctx.get(c, Size);\n if (cp === undefined || cs === undefined) continue;\n incumbents.push({ x: cp.x, y: cp.y, w: cs.w, h: cs.h });\n }\n // An OBJECT goes in through the inside's EMBEDDING (design-015 §9, the prototype's\n // `dropInto`): where its centre lay on the face, in the inside's own units — `(n − M.o) / M.s`\n // — its size kept, so it takes the inside's scale; no free-slot placement (it lands where\n // it was let go, as a thing put into a nested desk does).\n const M = objects ? drop?.affine : undefined;\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 ws = ctx.get(w, Size) ?? { w: 0, h: 0 };\n let slot: { x: number; y: number };\n if (M !== undefined) {\n const ncx = g.x + wx + ws.w / 2;\n const ncy = g.y + wy + ws.h / 2;\n slot = { x: (ncx - M.ox) / M.s - ws.w / 2, y: (ncy - M.oy) / M.s - ws.h / 2 };\n } else {\n // Container-frame conversion: world → container-local (M8 refines\n // to the kernel container-frame path once nested canvas lands).\n const hint = { x: g.x + wx - containerPos.x, y: g.y + wy - containerPos.y };\n slot = insertSlot(incumbents, ws, hint, CONSUME_GUTTER);\n // Later cards in a multi-drop see the earlier ones as occupied.\n incumbents.push({ x: slot.x, y: slot.y, w: ws.w, h: ws.h });\n }\n if (ctx.has(w, InsertGhost)) {\n const gh = ctx.read(w, InsertGhost);\n const props = parseGhostProps(gh.props ?? \"\");\n creates.push({\n type: gh.type ?? \"\",\n x: slot.x,\n y: slot.y,\n w: ws.w,\n h: ws.h,\n ...(props !== undefined ? { props } : {}),\n parent: container,\n select: true,\n });\n promotingGhosts.push(w);\n continue;\n }\n writes.push({ entity: w, component: Position, value: slot });\n reparents.push({ entity: w, container });\n // ⌥ at the drag's start leaves a copy where it lay on THIS desk even when the original goes in (2026-09-26 —\n // the recorded D4a × D2b design), in the consume's one transaction. The original has left this frame, so the\n // copy takes its lifted place, on top (\"last\"): `{ before: w }` would name a sibling that is no longer here.\n if (ctx.hasTag(rec, LeavesCopy)) {\n const copy = copyOf(ctx, w, g);\n if (copy !== undefined) creates.push({ ...copy, order: \"last\" });\n }\n }\n if (writes.length > 0 || creates.length > 0) {\n const accepted = sink.commit({\n kind: \"consume\",\n gesture: rec,\n writes,\n reparents,\n ...(creates.length > 0 ? { creates } : {}),\n });\n if (accepted === false) rejectCommit(ctx, dragged);\n else for (const ghost of promotingGhosts) ctx.addTag(ghost, GhostCommitted);\n }\n } else {\n // Plain move commit: final Position per live edge + the elevated\n // sibling placement as ORDER ops — one gesture, one transaction,\n // one undo step (petition 8). A tray-insert ghost becomes the\n // gesture's CREATE at its final position (the promote — design-001\n // §3): same single transaction, selected at projection.\n const writes: CommitWrite[] = [];\n const creates: CommitCreate[] = [];\n const promotingGhosts: Entity[] = [];\n for (const w of dragged) {\n if (!ctx.isAlive(w) || !ctx.has(w, Grab)) continue;\n const g = ctx.read(w, Grab);\n if (ctx.has(w, InsertGhost)) {\n const gh = ctx.read(w, InsertGhost);\n const props = parseGhostProps(gh.props ?? \"\");\n const ws = ctx.get(w, Size) ?? { w: 0, h: 0 };\n creates.push({\n type: gh.type ?? \"\",\n x: g.x + wx,\n y: g.y + wy,\n w: ws.w,\n h: ws.h,\n ...(props !== undefined ? { props } : {}),\n select: true,\n });\n promotingGhosts.push(w);\n continue;\n }\n writes.push({ entity: w, component: Position, value: { x: g.x + wx, y: g.y + wy } });\n // ⌥ at the drag's start: a copy stays where it lay, just under it — in this one transaction (D4a)\n if (ctx.hasTag(rec, LeavesCopy)) {\n const copy = copyOf(ctx, w, g);\n if (copy !== undefined) creates.push(copy);\n }\n }\n if (writes.length > 0 || creates.length > 0) {\n const accepted = sink.commit({\n kind: creates.length > 0 && writes.length === 0 ? \"create\" : \"move\",\n gesture: rec,\n writes,\n orders: commitOrders(ctx, dragged),\n ...(creates.length > 0 ? { creates } : {}),\n });\n if (accepted === false) rejectCommit(ctx, dragged);\n else for (const ghost of promotingGhosts) ctx.addTag(ghost, GhostCommitted);\n }\n }\n clearGestureState(ctx, rec, dragged);\n continue;\n }\n\n if (ctx.hasTag(rec, P.justTags.Cancelled) || ctx.hasTag(rec, P.justTags.Failed)) {\n // Restore Position AND sibling order from Grab (design-003 §5.3),\n // then clean up. A tray-insert ghost has nothing to restore TO —\n // it flies home to the tray and retires (Escape / blur / integrity).\n for (const w of dragged) {\n if (!ctx.isAlive(w) || !ctx.has(w, Grab)) continue;\n if (ctx.has(w, InsertGhost)) {\n ghostFlyBack(ctx, w);\n continue;\n }\n const g = ctx.read(w, Grab);\n ctx.edit(w).set(Position, { x: g.x, y: g.y });\n }\n restoreOrder(ctx, dragged);\n clearGestureState(ctx, rec, dragged);\n }\n }\n },\n {\n name: \"moveBehavior\",\n // Position is co-written with resizeBehavior in ctl:behave BY DESIGN\n // (design-003 §5 in-phase order) and row-disjoint by construction\n // (dragRoute: RoutedMove xor RoutedResize) — attested (strata 0.4.0,\n // petition 3a), so the writer-pair advisory stays quiet here and loud\n // for real mistakes.\n access: { write: [Position], orderIndependent: [Position] },\n },\n );\n\n return { selectBehavior, moveBehavior };\n}\n","/**\n * L3 — drop candidate detection (design-003 §5 item 4; `ctl:behave`, ordered\n * AFTER moveBehavior so it tests POST-move bounds).\n *\n * For Active `RoutedMove` drags: spatial-query the dragged union bounds for\n * `Container` widgets (∉dragged), pick the topmost by sibling order (petition\n * 8 — compareStackOrder, the SAME comparator pick/paint use, so the drop\n * candidate can never diverge from what the user sees on top), and publish two\n * signals the move-outcome tree consumes (l3-behave §5.5):\n * - `DropTarget(recognizer → container)` — set for the container under the\n * bounds REGARDLESS of an accepts-match (so the outcome tree can distinguish\n * a rejected drop from a plain move).\n * - `OverlapCandidate` on the container — ONLY when the container's `Accepts`\n * intersects the dragged set's `Provides` (a widget with no `Provides` never\n * matches; RFC-004 contracts).\n * BOTH are strictly change-only: `setRelation`/`addTag` bump the GLOBAL tag/\n * relation version, and any churn wakes every row-filtered observer world-wide\n * (design-002 §4). Both clear when no container is under the bounds; the move\n * behavior clears them on every terminal path.\n *\n * THIRD SIGNAL (2026-09-06, design-013 §5 rev 6 / GLOW.md §3): `DragBounds` on\n * the recognizer — the same post-move union this system computes for its\n * spatial query, published instead of discarded. The overlap glow is cast light\n * from the lifted set's own SDF, so the compose reflector needs its rect; there\n * is no second computation and no new walk. Change-only over all four fields,\n * for the same reason the other two are: a value write stamps, and a still\n * frame must cost nothing.\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 DragBounds,\n Drags,\n DropTarget,\n GestureActive,\n OverlapCandidate,\n OverlapRejected,\n Position,\n Provides,\n RoutedMove,\n Size,\n Solid,\n SweepsContained,\n} from \"../catalog\";\nimport { Camera } from \"../catalog/camera-derived\";\nimport { widgetTypeFor } from \"../canvas/engine-catalog\";\nimport type { CanvasRect } from \"../canvas/frame-view\";\nimport { type NavGeometrySlot, resolveNavFace } from \"../nav/nav-geometry\";\nimport { compareStackOrder, createSiblingOrderIndex } from \"../ops/sibling-order\";\nimport { PrefabId } from \"../schema/prefab\";\nimport type { PortalAffine } from \"@ice/kernel\";\n\n/** Is every one of these a GPU OBJECT (an `object` kind binding, design-015 §5.2)? The desk's drop rules apply to an all-object set. */\nexport function objectsOnly(world: World, entities: readonly Entity[]): boolean {\n if (entities.length === 0) return false;\n for (const e of entities) {\n if (!world.isAlive(e)) continue;\n const id = world.get(e, PrefabId)?.id;\n if (typeof id !== \"string\" || widgetTypeFor(world, id)?.object === undefined) return false;\n }\n return true;\n}\n\n/**\n * A container's FACE and its inside's embedding for a drop (design-015 §9): the renderer's word\n * through the nav geometry seam under the current camera (the face as drawn), else core's static\n * portal rect and default framing. `undefined` = the container has no face (no area).\n */\nexport function dropFaceOf(world: World, container: Entity, slot: NavGeometrySlot | undefined): { readonly face: CanvasRect; readonly affine: PortalAffine } | undefined {\n const cam = world.getResource(Camera) ?? { x: 0, y: 0, zoom: 1 };\n const f = resolveNavFace(world, container, { x: cam.x, y: cam.y, zoom: cam.zoom }, slot);\n return f === undefined ? undefined : { face: f.face, affine: f.affine };\n}\n\n/** Is the world point inside the rect (edges included)? */\nexport const insideRect = (r: CanvasRect, x: number, y: number): boolean => x >= r.x && x <= r.x + r.width && y >= r.y && y <= r.y + r.height;\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 interface DropPlacementPolicy {\n canIngress(widgetTypeId: string, targetContainer: Entity): boolean;\n /** K9: may an object of this type be made in this frame at all — the root's CanvasType placement (inside a container, `canIngress`). */\n canPlace?(widgetTypeId: string, targetFrame: Entity): boolean;\n}\n\nexport function createDropSystem(\n world: World,\n index: SpatialIndex<Entity>,\n placement?: DropPlacementPolicy,\n navGeometry?: NavGeometrySlot,\n): System {\n // Frame ordinal map for the topmost-container compare (petition 8) — the\n // same pull-based source the pick systems read; candidates are same-frame\n // by construction (the spatial index is Active-gated).\n const order = createSiblingOrderIndex(world);\n return defineSystem(\n dropDragQ,\n (b, ctx) => {\n for (const r of b) {\n const rec = b.entity(r);\n const dragged = ctx.getRelations(rec, Drags);\n\n // A comment-box group (any dragged SweepsContained widget) is\n // LANDSCAPE, not cargo — with ONE exception (2026-07-18, James: \"i\n // do want that\"): it CAN file into an ACCEPTING container. So for\n // sweeper sets, Solid widgets never reject (the group's union bounds\n // overlap half the board by construction — that's what a comment is\n // FOR), and a NON-matching container is scenery (plain move), never\n // a fly-back: DropTarget only lands together with OverlapCandidate.\n const sweeper = dragged.some((w) => ctx.isAlive(w) && ctx.hasTag(w, SweepsContained));\n const draggedSet = new Set<Entity>(dragged);\n\n // Post-move union bounds from the dragged widgets' CURRENT transform.\n let minX = Number.POSITIVE_INFINITY;\n let minY = Number.POSITIVE_INFINITY;\n let maxX = Number.NEGATIVE_INFINITY;\n let maxY = Number.NEGATIVE_INFINITY;\n let any = false;\n for (const w of dragged) {\n if (!ctx.isAlive(w) || !ctx.has(w, Position) || !ctx.has(w, Size)) continue;\n const p = ctx.read(w, Position);\n const s = ctx.read(w, Size);\n minX = Math.min(minX, p.x);\n minY = Math.min(minY, p.y);\n maxX = Math.max(maxX, p.x + s.w);\n maxY = Math.max(maxY, p.y + s.h);\n any = true;\n }\n\n // Publish the union (design-013 §5). Only when the walk found a live\n // dragged widget: with `any` false the four accumulators are still\n // ±Infinity, and writing those would put a number in the world that no\n // reader could tell from a real rect. A resize drag never populates\n // `Drags`, so its recognizer keeps the spawn zeros — which is the\n // honest answer, since there is no lifted set to cast light.\n if (any) {\n const cur = ctx.get(rec, DragBounds);\n if (\n cur === undefined ||\n cur.minX !== minX ||\n cur.minY !== minY ||\n cur.maxX !== maxX ||\n cur.maxY !== maxY\n ) {\n ctx.edit(rec).set(DragBounds, { minX, minY, maxX, maxY });\n }\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 // An all-OBJECT set (design-015 §9, D2b) follows the desk's rule instead: the\n // container whose FACE — the portal rect as drawn (the nav geometry seam) — holds\n // the set's CENTRE, topmost first; a face the centre is not over is scenery.\n const objects = any && objectsOnly(world, dragged);\n const cx = (minX + maxX) / 2;\n const cy = (minY + maxY) / 2;\n let container: Entity | undefined;\n if (any) {\n const ordinals = order.ordinals();\n for (const entry of index.search({ minX, minY, maxX, maxY })) {\n const e = entry.id;\n if (draggedSet.has(e) || !ctx.isAlive(e)) continue;\n if (!ctx.hasTag(e, Container) && !(!sweeper && ctx.hasTag(e, Solid))) continue;\n if (objects && ctx.hasTag(e, Container)) {\n const drop = dropFaceOf(world, e, navGeometry);\n if (drop === undefined || !insideRect(drop.face, cx, cy)) continue;\n }\n if (container === undefined || compareStackOrder(ctx, ordinals, e, container) > 0) {\n container = e;\n }\n }\n }\n\n const clearSignals = (e: Entity): void => {\n if (!ctx.isAlive(e)) return;\n if (ctx.hasTag(e, OverlapCandidate)) ctx.removeTag(e, OverlapCandidate);\n if (ctx.hasTag(e, OverlapRejected)) ctx.removeTag(e, OverlapRejected);\n };\n\n if (container === undefined) {\n if (prev !== undefined) {\n clearSignals(prev);\n ctx.removeRelation(rec, DropTarget);\n }\n continue;\n }\n\n // accepts ∩ (union of dragged provides) — a widget with no Provides never\n // matches; a Solid non-container has no Accepts and always rejects. A type\n // that declares `interaction.drop: \"never\"` (design-015 D-D18) matches nothing,\n // whichever path decides — the typed placement authority or the cells.\n let matches: boolean;\n const neverDrops = dragged.some((w) => {\n if (!ctx.isAlive(w)) return false;\n const typeId = ctx.get(w, PrefabId)?.id;\n return typeof typeId === \"string\" && widgetTypeFor(world, typeId)?.drop === \"never\";\n });\n if (neverDrops) {\n matches = false;\n } else if (placement !== undefined && ctx.hasTag(container, Container)) {\n matches = dragged.every((w) => {\n if (!ctx.isAlive(w)) return false;\n const typeId = ctx.get(w, PrefabId)?.id;\n return typeof typeId === \"string\" && placement.canIngress(typeId, container as Entity);\n });\n } else {\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 matches = accepts.some((k) => provided.has(k));\n }\n\n // Sweeper sets never fly back: a non-matching container is treated\n // like no container at all (release = plain move).\n // Sweeper sets never fly back: a non-matching container is treated\n // like no container at all (release = plain move). An OBJECT set is the same\n // (design-015 §9, D-D18): a whiteboard let go over a mini mat lies on it as a\n // root object — the desk has no fly-back.\n if ((sweeper || objects) && !matches) {\n if (prev !== undefined) {\n clearSignals(prev);\n ctx.removeRelation(rec, DropTarget);\n }\n continue;\n }\n\n // A moved-off previous target loses its signal tags.\n if (prev !== undefined && prev !== container) clearSignals(prev);\n if (prev !== container) ctx.setRelation(rec, DropTarget, container);\n\n if (matches) {\n if (!ctx.hasTag(container, OverlapCandidate)) ctx.addTag(container, OverlapCandidate);\n if (ctx.hasTag(container, OverlapRejected)) ctx.removeTag(container, OverlapRejected);\n } else {\n if (ctx.hasTag(container, OverlapCandidate)) ctx.removeTag(container, OverlapCandidate);\n if (!ctx.hasTag(container, OverlapRejected)) ctx.addTag(container, OverlapRejected);\n }\n }\n },\n { name: \"dropSystem\", access: { write: [DragBounds] } },\n );\n}\n","/**\n * The desk's drag modifiers (design-015 §7, *Marks on the Mat*'s keys; D4a) — read off the recognizer's\n * WATCHED pointer, whose `PointerMods` is the pointer's latched sample (design-003 §4.5; the keyboard\n * carries only key events), so a modifier pressed or let go mid-drag takes effect on the next frame:\n *\n * - ⇧ locks the drag to ONE axis — its dominant one, recomputed from the total each frame (the page's\n * `if (|dx| > |dy|) dy = 0 else dx = 0`); the snap then corrects only along the free axis.\n * - ⌘ (or Ctrl) held holds the snap off.\n * - ⌥ as the drag STARTS leaves a copy behind (moveClaim latches it as `LeavesCopy` on the recognizer;\n * the release commits the copies with the move — one gesture, one undo step).\n *\n * Shared by the snap system and the move behavior, so the delta the snap aligns is the delta the move\n * writes. Pure over the ctx: no writes.\n */\nimport type { Entity, SystemCtx } from \"@vibecook/strata-ecs\";\nimport { Drag, PointerMods, Watches } from \"../catalog\";\n\nexport interface DragMods {\n readonly shift: boolean;\n readonly alt: boolean;\n readonly meta: boolean;\n readonly ctrl: boolean;\n}\nconst NONE: DragMods = { shift: false, alt: false, meta: false, ctrl: false };\n\n/** The recognizer's watched pointer's modifiers now (none when it watches no pointer). */\nexport function watchedMods(ctx: Pick<SystemCtx, \"getRelations\" | \"get\">, rec: Entity): DragMods {\n const pointer = ctx.getRelations(rec, Watches)[0];\n const m = pointer === undefined ? undefined : ctx.get(pointer, PointerMods);\n return m === undefined ? NONE : { shift: m.shift, alt: m.alt, meta: m.meta, ctrl: m.ctrl };\n}\n\n/** ⌘ or Ctrl held: the snap stands down for this frame. */\nexport const snapHeldOff = (mods: DragMods): boolean => mods.meta || mods.ctrl;\n\n/**\n * A move drag's WORLD delta: the screen total over the zoom at its claim, locked to its dominant axis while ⇧ is\n * held. `lock` names the axis it runs along (`x` = horizontally, its y held), null when free.\n */\nexport function moveDelta(ctx: Pick<SystemCtx, \"read\" | \"getRelations\" | \"get\">, rec: Entity): { readonly x: number; readonly y: number; readonly lock: \"x\" | \"y\" | null } {\n const d = ctx.read(rec, Drag);\n const x = d.totalX / d.zoomAtClaim;\n const y = d.totalY / d.zoomAtClaim;\n if (!watchedMods(ctx, rec).shift) return { x, y, lock: null };\n return Math.abs(x) > Math.abs(y) ? { x, y: 0, lock: \"x\" } : { x: 0, y, lock: \"y\" };\n}\n","/**\n * ctl:claim — the rider settle point (design-003 §4.5).\n *\n * This sub-phase exists for exactly one reason: riders (`Grab`) and edges\n * (`Drags`) attached via `ctx` must be readable by the behaviors that consume\n * them ON THE CLAIM FRAME — without it, the first mutation lags a frame and a\n * claim-frame `read(w, Grab)` throws (design-003 review C1).\n *\n * `moveClaim` (JustActive × RoutedMove): select-on-grab, `Drags` edges over the\n * dragged set, `Grab` per widget with the CURRENT Position/Size + the ORDER\n * MEMO embedded (petition 8: ChildOf parent, nearest non-dragged predecessor\n * sibling, original sibling index), and the sibling elevate — `moveRelation(w,\n * ChildOf, \"last\")`, frame-scoped, equivalent to the old global-top within the\n * frame; part of the gesture divergence, restored from the memo on cancel.\n * Edge-less widgets (legacy/runtime world) skip both memo and elevate — the\n * move would be a strata no-op and there is no sequence to restore.\n *\n * `resizeClaim` (JustActive × RoutedResize): `Drags` + `Grab` over the Selected\n * ∧ Resizable set; the anchor lives on the captured handle's `HandleSpec` — no\n * extra state.\n *\n * Same-widget double-grab guard: a widget already in another recognizer's\n * `Drags` set is skipped (first gesture owns it) — two `ctx.addComponent(Grab)`\n * for one widget in one frame would hit strata's flush-time duplicate policy.\n *\n * The tape (design-015 §5.1, D2a-core): a `Locked` widget gets no rider from\n * either claim — never moved, never resized by a gesture — and nothing else\n * changes: select-on-grab still selects it, the pointer is still claimed, and\n * the untaped members of the same selection move without it. A claim whose set\n * is all tape moves nothing and commits nothing (the release paths commit only\n * what carries a `Grab`).\n */\nimport type { Entity, System, SystemCtx, World } from \"@vibecook/strata-ecs\";\nimport { defineQuery, defineSystem } from \"@vibecook/strata-ecs\";\nimport {\n Active,\n Captures,\n ChildOf,\n Culled,\n Drag,\n Drags,\n GesturePhases,\n Grab,\n InsertGhost,\n LeavesCopy,\n Locked,\n Movable,\n MovesSelection,\n SelectionMovable,\n NO_ENTITY,\n PointerMods,\n Position,\n Resizable,\n RoutedMove,\n RoutedResize,\n Selected,\n Size,\n SweepsContained,\n Watches,\n} from \"../catalog\";\nimport { SelectionVersion, bumpVersion } from \"../helpers/version-stamps\";\nimport { widgetTypeFor } from \"../canvas/engine-catalog\";\nimport { PrefabId } from \"../schema/prefab\";\nimport { selectedEntities } from \"../ops/selection\";\n\nconst P = GesturePhases;\n\nconst moveClaimQ = defineQuery([Drag, P.justTags.Active, RoutedMove]);\nconst resizeClaimQ = defineQuery([Drag, P.justTags.Active, RoutedResize]);\nconst sweepCandidatesQ = defineQuery([Position, Size, Movable]);\n\n/**\n * Comment-box sweep (2026-07-18, James: the UE-Blueprint comment): expand the\n * dragged set with every widget FULLY INSIDE each SweepsContained member's\n * bounds at claim time. Spatial membership only — no reparenting, so dragging\n * a member out later is nothing at all. Frame-scoped via the canonical\n * non-member signature (Culled ∧ ¬Active — bare test worlds have no tags, so\n * requiring Active would break them; the wires-scope lesson 2026-07-17):\n * folder innards live in frame-local coords that can NUMERICALLY overlap a\n * root comment's rect and must never be swept across frames. Nested comments\n * need no recursion: inner ⊆ outer ⇒ the inner's members are inside the\n * outer's bounds already.\n */\nfunction expandSweep(world: World, ctx: SystemCtx, dragged: Entity[]): void {\n const roots = dragged.filter((w) => ctx.isAlive(w) && ctx.hasTag(w, SweepsContained));\n if (roots.length === 0) return;\n const inSet = new Set(dragged);\n for (const root of roots) {\n const rp = ctx.get(root, Position);\n const rs = ctx.get(root, Size);\n if (rp === undefined || rs === undefined) continue;\n world.query(sweepCandidatesQ).each((b) => {\n for (const r of b) {\n const w = b.entity(r);\n if (inSet.has(w)) continue;\n if (world.hasTag(w, Culled) && !world.hasTag(w, Active)) continue; // other frame\n const p = world.get(w, Position);\n const s = world.get(w, Size);\n if (p === undefined || s === undefined) continue;\n if (p.x >= rp.x && p.y >= rp.y && p.x + s.w <= rp.x + rs.w && p.y + s.h <= rp.y + rs.h) {\n inSet.add(w);\n dragged.push(w);\n }\n }\n });\n }\n}\n\n/**\n * The widgets a dragged widget's type says RIDE with it (`defineWidget({ riders })`, design-015 D3t-c — the desk calendar's stuck\n * notes): added to the dragged set once each, alive and of the same frame (the sweep's frame test), so they move live with it and\n * commit in the same transaction. A rider's own riders are not followed (one level — a note carries nothing).\n */\nfunction expandRiders(world: World, ctx: SystemCtx, dragged: Entity[]): void {\n const inSet = new Set(dragged);\n for (const w of [...dragged]) {\n if (!ctx.isAlive(w)) continue;\n const id = ctx.get(w, PrefabId)?.id;\n const riders = typeof id === \"string\" ? widgetTypeFor(world, id)?.riders?.(world, w) : undefined;\n for (const r of riders ?? []) {\n if (inSet.has(r) || !ctx.isAlive(r) || !ctx.has(r, Position)) continue;\n if (world.hasTag(r, Culled) && !world.hasTag(r, Active)) continue; // other frame\n inSet.add(r);\n dragged.push(r);\n }\n }\n}\n\n/**\n * Attach the drag riders for one widget; returns false if another gesture owns\n * it. `Grab` embeds the ORDER MEMO (petition 8): the widget's ChildOf parent,\n * its nearest predecessor sibling that is NOT itself mid-drag (`taken` covers\n * this pass's claims, a live `Grab` covers earlier frames' — both sit at \"last\"\n * and are unstable anchors; a predecessor dragged by THIS gesture is fine, the\n * restore walk reinserts in `ord` order so it is back in place when consulted),\n * and the original sibling index. The memo reads the PRE-FLUSH sequence — ctx\n * structure is deferred, so capture and the enqueued elevates never interleave.\n */\nfunction attachRiders(ctx: SystemCtx, recognizer: Entity, widget: Entity, taken: Set<Entity>): boolean {\n if (taken.has(widget)) return false;\n const otherOwner = ctx\n .getReverse(widget, Drags)\n .some((rec) => rec !== recognizer);\n if (otherOwner) return false;\n taken.add(widget);\n const pos = ctx.read(widget, Position);\n const size = ctx.get(widget, Size);\n const parent = ctx.getRelation(widget, ChildOf);\n let prev: Entity = NO_ENTITY;\n let ord = 0;\n if (parent !== undefined) {\n const siblings = ctx.getReverse(parent, ChildOf);\n const at = siblings.indexOf(widget);\n ord = at >= 0 ? at : 0;\n for (let i = at - 1; i >= 0; i--) {\n const sib = siblings[i] as Entity;\n if (!taken.has(sib) && !ctx.has(sib, Grab)) {\n prev = sib;\n break;\n }\n }\n }\n ctx.addRelation(recognizer, Drags, widget);\n ctx.addComponent(widget, Grab, {\n x: pos.x,\n y: pos.y,\n w: size?.w ?? 0,\n h: size?.h ?? 0,\n parent: parent ?? NO_ENTITY,\n prev,\n ord,\n });\n return true;\n}\n\nexport function createClaimSystems(world: World): { moveClaim: System; resizeClaim: System } {\n const moveClaim = defineSystem(\n moveClaimQ,\n (b, ctx) => {\n // Shared across recognizers in this pass — first gesture owns a widget.\n const taken = new Set<Entity>();\n for (const r of b) {\n const rec = b.entity(r);\n const grabbed = ctx.getRelation(rec, Captures);\n const fromSelection = ctx.hasTag(rec, MovesSelection);\n if (!fromSelection && (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 // ⌥ as the drag starts: its release leaves a copy behind (design-015 D4a) — latched like a route, never mid-gesture\n if (pointer !== undefined && ctx.get(pointer, PointerMods)?.alt === true && (grabbed === undefined || !ctx.has(grabbed, InsertGhost))) ctx.addTag(rec, LeavesCopy);\n const current = selectedEntities(world);\n let dragged: Entity[];\n if (fromSelection) {\n // A press in the union's empty space keeps the selection intact.\n dragged = current;\n } else if (grabbed === undefined) {\n continue;\n } else if (ctx.has(grabbed, InsertGhost)) {\n // Tray-insert ghosts drag SOLO (2026-07-19): the shift branch below\n // would sweep the standing selection into the insert, and a\n // selected-set join makes no sense for a widget that does not exist\n // yet. Replace-select the ghost (select-on-grab's plain posture) —\n // the reap system hands the selection to the projected twin at drop.\n for (const s of current) if (s !== grabbed) ctx.removeTag(s, Selected);\n if (!ctx.hasTag(grabbed, Selected)) ctx.addTag(grabbed, Selected);\n bumpVersion(world, SelectionVersion);\n dragged = [grabbed];\n } else if (ctx.hasTag(grabbed, Selected)) {\n dragged = current;\n } else if (shift) {\n ctx.addTag(grabbed, Selected);\n bumpVersion(world, SelectionVersion);\n dragged = [...current, grabbed];\n } else {\n for (const s of current) ctx.removeTag(s, Selected);\n ctx.addTag(grabbed, Selected);\n bumpVersion(world, SelectionVersion);\n dragged = [grabbed];\n }\n\n // Comment-box sweep BEFORE riders: swept members ride the same\n // recognizer; rider order keeps the comment BELOW its members in the\n // elevate (comment first, members after — each successive \"last\"\n // lands ABOVE the previous one).\n expandSweep(world, ctx, dragged);\n // …and what a dragged widget's TYPE says rides with it (design-015 D3t-c — a calendar's stuck notes): after it, so a\n // rider elevates above what it rides\n expandRiders(world, ctx, dragged);\n\n for (const w of dragged) {\n if (!ctx.isAlive(w) || !ctx.has(w, Position)) continue;\n if (ctx.hasTag(w, Culled) && !ctx.hasTag(w, Active)) continue;\n if (w !== grabbed && !ctx.hasTag(w, Movable) && !ctx.hasTag(w, SelectionMovable)) continue;\n // Taped down (design-015 §5.1): no rider, so no move, no elevate and no\n // commit for it — whether it was grabbed, rode the selection or was\n // swept. Selection above is untouched: a taped widget stays selectable.\n if (ctx.hasTag(w, Locked)) continue;\n if (!attachRiders(ctx, rec, w, taken)) continue;\n // Sibling elevate (petition 8): an immediate structural move —\n // gesture divergence; the Grab memo restores on cancel/fly-back.\n // Frame-scoped \"last\" = the old global-top within the frame. No\n // edge (legacy/runtime world) ⇒ strata no-op, skipped.\n if (ctx.getRelation(w, ChildOf) !== undefined) {\n ctx.moveRelation(w, ChildOf, \"last\");\n }\n }\n }\n },\n { name: \"moveClaim\" },\n );\n\n const resizeClaim = defineSystem(\n resizeClaimQ,\n (b, ctx) => {\n const taken = new Set<Entity>();\n for (const r of b) {\n const rec = b.entity(r);\n // Anchor = the captured handle's HandleSpec (read by resizeBehavior).\n for (const w of selectedEntities(world)) {\n if (!ctx.isAlive(w) || !ctx.hasTag(w, Resizable) || !ctx.has(w, Position)) continue;\n if (ctx.hasTag(w, Locked)) continue; // taped down: never resized by a gesture (design-015 §5.1)\n attachRiders(ctx, rec, w, taken);\n }\n }\n },\n { name: \"resizeClaim\" },\n );\n\n return { moveClaim, resizeClaim };\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. A `Locked` widget is never a\n * hit (design-015 §5.1, Q-g: the tape keeps it out of the vellum).\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 Locked,\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 // A taped widget is passed over (design-015 §5.1, *Marks on the Mat* Q-g) —\n // neither previewed nor gathered; a tap still selects it.\n if (ctx.isAlive(e) && ctx.hasTag(e, Selectable) && !ctx.hasTag(e, Locked)) out.push(e);\n }\n return out;\n };\n\n /** ctx-side selection flip — replace with hits (shift = union), one SelectionVersion bump. */\n const commitSelection = (ctx: SystemCtx, hits: Entity[], shift: boolean): void => {\n const current = selectedEntities(world);\n const next = new Set(hits);\n if (shift) for (const e of current) next.add(e);\n let changed = false;\n for (const e of current) {\n if (!next.has(e)) {\n ctx.removeTag(e, Selected);\n changed = true;\n }\n }\n for (const e of next) {\n if (!ctx.hasTag(e, Selected)) {\n ctx.addTag(e, Selected);\n changed = true;\n }\n }\n if (changed) bumpVersion(world, SelectionVersion);\n };\n\n // Tick system (strata 0.5.0): exactly once per frame by construction\n // (commitSelection is NOT idempotent within a tick: its tags defer, so a\n // re-run would re-bump SelectionVersion).\n const sys = defineTickSystem(\n (ctx) => {\n const cam = ctx.getResource(Camera) ?? IDENTITY_CAM;\n const canvas = ctx.firstOf(canvasSurfaceQ);\n let active = false;\n\n const process = (\n rec: Entity,\n sx0: number,\n sy0: number,\n sx1: number,\n sy1: number,\n isActive: boolean,\n justEnded: boolean,\n ): void => {\n const w0 = screenToWorld(sx0, sy0, cam);\n const w1 = screenToWorld(sx1, sy1, cam);\n const rx = Math.min(w0.x, w1.x);\n const ry = Math.min(w0.y, w1.y);\n const rw = Math.abs(w1.x - w0.x);\n const rh = Math.abs(w1.y - w0.y);\n const hits = queryHits(ctx, rx, ry, rw, rh);\n if (justEnded) {\n const pointer = ctx.getRelations(rec, Watches)[0];\n const shift = pointer !== undefined && ctx.get(pointer, PointerMods)?.shift === true;\n commitSelection(ctx, hits, shift);\n return;\n }\n if (isActive) {\n buffer.rect = { x: rx, y: ry, w: rw, h: rh };\n buffer.hits = hits;\n active = true;\n }\n };\n\n // Desktop: RoutedMarquee drag (start + total, screen space).\n world.query(dragMarqueeQ).each((bb) => {\n for (const r of bb) {\n const rec = bb.entity(r);\n const d = ctx.read(rec, Drag);\n process(\n rec,\n d.startX,\n d.startY,\n d.startX + d.totalX,\n d.startY + d.totalY,\n ctx.hasTag(rec, P.tags.Active),\n ctx.hasTag(rec, P.justTags.Ended),\n );\n }\n });\n\n // Touch: LongPress on the canvas, riding its continuous tail (start → cur).\n world.query(longPressQ).each((bb) => {\n for (const r of bb) {\n const rec = bb.entity(r);\n if (canvas === undefined || ctx.getRelation(rec, Captures) !== canvas) continue;\n const lp = ctx.read(rec, LongPress);\n process(\n rec,\n lp.startX,\n lp.startY,\n lp.curX,\n lp.curY,\n ctx.hasTag(rec, P.tags.Recognized),\n ctx.hasTag(rec, P.justTags.Ended),\n );\n }\n });\n\n if (!active) {\n buffer.rect = null;\n buffer.hits = [];\n }\n },\n { name: \"marqueeBehavior\" },\n );\n\n return Object.assign(sys, { buffer });\n}\n","/**\n * L3 — resize behavior (design-003 §5 item 6; `ctl:behave`).\n *\n * A drag captured on a `HandleSpec` chrome entity (route `RoutedResize`, riders\n * attached by `resizeClaim` §4.5). Per Active frame it writes ABSOLUTE Position+\n * Size for every live `Drags` target from its `Grab` origin + `Drag.total /\n * zoomAtClaim`, resized about the FIXED opposite edge/corner of the grabbed\n * handle (`n`/`s` height-only, `e`/`w` width-only, corners both). Modifiers ride\n * the watched pointer's `PointerMods`: `alt` = resize about center, `shift` =\n * preserve aspect (corner handles). Min size clamps to the target widget's\n * `defineWidget` `minSize` (via `PrefabId`), or 1×1 for non-widget resizables.\n * `JustEnded` emits ONE\n * `resize` commit (Position+Size per live target); `JustCancelled`/`JustFailed`\n * restore from `Grab`. Every terminal path removes `Grab` and the `Drags` edges\n * (mirrors l3-behave's clearGestureState; resize has no DropTarget).\n */\nimport type { Entity, System, SystemCtx, World } from \"@vibecook/strata-ecs\";\nimport { defineQuery, defineSystem } from \"@vibecook/strata-ecs\";\nimport {\n Captures,\n Drag,\n Drags,\n GesturePhases,\n Grab,\n HandleSpec,\n PointerMods,\n Position,\n RoutedResize,\n Size,\n Watches,\n} from \"../catalog\";\nimport { widgetTypeFor } from \"../canvas/engine-catalog\";\nimport type { CommitSink, CommitWrite } from \"../engine/commit-sink\";\nimport { PrefabId } from \"../schema/prefab\";\n\nconst P = GesturePhases;\nconst resizeDragQ = defineQuery([Drag, RoutedResize]);\n\ninterface RectVals {\n x: number;\n y: number;\n w: number;\n h: number;\n}\n\n/**\n * Resize a `Grab` rect by world deltas about the anchor handle's fixed opposite\n * edge/corner. `alt` pins the center instead; `shift` preserves aspect on corners.\n */\nfunction computeResize(\n g: { x: number; y: number; w: number; h: number },\n anchor: string,\n dx: number,\n dy: number,\n alt: boolean,\n shift: boolean,\n minW: number,\n minH: number,\n): RectVals {\n const affectsLeft = anchor === \"w\" || anchor === \"nw\" || anchor === \"sw\";\n const affectsRight = anchor === \"e\" || anchor === \"ne\" || anchor === \"se\";\n const affectsTop = anchor === \"n\" || anchor === \"nw\" || anchor === \"ne\";\n const affectsBottom = anchor === \"s\" || anchor === \"se\" || anchor === \"sw\";\n const lDelta = affectsLeft ? dx : 0;\n const rDelta = affectsRight ? dx : 0;\n const tDelta = affectsTop ? dy : 0;\n const bDelta = affectsBottom ? dy : 0;\n\n let left: number;\n let right: number;\n let top: number;\n let bottom: number;\n if (alt) {\n // About center: the opposite edge mirrors the grabbed edge's motion.\n left = g.x + lDelta - rDelta;\n right = g.x + g.w + rDelta - lDelta;\n top = g.y + tDelta - bDelta;\n bottom = g.y + g.h + bDelta - tDelta;\n } else {\n left = g.x + lDelta;\n right = g.x + g.w + rDelta;\n top = g.y + tDelta;\n bottom = g.y + g.h + bDelta;\n }\n\n const isCorner = (affectsLeft || affectsRight) && (affectsTop || affectsBottom);\n if (shift && isCorner && g.w > 0 && g.h > 0) {\n // Uniform-scale to the dominant relative change, re-anchored for the mode.\n const kW = Math.abs((right - left) / g.w);\n const kH = Math.abs((bottom - top) / g.h);\n const k = Math.max(kW, kH);\n const nw = g.w * k;\n const nh = g.h * k;\n if (alt) {\n const cx = g.x + g.w / 2;\n const cy = g.y + g.h / 2;\n left = cx - nw / 2;\n right = cx + nw / 2;\n top = cy - nh / 2;\n bottom = cy + nh / 2;\n } else {\n if (affectsRight) right = left + nw;\n else left = right - nw;\n if (affectsBottom) bottom = top + nh;\n else top = bottom - nh;\n }\n }\n\n // Min size — adjust the moving edge so the fixed (anchor) edge stays put.\n if (right - left < minW) {\n if (affectsLeft && !affectsRight) left = right - minW;\n else right = left + minW;\n }\n if (bottom - top < minH) {\n if (affectsTop && !affectsBottom) top = bottom - minH;\n else bottom = top + minH;\n }\n\n return { x: left, y: top, w: right - left, h: bottom - top };\n}\n\nexport function createResizeBehavior(world: World, sink: CommitSink): System {\n const clearResizeState = (ctx: SystemCtx, rec: Entity): void => {\n for (const w of ctx.getRelations(rec, Drags)) {\n if (ctx.isAlive(w) && ctx.has(w, Grab)) ctx.removeComponent(w, Grab);\n }\n ctx.removeRelation(rec, Drags);\n };\n\n // A resizable widget's declared floor (defineWidget `minSize`); non-widget\n // resizables (no `PrefabId`) keep the historical 1×1.\n const minSizeOf = (ctx: SystemCtx, w: Entity): { w: number; h: number } => {\n const type = ctx.get(w, PrefabId)?.id;\n const widget = typeof type === \"string\" ? widgetTypeFor(world, type) : undefined;\n return widget?.minSize ?? { w: 1, h: 1 };\n };\n\n return defineSystem(\n resizeDragQ,\n (b, ctx) => {\n for (const r of b) {\n const rec = b.entity(r);\n const handle = ctx.getRelation(rec, Captures);\n const anchor = handle !== undefined ? ctx.get(handle, HandleSpec)?.anchor : undefined;\n const pointer = ctx.getRelations(rec, Watches)[0];\n const mods = pointer !== undefined ? ctx.get(pointer, PointerMods) : undefined;\n const alt = mods?.alt === true;\n const shift = mods?.shift === true;\n\n if (ctx.hasTag(rec, P.tags.Active)) {\n if (anchor === undefined) continue; // handle died — integrity cancels next frame\n const d = ctx.read(rec, Drag);\n const zoom = d.zoomAtClaim || 1;\n const dx = d.totalX / zoom;\n const dy = d.totalY / zoom;\n for (const w of ctx.getRelations(rec, Drags)) {\n if (!ctx.isAlive(w) || !ctx.has(w, Grab)) continue;\n const g = ctx.read(w, Grab);\n const min = minSizeOf(ctx, w);\n const rz = computeResize(g, anchor, dx, dy, alt, shift, min.w, min.h);\n ctx.edit(w).set(Position, { x: rz.x, y: rz.y });\n ctx.edit(w).set(Size, { w: rz.w, h: rz.h });\n }\n continue;\n }\n\n if (ctx.hasTag(rec, P.justTags.Ended)) {\n const writes: CommitWrite[] = [];\n if (anchor !== undefined) {\n const d = ctx.read(rec, Drag);\n const zoom = d.zoomAtClaim || 1;\n const dx = d.totalX / zoom;\n const dy = d.totalY / zoom;\n for (const w of ctx.getRelations(rec, Drags)) {\n if (!ctx.isAlive(w) || !ctx.has(w, Grab)) continue;\n const g = ctx.read(w, Grab);\n const min = minSizeOf(ctx, w);\n const rz = computeResize(g, anchor, dx, dy, alt, shift, min.w, min.h);\n writes.push({ entity: w, component: Position, value: { x: rz.x, y: rz.y } });\n writes.push({ entity: w, component: Size, value: { w: rz.w, h: rz.h } });\n }\n }\n if (writes.length > 0) sink.commit({ kind: \"resize\", gesture: rec, writes });\n clearResizeState(ctx, rec);\n continue;\n }\n\n if (ctx.hasTag(rec, P.justTags.Cancelled) || ctx.hasTag(rec, P.justTags.Failed)) {\n for (const w of ctx.getRelations(rec, Drags)) {\n if (!ctx.isAlive(w) || !ctx.has(w, Grab)) continue;\n const g = ctx.read(w, Grab);\n ctx.edit(w).set(Position, { x: g.x, y: g.y });\n ctx.edit(w).set(Size, { w: g.w, h: g.h });\n }\n clearResizeState(ctx, rec);\n }\n }\n },\n {\n name: \"resizeBehavior\",\n // Position co-write attested — see moveBehavior (row-disjoint routes).\n access: { write: [Position, Size], orderIndependent: [Position] },\n },\n );\n}\n","/**\n * L3 — snap (design-003 §5 item 2, §6; `ctl:behave`, ordered BEFORE moveBehavior).\n *\n * For Active `RoutedMove` drags whose dragged set is a `SnapSource`: compute the\n * intended PRE-SNAP rect as `Grab.origin + Drag.total / zoomAtClaim`, unioned\n * over the dragged widgets — NEVER last-applied `Position` (one frame stale ⇒\n * guide-chasing oscillation, design-003 §5.2 red-team; `Grab` is readable here\n * thanks to the ctl:claim settle point, §4.5). Candidates come from the SHARED\n * spatial index (rect query = intended bounds ∪ VIEWPORT, expanded by\n * threshold — design-003 §5.2: a distant same-axis edge IN VIEW must\n * contribute a guide, the Figma behavior; the widgetlab field check 2026-07-16\n * caught the intended-rect-only query never seeing a card 115px above the\n * drag). Filtered to `SnapTarget ∧ ¬Culled ∧ ∉dragged` — ¬Culled is the\n * design's \"Visible\" scoping in cull-less rigs too (no cull system ⇒ nothing\n * is Culled ⇒ all candidates pass). Threshold is\n * `thresholdPx / zoomAtClaim` (screen-constant). The kernel `computeSnapGuides`\n * does the Figma math; we write `SnapState{dx,dy}` on the recognizer (moveBehavior\n * adds it to the absolute write). SnapState clears to 0,0 when snap is off / no\n * source / no candidate.\n *\n * GUIDE CHROME (design-003 §6, as-built 2026-07-16 — the once-deferred half):\n * the kernel result's `guides`/`spacings` become pooled runtime `GuideLine` /\n * `SpacingBar` entities the P0 snap-guides reflector draws (design-004 §1\n * amendment: ground stratum, under content — James's call). Pool mechanics\n * mirror selectionChrome: a TICK system (exactly one pass per frame — spawn/\n * destroy are not idempotent, and the pool must reap on the frame the last\n * snapping drag ENDS, when the recognizer query is empty), `ctx.spawn` on\n * grow, `ctx.destroy` on shrink, change-only `edit().set` in steady state\n * (same guide held across frames ⇒ zero writes). Alignment guides write\n * `from = to = 0` — the full-viewport sentinel (v1's full-canvas lines);\n * spacing indicators flatten one entity per segment (v1 `u_spacings` parity).\n * No silent caps: the pool grows to whatever the kernel returns (v1's\n * MAX_GUIDES=16 truncation is banned).\n */\nimport type { Entity, SystemCtx, TickSystem, World } from \"@vibecook/strata-ecs\";\nimport { defineQuery, defineTickSystem } from \"@vibecook/strata-ecs\";\nimport { type EntityBounds, type SpatialIndex, computeSnapGuides } from \"@ice/kernel\";\nimport {\n Camera,\n Captures,\n Culled,\n Drag,\n Drags,\n GestureActive,\n Grab,\n GuideLine,\n RoutedMove,\n SnapConfig,\n SnapSource,\n SnapState,\n SnapTarget,\n SpacingBar,\n Viewport,\n} from \"../catalog\";\nimport { SNAP_DEFAULTS } from \"../settings/defaults\";\nimport { moveDelta, snapHeldOff, watchedMods } from \"./drag-mods\";\n\nconst snapDragQ = defineQuery([Drag, GestureActive, RoutedMove]);\n\ninterface GuideWant {\n axis: \"x\" | \"y\";\n at: number;\n}\n\ninterface BarWant {\n axis: \"x\" | \"y\";\n from: number;\n to: number;\n perp: number;\n gap: number;\n}\n\nexport function createSnapSystem(world: World, index: SpatialIndex<Entity>): TickSystem {\n // Guide-chrome pools (derived caches, not world state — selectionChrome\n // pattern): live entities aligned to this frame's wanted visuals, plus the\n // last-written values for change-only writes.\n const guidePool: Entity[] = [];\n const guideCache = new Map<Entity, GuideWant>();\n const barPool: Entity[] = [];\n const barCache = new Map<Entity, BarWant>();\n\n const syncGuides = (ctx: SystemCtx, want: readonly GuideWant[]): void => {\n for (let i = 0; i < want.length; i++) {\n const w = want[i] as GuideWant;\n const existing = guidePool[i];\n if (existing === undefined) {\n const e = ctx.spawn({\n components: [[GuideLine, { axis: w.axis, at: w.at, from: 0, to: 0 }]],\n });\n guidePool.push(e);\n guideCache.set(e, w);\n continue;\n }\n const c = guideCache.get(existing);\n if (c === undefined || c.axis !== w.axis || c.at !== w.at) {\n ctx.edit(existing).set(GuideLine, { axis: w.axis, at: w.at, from: 0, to: 0 });\n guideCache.set(existing, w);\n }\n }\n while (guidePool.length > want.length) {\n const e = guidePool.pop() as Entity;\n ctx.destroy(e);\n guideCache.delete(e);\n }\n };\n\n const syncBars = (ctx: SystemCtx, want: readonly BarWant[]): void => {\n for (let i = 0; i < want.length; i++) {\n const w = want[i] as BarWant;\n const existing = barPool[i];\n if (existing === undefined) {\n const e = ctx.spawn({\n components: [[SpacingBar, { axis: w.axis, from: w.from, to: w.to, perp: w.perp, gap: w.gap }]],\n });\n barPool.push(e);\n barCache.set(e, w);\n continue;\n }\n const c = barCache.get(existing);\n if (\n c === undefined ||\n c.axis !== w.axis ||\n c.from !== w.from ||\n c.to !== w.to ||\n c.perp !== w.perp ||\n c.gap !== w.gap\n ) {\n ctx.edit(existing).set(SpacingBar, { axis: w.axis, from: w.from, to: w.to, perp: w.perp, gap: w.gap });\n barCache.set(existing, w);\n }\n }\n while (barPool.length > want.length) {\n const e = barPool.pop() as Entity;\n ctx.destroy(e);\n barCache.delete(e);\n }\n };\n\n return defineTickSystem(\n (ctx) => {\n const cfg = ctx.getResource(SnapConfig);\n const enabled = cfg?.enabled ?? SNAP_DEFAULTS.enabled;\n const thresholdPx = cfg?.thresholdPx ?? SNAP_DEFAULTS.thresholdPx;\n\n const setSnap = (rec: Entity, dx: number, dy: number): void => {\n const cur = ctx.get(rec, SnapState);\n if (cur === undefined || cur.dx !== dx || cur.dy !== dy) ctx.edit(rec).set(SnapState, { dx, dy });\n };\n\n // This frame's wanted visuals, accumulated across every snapping drag\n // (multi-pointer drags each contribute; usually one).\n const wantGuides: GuideWant[] = [];\n const wantBars: BarWant[] = [];\n\n ctx.query(snapDragQ).each((b) => {\n for (const r of b) {\n const rec = b.entity(r);\n const dragged = ctx.getRelations(rec, Drags);\n const captured = ctx.getRelation(rec, Captures);\n const hasSource =\n (captured !== undefined && ctx.hasTag(captured, SnapSource)) ||\n dragged.some((w) => ctx.hasTag(w, SnapSource));\n // ⌘ (or Ctrl) held holds the snap off — no correction, no guides (design-015 D4a, the desk's keys)\n if (!enabled || !hasSource || snapHeldOff(watchedMods(ctx, rec))) {\n setSnap(rec, 0, 0);\n continue;\n }\n\n // Intended union rect from Grab + the drag's delta (never last-applied Position) — ⇧'s axis lock\n // included: the delta the snap aligns is the delta the move writes (drag-mods.ts).\n const d = ctx.read(rec, Drag);\n const zoom = d.zoomAtClaim || 1;\n const delta = moveDelta(ctx, rec);\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 + delta.x;\n const y = g.y + delta.y;\n minX = Math.min(minX, x);\n minY = Math.min(minY, y);\n maxX = Math.max(maxX, x + g.w);\n maxY = Math.max(maxY, y + g.h);\n any = true;\n }\n if (!any) {\n setSnap(rec, 0, 0);\n continue;\n }\n\n const threshold = thresholdPx / zoom;\n const intended: EntityBounds = { x: minX, y: minY, width: maxX - minX, height: maxY - minY };\n\n // Candidates: index rect query over intended ∪ viewport (± threshold),\n // SnapTarget ∧ ¬Culled ∧ ∉dragged (design-003 §5.2).\n let qMinX = minX - threshold;\n let qMinY = minY - threshold;\n let qMaxX = maxX + threshold;\n let qMaxY = maxY + threshold;\n const cam = ctx.getResource(Camera);\n const vp = ctx.getResource(Viewport);\n if (cam !== undefined && vp !== undefined && vp.w > 0) {\n const vz = cam.zoom || 1; // Camera.x/y = world top-left (grid contract)\n qMinX = Math.min(qMinX, cam.x);\n qMinY = Math.min(qMinY, cam.y);\n qMaxX = Math.max(qMaxX, cam.x + vp.w / vz);\n qMaxY = Math.max(qMaxY, cam.y + vp.h / vz);\n }\n const refs: EntityBounds[] = [];\n for (const entry of index.search({ minX: qMinX, minY: qMinY, maxX: qMaxX, maxY: qMaxY })) {\n const e = entry.id;\n if (draggedSet.has(e) || !ctx.isAlive(e) || !ctx.hasTag(e, SnapTarget) || ctx.hasTag(e, Culled)) continue;\n refs.push({\n x: entry.minX,\n y: entry.minY,\n width: entry.maxX - entry.minX,\n height: entry.maxY - entry.minY,\n });\n }\n if (refs.length === 0) {\n setSnap(rec, 0, 0);\n continue;\n }\n\n const res = computeSnapGuides(intended, refs, threshold);\n // ⇧ locks the drag to one axis: the snap corrects along it alone, and states nothing about the other\n const free = (axis: \"x\" | \"y\"): boolean => delta.lock === null || delta.lock === axis;\n setSnap(rec, free(\"x\") ? res.snapDx : 0, free(\"y\") ? res.snapDy : 0);\n for (const g of res.guides) if (free(g.axis)) wantGuides.push({ axis: g.axis, at: g.position });\n for (const sp of res.spacings) {\n if (!free(sp.axis)) continue;\n for (const seg of sp.segments) {\n wantBars.push({ axis: sp.axis, from: seg.from, to: seg.to, perp: sp.perpPosition, gap: sp.gap });\n }\n }\n }\n });\n\n // Pool reconcile runs EVERY frame — the drag-ended frame (empty query)\n // is exactly the one that must reap; steady state is zero ops.\n syncGuides(ctx, wantGuides);\n syncBars(ctx, wantBars);\n },\n { name: \"snapSystem\", access: { write: [SnapState, GuideLine, SpacingBar] } },\n );\n}\n","/**\n * The insert-ghost reap (cleanup phase; catalog/insert.ts, 2026-07-19).\n *\n * Three exits for a tray-insert ghost, all owned here so nothing transient\n * crosses frames unaccounted (design-002 §2 cleanup law):\n *\n * - PROMOTED (`GhostCommitted`, set by moveBehavior at the create commit):\n * despawned ONE tick after the commit — the projected twin lands at the\n * NEXT sync, so waiting one tick makes the swap happen inside a single\n * reflect flush (twin mounts, ghost unmounts, same frame — no blink).\n * Selection rides the same beat: the doc sink parked the twin ids in its\n * out-of-ECS hand-off (`drainCreatedSelections`); they are drained on the\n * commit tick and applied HERE one tick later, when the projection is\n * alive — the select-on-grab the ghost held transfers to the real widget.\n * Not to a twin created INSIDE a container: it is no member of this frame\n * (`Selected ⇒ Active`, nested-canvas.ts), so the drop selects nothing.\n *\n * - RETIRING (`GhostRetiring`, cancel / rejected drop): despawned when the\n * fly-back `TransformTween` lands (camera-sim removes it on arrival).\n *\n * - STRANDED (no Grab, no tween, no live recognizer still capturing it): a\n * clean click on a tray tile (the drag never formed), or an integrity\n * cancel that raced the claim. Despawned silently — it never left the\n * press point under the tray.\n */\nimport type { Entity, System, SystemCtx, World } from \"@vibecook/strata-ecs\";\nimport { defineQuery, defineSystem } from \"@vibecook/strata-ecs\";\nimport {\n Active,\n Captures,\n Culled,\n GesturePhases,\n GhostCommitted,\n GhostRetiring,\n Grab,\n InsertGhost,\n Selected,\n TransformTween,\n} from \"../catalog\";\nimport { drainCreatedSelections } from \"../doc/doc-commit-sink\";\nimport { SelectionVersion, bumpVersion } from \"../helpers/version-stamps\";\nimport { selectedEntities } from \"../ops/selection\";\n\nconst P = GesturePhases;\nconst ghostQ = defineQuery([InsertGhost]);\n\n/** Terminal recognizer phases — a capture from one no longer holds the ghost. */\nfunction isTerminal(ctx: SystemCtx, rec: Entity): boolean {\n return (\n ctx.hasTag(rec, P.tags.Ended) ||\n ctx.hasTag(rec, P.tags.Failed) ||\n ctx.hasTag(rec, P.tags.Cancelled) ||\n ctx.hasTag(rec, P.tags.Recognized)\n );\n}\n\nexport function createInsertGhostReap(world: World): System {\n // Commit-tick memory (both live exactly one tick, and only while the ghost\n // is still alive — the zero-match chunk skip can never starve them):\n // ghosts sighted GhostCommitted last tick → despawn now; twin ids drained\n // last tick → their projection is alive now, select them.\n const committedSeen = new Set<Entity>();\n let pendingSelect: Entity[] = [];\n\n return defineSystem(\n ghostQ,\n (b, ctx) => {\n if (pendingSelect.length > 0) {\n // Membership classified the twin this tick (derive runs before cleanup): the non-member signature is Culled ∧ ¬Active.\n const live = pendingSelect.filter((e) => ctx.isAlive(e) && !(ctx.hasTag(e, Culled) && !ctx.hasTag(e, Active)));\n pendingSelect = [];\n if (live.length > 0) {\n const keep = new Set(live);\n for (const s of selectedEntities(world)) {\n if (!keep.has(s)) ctx.removeTag(s, Selected);\n }\n for (const e of live) {\n if (!ctx.hasTag(e, Selected)) ctx.addTag(e, Selected);\n }\n bumpVersion(world, SelectionVersion);\n }\n }\n\n for (const r of b) {\n const ghost = b.entity(r);\n if (ctx.hasTag(ghost, GhostCommitted)) {\n if (committedSeen.has(ghost)) {\n committedSeen.delete(ghost);\n ctx.destroy(ghost); // twin projected THIS tick's sync — same-flush swap\n } else {\n committedSeen.add(ghost); // commit tick — twin lands next sync\n }\n continue;\n }\n if (ctx.hasTag(ghost, GhostRetiring)) {\n if (!ctx.has(ghost, TransformTween)) ctx.destroy(ghost); // tween landed\n continue;\n }\n if (ctx.has(ghost, Grab) || ctx.has(ghost, TransformTween)) continue;\n const held = ctx.getReverse(ghost, Captures).some((rec) => !isTerminal(ctx, rec));\n if (!held) ctx.destroy(ghost); // stranded — click-no-drag or a raced cancel\n }\n\n // Drained on the COMMIT tick (sink wrote it in ctl:behave, this phase is\n // cleanup — same tick); applied at the top of the NEXT pass, above.\n const created = drainCreatedSelections(world);\n if (created.length > 0) pendingSelect.push(...created);\n },\n { name: \"insertGhostReap\" },\n );\n}\n","/**\n * 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, rootCanvas?, 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 */\nimport type { CanvasTypeIdentity } from \"../canvas/define-canvas-type\";\n\nexport const ENVELOPE_MAGIC = \"ICE1\";\nexport const ENVELOPE_VERSION = 1;\nexport const MAX_ENVELOPE_HEADER_BYTES = 1024 * 1024;\n\n/** The document-format version this build writes (gate compares against it). */\nexport const ENGINE_SCHEMA_VERSION = 3; // 3 = durable root CanvasType identity + canvas pack gate\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 /** Coarse pre-import mirror; in-document ice:rootCanvas remains authoritative. */\n readonly rootCanvas?: CanvasTypeIdentity;\n /** App-supplied wall-clock ms (the engine never reads a clock). */\n readonly savedAt?: number;\n}\n\nexport class EnvelopeError extends Error {\n constructor(\n message: string,\n readonly reason: \"magic\" | \"version\" | \"truncated\" | \"header\",\n ) {\n super(`ice: envelope — ${message}`);\n this.name = \"EnvelopeError\";\n }\n}\n\nexport function encodeEnvelope(header: EnvelopeHeader, payload: Uint8Array): Uint8Array {\n const headerBytes = new TextEncoder().encode(JSON.stringify(header));\n const out = new Uint8Array(4 + 1 + 4 + headerBytes.length + payload.length);\n const view = new DataView(out.buffer);\n out.set(new TextEncoder().encode(ENVELOPE_MAGIC), 0);\n out[4] = ENVELOPE_VERSION;\n view.setUint32(5, headerBytes.length, true);\n out.set(headerBytes, 9);\n out.set(payload, 9 + headerBytes.length);\n return out;\n}\n\nexport function decodeEnvelope(bytes: Uint8Array): { header: EnvelopeHeader; payload: Uint8Array } {\n if (bytes.length < 9) throw new EnvelopeError(\"too short to hold a frame\", \"truncated\");\n const magic = new TextDecoder().decode(bytes.subarray(0, 4));\n if (magic !== ENVELOPE_MAGIC) throw new EnvelopeError(`bad magic \"${magic}\"`, \"magic\");\n const version = bytes[4];\n if (version !== ENVELOPE_VERSION) {\n throw new EnvelopeError(`unknown envelope version ${version}`, \"version\");\n }\n const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n const headerLen = view.getUint32(5, true);\n if (headerLen > MAX_ENVELOPE_HEADER_BYTES) {\n throw new EnvelopeError(`header exceeds ${MAX_ENVELOPE_HEADER_BYTES} bytes`, \"header\");\n }\n if (9 + headerLen > bytes.length) throw new EnvelopeError(\"header overruns the frame\", \"truncated\");\n let header: EnvelopeHeader;\n try {\n header = JSON.parse(new TextDecoder().decode(bytes.subarray(9, 9 + headerLen))) as EnvelopeHeader;\n } catch {\n throw new EnvelopeError(\"header is not valid JSON\", \"header\");\n }\n if (\n !Number.isSafeInteger(header.engineSchema) ||\n header.engineSchema < 1 ||\n header.prefabVersions === null ||\n Array.isArray(header.prefabVersions) ||\n typeof header.prefabVersions !== \"object\" ||\n (header.rootCanvas !== undefined &&\n (header.rootCanvas === null ||\n typeof header.rootCanvas !== \"object\" ||\n typeof header.rootCanvas.id !== \"string\" ||\n header.rootCanvas.id.length === 0 ||\n !Number.isSafeInteger(header.rootCanvas.semanticVersion) ||\n header.rootCanvas.semanticVersion < 1)) ||\n (header.savedAt !== undefined &&\n (!Number.isSafeInteger(header.savedAt) || header.savedAt < 0))\n ) {\n throw new EnvelopeError(\"header is missing required fields\", \"header\");\n }\n for (const [id, version] of Object.entries(header.prefabVersions)) {\n if (id.length === 0 || !Number.isSafeInteger(version) || version < 1) {\n throw new EnvelopeError(\"header carries an invalid prefab version\", \"header\");\n }\n }\n return { header, payload: bytes.subarray(9 + headerLen) };\n}\n","/**\n * The M9 migration runner — read-repair at open (design-005 §6.4).\n *\n * A migration is NOT an offline byte transform: the document is already\n * attached, its old cells projected into the runtime, and we upgrade them in\n * place. For each durable type whose doc-side pack marker is OLDER than the\n * local registry (`report.olderInDoc`) and whose widget carries a `migrate`\n * chain covering the gap, `runMigrations`:\n * 1. reads each entity's current group values from the runtime (already\n * canonicalised to the LOCAL schema — see the field-tolerance note below),\n * 2. folds the chain `docV → docV+1 → … → localV-1` over a flat prop record,\n * 3. writes the absolute per-group result back in ONE\n * `store.transaction(fn, { undoable: false })` — the commit never enters\n * the user's undo stack, history hooks skip it, a pending redo survives,\n * 4. stamps the new `engine.pack.<id>.<localV>` write-once marker via\n * `store.metaTransaction` (excluded from undo, invisible to observers).\n *\n * WHY NO LEGACY-SCHEMA REGISTRATION (the as-built finding — design-005 §6.4 is\n * conservative here): design-005 says \"the compiler keeps legacy group\n * components registered for every version covered by the migrate chain\" because\n * \"strata skips unknown inbound components at projection.\" That is TRUE at the\n * COMPONENT-NAME granularity — an unknown component name is never projected\n * (strata-ecs binding.ts:390-392, 804; \"unknown component — never projected\").\n * But it is field-TOLERANT within a known name: `canon(C, v)` iterates the\n * LOCAL schema's `C.fields` (strata-ecs substrate/canon.ts:57-64), so a stored\n * cell that carries EXTRA fields (a v2 that dropped a field) has them dropped,\n * and one MISSING fields (a v2 that added a field) gets them default-filled by\n * `encodeComponentValue`. Because `defineWidget` gives EVERY generated field a\n * default (define-widget.ts strataFieldOf), a v1 cell projects cleanly into a\n * v2 group component of the SAME name with no legacy registration — the\n * transform reads the already-v2-shaped runtime value. Legacy registration\n * would only be needed to migrate data OUT of a group REMOVED wholesale in v2\n * (its component name unregistered → never projected); that coincides with the\n * cross-schema data movement design-005 §6.4 already defers to vNext, so the\n * `migrate` API stays the doc's `{ fromVersion: (prev) => next }` shape with no\n * parallel legacy field. The `migrate.test.ts` \"field tolerance\" case proves\n * the v1→v2 projection empirically (a v1 cell missing a v2-added field).\n *\n * Idempotence / convergence: writes are ABSOLUTE (whole-group values computed\n * from v1), so two peers that migrate the same v1 doc independently produce\n * identical cells that merge by last-writer-wins, and the marker is a\n * first-writer-wins ADD. Re-opening an already-migrated doc reads the v2 marker\n * → the type is no longer `olderInDoc` → the runner skips it. The runner must\n * therefore run once per open against the open-time report (the caller re-gates\n * after it, never re-invokes it against the same report).\n */\nimport type { Component, Entity, World } from \"@vibecook/strata-ecs\";\nimport { defineQuery } from \"@vibecook/strata-ecs\";\nimport type { DurableStore } from \"@vibecook/strata-ecs/durable\";\nimport { dataPrefabFor, engineCatalogFor, widgetTypeFor } from \"../canvas/engine-catalog\";\nimport { PrefabId } from \"../schema/prefab\";\nimport type { DocVersionReport } from \"./version-gate\";\n\n/** Same reserved prefix as version-gate's markers (that module owns the read side). */\nconst PACK_PREFIX = \"engine.pack.\";\n\n/** What the runner needs: the doc store to write through, the world to read from. */\nexport interface MigrationCtx {\n readonly store: DurableStore;\n readonly world: World;\n}\n\nexport interface MigrationOutcome {\n /** Type ids whose entities were upgraded and whose v-local marker was stamped. */\n readonly migrated: string[];\n /** Type ids left as-is (no widget, no/gappy chain) — they stay read-only per the re-gate. */\n readonly skipped: string[];\n}\n\n// One durable-identity query, reused across opens (defineQuery interns; a module\n// singleton avoids re-defining per call).\nconst allDurableQ = defineQuery([PrefabId]);\n\ninterface EntityPlan {\n readonly e: Entity;\n /** The transform's absolute output — a flat prop record spanning every group. */\n readonly next: Record<string, unknown>;\n /** Component ids present on the entity NOW (edit vs add decision at write time). */\n readonly present: ReadonlySet<number>;\n}\n\ninterface TypePlan {\n readonly id: string;\n /** The cells a type's migration reads and writes: a widget's prop groups, a data prefab's essential components (D3t-a). */\n readonly components: readonly Component[];\n readonly localV: number;\n readonly plans: EntityPlan[];\n}\n\n/**\n * Run every applicable per-type migration against an ATTACHED doc. ALL types\n * are planned (read + transform-fold) BEFORE anything is written — a throwing\n * transform on the Nth type therefore aborts with the document untouched,\n * never with types 1..N-1 permanently migrated and the rest old (2026-07-13\n * review). Each type then writes one non-undoable transaction and stamps its\n * marker. Never throws for a merely-un-migratable type (missing widget /\n * gappy chain → skipped); a genuine fault (a throwing transform) propagates so\n * the caller can fall back read-only.\n */\nexport function runMigrations(ctx: MigrationCtx, report: DocVersionReport): MigrationOutcome {\n const { store, world } = ctx;\n const migrated: string[] = [];\n const skipped: string[] = [];\n\n // --- plan pass: every type's reads + chain folds, NO writes yet ---\n const typePlans: TypePlan[] = [];\n for (const id of report.olderInDoc) {\n // a widget migrates by its widget's chain over its prop groups; an object's DATA prefab (design-015 §5.1, D3t-a — the\n // board's strokes) by its own chain over its essential components\n const widget = widgetTypeFor(world, id) ?? engineCatalogFor(world)?.retiredWidget(id);\n const data = widget === undefined ? dataPrefabFor(world, id) : undefined;\n const chain = widget?.migrate ?? data?.migrate;\n if ((widget === undefined && data === 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 const components: readonly Component[] = widget !== undefined ? widget.groups.map((g) => g.component as Component) : (data?.components ?? []).map(([c]) => c);\n\n const docV = report.docPacks[id] ?? 1;\n const localV = report.localPacks[id] ?? widget?.version ?? data?.version ?? 1;\n\n // The chain must cover every step fromVersion docV..localV-1. A gap means we\n // cannot reach localV from docV safely — skip the whole type (stays read-only)\n // rather than half-apply. (defineWidget already warns at definition time.)\n let contiguous = true;\n for (let v = docV; v < localV; v++) {\n if (typeof chain[v] !== \"function\") {\n contiguous = false;\n break;\n }\n }\n if (!contiguous) {\n skipped.push(id);\n continue;\n }\n\n // Gather each entity's current props + fold the chain (transforms run HERE,\n // pre-write — their throws leave the doc byte-identical).\n const plans: EntityPlan[] = [];\n world.query(allDurableQ).each((batch) => {\n for (const row of batch) {\n const e = batch.entity(row);\n if (world.read(e, PrefabId).id !== id) continue;\n\n const prev: Record<string, unknown> = {};\n const present = new Set<number>();\n for (const c of components) {\n const val = world.get(e, c);\n if (val === undefined) continue; // an added-in-v2 group has no v1 cell — written fresh below\n present.add(c.id);\n Object.assign(prev, val as Record<string, unknown>);\n }\n\n let cur = prev;\n for (let v = docV; v < localV; v++) {\n const step = chain[v];\n if (typeof step === \"function\") cur = step(cur); // contiguity checked above\n }\n plans.push({ e, next: cur, present });\n }\n });\n typePlans.push({ id, components, localV, plans });\n }\n\n // --- write pass: per type, ONE non-undoable transaction of absolute per-group\n // writes. `edit().set` / `addComponent` canon the value against the group\n // schema, so a flat `next` spanning all groups is picked apart per group\n // (extra keys ignored, missing declared-default keys default-filled).\n for (const { id, components, localV, plans } of typePlans) {\n store.transaction(\n (tx) => {\n for (const { e, next, present } of plans) {\n for (const c of components) {\n if (present.has(c.id)) {\n tx.edit(e).set(c, next);\n } else {\n // Added-in-v2 group: structure rides projection at the next sync().\n tx.addComponent(e, c, next);\n }\n }\n }\n },\n { undoable: false },\n );\n\n // Stamp the reached version as a write-once marker (idempotent; first-writer-wins).\n store.metaTransaction((meta) => {\n const key = `${PACK_PREFIX}${id}.${localV}`;\n if (meta.get(key) === undefined) meta.set(key, true);\n });\n\n migrated.push(id);\n }\n\n return { migrated, skipped };\n}\n","/**\n * The per-cell gesture guard (design-001 §2 rule 4 + §3), as the engine's\n * live-write path. strata worlds can't intercept writes, so behaviors write\n * doc-SENSITIVE values through this facade:\n *\n * a world value-write to a cell that exists in the doc for that entity is\n * legal iff the entity is currently allowed to diverge — an Active\n * recognizer Captures/Drags it, or it carries a live TransformTween\n * (fly-back holds the claim; design-003 review M3).\n *\n * \"Cell in doc\" is approximated conservatively from public API: entity is\n * doc-bound (keyOf defined) AND the component is durable-eligible for its\n * prefab. Eligible-but-uncommitted optionals are guarded too (documented).\n * The divergence predicate is injected — M4 wires claims + tween; tests stub.\n */\nimport type { Component, Entity, World } from \"@vibecook/strata-ecs\";\nimport { PrefabId } from \"../schema/prefab\";\nimport { durablePrefabFor } from \"../canvas/engine-catalog\";\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 =\n typeof prefabId === \"string\" ? durablePrefabFor(world, prefabId) : undefined;\n if (!opts.cellInDoc && prefab === undefined) {\n // Fail CLOSED (review finding A5): a doc-bound entity whose prefab we\n // cannot resolve must not get free live writes — without eligibility\n // knowledge every write could be a doc cell. Wire `cellInDoc` (exact)\n // or ensure durable spawns stamp a registered PrefabId.\n throw new Error(\n `ice: live write to a doc-bound entity with no resolvable prefab (PrefabId=${String(prefabId)}) — the guard cannot determine cell sovereignty; wire cellInDoc or spawn via a registered prefab.`,\n );\n }\n const guardedCell = opts.cellInDoc\n ? opts.cellInDoc(e, component as Component)\n : (prefab?.eligible.has(component as Component) ?? false);\n if (guardedCell && !opts.mayDiverge(e)) {\n const name = String(prefabId);\n throw new Error(\n `ice: live write to a doc cell of \"${name}\" without a gesture claim — doc-sovereign values are written live only under an Active recognizer's Captures/Drags (or a TransformTween), then committed once at JustEnded (design-001 §3). Use a transaction for non-gesture edits.`,\n );\n }\n }\n world.edit(e).set(component, value);\n },\n };\n}\n","/**\n * The DEFAULT divergence predicate for the live-write guard (design-001 §3):\n * an entity's doc cells may diverge iff\n * - some recognizer in `GestureActive` currently `Captures` or `Drags` it, or\n * - it carries a live `TransformTween` (fly-back holds the claim after the\n * recognizer is reaped — design-003 review M3 / design-001 §3 amendment).\n *\n * This replaces the \"inject a stub\" posture (review finding A2): engines wire\n * `createLiveWriter(world, { keyOf, mayDiverge: makeDefaultMayDiverge(world), … })`\n * by default; tests and special hosts may still inject their own predicate.\n * Discrete claims (`GestureRecognized`) deliberately do NOT grant divergence —\n * design-001 §3 live-writes happen only under continuous Active gestures.\n *\n * The KEYBOARD is a continuous gesture too (design-015 §6.1, D2c): an object\n * carrying the runtime `Editing` rider is claimed by the one focused editor's\n * typing session, which live-writes its text and commits it once at the\n * session's end — a third SOURCE of the gesture claim, not a third kind of\n * grant (design-009 §3's divergence law stands: a claim or a tween).\n */\nimport type { Entity, World } from \"@vibecook/strata-ecs\";\nimport { Editing } from \"../catalog/desk\";\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 if (world.hasTag(e, Editing)) return true;\n for (const claimant of world.getReverse(e, Captures)) {\n if (world.hasTag(claimant, GestureActive)) return true;\n }\n for (const claimant of world.getReverse(e, Drags)) {\n if (world.hasTag(claimant, GestureActive)) return true;\n }\n return false;\n };\n}\n","/**\n * The document version gate (design-001 §6.1/§5.2, design-005 §6.3).\n *\n * Version state lives in the doc's reserved `meta` root map as WRITE-ONCE\n * MARKER KEYS — a monotone key SET, never a mutated cell (sidestepping\n * first-writer-wins): `engine.schema.<n>` and `engine.pack.<type>.<v>` are\n * presence markers. Reading needs no strata API: the gate reads\n * `doc.getMap(\"meta\")` on the RAW LoroDoc after import, BEFORE\n * `createDurableStore`/`attachDurable` — an incompatible doc never projects.\n *\n * Stamps go through `store.metaTransaction` (strata 0.4.0 — petition 3b\n * LANDED): the commit is properly tagged (peers no longer warn about an\n * untagged foreign writer), excluded from undo/redo, and invisible to\n * observers. Same underlying `meta` root map and raw keys as the pre-0.4.0\n * raw-doc stamps, so docs stamped by either path read identically here —\n * and importers also stopped warning about metadata-only commits from\n * before the API, so legacy docs are quiet too.\n *\n * M5 gate policy: exact schema + no doc-side pack NEWER than local ⇒ ok;\n * anything else ⇒ readOnly (or reject via policy). The migrate verdict (older\n * doc packs with a migrate chain) lands at M9 — the gate's verdict surface\n * already carries it so the facade policy hook is stable.\n */\nimport type { LoroDoc } from \"loro-crdt\";\nimport type { DurableStore } from \"@vibecook/strata-ecs/durable\";\nimport {\n DefaultCanvasType,\n ROOT_CANVAS_META_KEY,\n canvasIdentityOf,\n canvasPackId,\n encodeCanvasIdentity,\n parseCanvasIdentity,\n type CanvasTypeIdentity,\n} from \"../canvas/define-canvas-type\";\nimport { prefabs } from \"../schema/prefab\";\nimport { renames } from \"../widget/define-widget\";\nimport { ENGINE_SCHEMA_VERSION, type EnvelopeHeader } from \"./envelope\";\n\nconst SCHEMA_PREFIX = \"engine.schema.\";\nconst PACK_PREFIX = \"engine.pack.\";\n/** `engine.renamed.<oldId>` = \"<newId>\" — the rename tombstone (design-008 §4). */\nconst RENAMED_PREFIX = \"engine.renamed.\";\n\nexport interface DocVersionReport {\n /** Highest engine.schema.<n> marker present (0 = unstamped/pre-engine doc). */\n readonly docSchema: number;\n readonly localSchema: number;\n /** Highest engine.pack.<id>.<v> per prefab id present in the doc. */\n readonly docPacks: Readonly<Record<string, number>>;\n /** Local registry versions for DURABLE prefabs. */\n readonly localPacks: Readonly<Record<string, number>>;\n /** Prefab ids whose doc marker is NEWER than local (built by a newer app). */\n readonly newerInDoc: readonly string[];\n /** Prefab ids whose doc marker is OLDER than local (M9 migration input). */\n readonly olderInDoc: readonly string[];\n /**\n * Old ids with a REGISTERED rename, present in the doc and not yet\n * tombstoned → the doc pack version their markers carry (design-008 §4).\n * The rename runner's exact input; non-empty forces at least \"migrate\".\n * Meta has no delete, so a stale old marker without this classification\n * would brick the doc `readOnly` via `newerInDoc` — the I5 failure mode.\n */\n readonly renamedInDoc: Readonly<Record<string, number>>;\n /** Authoritative semantic identity for the document's BoardRoot. */\n readonly rootCanvas?: CanvasTypeIdentity;\n /** A schema-3 root invariant failure. It can never be overridden into writable. */\n readonly rootIssue?: string;\n /**\n * Missing exact semantic dependency markers for otherwise-current packs.\n * Evaluated only on a CURRENT-schema document — see {@link dependencyIssues}.\n */\n readonly dependencyIssues?: readonly string[];\n}\n\n/** Engine-scoped definition authority used by stamping and comparison. */\nexport interface DocVersionScope {\n /** Every pack/version this engine can understand while opening a document. */\n readonly localPacks: Readonly<Record<string, number>>;\n /** Exact capability manifest stamped on a newly created document. */\n readonly initialPacks?: Readonly<Record<string, number>>;\n readonly packDependencies?: Readonly<\n Record<string, Readonly<Record<string, number>>>\n >;\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(\n store: DurableStore,\n scope?: DocVersionScope,\n rootCanvas: CanvasTypeIdentity = canvasIdentityOf(DefaultCanvasType),\n): void {\n const initialPacks = scope?.initialPacks ?? scope?.localPacks ?? defaultPackVersions();\n const rootPack = canvasPackId(rootCanvas.id);\n if (initialPacks[rootPack] !== rootCanvas.semanticVersion) {\n throw new Error(\n `ice: new-document manifest does not include root CanvasType pack \"${rootPack}\"@${rootCanvas.semanticVersion}.`,\n );\n }\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 [id, version] of Object.entries(initialPacks)) {\n stamp(`${PACK_PREFIX}${id}.${version}`);\n }\n const encoded = encodeCanvasIdentity(rootCanvas);\n const existing = meta.get(ROOT_CANVAS_META_KEY);\n if (existing === undefined) {\n meta.set(ROOT_CANVAS_META_KEY, encoded);\n } else if (existing !== encoded) {\n throw new Error(\"ice: document root CanvasType identity is write-once and already differs.\");\n }\n });\n}\n\n/**\n * Fold raw doc-side pack versions through the rename layer (design-008 §4):\n * tombstoned old ids are DEAD HISTORY (meta cannot delete, so their markers\n * persist forever — skip them entirely); registered-rename old ids without a\n * tombstone alias their version onto the NEW id (`max` — the strongest\n * evidence wins) and land in `renamedInDoc` instead of `newerInDoc`.\n */\nfunction foldRenames(\n rawPacks: Readonly<Record<string, number>>,\n tombstoned: ReadonlySet<string>,\n): { docPacks: Record<string, number>; renamedInDoc: Record<string, number> } {\n const docPacks: Record<string, number> = {};\n const renamedInDoc: Record<string, number> = {};\n for (const [id, v] of Object.entries(rawPacks)) {\n if (tombstoned.has(id)) continue; // renamed away — the tombstone is doc-side truth\n const rename = renames.get(id);\n if (rename !== undefined) {\n renamedInDoc[id] = Math.max(renamedInDoc[id] ?? 0, v);\n const target = rename.widget.type;\n docPacks[target] = Math.max(docPacks[target] ?? 0, v);\n continue;\n }\n docPacks[id] = Math.max(docPacks[id] ?? 0, v);\n }\n return { docPacks, renamedInDoc };\n}\n\nfunction compare(\n docPacks: Readonly<Record<string, number>>,\n localPacks: Readonly<Record<string, number>>,\n): { newerInDoc: string[]; olderInDoc: string[] } {\n const newerInDoc: string[] = [];\n const olderInDoc: string[] = [];\n for (const [id, v] of Object.entries(docPacks)) {\n const local = localPacks[id];\n if (local === undefined || v > local) newerInDoc.push(id);\n else if (v < local) olderInDoc.push(id);\n }\n return { newerInDoc, olderInDoc };\n}\n\nfunction dependencyIssues(\n docSchema: number,\n docPacks: Readonly<Record<string, number>>,\n localPacks: Readonly<Record<string, number>>,\n dependencies: DocVersionScope[\"packDependencies\"],\n): string[] {\n if (dependencies === undefined) return [];\n // The compiled closure describes THIS schema's documents. A doc below the\n // local schema has not run its structural migrations yet, and those steps are\n // what install the markers the closure demands — schema-migrate's 2→3 step is\n // the SOLE writer of the root canvas marker every `defineContainer` prefab\n // depends on. Enforcing the closure here would decide `readOnly` before the\n // gate could ever say `migrate` (and `constrainSemanticVerdict` would clamp\n // an override), so the migration that clears the issue could never run. Same\n // principle as the per-owner skip below, one level up: historical closures\n // belong to historical migration code. The open path re-gates afterwards, so\n // a closure the migration could NOT satisfy still lands read-only.\n if (docSchema < ENGINE_SCHEMA_VERSION) return [];\n const issues: string[] = [];\n for (const [owner, required] of Object.entries(dependencies)) {\n // Historical dependency closures belong to historical migration code. We\n // can enforce the compiled closure only once the owner itself is current.\n if (docPacks[owner] === undefined || docPacks[owner] !== localPacks[owner]) continue;\n for (const [id, version] of Object.entries(required)) {\n if (docPacks[id] !== version) issues.push(`${owner} requires ${id}@${version}`);\n }\n }\n return issues.sort();\n}\n\nfunction defaultPackVersions(): Record<string, number> {\n const localPacks: Record<string, number> = {};\n for (const p of prefabs.all()) {\n if (p.store === \"durable\") localPacks[p.id] = p.version ?? 1;\n }\n localPacks[canvasPackId(DefaultCanvasType.id)] = DefaultCanvasType.semanticVersion;\n return localPacks;\n}\n\nfunction rootFields(\n docSchema: number,\n rawRoot: unknown,\n docPacks: Readonly<Record<string, number>>,\n localPacks: Readonly<Record<string, number>>,\n): Pick<DocVersionReport, \"rootCanvas\" | \"rootIssue\"> {\n const rootCanvas =\n typeof rawRoot === \"string\"\n ? parseCanvasIdentity(rawRoot)\n : rawRoot !== null && typeof rawRoot === \"object\"\n ? (rawRoot as CanvasTypeIdentity)\n : undefined;\n if (docSchema < 3) return rootCanvas === undefined ? {} : { rootCanvas };\n if (\n rootCanvas === undefined ||\n typeof rootCanvas.id !== \"string\" ||\n rootCanvas.id.length === 0 ||\n !Number.isSafeInteger(rootCanvas.semanticVersion) ||\n rootCanvas.semanticVersion < 1\n ) {\n return { rootIssue: `schema-${docSchema} document has missing or malformed ${ROOT_CANVAS_META_KEY}` };\n }\n const packId = canvasPackId(rootCanvas.id);\n if (docPacks[packId] !== rootCanvas.semanticVersion) {\n return {\n rootCanvas,\n rootIssue: `root CanvasType ${rootCanvas.id}@${rootCanvas.semanticVersion} has no exact document requirement`,\n };\n }\n const localVersion = localPacks[packId];\n if (localVersion === undefined || rootCanvas.semanticVersion > localVersion) {\n return {\n rootCanvas,\n rootIssue: `root CanvasType ${rootCanvas.id}@${rootCanvas.semanticVersion} is not available at a compatible semantic version in this engine`,\n };\n }\n return { rootCanvas };\n}\n\n/** Read the marker keys off a raw (imported, unattached) doc and compare. */\nexport function readDocVersionReport(doc: LoroDoc, scope?: DocVersionScope): DocVersionReport {\n const meta = doc.getMap(\"meta\");\n let docSchema = 0;\n const rawPacks: Record<string, number> = {};\n const tombstoned = new Set<string>();\n for (const key of meta.keys()) {\n if (key.startsWith(SCHEMA_PREFIX)) {\n const n = Number(key.slice(SCHEMA_PREFIX.length));\n if (Number.isInteger(n) && n > docSchema) docSchema = n;\n } else if (key.startsWith(RENAMED_PREFIX)) {\n tombstoned.add(key.slice(RENAMED_PREFIX.length));\n } else if (key.startsWith(PACK_PREFIX)) {\n const rest = key.slice(PACK_PREFIX.length);\n const dot = rest.lastIndexOf(\".\");\n if (dot <= 0) continue;\n const id = rest.slice(0, dot);\n const v = Number(rest.slice(dot + 1));\n if (!Number.isInteger(v)) continue;\n if ((rawPacks[id] ?? 0) < v) rawPacks[id] = v;\n }\n }\n\n const localPacks = { ...(scope?.localPacks ?? defaultPackVersions()) };\n const { docPacks, renamedInDoc } = foldRenames(rawPacks, tombstoned);\n const { newerInDoc, olderInDoc } = compare(docPacks, localPacks);\n const missingDependencies = dependencyIssues(\n docSchema,\n docPacks,\n localPacks,\n scope?.packDependencies,\n );\n const root = rootFields(docSchema, meta.get(ROOT_CANVAS_META_KEY), docPacks, localPacks);\n return {\n docSchema,\n localSchema: ENGINE_SCHEMA_VERSION,\n docPacks,\n localPacks,\n newerInDoc,\n olderInDoc,\n renamedInDoc,\n dependencyIssues: missingDependencies,\n ...root,\n };\n}\n\n/**\n * Build the same comparison report from an envelope header, before Loro\n * import. The header carries no meta, so no tombstone knowledge here —\n * registry aliasing only. This preflight is coarse by design; the\n * authoritative in-document gate re-runs right after import.\n */\nexport function readEnvelopeVersionReport(\n header: EnvelopeHeader,\n scope?: DocVersionScope,\n): DocVersionReport {\n const localPacks = { ...(scope?.localPacks ?? defaultPackVersions()) };\n const { docPacks, renamedInDoc } = foldRenames(header.prefabVersions, new Set());\n const { newerInDoc, olderInDoc } = compare(docPacks, localPacks);\n const missingDependencies = dependencyIssues(\n header.engineSchema,\n docPacks,\n localPacks,\n scope?.packDependencies,\n );\n const root = rootFields(header.engineSchema, header.rootCanvas, docPacks, localPacks);\n return {\n docSchema: header.engineSchema,\n localSchema: ENGINE_SCHEMA_VERSION,\n docPacks,\n localPacks,\n newerInDoc,\n olderInDoc,\n renamedInDoc,\n dependencyIssues: missingDependencies,\n ...root,\n };\n}\n\n/** The default M5 policy. A facade policy hook may override (design-005 §6.3). */\nexport function gateVerdict(report: DocVersionReport): GateVerdict {\n if (report.docSchema === 0) return \"reject\"; // not an engine doc (or pre-stamp corruption)\n if (report.docSchema > report.localSchema) return \"readOnly\"; // newer app wrote it\n if (report.rootIssue !== undefined) return \"readOnly\";\n // Both semantic bars sit ABOVE the migrate branch, so both are meaningful\n // only on a current-schema doc — which is exactly where `rootFields` and\n // `dependencyIssues` raise them. A below-current doc reaches `migrate` and\n // is re-gated against these bars after its structural chain has run.\n if ((report.dependencyIssues?.length ?? 0) > 0) return \"readOnly\";\n if (report.newerInDoc.length > 0) return \"readOnly\";\n if (\n report.docSchema < report.localSchema ||\n report.olderInDoc.length > 0 ||\n Object.keys(report.renamedInDoc).length > 0 // design-008: pending renames fold at open\n ) {\n return \"migrate\"; // M9 runs the chain; M5 treats as readOnly downstream\n }\n return \"ok\";\n}\n","/**\n * The doc kit core — create/open/close on ONE world (design-001 §6, design-005\n * §6.1–§6.3; the engine.docs.* facade sugar lands at M10).\n *\n * - create: new LoroDoc → engine.* meta stamps (write-once markers, meta\n * origin — excluded from undo like the docId) → createDurableStore →\n * attachDurable → selection history hooks → doc-backed CommitSink.\n * - open: decode envelope (BEFORE any import) → import into a raw doc → read\n * the marker keys pre-attach → gate verdict → attach read-write, attach\n * read-only (tx path swapped for the warn-and-drop sink), or reject.\n * Corrupt/incompatible bytes NEVER throw out of open — quarantine is a\n * return value (the autosave kit and boot paths must not brick).\n * - close: cancelActiveGestures → detach → in-place world.reset (observers\n * and systems survive — R3) → respawn the canvas-surface anchor. Undo\n * stack, baseline, and held-cell ledger die with the attachment by\n * construction. Switching docs = close() then create/open the next.\n *\n * Selection history hooks (design-001 §12 / M5 exit \"undo restores\n * selection\"): capture = the Selected set as durable EntityKeys (stable across\n * peers and restarts); restore = resolve keys → setSelection. Runtime-only\n * selections (never-committed drafts) are skipped by construction.\n */\nimport { LoroDoc } from \"loro-crdt\";\nimport type { Entity, World } from \"@vibecook/strata-ecs\";\nimport { attachDurable, createDurableStore } from \"@vibecook/strata-ecs/durable\";\nimport type { Attachment, DurableStore } from \"@vibecook/strata-ecs/durable\";\nimport {\n DefaultCanvasType,\n canvasIdentityOf,\n sameCanvasIdentity,\n type CanvasTypeIdentity,\n} from \"../canvas/define-canvas-type\";\nimport type { EngineCatalog } from \"../canvas/engine-catalog\";\nimport { runCanvasSemanticMigrations } from \"../canvas/migrate\";\nimport { Selected } from \"../catalog\";\nimport type { CommitIntent, CommitSink } from \"../engine/commit-sink\";\nimport { ensureCanvasSurface } from \"../interaction/install\";\nimport { ensureTray } from \"../ops/tray\";\nimport { cancelActiveGestures } from \"../ops/gestures\";\nimport { selectedEntities, setSelection } from \"../ops/selection\";\nimport {\n EnvelopeError,\n decodeEnvelope,\n encodeEnvelope,\n type EnvelopeHeader,\n} from \"./envelope\";\nimport { type CommitExtender, createDocCommitSink, createReadOnlyCommitSink } from \"./doc-commit-sink\";\nimport { runMigrations } from \"./migrate\";\nimport { runRenames } from \"./rename\";\nimport { armRenameSweep } from \"./rename-sweep\";\nimport { ensureBoardRoot, resolveBoardRoot, runSchemaMigrations } from \"./schema-migrate\";\nimport { BoardRoot } from \"../catalog/scene\";\nimport { writeRuntimeResource } from \"../guards/resource-writer\";\nimport { createLiveWriter, type LiveWriter } from \"../guards/live-writer\";\nimport { makeDefaultMayDiverge } from \"../ops/claims\";\nimport {\n gateVerdict,\n readEnvelopeVersionReport,\n readDocVersionReport,\n stampEngineMeta,\n type DocVersionScope,\n type DocVersionReport,\n type GateVerdict,\n} from \"./version-gate\";\n\nexport interface DocSessionOpts {\n readonly maxUndoSteps?: number;\n /** Override the default gate policy (design-005 §6.3 facade hook). */\n readonly onGate?: (report: DocVersionReport, verdict: GateVerdict) => GateVerdict;\n /**\n * Run the M9 read-repair migrator on a \"migrate\" verdict (design-005 §6.4).\n * Default TRUE: the doc attaches writable, the migrator upgrades older packs\n * in place, and the session re-gates. Set false to keep M5 behavior (a\n * \"migrate\" verdict attaches read-only, no upgrade).\n */\n readonly migrate?: boolean;\n /** Low-level engine-scoped pack authority; the facade always supplies this. */\n readonly versionScope?: DocVersionScope;\n /** New-document identity only. Existing documents always use their stored value. */\n readonly rootCanvas?: CanvasTypeIdentity;\n /** Engine-owned final mutation guard; low-level unscoped sessions may omit it. */\n readonly commitGuard?: (intent: CommitIntent) => CommitIntent | undefined;\n /** The layers' word on a gesture's landing, inside its transaction (the facade fans its registered extenders through this). */\n readonly commitExtend?: CommitExtender;\n /** Engine-scoped CanvasType definitions used by solo semantic migration. */\n readonly canvasCatalog?: EngineCatalog;\n}\n\nexport interface DocSession {\n readonly store: DurableStore;\n readonly sink: CommitSink;\n /**\n * The strata attachment — a read-only INSPECTION seam: its `baseline` feeds\n * the observer devtools' durable tab (runtime-vs-baseline = the un-agreed\n * sync delta). Never a sync path; `close()` owns its lifecycle.\n */\n readonly attachment: Attachment;\n readonly readOnly: boolean;\n /** Authoritative stored root identity, absent only for malformed legacy/read-only data. */\n readonly rootCanvas?: CanvasTypeIdentity;\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 /** Re-read current monotone requirements after remote/capability changes. */\n versionReport(): DocVersionReport;\n /** Solo/local capability grant: requirement markers land before any content. */\n upgradePacks(packs: Readonly<Record<string, number>>): boolean;\n /** Envelope-framed snapshot for storage (autosave kit consumes this). */\n exportEnvelope(savedAt?: number): Uint8Array;\n /** Relay passthroughs (M5 dumb relay; M9 brings the bootstrap protocol). */\n exportSnapshot(): Uint8Array;\n applyRemote(bytes: Uint8Array): void;\n /**\n * Fires after each successful `applyRemote` on THIS session (strata's\n * `subscribeOutbound` is local-commits-only by design, so remote imports are\n * otherwise unobservable). Autosave rides this so a peer's local backup\n * reflects the last-seen document, not just what it authored (2026-07-13\n * review). A transport writing through `store.applyRemote` directly bypasses\n * it — engine paths (bootstrap, broadcast relay) all go through the session.\n */\n subscribeRemote(fn: (bytes: Uint8Array) => void): () => void;\n /** cancel gestures → detach → world reset in place → respawn the anchor. */\n close(): void;\n}\n\nexport type OpenDocResult =\n | { readonly ok: true; readonly session: DocSession }\n | { readonly ok: false; readonly reason: string; readonly report?: DocVersionReport };\n\nconst constrainSemanticVerdict = (\n report: DocVersionReport,\n verdict: GateVerdict,\n): GateVerdict =>\n (report.rootIssue !== undefined || (report.dependencyIssues?.length ?? 0) > 0) &&\n verdict !== \"reject\"\n ? \"readOnly\"\n : verdict;\n\n/**\n * WHICH SESSION A WORLD IS PROJECTING (D-C4.14). A world has one binding, but\n * strata's double-attach guard is per STORE, not per world — attaching a second\n * session to the same world does NOT throw, it silently supersedes the first.\n * The superseded session then still holds a live handle, and its `close()`\n * ends in `world.reset()`: it would wipe the NEWER document's entities and\n * every resource on the world.\n *\n * So the reset is the OWNER's. Every session records itself here when it\n * attaches, and `close()` resets only while the world still points at it; a\n * superseded session tears down its own binding and nothing else. Keyed weakly\n * so a discarded world is collectable.\n */\nconst worldOwner = new WeakMap<World, symbol>();\n\nfunction makeSession(\n world: World,\n doc: LoroDoc,\n store: DurableStore,\n attachment: Attachment,\n readOnly: boolean,\n versionScope: DocVersionScope | undefined,\n commitGuard: DocSessionOpts[\"commitGuard\"],\n commitExtend: DocSessionOpts[\"commitExtend\"],\n report?: DocVersionReport,\n): DocSession {\n // Claimed at construction — `makeSession` is the one choke point both\n // `createDocSession` and `openDocSession` pass through, immediately after\n // their `attachDurable`, so the token and the live binding move together.\n const ownership = Symbol(\"ice:doc-session\");\n worldOwner.set(world, ownership);\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\n ? createReadOnlyCommitSink()\n : createDocCommitSink(store, world, {\n ...(commitGuard === undefined ? {} : { guard: commitGuard }),\n ...(commitExtend === undefined ? {} : { extend: commitExtend }),\n });\n const liveWriter = createLiveWriter(world, {\n keyOf: (e) => store.keyOf(e),\n mayDiverge: makeDefaultMayDiverge(world),\n cellInDoc: (e, c) => store.getComponent(e, c) !== undefined,\n });\n // The rename zombie sweep (design-008 §6): writable sessions fold stale\n // pre-rename deliveries between frames; read-only sessions never write, so\n // their zombies stay visible-but-inert until a writable open folds them.\n const disarmRenameSweep = readOnly ? undefined : armRenameSweep(world, store);\n let closed = false;\n const remoteSubs = new Set<(bytes: Uint8Array) => void>();\n let currentVersionReport = report ?? readDocVersionReport(doc, versionScope);\n\n return {\n store,\n sink,\n attachment,\n readOnly,\n liveWriter,\n ...(currentVersionReport.rootCanvas === undefined\n ? {}\n : { rootCanvas: currentVersionReport.rootCanvas }),\n ...(report !== undefined ? { report } : {}),\n versionReport: () => currentVersionReport,\n upgradePacks(packs) {\n if (closed || readOnly || gateVerdict(currentVersionReport) !== \"ok\") {\n throw new Error(\"ice: cannot upgrade capabilities on a closed or read-only document.\");\n }\n const additions: Array<readonly [string, number]> = [];\n for (const [id, version] of Object.entries(packs)) {\n if (!Number.isSafeInteger(version) || version < 1) {\n throw new Error(`ice: invalid capability pack version for \"${id}\".`);\n }\n if (currentVersionReport.localPacks[id] !== version) {\n throw new Error(`ice: capability pack \"${id}\"@${version} is not compiled by this engine.`);\n }\n const existing = currentVersionReport.docPacks[id];\n if (existing === undefined) additions.push([id, version]);\n else if (existing !== version) {\n throw new Error(\n `ice: capability pack \"${id}\" already has version ${existing}; semantic upgrades require migration.`,\n );\n }\n }\n if (additions.length === 0) return false;\n store.metaTransaction((meta) => {\n for (const [id, version] of additions) {\n const key = `engine.pack.${id}.${version}`;\n if (meta.get(key) === undefined) meta.set(key, true);\n }\n });\n currentVersionReport = readDocVersionReport(doc, versionScope);\n if (gateVerdict(currentVersionReport) !== \"ok\") {\n throw new Error(\"ice: capability upgrade left the document gate non-writable.\");\n }\n return true;\n },\n exportEnvelope(savedAt) {\n const current = readDocVersionReport(doc, versionScope);\n currentVersionReport = current;\n const header: EnvelopeHeader = {\n engineSchema: current.docSchema,\n prefabVersions: current.docPacks,\n ...(current.rootCanvas === undefined ? {} : { rootCanvas: current.rootCanvas }),\n ...(savedAt !== undefined ? { savedAt } : {}),\n };\n return encodeEnvelope(header, store.exportSnapshot());\n },\n exportSnapshot: () => store.exportSnapshot(),\n applyRemote(bytes) {\n if (closed) throw new Error(\"ice: cannot apply a remote update to a closed document\");\n store.applyRemote(bytes); // a throw (PendingImportError et al.) skips notification\n currentVersionReport = readDocVersionReport(doc, versionScope);\n for (const fn of [...remoteSubs]) fn(bytes);\n },\n subscribeRemote(fn) {\n remoteSubs.add(fn);\n return () => remoteSubs.delete(fn);\n },\n close() {\n if (closed) return;\n closed = true;\n // Does the world still point at THIS session (D-C4.14)? Read it before\n // anything runs; a superseded session owns its own teardown and nothing\n // on the world. Nothing below can change the answer.\n const owns = worldOwner.get(world) === ownership;\n disarmRenameSweep?.();\n if (owns) {\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 }\n store.setHistoryHooks(null);\n remoteSubs.clear();\n attachment.detach();\n // The reset is the OWNER's: for a superseded session it would destroy the\n // entities and resources of whatever document attached after it.\n if (!owns) return;\n worldOwner.delete(world);\n world.reset(); // in place: observers/systems survive (R3); entities die\n ensureCanvasSurface(world); // the interaction stack's anchor must exist again\n ensureTray(world); // …and the view's tray (closed: a document switch closes the drawer — design-017 §2)\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 const rootCanvas = opts.rootCanvas ?? canvasIdentityOf(DefaultCanvasType);\n stampEngineMeta(store, opts.versionScope, rootCanvas);\n const attachment = attachDurable(world, store);\n // Petition 8: every schema-2 doc carries a board root from birth — root-level widgets hang\n // their ordered ChildOf edges on it. Runtime resource names it for the ops/renderers.\n const root = ensureBoardRoot(world, store);\n writeRuntimeResource(world, BoardRoot, { root });\n const report = readDocVersionReport(doc, opts.versionScope);\n return makeSession(\n world,\n doc,\n store,\n attachment,\n false,\n opts.versionScope,\n opts.commitGuard,\n opts.commitExtend,\n report,\n );\n}\n\n/** Open an envelope: gate BEFORE attach; quarantine is a return value, never a throw. */\nexport function openDocSession(world: World, bytes: Uint8Array, opts: DocSessionOpts = {}): OpenDocResult {\n let payload: Uint8Array;\n let envelopeReport: DocVersionReport;\n let header: EnvelopeHeader;\n try {\n const decoded = decodeEnvelope(bytes);\n payload = decoded.payload;\n header = decoded.header;\n envelopeReport = readEnvelopeVersionReport(header, opts.versionScope);\n } catch (err) {\n const reason = err instanceof EnvelopeError ? err.message : String(err);\n return { ok: false, reason };\n }\n\n // Coarse gate before the WASM import. The in-document markers are still\n // authoritative and are checked again below; this fast path prevents a\n // policy-rejected future envelope from reaching Loro at all.\n try {\n const requested = (opts.onGate ?? ((_, v) => v))(\n envelopeReport,\n gateVerdict(envelopeReport),\n );\n const preflight = constrainSemanticVerdict(envelopeReport, requested);\n if (preflight === \"reject\") {\n return { ok: false, reason: \"ice: version gate rejected the envelope\", report: envelopeReport };\n }\n } catch (err) {\n return { ok: false, reason: `ice: onGate callback threw during envelope preflight — ${String(err)}`, report: envelopeReport };\n }\n\n const doc = new LoroDoc();\n let attachment: Attachment | undefined;\n try {\n doc.import(payload);\n } catch (err) {\n return { ok: false, reason: `ice: payload import failed — ${String(err)}` };\n }\n\n const rawReport = readDocVersionReport(doc, opts.versionScope);\n // The header mirror is OPTIONAL and coarse (envelope.ts:31, design-011 §13.2:\n // \"in-document metadata remains authoritative … older envelopes without the\n // field remain readable\"). Only a mirror that is PRESENT can disagree —\n // reading its absence as disagreement gave every hand-rolled envelope, and\n // every pre-mirror one, a permanent unoverridable rootIssue (no migrate path\n // clears it and `constrainSemanticVerdict` blocks the override).\n const mirrorDisagrees =\n header.rootCanvas !== undefined &&\n !sameCanvasIdentity(header.rootCanvas, rawReport.rootCanvas);\n const report: DocVersionReport =\n rawReport.docSchema >= 3 && mirrorDisagrees\n ? {\n ...rawReport,\n rootIssue:\n rawReport.rootIssue ??\n \"envelope rootCanvas does not agree with authoritative document metadata\",\n }\n : rawReport;\n let verdict: ReturnType<typeof gateVerdict>;\n try {\n const requested = (opts.onGate ?? ((_, v) => v))(report, gateVerdict(report));\n verdict = constrainSemanticVerdict(report, requested);\n } catch (err) {\n // A throwing policy callback must not break open()'s no-throw contract —\n // during network bootstrap it would escape an inbound channel callback and\n // leave the join promise pending forever. Quarantine instead.\n return { ok: false, reason: `ice: onGate callback threw — ${String(err)}`, report };\n }\n if (verdict === \"reject\") {\n return { ok: false, reason: \"ice: version gate rejected the document\", report };\n }\n\n try {\n const store = createDurableStore(\n doc,\n opts.maxUndoSteps !== undefined ? { maxUndoSteps: opts.maxUndoSteps } : undefined,\n );\n attachment = attachDurable(world, store);\n\n // M9 (design-005 §6.4): the \"migrate\" verdict upgrades in place. Attach is\n // identical either way — readOnly is an engine concept (the commit sink), and\n // the migrator writes through store.transaction directly — so we run it on the\n // live attachment, then RE-GATE off the freshly stamped markers. A migrate that\n // catches the doc fully up flips the session writable; one that could not\n // upgrade every older pack (a type with no/gappy chain) stays read-only. Opt\n // out with opts.migrate=false (then \"migrate\" keeps M5's read-only behavior).\n let effectiveReport = report;\n let readOnly = verdict !== \"ok\";\n if (verdict === \"migrate\" && (opts.migrate ?? true)) {\n try {\n // Petition 8: STRUCTURAL schema steps run FIRST (they may spawn the board root and\n // rewrite relations the pack runner's entities already carry), then RENAMES\n // (design-008 §5 — type folds must precede the pack runner so version chains\n // operate on new-name cells; schema steps touch no pack markers, so the original\n // report's renamedInDoc is still exact), then the per-prefab pack runner, then ONE\n // re-gate off the freshly stamped markers. SINGLE-WRITER LAW: this branch is the\n // solo-open path only — a live-room joiner passes migrate:false (bootstrap) and\n // stays read-only on an old-schema doc.\n runSchemaMigrations({ store, world }, report);\n const renamed = runRenames({ store, world }, report);\n // A rename WRITES cells the pack runner READS through the world, and\n // local transactions project only at the next sync — without this\n // drain the chain would fold an empty record (the runners before it\n // never had a write→read dependency, so this is the first sync the\n // open path needs).\n if (renamed.renamed.length > 0) world.sync();\n runMigrations({ store, world }, readDocVersionReport(doc, opts.versionScope));\n world.sync();\n if (opts.canvasCatalog !== undefined) {\n const migrationRoot = resolveBoardRoot(world, store);\n if (migrationRoot !== undefined) {\n writeRuntimeResource(world, BoardRoot, { root: migrationRoot });\n }\n runCanvasSemanticMigrations(\n store,\n world,\n opts.canvasCatalog,\n readDocVersionReport(doc, opts.versionScope),\n );\n }\n effectiveReport = readDocVersionReport(doc, opts.versionScope);\n readOnly = gateVerdict(effectiveReport) !== \"ok\";\n } catch {\n // A faulting transform must never brick open(): keep the doc, fall back\n // read-only (the user still gets projection + presence). Re-read the\n // report — runMigrations plans all types before writing, so a transform\n // throw leaves the doc untouched, but a write-phase fault may have\n // stamped earlier types; session.report must describe the doc AS IS.\n effectiveReport = readDocVersionReport(doc, opts.versionScope);\n readOnly = true;\n }\n }\n // Petition 8: name the board root for ops/renderers when the doc has one (any schema-2\n // doc). Absent on a pre-schema-2 read-only doc — renderers fall back to the legacy\n // StackZ sort; never minted here on the read-only path (minting is a write).\n if (readOnly) {\n const root = resolveBoardRoot(world, store);\n if (root !== undefined) writeRuntimeResource(world, BoardRoot, { root });\n } else {\n writeRuntimeResource(world, BoardRoot, { root: ensureBoardRoot(world, store) });\n }\n return {\n ok: true,\n session: makeSession(\n world,\n doc,\n store,\n attachment,\n readOnly,\n opts.versionScope,\n opts.commitGuard,\n opts.commitExtend,\n effectiveReport,\n ),\n };\n } catch (err) {\n // Store/attach residuals (already-attached world, pending-import state,\n // mid-emit) quarantine like everything else on this path — open() NEVER\n // throws (review hardening; the corrupt-bytes exit bar extended to attach).\n try {\n attachment?.detach();\n world.reset();\n ensureCanvasSurface(world);\n ensureTray(world);\n } catch (rollbackErr) {\n return {\n ok: false,\n reason: `ice: attach failed — ${String(err)}; rollback failed — ${String(rollbackErr)}`,\n report,\n };\n }\n return { ok: false, reason: `ice: attach failed — ${String(err)}`, report };\n }\n}\n","/** CanvasType semantic migrations — bounded, frame-scoped, and view-independent. */\nimport {\n defineQuery,\n valueEquals,\n type Component,\n type Entity,\n type Relation,\n type Resource,\n type Tag,\n type World,\n} from \"@vibecook/strata-ecs\";\nimport type { DurableStore } from \"@vibecook/strata-ecs/durable\";\nimport { BoardRoot, ChildOf } from \"../catalog/scene\";\nimport { guardedTransaction } from \"../guards/guarded-tx\";\nimport { PrefabId } from \"../schema/prefab\";\nimport { schemaMeta } from \"../schema/meta\";\nimport type { DocVersionReport } from \"../doc/version-gate\";\nimport {\n ROOT_CANVAS_META_KEY,\n canvasPackId,\n encodeCanvasIdentity,\n type CanvasType,\n} from \"./define-canvas-type\";\nimport type { EngineCatalog } from \"./engine-catalog\";\nimport {\n frameBehaviorPackId,\n type CanvasReadFacet,\n type CanvasSemanticMigration,\n} from \"./extensions\";\n\nconst PACK_PREFIX = \"engine.pack.\";\nconst durableQ = defineQuery([PrefabId]);\n\ntype MigrationOp =\n | { readonly kind: \"set\"; readonly entity: Entity; readonly component: Component; readonly value: unknown }\n | { readonly kind: \"remove\"; readonly entity: Entity; readonly component: Component }\n | { readonly kind: \"set-relation\"; readonly entity: Entity; readonly relation: Relation; readonly target: Entity }\n | { readonly kind: \"remove-relation\"; readonly entity: Entity; readonly relation: Relation; readonly target?: Entity };\n\nfunction partitionFacets(facets: readonly CanvasReadFacet[]): {\n components: Set<Component>;\n tags: Set<Tag>;\n relations: Set<Relation>;\n resources: Set<Resource>;\n} {\n const components = new Set<Component>();\n const tags = new Set<Tag>();\n const relations = new Set<Relation>();\n const resources = new Set<Resource>();\n for (const facet of facets) {\n if (schemaMeta.component(facet as Component) !== undefined) components.add(facet as Component);\n else if (schemaMeta.tagName(facet as Tag) !== undefined) tags.add(facet as Tag);\n else if (schemaMeta.relation(facet as Relation) !== undefined) relations.add(facet as Relation);\n else if (schemaMeta.resource(facet as Resource) !== undefined) resources.add(facet as Resource);\n }\n return { components, tags, relations, resources };\n}\n\nfunction framesFor(\n store: DurableStore,\n world: World,\n catalog: EngineCatalog,\n report: DocVersionReport,\n canvas: CanvasType,\n): Entity[] {\n const frames: Entity[] = [];\n const root = world.getResource(BoardRoot)?.root;\n if (root !== undefined && report.rootCanvas?.id === canvas.id) frames.push(root);\n // Migrations are solo-open, one-shot work; a full durable walk here is\n // deliberately outside every steady-state path.\n world.query(durableQ).each((batch) => {\n for (const row of batch) {\n const entity = batch.entity(row);\n const typeId = world.read(entity, PrefabId).id;\n if (\n typeof typeId === \"string\" &&\n catalog.widget(typeId)?.container?.canvasTypeId === canvas.id\n ) {\n frames.push(entity);\n }\n }\n });\n const unique = [...new Set(frames)];\n unique.sort((a, b) => {\n const ka = String(store.keyOf(a) ?? a);\n const kb = String(store.keyOf(b) ?? b);\n return ka.localeCompare(kb);\n });\n return unique;\n}\n\nfunction validFrame(world: World, catalog: EngineCatalog, entity: Entity): boolean {\n const root = world.getResource(BoardRoot)?.root;\n if (entity === root) return true;\n const typeId = world.get(entity, PrefabId)?.id;\n return typeof typeId === \"string\" && catalog.widget(typeId)?.container !== undefined;\n}\n\nfunction planFrame(\n world: World,\n catalog: EngineCatalog,\n canvas: CanvasType,\n migration: CanvasSemanticMigration,\n frame: Entity,\n): MigrationOp[] {\n const children = world\n .getReverse(frame, ChildOf)\n .filter((entity) => world.isAlive(entity) && world.get(entity, PrefabId) !== undefined);\n const scope = new Set<Entity>([frame, ...children]);\n const reads = partitionFacets(migration.reads ?? []);\n const writeComponents = new Set<Component>();\n const writeRelations = new Set<Relation>();\n for (const output of migration.writes ?? []) {\n if (schemaMeta.component(output as Component) !== undefined) writeComponents.add(output as Component);\n else if (schemaMeta.relation(output as Relation) !== undefined) writeRelations.add(output as Relation);\n }\n const ops: MigrationOp[] = [];\n const assertScoped = (entity: Entity): void => {\n if (!scope.has(entity) || !world.isAlive(entity)) {\n throw new Error(\n `ice: CanvasType \"${canvas.id}\" migration addressed an entity outside its direct frame scope.`,\n );\n }\n };\n const assertComponentRead = (component: Component): void => {\n if (!reads.components.has(component)) {\n throw new Error(`ice: CanvasType \"${canvas.id}\" migration read an undeclared component.`);\n }\n };\n const assertRelationRead = (relation: Relation): void => {\n if (!reads.relations.has(relation)) {\n throw new Error(`ice: CanvasType \"${canvas.id}\" migration read an undeclared relation.`);\n }\n };\n migration.migrate({\n canvasTypeId: canvas.id,\n from: migration.from,\n to: migration.to,\n frame,\n children: Object.freeze([...children]),\n read(entity, component) {\n assertScoped(entity);\n assertComponentRead(component);\n return world.read(entity, component);\n },\n get(entity, component) {\n assertScoped(entity);\n assertComponentRead(component);\n return world.get(entity, component);\n },\n hasTag(entity, tag) {\n assertScoped(entity);\n if (!reads.tags.has(tag)) {\n throw new Error(`ice: CanvasType \"${canvas.id}\" migration read an undeclared tag.`);\n }\n return world.hasTag(entity, tag);\n },\n getRelation(entity, relation) {\n assertScoped(entity);\n assertRelationRead(relation);\n const target = world.getRelation(entity, relation);\n return target !== undefined && scope.has(target) ? target : undefined;\n },\n getRelations(entity, relation) {\n assertScoped(entity);\n assertRelationRead(relation);\n return world.getRelations(entity, relation).filter((target) => scope.has(target));\n },\n getReverse(entity, relation) {\n assertScoped(entity);\n assertRelationRead(relation);\n return world.getReverse(entity, relation).filter((source) => scope.has(source));\n },\n getResource(resource) {\n if (!reads.resources.has(resource)) {\n throw new Error(`ice: CanvasType \"${canvas.id}\" migration read an undeclared resource.`);\n }\n return world.getResource(resource);\n },\n set(entity, component, value) {\n assertScoped(entity);\n if (entity === world.getResource(BoardRoot)?.root) {\n throw new Error(\"ice: CanvasType migrations cannot add mutable settings to BoardRoot.\");\n }\n if (!writeComponents.has(component)) {\n throw new Error(`ice: CanvasType \"${canvas.id}\" migration wrote an undeclared component.`);\n }\n ops.push({ kind: \"set\", entity, component, value });\n },\n remove(entity, component) {\n assertScoped(entity);\n if (!writeComponents.has(component)) {\n throw new Error(`ice: CanvasType \"${canvas.id}\" migration removed an undeclared component.`);\n }\n ops.push({ kind: \"remove\", entity, component });\n },\n setRelation(entity, relation, target) {\n assertScoped(entity);\n if (!scope.has(target) || !writeRelations.has(relation)) {\n throw new Error(`ice: CanvasType \"${canvas.id}\" migration wrote an undeclared/cross-frame relation.`);\n }\n ops.push({ kind: \"set-relation\", entity, relation, target });\n },\n removeRelation(entity, relation, target) {\n assertScoped(entity);\n if (!writeRelations.has(relation) || (target !== undefined && !scope.has(target))) {\n throw new Error(`ice: CanvasType \"${canvas.id}\" migration removed an undeclared/cross-frame relation.`);\n }\n ops.push({ kind: \"remove-relation\", entity, relation, ...(target === undefined ? {} : { target }) });\n },\n reparent(entity, targetFrame) {\n assertScoped(entity);\n if (!writeRelations.has(ChildOf) || !world.isAlive(targetFrame) || !validFrame(world, catalog, targetFrame)) {\n throw new Error(`ice: CanvasType \"${canvas.id}\" migration attempted an undeclared/invalid frame repair.`);\n }\n ops.push({ kind: \"set-relation\", entity, relation: ChildOf, target: targetFrame });\n },\n });\n return ops;\n}\n\nfunction applyOps(store: DurableStore, world: World, ops: readonly MigrationOp[]): void {\n guardedTransaction(\n store,\n world,\n (tx) => {\n for (const op of ops) {\n switch (op.kind) {\n case \"set\": {\n const current = world.get(op.entity, op.component);\n if (current !== undefined && valueEquals(op.component, current, op.value)) break;\n if (current === undefined) tx.addComponent(op.entity, op.component, op.value);\n else tx.edit(op.entity).set(op.component, op.value);\n break;\n }\n case \"remove\":\n if (world.has(op.entity, op.component)) tx.removeComponent(op.entity, op.component);\n break;\n case \"set-relation\":\n if (world.getRelation(op.entity, op.relation) !== op.target) {\n tx.setRelation(op.entity, op.relation, op.target);\n }\n break;\n case \"remove-relation\":\n if (\n op.target === undefined\n ? world.getRelation(op.entity, op.relation) !== undefined\n : world.getRelations(op.entity, op.relation).includes(op.target)\n ) {\n tx.removeRelation(op.entity, op.relation, op.target);\n }\n break;\n }\n }\n },\n { undoable: false, meta: { origin: \"canvas-migration\" } },\n );\n}\n\nexport interface CanvasMigrationOutcome {\n readonly migrated: readonly string[];\n readonly skipped: readonly string[];\n}\n\n/**\n * Run semantic steps after structural/prefab normalization. Each step plans\n * every bound frame before writing, then stamps its reached version last.\n */\nexport function runCanvasSemanticMigrations(\n store: DurableStore,\n world: World,\n catalog: EngineCatalog,\n initialReport: DocVersionReport,\n): CanvasMigrationOutcome {\n const migrated: string[] = [];\n const skipped: string[] = [];\n let report = initialReport;\n\n for (const canvas of catalog.canvasTypeDefs()) {\n const packId = canvasPackId(canvas.id);\n let version = report.docPacks[packId];\n if (version === undefined || version >= canvas.semanticVersion) continue;\n const byFrom = new Map((canvas.migrations ?? []).map((step) => [step.from, step] as const));\n let contiguous = true;\n for (let cursor = version; cursor < canvas.semanticVersion; cursor++) {\n if (byFrom.get(cursor)?.to !== cursor + 1) {\n contiguous = false;\n break;\n }\n }\n if (!contiguous) {\n skipped.push(canvas.id);\n continue;\n }\n\n while (version < canvas.semanticVersion) {\n const migration = byFrom.get(version) as CanvasSemanticMigration;\n world.sync();\n const frames = framesFor(store, world, catalog, report, canvas);\n const ops = frames.flatMap((frame) => planFrame(world, catalog, canvas, migration, frame));\n applyOps(store, world, ops);\n world.sync();\n\n const reached = migration.to;\n store.metaTransaction((meta) => {\n const marker = `${PACK_PREFIX}${packId}.${reached}`;\n if (meta.get(marker) === undefined) meta.set(marker, true);\n if (report.rootCanvas?.id === canvas.id) {\n meta.set(\n ROOT_CANVAS_META_KEY,\n encodeCanvasIdentity({ id: canvas.id, semanticVersion: reached }),\n );\n }\n if (reached === canvas.semanticVersion) {\n for (const behavior of catalog.frameBehaviorsFor(canvas.id)) {\n const behaviorMarker =\n `${PACK_PREFIX}${frameBehaviorPackId(behavior.id)}.${behavior.version}`;\n if (meta.get(behaviorMarker) === undefined) meta.set(behaviorMarker, true);\n }\n }\n });\n version = reached;\n report = {\n ...report,\n docPacks: { ...report.docPacks, [packId]: reached },\n ...(report.rootCanvas?.id === canvas.id\n ? { rootCanvas: { id: canvas.id, semanticVersion: reached } }\n : {}),\n };\n }\n migrated.push(canvas.id);\n }\n return { migrated, skipped };\n}\n","/**\n * The prefab rename runner (design-008 §5, petition I5) — the open-path half.\n *\n * Runs in doc-kit's migrate branch AFTER the structural schema steps and\n * BEFORE the M9 pack runner, under the same SINGLE-WRITER LAW (solo-open\n * only; live joiners pass migrate:false and stay read-only). For each old id\n * the gate reported (`report.renamedInDoc` — old id → its doc pack version):\n *\n * 1. PLAN: every durable entity whose `PrefabId.id` is the old id; its\n * legacy `<old>:<group>` cells read through the world — they PROJECT\n * because `renamedFrom` registered same-shaped components under the old\n * names (design-008 §1.1: projection is name-registry-driven).\n * 2. WRITE, one non-undoable transaction per old id: PrefabId → new id;\n * each legacy value moved to the new-name group cell (absolute writes;\n * a defensively-present new cell wins — §6.2); legacy cells removed.\n * NO version-chain folding here — that is the pack runner's job, right\n * after, on the new names.\n * 3. STAMP (write-once): the tombstone `engine.renamed.<old>` = newId, and\n * the carried pack marker `engine.pack.<new>.<docOldV>`. The tombstone\n * makes the gate skip the undeletable old markers forever; the carried\n * marker preserves the doc's version evidence under the NEW id — without\n * it the fresh report would show no `olderInDoc` entry and the pack\n * runner would silently skip the migrate chain over v-old cells.\n *\n * Idempotence/convergence: absolute cell writes + write-once markers — two\n * solo peers folding the same doc produce identical cells that merge LWW\n * (the migrate.ts argument). A fault mid-plan writes nothing; a fault after\n * the fold but before the stamps re-runs cleanly (folded entities no longer\n * match the old id).\n */\nimport { defineQuery } from \"@vibecook/strata-ecs\";\nimport type { Component, Entity } from \"@vibecook/strata-ecs\";\nimport { PrefabId } from \"../schema/prefab\";\nimport { renames } from \"../widget/define-widget\";\nimport type { MigrationCtx } from \"./migrate\";\nimport type { DocVersionReport } from \"./version-gate\";\n\nconst PACK_PREFIX = \"engine.pack.\";\nconst RENAMED_PREFIX = \"engine.renamed.\";\n\nconst allDurableQ = defineQuery([PrefabId]);\n\nexport interface RenameOutcome {\n /** Old ids folded and tombstoned this open (marker-only docs still stamp). */\n readonly renamed: string[];\n}\n\ninterface EntityRenamePlan {\n readonly e: Entity;\n /** Legacy value per group index (undefined = cell absent on this entity). */\n readonly legacyValues: readonly (Record<string, unknown> | undefined)[];\n /** New-name cell already present per group index (defensive new-wins). */\n readonly newPresent: readonly boolean[];\n}\n\nexport function runRenames(ctx: MigrationCtx, report: DocVersionReport): RenameOutcome {\n const { store, world } = ctx;\n const renamed: string[] = [];\n\n for (const [oldId, docOldV] of Object.entries(report.renamedInDoc)) {\n const entry = renames.get(oldId);\n if (entry === undefined) continue; // registry changed mid-open — defensive\n const { widget, legacyGroups } = entry;\n\n // --- plan (reads only; a throw leaves the doc byte-identical) ---\n const plans: EntityRenamePlan[] = [];\n world.query(allDurableQ).each((batch) => {\n for (const row of batch) {\n const e = batch.entity(row);\n if (world.read(e, PrefabId).id !== oldId) continue;\n const legacyValues: (Record<string, unknown> | undefined)[] = [];\n const newPresent: boolean[] = [];\n for (let i = 0; i < widget.groups.length; i++) {\n const legacy = world.get(e, legacyGroups[i] as Component);\n legacyValues.push(legacy as Record<string, unknown> | undefined);\n newPresent.push(world.get(e, (widget.groups[i] as { component: Component }).component) !== undefined);\n }\n plans.push({ e, legacyValues, newPresent });\n }\n });\n\n // --- write: ONE non-undoable transaction per old id ---\n if (plans.length > 0) {\n store.transaction(\n (tx) => {\n for (const { e, legacyValues, newPresent } of plans) {\n tx.edit(e).set(PrefabId, { id: widget.type });\n for (let i = 0; i < widget.groups.length; i++) {\n const value = legacyValues[i];\n if (value === undefined) continue;\n if (!newPresent[i]) {\n tx.addComponent(e, (widget.groups[i] as { component: Component }).component, value);\n }\n tx.removeComponent(e, legacyGroups[i] as Component);\n }\n }\n },\n { undoable: false },\n );\n }\n\n // --- stamp: tombstone + carried pack version (write-once, after the fold) ---\n store.metaTransaction((meta) => {\n const tomb = `${RENAMED_PREFIX}${oldId}`;\n if (meta.get(tomb) === undefined) meta.set(tomb, widget.type);\n const pack = `${PACK_PREFIX}${widget.type}.${docOldV}`;\n if (meta.get(pack) === undefined) meta.set(pack, true);\n });\n renamed.push(oldId);\n }\n\n return { renamed };\n}\n","/**\n * The rename zombie sweep (design-008 §6, petition I5) — the live half.\n *\n * The open-path runner (rename.ts) folds a doc once, solo. The CRDT layer\n * then converges BYTES with any stale replica — but it cannot know that\n * `comp:old:props` and `comp:new:props` are the same cell, so three shapes of\n * pre-rename traffic can land post-rename as ordinary deliveries:\n *\n * - a value set on an old cell winning LWW over the fold's delete\n * (resurrection);\n * - a `PrefabId = old` set winning over the fold's rewrite;\n * - a whole LATE ENTITY spawned old-shape by an offline pre-rename peer.\n *\n * The sweep folds all three, deterministically, on EVERY writable current\n * peer — identical absolute writes converge (the migrate.ts argument), so\n * \"zero zombies\" is a sweep property the replicas share, not a CRDT freebie.\n *\n * MECHANISM (frame-contract-legal): `observeQuery` watchers on the legacy\n * components and on `PrefabId` fire at notify (in-frame) and only SCHEDULE —\n * `queueMicrotask` runs the fold after the rAF task, between frames, the same\n * slot ops occupy. Bursts coalesce on a pending flag; the fold's own writes\n * re-fire the watchers into one empty pass, then quiet. Steady state is free\n * (zero-match chunk skip), and the first-party observers arm strata's write\n * enforcement as a side effect. Why not fold inside `applyRemote`? The\n * delivery has not PROJECTED yet — world queries see it exactly when the\n * observer fires.\n *\n * CONFLICT RULE (design-008 §6.2, stated honestly): a legacy value moves into\n * an ABSENT new cell (chain-folded per §6.3); a legacy value beside a PRESENT\n * new cell is dropped — NEW WINS. The true LWW order between a stale edit and\n * post-rename edits lives in Loro's clocks, which the engine cannot consult\n * per cell; any fixed rule converges, and new-wins is the only one that never\n * clobbers post-rename work with pre-rename state. Late entities lose\n * nothing.\n *\n * VERSIONING (§6.3): legacy cells are only ever written by old builds, so a\n * moved value is shaped at `renamedFrom.atVersion`. When the widget's migrate\n * chain covers atVersion → current, the flat record chain-folds before the\n * per-group write (the migrate.ts fold, per entity); a gap leaves that\n * entity's legacy cells in place with a dev warning — the per-entity analogue\n * of the pack runner's skip-stays-read-only, because the sweep must not guess\n * a transform.\n */\nimport { Any, defineQuery } from \"@vibecook/strata-ecs\";\nimport type { Component, Entity, Query, World } from \"@vibecook/strata-ecs\";\nimport type { DurableStore } from \"@vibecook/strata-ecs/durable\";\nimport { PrefabId } from \"../schema/prefab\";\nimport { renames, type WidgetRenameEntry } from \"../widget/define-widget\";\n\nconst RENAMED_PREFIX = \"engine.renamed.\";\n\nconst prefabQ = defineQuery([PrefabId]);\n\n// Legacy queries cached per REGISTRY ENTRY, not per old-id string (2026-08-09\n// review): a re-registration of the same old id (tests, hot reload) mints a\n// new entry with possibly different legacy components — a string-keyed cache\n// would keep watching the previous registration's cells. WeakMap lets dead\n// entries and their queries go with the registry reset.\nconst legacyQByEntry = new WeakMap<WidgetRenameEntry, Query>();\nfunction legacyQueryOf(entry: WidgetRenameEntry): Query | undefined {\n if (entry.legacyGroups.length === 0) return undefined;\n let q = legacyQByEntry.get(entry);\n if (q === undefined) {\n q =\n entry.legacyGroups.length === 1\n ? defineQuery([entry.legacyGroups[0] as Component])\n : defineQuery([Any(...(entry.legacyGroups as Component[]))]);\n legacyQByEntry.set(entry, q);\n }\n return q;\n}\n\n/** Chain coverage atVersion..widget.version (the migrate.ts contiguity rule). */\nfunction chainCovered(entry: WidgetRenameEntry): boolean {\n for (let v = entry.atVersion; v < entry.widget.version; v++) {\n if (typeof entry.widget.migrate[v] !== \"function\") return false;\n }\n return true;\n}\n\ninterface FoldPlan {\n readonly e: Entity;\n readonly rewriteId: boolean;\n /** Chain-folded flat record spanning the entity's legacy groups (write source). */\n readonly folded: Record<string, unknown>;\n /** Group indices whose new cell is absent → written from `folded`. */\n readonly writeGroups: readonly number[];\n /** Legacy components present on the entity → removed. */\n readonly removeLegacy: readonly Component[];\n}\n\nexport function armRenameSweep(world: World, store: DurableStore): () => void {\n const entries = renames.all();\n if (entries.length === 0) return () => {};\n\n let pending = false;\n let disposed = false;\n const warnedGap = new Set<string>();\n\n const sweep = (): void => {\n for (const entry of entries) {\n const { widget, legacyGroups, oldType } = entry;\n const covered = chainCovered(entry);\n\n // --- plan: entities carrying the old id and/or any legacy cell ---\n const seen = new Set<Entity>();\n const plans: FoldPlan[] = [];\n const consider = (e: Entity): void => {\n if (seen.has(e)) return;\n seen.add(e);\n const id = world.get(e, PrefabId)?.id;\n const rewriteId = id === oldType;\n let anyLegacy = false;\n const flat: Record<string, unknown> = {};\n const removeLegacy: Component[] = [];\n for (let i = 0; i < widget.groups.length; i++) {\n const legacy = world.get(e, legacyGroups[i] as Component);\n if (legacy === undefined) continue;\n anyLegacy = true;\n Object.assign(flat, legacy as Record<string, unknown>);\n removeLegacy.push(legacyGroups[i] as Component);\n }\n if (!rewriteId && !anyLegacy) return;\n // A foreign-typed entity carrying legacy cells is unfoldable — leave it visible.\n if (!rewriteId && anyLegacy && id !== widget.type) return;\n if (anyLegacy && !covered) {\n if (!warnedGap.has(oldType)) {\n warnedGap.add(oldType);\n console.warn(\n `ice: rename sweep — \"${oldType}\" values are at pack v${entry.atVersion} but \"${widget.type}\"'s migrate chain has a gap; leaving legacy cells in place (design-008 §6.3).`,\n );\n }\n return;\n }\n let folded = flat;\n for (let v = entry.atVersion; v < widget.version; v++) {\n const step = widget.migrate[v];\n if (typeof step === \"function\") folded = step(folded);\n }\n const writeGroups: number[] = [];\n if (anyLegacy) {\n for (let i = 0; i < widget.groups.length; i++) {\n const present = world.get(e, (widget.groups[i] as { component: Component }).component) !== undefined;\n if (!present) writeGroups.push(i); // new-wins: present cells keep their value\n }\n }\n plans.push({ e, rewriteId, folded, writeGroups, removeLegacy });\n };\n\n // The full PrefabId walk runs ONLY for zero-prop renames (no legacy\n // components to observe). For prop-bearing renames every reachable\n // zombie shape carries a legacy cell — an old build writes PrefabId\n // exactly once, at spawn, alongside its group cells, and no op it can\n // emit rewrites the id afterward — so the legacy-component pass below\n // is complete on its own and the O(entities) scan would be pure waste\n // on every spawn (2026-08-09 review).\n if (legacyGroups.length === 0) {\n world.query(prefabQ).each((batch) => {\n for (const row of batch) {\n const e = batch.entity(row);\n if (world.read(e, PrefabId).id === oldType) consider(e);\n }\n });\n }\n const legacyQ = legacyQueryOf(entry);\n if (legacyQ !== undefined) {\n world.query(legacyQ).each((batch) => {\n for (const row of batch) consider(batch.entity(row));\n });\n }\n if (plans.length === 0) continue;\n\n // --- write: one non-undoable transaction per old id, then tombstone ---\n store.transaction(\n (tx) => {\n for (const plan of plans) {\n if (plan.rewriteId) tx.edit(plan.e).set(PrefabId, { id: widget.type });\n for (const i of plan.writeGroups) {\n tx.addComponent(plan.e, (widget.groups[i] as { component: Component }).component, plan.folded);\n }\n for (const legacy of plan.removeLegacy) tx.removeComponent(plan.e, legacy);\n }\n },\n { undoable: false },\n );\n store.metaTransaction((meta) => {\n const tomb = `${RENAMED_PREFIX}${oldType}`;\n if (meta.get(tomb) === undefined) meta.set(tomb, widget.type);\n });\n }\n };\n\n const schedule = (): void => {\n if (pending || disposed) return;\n pending = true;\n queueMicrotask(() => {\n pending = false;\n if (!disposed) sweep();\n });\n };\n\n const watchers: Array<() => void> = [];\n let anyZeroProp = false;\n for (const entry of entries) {\n const q = legacyQueryOf(entry);\n if (q !== undefined) {\n watchers.push(world.reactive.observeQuery(q, schedule, { cols: [...(entry.legacyGroups as Component[])] }));\n } else {\n anyZeroProp = true;\n }\n }\n // The wide PrefabId watcher arms ONLY when some rename has no legacy\n // components to observe (a zero-prop widget's late entity carries nothing\n // but PrefabId + geometry). For every prop-bearing rename the legacy\n // watchers above are complete (see the sweep's reachability note), and\n // arming this unconditionally made EVERY widget spawn schedule a full\n // O(entities × renames) scan for the session's lifetime.\n if (anyZeroProp) {\n watchers.push(world.reactive.observeQuery(prefabQ, schedule, { cols: [PrefabId] }));\n }\n\n return () => {\n disposed = true;\n for (const u of watchers) u();\n };\n}\n","/**\n * STRUCTURAL schema migrations (engineSchema 1 → current).\n *\n * The per-prefab runner (migrate.ts) folds per-entity group values — it cannot spawn entities,\n * see siblings, write relations, or stamp `engine.schema`, so a schema-version bump used to\n * leave old docs read-only FOREVER (the gate re-ran, saw docSchema < local, and nothing ever\n * advanced it). This module is the missing half: whole-document transforms keyed by the schema\n * version they migrate FROM, run at open on a \"migrate\" verdict BEFORE the pack runner, each\n * stamping `engine.schema.<n+1>` on success.\n *\n * SINGLE-WRITER LAW: a structural migration may only run when this peer is the document's sole\n * occupant — the local open path (autosave restore, file open). A LIVE-ROOM JOINER MUST NOT\n * migrate (bootstrap passes `migrate: false`): the room's peers are still writing the old\n * shape, sync never re-gates, and a mid-room migration split-brains the doc (old peers write\n * scalar z the new shape ignores, and vice versa). An old-schema doc joined live is read-only\n * until it is opened solo by a current build.\n *\n * Step 1→2 — ordered relations:\n * 1. BOARD ROOT: mint the componentless durable entity root-level widgets hang `ChildOf` on\n * ({@link ensureBoardRoot}); its key is recorded first-writer-wins in the meta map.\n * 2. StackZ → sibling order: every durable widget is grouped by parent scope (existing\n * `ChildOf` target, else the board root), each group sorted by `(z asc, entityKey asc)`,\n * and re-linked in that order with `tx.setRelation(e, ChildOf, parent, \"last\")` — a\n * same-target re-set WITH a place is a move, so applying in sorted order lands the sorted\n * sequence; root-level widgets gain their first edge the same way. ONE non-undoable\n * transaction; absolute, idempotent, convergent (same doc → same sort → same sequence).\n * 3. The legacy `StackZ` CELLS ARE KEPT: an old build opening the migrated doc read-only\n * (docSchema newer than local) still paints z-correct from them. New entities never write\n * StackZ; the cells are simply never read by current builds outside the legacy fallback.\n */\nimport type { Entity, EntityKey, World } from \"@vibecook/strata-ecs\";\nimport { defineQuery } from \"@vibecook/strata-ecs\";\nimport type { DurableStore } from \"@vibecook/strata-ecs/durable\";\nimport {\n DefaultCanvasType,\n ROOT_CANVAS_META_KEY,\n canvasIdentityOf,\n canvasPackId,\n encodeCanvasIdentity,\n parseCanvasIdentity,\n sameCanvasIdentity,\n} from \"../canvas/define-canvas-type\";\nimport { ChildOf, StackZ } from \"../catalog/scene\";\nimport { PrefabId } from \"../schema/prefab\";\nimport type { MigrationCtx } from \"./migrate\";\nimport { ENGINE_SCHEMA_VERSION } from \"./envelope\";\nimport type { DocVersionReport } from \"./version-gate\";\n\nconst SCHEMA_PREFIX = \"engine.schema.\";\nconst PACK_PREFIX = \"engine.pack.\";\n/** Meta key holding the board-root's EntityKey (a VALUE key, unlike the presence markers). */\nconst BOARD_ROOT_META = \"engine.boardRoot\";\n\n// Durable-identity + legacy-z queries (module singletons; defineQuery interns).\nconst allDurableQ = defineQuery([PrefabId]);\n\n/**\n * Resolve the document's board root, minting it if absent (create path + step 1→2). The mint\n * is a componentless `tx.spawn()` in a non-undoable transaction; the key is recorded in meta\n * first-writer-wins and re-read after the write so a raced winner is honored (the single-writer\n * law makes a race unreachable in practice — belt and braces). Returns the LIVE handle.\n */\nexport function ensureBoardRoot(world: World, store: DurableStore): Entity {\n let recorded: string | undefined;\n store.metaTransaction((meta) => {\n const v = meta.get(BOARD_ROOT_META);\n if (typeof v === \"string\") recorded = v;\n });\n if (recorded !== undefined) {\n const e = store.resolve(recorded as EntityKey);\n if (e !== undefined && world.isAlive(e)) return e;\n }\n const minted = store.transaction((tx) => tx.spawn(), { undoable: false });\n const mintedKey = store.keyOf(minted);\n if (mintedKey === undefined) throw new Error(\"ice: board-root mint failed to bind a key.\");\n store.metaTransaction((meta) => {\n if (meta.get(BOARD_ROOT_META) === undefined) meta.set(BOARD_ROOT_META, mintedKey as unknown as string);\n });\n let winner: string = mintedKey as unknown as string;\n store.metaTransaction((meta) => {\n const v = meta.get(BOARD_ROOT_META);\n if (typeof v === \"string\") winner = v;\n });\n return store.resolve(winner as EntityKey) ?? minted;\n}\n\n/** Read the board-root handle WITHOUT minting — read-only opens and post-attach lookups. */\nexport function resolveBoardRoot(world: World, store: DurableStore): Entity | undefined {\n let recorded: string | undefined;\n store.metaTransaction((meta) => {\n const v = meta.get(BOARD_ROOT_META);\n if (typeof v === \"string\") recorded = v;\n });\n if (recorded === undefined) return undefined;\n const e = store.resolve(recorded as EntityKey);\n return e !== undefined && world.isAlive(e) ? e : undefined;\n}\n\n/** Step 1→2: board root + StackZ→sibling-order rewrite (header). */\nfunction migrateToOrderedRelations(ctx: MigrationCtx): void {\n const { store, world } = ctx;\n const root = ensureBoardRoot(world, store);\n\n // Group every durable widget by parent scope; sort each group (z asc, entityKey asc).\n const groups = new Map<Entity, { e: Entity; z: number; key: string }[]>();\n world.query(allDurableQ).each((batch) => {\n for (const row of batch) {\n const e = batch.entity(row);\n if (e === root) continue;\n const key = store.keyOf(e);\n if (key === undefined) continue;\n const parent = world.getRelation(e, ChildOf) ?? root;\n const z = world.get(e, StackZ)?.z ?? 0; // legacy cell; absent (post-flip spawns) sorts at 0\n let g = groups.get(parent);\n if (g === undefined) {\n g = [];\n groups.set(parent, g);\n }\n g.push({ e, z, key: key as unknown as string });\n }\n });\n for (const g of groups.values()) {\n g.sort((a, b) => (a.z !== b.z ? a.z - b.z : a.key < b.key ? -1 : a.key > b.key ? 1 : 0));\n }\n\n // ONE non-undoable transaction: re-link in sorted order. Same-target re-set WITH a place is\n // a move (never a duplicate), so this is exact for already-parented children and appends\n // root-level widgets in sorted order.\n store.transaction(\n (tx) => {\n for (const [parent, g] of groups) {\n for (const { e } of g) tx.setRelation(e, ChildOf, parent, \"last\");\n }\n },\n { undoable: false },\n );\n}\n\n/** Step 2→3: bind every legacy document to the deterministic default CanvasType. */\nfunction migrateToDurableRootCanvas(ctx: MigrationCtx): void {\n const identity = canvasIdentityOf(DefaultCanvasType);\n const encoded = encodeCanvasIdentity(identity);\n const packMarker = `${PACK_PREFIX}${canvasPackId(identity.id)}.${identity.semanticVersion}`;\n ctx.store.metaTransaction((meta) => {\n const existing = meta.get(ROOT_CANVAS_META_KEY);\n if (existing !== undefined && !sameCanvasIdentity(parseCanvasIdentity(existing), identity)) {\n throw new Error(\n `ice: schema 2→3 cannot overwrite conflicting ${ROOT_CANVAS_META_KEY} metadata.`,\n );\n }\n if (existing === undefined) meta.set(ROOT_CANVAS_META_KEY, encoded);\n if (meta.get(packMarker) === undefined) meta.set(packMarker, true);\n });\n}\n\n/** Structural steps keyed by the schema version they migrate FROM. */\nconst STEPS: Record<number, (ctx: MigrationCtx) => void> = {\n 1: migrateToOrderedRelations,\n 2: migrateToDurableRootCanvas,\n};\n\n/**\n * Run the structural chain `docSchema → … → localSchema`, stamping `engine.schema.<n+1>` after\n * each step. A gap (missing step) stops the walk — the caller's re-gate keeps the doc\n * read-only, exactly like a gappy pack chain. A docSchema of 0 is the gate's \"reject\" domain\n * and never reaches here. Returns true when the doc reached the local schema version.\n */\nexport function runSchemaMigrations(ctx: MigrationCtx, report: DocVersionReport): boolean {\n let v = report.docSchema;\n while (v < ENGINE_SCHEMA_VERSION) {\n const step = STEPS[v];\n if (step === undefined) return false;\n step(ctx);\n const reached = v + 1;\n ctx.store.metaTransaction((meta) => {\n const key = `${SCHEMA_PREFIX}${reached}`;\n if (meta.get(key) === undefined) meta.set(key, true);\n });\n v = reached;\n }\n return true;\n}\n","/**\n * `createBehaviorHarness` — the testing story, shipped WITH the framework\n * rather than after it (design-009 §7).\n *\n * A behavior is frame-cadence, collaboration-native, transaction-writing code.\n * Testing that without a rig means standing up an engine, a document, a\n * pipeline and a hand-driven clock — enough ceremony that most authors would\n * simply not test the interesting parts. The interesting parts are exactly the\n * ones they will get wrong:\n *\n * - `claim(e)` fakes a live gesture claim, so an author can see their derived\n * behavior go quiet during a drag and coalesce at the settle. Suppression\n * is the single most surprising rule in the framework.\n * - `pair()` gives a SECOND engine on the same document. Convergence bugs are\n * invisible on one peer by definition, and \"it works for me\" is what a\n * collaborative editor's bug reports look like.\n * - `commits` records what actually reached the store, which is how you tell\n * \"the differ dropped it\" from \"it never ran\".\n */\nimport { createWorld, defineQuery, type Entity, type Query, type World } from \"@vibecook/strata-ecs\";\nimport { Captures, ChildOf, GestureActive, Position, Size } from \"../catalog\";\nimport { createEngine, type Engine } from \"../engine/engine\";\nimport { createDocSession, openDocSession, type DocSession } from \"../doc/doc-kit\";\nimport { guardedTransaction } from \"../guards/guarded-tx\";\nimport { definePrefab, init, prefabs, type Prefab } from \"../schema/prefab\";\nimport { createBehaviorRuntime, type BehaviorRuntime, type BehaviorSession } from \"./runtime\";\nimport type { AnyBehaviorDef } from \"./types\";\n\n/** One commit the harness observed reaching the store. */\nexport interface HarnessCommit {\n readonly undoable: boolean;\n /** `{ behavior, label }` for a `ctx.commit`; undefined for anything else. */\n readonly meta: Record<string, unknown> | undefined;\n}\n\nexport interface BehaviorHarnessOpts {\n /**\n * Attach a document. Default TRUE — durable behaviors need one, and a\n * runtime behavior is unharmed by having it. `false` exercises the doc-less\n * path deliberately (where `ctx.commit` refuses, by design).\n */\n readonly docs?: boolean;\n /** Extra behaviors to register beside the one under test. */\n readonly also?: readonly AnyBehaviorDef[];\n}\n\nexport interface BehaviorHarness {\n readonly world: World;\n readonly engine: Engine;\n readonly runtime: BehaviorRuntime;\n doc(): DocSession | undefined;\n /** Drive `n` frames (default 1). The clock advances 16ms per frame. */\n step(n?: number): void;\n /** A bare durable node with Position + Size, for behaviors to ride. */\n spawn(x?: number, y?: number): Entity;\n /** Attach the behavior under test — durable through a transaction, else direct. */\n attach(e: Entity, data?: Record<string, unknown>): void;\n detach(e: Entity): void;\n /** The behavior's live instances, as the runtime sees them. */\n instances(): readonly Entity[];\n /** Every commit that reached the store since construction. */\n readonly commits: readonly HarnessCommit[];\n /** Simulate a live gesture claim on `e`. Returns the release. */\n claim(e: Entity): () => void;\n /** A SECOND engine on this document — the two-peer rig. */\n pair(): BehaviorHarness;\n /** Exchange updates with every paired harness, both ways. */\n sync(): void;\n dispose(): void;\n}\n\nconst HARNESS_PREFAB_ID = \"ice.harness.node\";\n\nfunction harnessPrefab(): Prefab {\n return (\n prefabs.get(HARNESS_PREFAB_ID) ??\n definePrefab(HARNESS_PREFAB_ID, {\n store: \"durable\",\n components: [init(Position, { x: 0, y: 0 }), init(Size, { w: 100, h: 100 })],\n relations: [ChildOf],\n })\n );\n}\n\nexport function createBehaviorHarness(b: AnyBehaviorDef, opts: BehaviorHarnessOpts = {}): BehaviorHarness {\n const peers: BehaviorHarness[] = [];\n const root = build(b, opts, peers, undefined);\n peers.push(root);\n return root;\n}\n\nfunction build(\n b: AnyBehaviorDef,\n opts: BehaviorHarnessOpts,\n peers: BehaviorHarness[],\n seed: Uint8Array | undefined,\n): BehaviorHarness {\n const world = createWorld();\n const engine = createEngine(world);\n const commits: HarnessCommit[] = [];\n let session: DocSession | undefined;\n\n if (opts.docs !== false) {\n if (seed === undefined) {\n session = createDocSession(world);\n } else {\n const opened = openDocSession(world, seed);\n if (!opened.ok) throw new Error(`ice: behavior harness pair() could not open the seed doc — ${opened.reason}`);\n session = opened.session;\n }\n }\n\n // The recording shim: `ctx.commit` is the only way a behavior reaches the\n // document, so wrapping the store's transaction is how the harness can say\n // \"nothing was committed\" — a claim the differ makes constantly and that no\n // amount of reading final values can confirm.\n const view: BehaviorSession | undefined =\n session === undefined\n ? undefined\n : ({\n get readOnly() {\n return session?.readOnly ?? true;\n },\n get liveWriter() {\n return session?.liveWriter;\n },\n store: {\n transaction: (fn: never, o?: { undoable?: boolean; meta?: Record<string, unknown> }) => {\n commits.push({ undoable: o?.undoable !== false, meta: o?.meta });\n return session?.store.transaction(fn as never, o as never);\n },\n keyOf: (e: Entity) => session?.store.keyOf(e),\n resolve: (k: never) => session?.store.resolve(k),\n getComponent: (e: Entity, c: never) => session?.store.getComponent(e, c),\n get snapshot() {\n // `snapshot` is on the store CLASS, not the published\n // `DurableStore` interface — the behavior marker family reads\n // through it (behavior/migrate.ts), so the harness forwards it.\n return (session?.store as unknown as { snapshot?: unknown } | undefined)?.snapshot;\n },\n metaTransaction: (fn: never) => session?.store.metaTransaction(fn as never),\n },\n } as unknown as BehaviorSession);\n\n const runtime = createBehaviorRuntime({\n world,\n engine,\n session: () => view,\n onLog: () => {},\n });\n for (const extra of opts.also ?? []) runtime.register(extra);\n runtime.register(b);\n\n let clock = 0;\n const prefab = harnessPrefab();\n\n const harness: BehaviorHarness = {\n world,\n engine,\n runtime,\n commits,\n doc: () => session,\n\n step(n = 1) {\n for (let i = 0; i < n; i++) {\n clock += 16;\n engine.step(clock);\n }\n },\n\n spawn(x = 0, y = 0) {\n if (session === undefined) {\n return world.spawn({ components: [[Position, { x, y }], [Size, { w: 100, h: 100 }]] });\n }\n let e: Entity | undefined;\n guardedTransaction(\n session.store,\n world,\n (tx) => {\n e = tx.spawnPrefab(prefab, [[Position, { x, y }]]);\n },\n { undoable: false },\n );\n world.sync(); // the spawn projects at the next sync\n return e as Entity;\n },\n\n attach(e, data) {\n if (b.store !== \"durable\") {\n runtime.attach(e, b, data);\n return;\n }\n if (session === undefined) throw new Error(\"ice: behavior harness — a durable behavior needs docs: true.\");\n session.store.transaction((tx) => {\n tx.addComponent(e, b.component, { ...(b.defaults as Record<string, unknown>), ...(data ?? {}) });\n });\n world.sync();\n },\n\n detach(e) {\n if (b.store !== \"durable\") {\n runtime.detach(e, b);\n return;\n }\n session?.store.transaction((tx) => tx.removeComponent(e, b.component));\n world.sync();\n },\n\n instances() {\n const out: Entity[] = [];\n // Read through the world rather than the runtime's private registry: a\n // test asserting on instances should see what the WORLD says, or it can\n // pass while the two have quietly disagreed.\n for (const e of allEntitiesWith(world, b)) out.push(e);\n return out;\n },\n\n claim(e) {\n // The engine's own claim shape: an ACTIVE recognizer that `Captures` the\n // target. Discrete claims deliberately do not count (design-001 §3).\n const recognizer = world.spawn({});\n world.setRelation(recognizer, Captures, e);\n world.addTag(recognizer, GestureActive);\n return () => {\n if (world.isAlive(recognizer)) world.destroy(recognizer);\n };\n },\n\n pair() {\n if (session === undefined) throw new Error(\"ice: behavior harness pair() needs a document (docs: true).\");\n const bytes = session.exportEnvelope();\n const peer = build(b, opts, peers, bytes);\n peers.push(peer);\n return peer;\n },\n\n sync() {\n // Full-snapshot exchange, both ways, until every peer has seen every\n // other. Crude next to a real transport and exactly right for a rig: the\n // property under test is convergence, not the wire.\n for (const from of peers) {\n const src = from.doc();\n if (src === undefined) continue;\n const bytes = src.exportSnapshot();\n for (const to of peers) {\n if (to === from) continue;\n to.doc()?.applyRemote(bytes);\n }\n }\n for (const peer of peers) peer.world.sync();\n },\n\n dispose() {\n runtime.dispose();\n session?.close();\n session = undefined;\n const i = peers.indexOf(harness);\n if (i !== -1) peers.splice(i, 1);\n },\n };\n\n return harness;\n}\n\nfunction allEntitiesWith(world: World, b: AnyBehaviorDef): Entity[] {\n const out: Entity[] = [];\n world.query(behaviorQuery(b)).each((batch) => {\n for (const row of batch) out.push(batch.entity(row));\n });\n return out;\n}\n\n// Cached on the handle: `defineQuery` identity is strata's own cache key for\n// the matched-archetype list, so re-compiling per call defeats two caches.\nconst queryCache = new WeakMap<object, Query>();\nfunction behaviorQuery(b: AnyBehaviorDef): Query {\n let q = queryCache.get(b as object);\n if (q === undefined) {\n q = defineQuery([b.component]);\n queryCache.set(b as object, q);\n }\n return q;\n}\n","/**\n * ops.arrange — the explicit desktop-style \"Clean Up\" (2026-07-17, James:\n * \"if user click auto layout, it will try to organize the canvas nicely, bit\n * like desktop auto layout feature in windows and mac\").\n *\n * Scope: explicit `ids` > the current selection (when ≥2, Figma-tidy style) >\n * every widget of the CURRENT nav frame (the same Selectable ∧ Active ∧\n * WidgetEquipped set selectAll sees — works at any nav depth, coordinates are\n * frame-local for every member by construction).\n *\n * Placement (v2 2026-07-17, James: \"can this clean up be more smarter?\"):\n * - WIRED widgets arrange like Unreal Blueprint's auto-format: each\n * connected component (WireFrom/WireTo among the movers) is laid out by\n * kernel `layerGraph` — layered columns along wire direction — and moves\n * as one rigid block.\n * - Blocks + loose widgets then pack via kernel `packLayout` (bottom-left\n * candidates: dense with mixed sizes, anchored at the cluster's own bbox\n * top-left, idempotent — a second click is a no-op and commits nothing).\n * - Frame widgets OUTSIDE the moving set are passed as OBSTACLES: a scoped\n * Clean Up flows around bystanders instead of landing on top of them.\n *\n * Write protocol (design-001 §3, composed from existing primitives only):\n * 1. ONE guarded transaction sets every mover's final Position — a single\n * undo step restores the whole arrangement. The tx write-through snaps\n * runtime + baseline to the target synchronously (strata transaction.ts\n * §13.2 rule 2: pre-existing component value writes are committer-wins).\n * 2. Per mover: attach TransformTween(→ target), then write the runtime\n * cell BACK to the old position through the session LiveWriter — legal\n * divergence (a live tween IS the claim, design-001 §3 amendment), so\n * the card glides while the document already holds the truth. The tween\n * reconverges with the committed value on land; no commit-at-land\n * machinery exists or is needed.\n *\n * **[AMENDED 2026-08-15, petition I15]** Two corrections, both from the door\n * review:\n * - The parenthetical that used to sit here — \"undo DURING the glide is the\n * same accepted divergence window fly-back already has\" — was WRONG. It is\n * not a window: an undo mid-glide advanced the baseline alone (strata's\n * `(own, value)` branch banks nothing), the tween landed on the stale\n * target, and the cell stayed diverged FOREVER, poisoned against later\n * remote updates. The facade's history chokepoint now retargets live tweens\n * onto doc truth, so ⌘Z mid-glide converges by landing.\n * - Movers already tweening are RETARGETED, not skipped. Skipping them left a\n * second Clean Up gliding everyone else while the in-flight ones completed\n * at their previous, now-wrong targets.\n *\n * The user's hand still always wins: widgets under a live Grab are skipped.\n * Runtime-only widgets (no doc key) skip the tx and are tweened/written\n * directly — no doc cell, nothing to guard.\n */\nimport { layerGraph, packLayout, type LayoutRect } from \"@ice/kernel\";\nimport type { Entity, World } from \"@vibecook/strata-ecs\";\nimport { defineQuery } from \"@vibecook/strata-ecs\";\nimport type { DurableStore } from \"@vibecook/strata-ecs/durable\";\nimport {\n Active,\n Grab,\n Locked,\n Position,\n Selectable,\n Size,\n TransformTween,\n Wire,\n WireFrom,\n WireTo,\n} from \"../catalog\";\nimport { guardedTransaction } from \"../guards/guarded-tx\";\nimport type { LiveWriter } from \"../guards/live-writer\";\nimport { WidgetEquipped } from \"../widget/define-widget\";\nimport { selectedEntities } from \"./selection\";\n\nexport interface ArrangeOpts {\n /** Explicit scope; wins over selection/frame resolution. */\n readonly ids?: readonly Entity[];\n /** Min separation between packed widgets (default 24). */\n readonly gutter?: number;\n /** Row wrap width; default = packLayout's near-square derivation. */\n readonly maxWidth?: number;\n /** Glide duration; 0 snaps instantly (tests/headless). Default 240ms. */\n readonly durationMs?: number;\n}\n\nconst ARRANGE_MS = 240;\nconst ARRANGE_GUTTER = 24;\n\nconst frameWidgetsQ = defineQuery([Position, Size, Selectable, Active, WidgetEquipped]);\nconst wireQ = defineQuery([Wire]);\n\n/** Returns the entities that actually moved (empty = already tidy). */\nexport function arrangeWidgets(\n store: DurableStore,\n liveWriter: LiveWriter,\n world: World,\n opts: ArrangeOpts = {},\n): Entity[] {\n let targets: Entity[];\n if (opts.ids !== undefined && opts.ids.length > 0) {\n targets = [...opts.ids];\n } else {\n const sel = selectedEntities(world);\n if (sel.length >= 2) {\n targets = sel;\n } else {\n targets = [];\n world.query(frameWidgetsQ).each((b) => {\n for (const r of b) targets.push(b.entity(r));\n });\n }\n }\n\n const movable = targets.filter(\n (e) =>\n world.isAlive(e) &&\n // Grab-held only: an in-flight tween is RETARGETED below (I15), not\n // skipped — skipping stranded it at the previous run's target.\n !world.has(e, Grab) &&\n // taped down (design-015 §5.1, D4a): Clean Up flows around it — it stays, an obstacle like any bystander\n !world.hasTag(e, Locked) &&\n world.get(e, Position) !== undefined,\n );\n if (movable.length < 2) return [];\n\n const rectOf = (e: Entity): LayoutRect => {\n const p = world.get(e, Position) as { x: number; y: number };\n const s = world.get(e, Size) ?? { w: 0, h: 0 };\n return { x: p.x, y: p.y, w: s.w, h: s.h };\n };\n const rects: LayoutRect[] = movable.map(rectOf);\n const gutter = opts.gutter ?? ARRANGE_GUTTER;\n\n // One band width rules both layers: wired blocks WRAP into stacked bands\n // when a chain would outgrow it (2026-07-17 \"rigid blocks\" limit lifted),\n // and the packer wraps loose rows at the same width. Explicit maxWidth\n // wins; the default is packLayout's own near-square derivation, computed\n // over the individual movers.\n const bandWidth =\n opts.maxWidth ??\n (() => {\n let area = 0;\n let widest = 0;\n for (const r of rects) {\n area += (r.w + gutter) * (r.h + gutter);\n widest = Math.max(widest, r.w);\n }\n return Math.max(widest, Math.sqrt(area * 1.6));\n })();\n\n // Bystanders are obstacles: every frame widget outside the moving set\n // (unselected, live-claimed, in-flight) stays put and must not be crowded.\n const movableSet = new Set(movable);\n const obstacles: LayoutRect[] = [];\n world.query(frameWidgetsQ).each((b) => {\n for (const r of b) {\n const e = b.entity(r);\n if (!movableSet.has(e)) obstacles.push(rectOf(e));\n }\n });\n\n // Wire edges among the movers (WireFrom/WireTo point at widgets): each\n // connected component becomes a rigid layerGraph block.\n const indexOf = new Map<Entity, number>();\n movable.forEach((e, i) => indexOf.set(e, i));\n const edges: Array<[number, number]> = [];\n world.query(wireQ).each((b) => {\n for (const r of b) {\n const wire = b.entity(r);\n const from = world.getRelation(wire, WireFrom);\n const to = world.getRelation(wire, WireTo);\n if (from === undefined || to === undefined) continue;\n const fi = indexOf.get(from);\n const ti = indexOf.get(to);\n if (fi !== undefined && ti !== undefined && fi !== ti) edges.push([fi, ti]);\n }\n });\n const parent = movable.map((_, i) => i);\n const find = (i: number): number => {\n let root = i;\n while (parent[root] !== root) root = parent[root] as number;\n let cursor = i;\n while (parent[cursor] !== root) {\n const next = parent[cursor] as number;\n parent[cursor] = root;\n cursor = next;\n }\n return root;\n };\n for (const [u, v] of edges) {\n const a = find(u);\n const b = find(v);\n if (a !== b) parent[a] = b;\n }\n const comps = new Map<number, number[]>();\n for (let i = 0; i < movable.length; i++) {\n const root = find(i);\n const list = comps.get(root);\n if (list === undefined) comps.set(root, [i]);\n else list.push(i);\n }\n\n // Pack units: wired components as blocks (internal layerGraph placement),\n // everything else as itself.\n type Unit = { members: number[]; rel: Array<{ x: number; y: number }> };\n const units: Unit[] = [];\n const unitRects: LayoutRect[] = [];\n for (const members of comps.values()) {\n if (members.length < 2) {\n const i = members[0] as number;\n units.push({ members: [i], rel: [{ x: 0, y: 0 }] });\n unitRects.push(rects[i] as LayoutRect);\n continue;\n }\n const local = new Map<number, number>();\n members.forEach((gi, li) => local.set(gi, li));\n const localEdges: Array<[number, number]> = [];\n for (const [u, v] of edges) {\n const lu = local.get(u);\n const lv = local.get(v);\n if (lu !== undefined && lv !== undefined) localEdges.push([lu, lv]);\n }\n const sizes = members.map((gi) => ({ w: (rects[gi] as LayoutRect).w, h: (rects[gi] as LayoutRect).h }));\n const measure = (placements: Array<{ x: number; y: number }>): { w: number; h: number } => {\n let w = 0;\n let h = 0;\n placements.forEach((p, li) => {\n const r = rects[members[li] as number] as LayoutRect;\n w = Math.max(w, p.x + r.w);\n h = Math.max(h, p.y + r.h);\n });\n return { w, h };\n };\n // Short chains stay LINEAR (the Blueprint promise: follow the wires);\n // only a run clearly wider than the band (>1.5×) wraps into stacked\n // bands. The decision depends only on the graph, so re-runs repeat it —\n // idempotence holds.\n let rel = layerGraph(sizes, localEdges, { gapX: gutter * 2, gapY: gutter });\n let dims = measure(rel);\n if (dims.w > bandWidth * 1.5) {\n rel = layerGraph(sizes, localEdges, { gapX: gutter * 2, gapY: gutter, maxWidth: bandWidth });\n dims = measure(rel);\n }\n let bx = Number.POSITIVE_INFINITY;\n let by = Number.POSITIVE_INFINITY;\n for (const gi of members) {\n const r = rects[gi] as LayoutRect;\n bx = Math.min(bx, r.x); // the block's CURRENT anchor: members' bbox top-left\n by = Math.min(by, r.y);\n }\n units.push({ members, rel });\n unitRects.push({ x: bx, y: by, w: dims.w, h: dims.h });\n }\n\n const placedUnits = packLayout(unitRects, { gutter, obstacles, maxWidth: bandWidth });\n\n const finalPos = new Array<{ x: number; y: number }>(movable.length);\n units.forEach((u, k) => {\n const p = placedUnits[k] as { x: number; y: number };\n u.members.forEach((gi, li) => {\n const rel = u.rel[li] as { x: number; y: number };\n finalPos[gi] = { x: p.x + rel.x, y: p.y + rel.y };\n });\n });\n\n const moves: Array<{ e: Entity; from: { x: number; y: number }; to: { x: number; y: number } }> = [];\n for (let i = 0; i < movable.length; i++) {\n const from = rects[i] as LayoutRect;\n const to = finalPos[i] as { x: number; y: number };\n if (Math.abs(from.x - to.x) < 0.5 && Math.abs(from.y - to.y) < 0.5) continue;\n moves.push({ e: movable[i] as Entity, from: { x: from.x, y: from.y }, to });\n }\n if (moves.length === 0) return [];\n\n // ONE transaction owns capture, the durable finals, and the glide — the\n // write protocol above, now expressed in the primitive it seeded\n // (`tx.move`, petition I15). Runtime-only movers are recognised by `keyOf`\n // and skip the durable half without a second code path here.\n const dur = opts.durationMs ?? ARRANGE_MS;\n guardedTransaction(\n store,\n world,\n (tx) => {\n for (const m of moves) tx.move(m.e, m.to, { animateMs: dur });\n },\n { live: liveWriter, keyOf: (e) => store.keyOf(e) },\n );\n return moves.map((m) => m.e);\n}\n","/**\n * Engine-owned destroy cascade (design-001 §5.1, §5.3, design-003 §5).\n *\n * strata clears an entity's edges on `tx.destroy` but does NOT recurse, so the\n * engine walks containment itself: depth-first over `getReverse(e, ChildOf)`,\n * destroying descendants before their parent, then the root. Wires are reified\n * edge entities, so a wire whose `WireFrom`/`WireTo` endpoint dies is destroyed\n * with it (reverse-index lookup, same transaction).\n *\n * Beyond the wires, any source of a DEPENDENT relation pointing at a doomed entity dies with it (`defineRelation({ dependent:\n * true })`, design-015 D3t-c). 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\";\nimport { schemaMeta } from \"../schema/meta\";\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 // …and any DEPENDENT edge's source pointing here (design-015 D3t-c — the wire's rule, generalised: a calendar's pin dies with its note)\n for (const r of schemaMeta.dependents()) for (const src of world.getReverse(e, r)) walk(src);\n\n tx.destroy(e);\n };\n\n walk(root);\n}\n","/**\n * \"Is a gesture in flight?\" — the one read, shared by every subsystem that\n * must not act mid-interaction (design-003 §8 terminal phases).\n *\n * Extracted from `doc/autosave.ts` on 2026-08-04 when the frame gate needed\n * the same question: autosave defers a save so it never captures a half-\n * applied interaction, and a freeze walks its settle until the gesture it\n * cancelled has reached its commit tick. One definition of \"in flight\", so the\n * two can never drift apart.\n */\nimport { Any, defineQuery } from \"@vibecook/strata-ecs\";\nimport type { World } from \"@vibecook/strata-ecs\";\nimport { Camera, Drag, GesturePhases, LongPress, Pinch, Tap, WheelPan, WheelZoom } from \"../catalog\";\n\nconst gestureQ = defineQuery([Any(Tap, LongPress, Drag, Pinch, WheelPan, WheelZoom)]);\nconst P = GesturePhases;\n\n/**\n * Any recognizer NOT in a terminal phase ⇒ a gesture is in flight (mirrors the\n * cleanup.ts terminal definition: Failed/Cancelled/Ended, plus Recognized-Tap).\n */\nexport function anyGestureNonTerminal(world: World): boolean {\n let active = false;\n world.query(gestureQ).each((b) => {\n for (const r of b) {\n const e = b.entity(r);\n const terminal =\n world.hasTag(e, P.tags.Failed) ||\n world.hasTag(e, P.tags.Cancelled) ||\n world.hasTag(e, P.tags.Ended) ||\n (world.hasTag(e, P.tags.Recognized) && world.has(e, Tap));\n if (!terminal) {\n active = true;\n return;\n }\n }\n });\n return active;\n}\n\n/**\n * The full mid-interaction read: a live camera gesture (pan/zoom, which writes\n * `Camera.gesturing` without a recognizer entity of its own) OR any recognizer\n * still walking its phases. Either means runtime edits are outstanding and the\n * durable transaction that will carry them has not been sealed yet.\n */\nexport function isMidGesture(world: World): boolean {\n return world.getResource(Camera)?.gesturing === true || anyGestureNonTerminal(world);\n}\n","/** `defineContainer` — an ordinary WidgetType with one fixed CanvasType portal. */\nimport type { CanvasType } from \"./define-canvas-type\";\nimport type { FrameProjection } from \"./frame-projection\";\nimport { defineWidget, type WidgetDef, type WidgetPortalInsets, type WidgetType } from \"../widget/define-widget\";\n\nexport interface ContainerIngressDef {\n readonly accepts?: readonly string[];\n readonly widgets?: readonly WidgetType[];\n}\n\nexport type ContainerDef = Omit<WidgetDef, \"container\" | \"provides\"> & {\n readonly canvas: CanvasType;\n /** Omission inherits the CanvasType's complete compiled legal placement set. */\n readonly drop?: ContainerIngressDef;\n readonly provides?: readonly string[];\n readonly portal?: WidgetPortalInsets;\n readonly frameProjection?: FrameProjection;\n};\n\nexport function defineContainer(def: ContainerDef): WidgetType {\n const { canvas, drop, provides, portal, frameProjection, ...widget } = def;\n return defineWidget({\n ...widget,\n container: {\n canvas,\n accepts: drop?.accepts ?? canvas.semantic.placement.accepts ?? [],\n widgets: drop?.widgets ?? [],\n inheritCanvasPlacement: drop === undefined,\n provides: provides ?? [],\n ...(portal === undefined ? {} : { portal }),\n ...(frameProjection === undefined ? {} : { frameProjection }),\n typed: true,\n },\n });\n}\n","/** One semantic placement authority for facade mutation and typed drop paths. */\nimport type { Entity, World } from \"@vibecook/strata-ecs\";\nimport { BoardRoot, ChildOf } from \"../catalog/scene\";\nimport { PrefabId } from \"../schema/prefab\";\nimport { canvasPackId } from \"./define-canvas-type\";\nimport type { EngineCatalog } from \"./engine-catalog\";\n\nexport type PlacementReason =\n | \"ok\"\n | \"unknown-widget\"\n | \"pack-disabled\"\n | \"target-dead\"\n | \"target-not-frame\"\n | \"unknown-canvas\"\n | \"canvas-pack-disabled\"\n | \"frame-behavior-unavailable\"\n | \"widget-not-allowed\"\n | \"ingress-rejected\"\n | \"cycle\"\n | \"malformed-parent\"\n | \"depth-limit\";\n\nexport type PlacementDecision =\n | { readonly ok: true; readonly canvasTypeId: string; readonly targetFrame: Entity }\n | {\n readonly ok: false;\n readonly reason: Exclude<PlacementReason, \"ok\">;\n readonly message: string;\n };\n\nexport interface PlacementAuthority {\n canPlace(widgetTypeId: string, targetFrame: Entity): PlacementDecision;\n canIngress(widgetTypeId: string, targetContainer: Entity): PlacementDecision;\n validateReparent(entity: Entity, targetFrame: Entity): PlacementDecision;\n assertPlace(widgetTypeId: string, targetFrame: Entity, operation: string): void;\n assertReparent(entity: Entity, targetFrame: Entity, operation: string): void;\n}\n\nexport interface PlacementAuthorityOpts {\n readonly world: World;\n readonly catalog: EngineCatalog;\n readonly rootCanvasTypeId: () => string | undefined;\n readonly packEnabled?: (id: string, version: number) => boolean;\n /** False while a required semantic FrameBehavior is faulted/suspended. */\n readonly canvasWritable?: (canvasTypeId: string) => boolean;\n readonly maxDepth?: number;\n}\n\nconst fail = (\n reason: Exclude<PlacementReason, \"ok\">,\n message: string,\n): PlacementDecision => ({ ok: false, reason, message });\n\nexport function createPlacementAuthority(opts: PlacementAuthorityOpts): PlacementAuthority {\n const { world, catalog } = opts;\n const maxDepth = opts.maxDepth ?? 64;\n\n const frameCanvas = (\n targetFrame: Entity,\n ): { readonly id: string; readonly depth: number } | PlacementDecision => {\n if (!world.isAlive(targetFrame)) return fail(\"target-dead\", \"target frame is not live\");\n const root = world.getResource(BoardRoot)?.root;\n if (root !== undefined && targetFrame === root) {\n const id = opts.rootCanvasTypeId();\n return id === undefined\n ? fail(\"unknown-canvas\", \"attached document has no root CanvasType\")\n : { id, depth: 0 };\n }\n\n const typeId = world.get(targetFrame, PrefabId)?.id;\n const widget = typeof typeId === \"string\" ? catalog.widget(typeId) : undefined;\n if (widget?.container === undefined) {\n return fail(\"target-not-frame\", \"target is neither BoardRoot nor a compiled container\");\n }\n\n let depth = 1;\n let current = targetFrame;\n const seen = new Set<Entity>([current]);\n while (true) {\n const parent = world.getRelation(current, ChildOf);\n if (parent === undefined) {\n return fail(\"malformed-parent\", \"container ancestry does not terminate at BoardRoot\");\n }\n if (root !== undefined && parent === root) break;\n if (seen.has(parent)) return fail(\"cycle\", \"container ancestry contains a ChildOf cycle\");\n seen.add(parent);\n const parentType = world.get(parent, PrefabId)?.id;\n const parentWidget = typeof parentType === \"string\" ? catalog.widget(parentType) : undefined;\n if (parentWidget?.container === undefined) {\n return fail(\"malformed-parent\", \"container ancestry passes through a non-container parent\");\n }\n depth += 1;\n if (depth > maxDepth) return fail(\"depth-limit\", `frame depth exceeds ${maxDepth}`);\n current = parent;\n }\n return { id: widget.container.canvasTypeId, depth };\n };\n\n const maxContainerHeight = (rootEntity: Entity): number | PlacementDecision => {\n const seen = new Set<Entity>();\n const walk = (entity: Entity, depth: number): number | PlacementDecision => {\n if (seen.has(entity)) return fail(\"cycle\", \"container subtree contains a ChildOf cycle\");\n seen.add(entity);\n let highest = depth;\n for (const child of world.getReverse(entity, ChildOf)) {\n const type = world.get(child, PrefabId)?.id;\n const widget = typeof type === \"string\" ? catalog.widget(type) : undefined;\n if (widget?.container === undefined) continue;\n const nested = walk(child, depth + 1);\n if (typeof nested !== \"number\") return nested;\n highest = Math.max(highest, nested);\n }\n seen.delete(entity);\n return highest;\n };\n return walk(rootEntity, 1);\n };\n\n const canPlace = (widgetTypeId: string, targetFrame: Entity): PlacementDecision => {\n const widget = catalog.widget(widgetTypeId);\n if (widget === undefined) return fail(\"unknown-widget\", `widget type \"${widgetTypeId}\" is not compiled`);\n if (opts.packEnabled !== undefined && !opts.packEnabled(widget.prefab.id, widget.version)) {\n return fail(\"pack-disabled\", `document does not enable widget pack \"${widget.prefab.id}\"@${widget.version}`);\n }\n const frame = frameCanvas(targetFrame);\n if (\"ok\" in frame) return frame;\n const canvas = catalog.canvasType(frame.id);\n if (canvas === undefined) return fail(\"unknown-canvas\", `CanvasType \"${frame.id}\" is not compiled`);\n if (\n opts.packEnabled !== undefined &&\n !opts.packEnabled(canvasPackId(canvas.id), canvas.semanticVersion)\n ) {\n return fail(\n \"canvas-pack-disabled\",\n `document does not enable CanvasType pack \"${canvas.id}\"@${canvas.semanticVersion}`,\n );\n }\n if (opts.canvasWritable?.(canvas.id) === false) {\n return fail(\n \"frame-behavior-unavailable\",\n `CanvasType \"${canvas.id}\" has an unavailable semantic FrameBehavior`,\n );\n }\n if (!catalog.placementFor(canvas.id).has(widgetTypeId)) {\n return fail(\n \"widget-not-allowed\",\n `CanvasType \"${canvas.id}\" does not allow widget \"${widgetTypeId}\"`,\n );\n }\n if (widget.container !== undefined && frame.depth + 1 > maxDepth) {\n return fail(\"depth-limit\", `creating this container would exceed frame depth ${maxDepth}`);\n }\n return { ok: true, canvasTypeId: canvas.id, targetFrame };\n };\n\n const canIngress = (widgetTypeId: string, targetContainer: Entity): PlacementDecision => {\n const placed = canPlace(widgetTypeId, targetContainer);\n if (!placed.ok) return placed;\n const targetType = world.get(targetContainer, PrefabId)?.id;\n const target = typeof targetType === \"string\" ? catalog.widget(targetType) : undefined;\n const ingress = target?.container;\n if (ingress === undefined) return fail(\"target-not-frame\", \"ingress target is not a compiled container\");\n if (ingress.inheritCanvasPlacement) return placed;\n const candidate = catalog.widget(widgetTypeId);\n if (candidate === undefined) return fail(\"unknown-widget\", `widget type \"${widgetTypeId}\" is not compiled`);\n const allowed =\n ingress.widgetTypeIds.includes(widgetTypeId) ||\n candidate.provides.some((key) => ingress.accepts.includes(key));\n return allowed\n ? placed\n : fail(\"ingress-rejected\", `container \"${targetType}\" rejects widget \"${widgetTypeId}\"`);\n };\n\n const validateReparent = (entity: Entity, targetFrame: Entity): PlacementDecision => {\n if (!world.isAlive(entity)) return fail(\"target-dead\", \"reparent source is not live\");\n if (entity === targetFrame) return fail(\"cycle\", \"an entity cannot parent itself\");\n const typeId = world.get(entity, PrefabId)?.id;\n if (typeof typeId !== \"string\") return fail(\"unknown-widget\", \"reparent source has no WidgetType\");\n const boardRoot = world.getResource(BoardRoot)?.root;\n const placed = targetFrame === boardRoot ? canPlace(typeId, targetFrame) : canIngress(typeId, targetFrame);\n if (!placed.ok) return placed;\n\n let ancestor: Entity | undefined = targetFrame;\n const seen = new Set<Entity>();\n for (let hops = 0; ancestor !== undefined && hops <= maxDepth; hops++) {\n if (ancestor === entity) return fail(\"cycle\", \"target frame is inside the entity's subtree\");\n if (seen.has(ancestor)) return fail(\"cycle\", \"target ancestry contains a ChildOf cycle\");\n seen.add(ancestor);\n ancestor = world.getRelation(ancestor, ChildOf);\n }\n\n const widget = catalog.widget(typeId);\n if (widget === undefined) return fail(\"unknown-widget\", `widget type \"${typeId}\" is not compiled`);\n if (widget.container !== undefined) {\n const target = frameCanvas(targetFrame);\n if (\"ok\" in target) return target;\n const height = maxContainerHeight(entity);\n if (typeof height !== \"number\") return height;\n if (target.depth + height > maxDepth) {\n return fail(\"depth-limit\", `reparent would exceed frame depth ${maxDepth}`);\n }\n }\n return placed;\n };\n\n return {\n canPlace,\n canIngress,\n validateReparent,\n assertPlace(widgetTypeId, targetFrame, operation) {\n const boardRoot = world.getResource(BoardRoot)?.root;\n const decision =\n targetFrame === boardRoot\n ? canPlace(widgetTypeId, targetFrame)\n : canIngress(widgetTypeId, targetFrame);\n if (!decision.ok) throw new Error(`ice: ${operation} — ${decision.message} (${decision.reason}).`);\n },\n assertReparent(entity, targetFrame, operation) {\n const decision = validateReparent(entity, targetFrame);\n if (!decision.ok) throw new Error(`ice: ${operation} — ${decision.message} (${decision.reason}).`);\n },\n };\n}\n","/** Deterministic, non-mutating diagnostics for remote/legacy frame violations. */\nimport { defineQuery, type Entity, type World } from \"@vibecook/strata-ecs\";\nimport type { DurableStore } from \"@vibecook/strata-ecs/durable\";\nimport { BoardRoot, ChildOf } from \"../catalog/scene\";\nimport type { DocVersionReport } from \"../doc/version-gate\";\nimport { PrefabId } from \"../schema/prefab\";\nimport type { EngineCatalog } from \"./engine-catalog\";\n\nconst durableQ = defineQuery([PrefabId]);\n\nexport type CanvasDiagnosticCode =\n | \"content-without-requirement\"\n | \"unknown-widget\"\n | \"malformed-parent\"\n | \"child-of-cycle\"\n | \"depth-limit\"\n | \"incompatible-placement\";\n\nexport interface CanvasDiagnostic {\n readonly code: CanvasDiagnosticCode;\n readonly key: string;\n readonly entity: Entity;\n readonly frame?: Entity;\n readonly canvasTypeId?: string;\n readonly message: string;\n /** This condition removes document-wide authority rather than locking one row. */\n readonly removesWriteAuthority: boolean;\n}\n\nexport interface CanvasDiagnosticSnapshot {\n readonly diagnostics: readonly CanvasDiagnostic[];\n readonly authorityIssue?: string;\n}\n\nfunction entityKey(store: DurableStore, entity: Entity): string {\n return String(store.keyOf(entity) ?? `runtime:${entity}`);\n}\n\nexport function collectCanvasDiagnostics(opts: {\n readonly world: World;\n readonly store: DurableStore;\n readonly catalog: EngineCatalog;\n readonly report: DocVersionReport;\n readonly maxDepth?: number;\n}): CanvasDiagnosticSnapshot {\n const { world, store, catalog, report } = opts;\n const maxDepth = opts.maxDepth ?? 64;\n const root = world.getResource(BoardRoot)?.root;\n const diagnostics: CanvasDiagnostic[] = [];\n const push = (\n entity: Entity,\n code: CanvasDiagnosticCode,\n message: string,\n extra: Pick<CanvasDiagnostic, \"frame\" | \"canvasTypeId\"> = {},\n ): void => {\n diagnostics.push({\n code,\n key: entityKey(store, entity),\n entity,\n message,\n removesWriteAuthority: code === \"content-without-requirement\",\n ...extra,\n });\n };\n\n world.query(durableQ).each((batch) => {\n for (const row of batch) {\n const entity = batch.entity(row);\n const typeId = world.read(entity, PrefabId).id;\n if (typeof typeId !== \"string\") continue;\n const widget = catalog.widget(typeId);\n if (widget === undefined) {\n push(entity, \"unknown-widget\", `WidgetType \"${typeId}\" is not compiled by this engine.`);\n if (report.docPacks[typeId] === undefined) {\n push(\n entity,\n \"content-without-requirement\",\n `Content for unknown WidgetType \"${typeId}\" arrived before a pack requirement.`,\n );\n }\n continue;\n }\n\n for (const [pack, version] of Object.entries(\n catalog.requirementsForWidget(typeId) ?? {},\n )) {\n if (report.docPacks[pack] !== version) {\n push(\n entity,\n \"content-without-requirement\",\n `Widget \"${typeId}\" requires ${pack}@${version}, but the document does not.`,\n );\n }\n }\n\n const parent = world.getRelation(entity, ChildOf);\n if (parent === undefined) {\n push(entity, \"malformed-parent\", `Widget \"${typeId}\" has no direct CanvasFrame owner.`);\n continue;\n }\n\n const frame = parent;\n let canvasTypeId: string | undefined;\n if (parent === root) {\n canvasTypeId = report.rootCanvas?.id;\n } else {\n const parentType = world.get(parent, PrefabId)?.id;\n const container =\n typeof parentType === \"string\" ? catalog.widget(parentType)?.container : undefined;\n if (container === undefined) {\n push(\n entity,\n \"malformed-parent\",\n `Widget \"${typeId}\" is directly owned by a non-container entity.`,\n { frame },\n );\n continue;\n }\n canvasTypeId = container.canvasTypeId;\n }\n\n const seen = new Set<Entity>([entity]);\n let cursor: Entity | undefined = parent;\n let depth = 0;\n while (cursor !== undefined && cursor !== root) {\n if (seen.has(cursor)) {\n push(entity, \"child-of-cycle\", `Widget \"${typeId}\" belongs to a ChildOf cycle.`, {\n frame,\n ...(canvasTypeId === undefined ? {} : { canvasTypeId }),\n });\n break;\n }\n seen.add(cursor);\n cursor = world.getRelation(cursor, ChildOf);\n depth += 1;\n if (depth + (widget.container === undefined ? 0 : 1) > maxDepth) {\n push(entity, \"depth-limit\", `Widget \"${typeId}\" exceeds frame depth ${maxDepth}.`, {\n frame,\n ...(canvasTypeId === undefined ? {} : { canvasTypeId }),\n });\n break;\n }\n }\n if (cursor === undefined) {\n push(entity, \"malformed-parent\", `Widget \"${typeId}\" ancestry does not reach BoardRoot.`, {\n frame,\n ...(canvasTypeId === undefined ? {} : { canvasTypeId }),\n });\n }\n\n if (\n canvasTypeId !== undefined &&\n catalog.canvasType(canvasTypeId) !== undefined &&\n !catalog.placementFor(canvasTypeId).has(typeId)\n ) {\n push(\n entity,\n \"incompatible-placement\",\n `CanvasType \"${canvasTypeId}\" does not allow WidgetType \"${typeId}\".`,\n { frame, canvasTypeId },\n );\n }\n }\n });\n\n diagnostics.sort(\n (a, b) => a.key.localeCompare(b.key) || a.code.localeCompare(b.code) || a.message.localeCompare(b.message),\n );\n const authority = diagnostics.find((diagnostic) => diagnostic.removesWriteAuthority);\n return Object.freeze({\n diagnostics: Object.freeze(diagnostics),\n ...(authority === undefined ? {} : { authorityIssue: authority.message }),\n });\n}\n","/**\n * Demand-driven, immutable semantic previews for container frames.\n *\n * This store intentionally has no timer and no eager frame index. A frame pays\n * for observers and projection work only while at least one consumer is\n * subscribed. Projection authors receive declared, bounded plain reads rather\n * than a World or document handle.\n */\nimport {\n Related,\n defineQuery,\n type Component,\n type Entity,\n type Relation,\n type World,\n} from \"@vibecook/strata-ecs\";\nimport type { DurableStore } from \"@vibecook/strata-ecs/durable\";\nimport {\n CameraLimits,\n ChildOf,\n Position,\n Size,\n Viewport,\n} from \"../catalog\";\nimport { PrefabId } from \"../schema/prefab\";\nimport { schemaMeta } from \"../schema/meta\";\nimport type { CanvasDiagnostic } from \"./diagnostics\";\nimport type { EngineCatalog } from \"./engine-catalog\";\nimport { CanvasSession } from \"./session\";\nimport type {\n FrameProjection,\n FrameProjectionChildRef,\n FrameProjectionRelationRow,\n} from \"./frame-projection\";\nimport {\n resolveFrameChildren,\n resolveFrameView,\n resolvePortal,\n type CanvasRect,\n} from \"./frame-view\";\n\nexport const FRAME_PREVIEW_DEFAULT_CHILDREN = 128;\nexport const FRAME_PREVIEW_DEFAULT_BYTES = 256 * 1024;\nexport const FRAME_PREVIEW_MAX_CHILDREN = 256;\nexport const FRAME_PREVIEW_MAX_BYTES = 512 * 1024;\n/** Smallest budget that can contain the mandatory immutable preview envelope. */\nexport const FRAME_PREVIEW_MIN_BYTES = 512;\n\nexport type FramePreviewValidity = \"valid\" | \"incompatible\" | \"malformed-parent\";\n\nexport interface FramePreviewChild {\n readonly key: string;\n readonly widgetType: string;\n readonly rect: CanvasRect;\n readonly order: number;\n readonly validity: FramePreviewValidity;\n}\n\nexport interface FramePreviewSnapshot {\n readonly revision: number;\n readonly frameKey: string;\n readonly bounds: CanvasRect;\n readonly resolvedView: { readonly x: number; readonly y: number; readonly zoom: number };\n /** Destination viewport used by the shared arrival-camera solve. */\n readonly viewport: { readonly width: number; readonly height: number };\n readonly portal: CanvasRect;\n readonly totalChildren: number;\n readonly truncated: boolean;\n readonly children: readonly FramePreviewChild[];\n readonly facets: Readonly<Record<string, unknown>>;\n}\n\nexport interface FramePreviewBudgets {\n readonly children?: number;\n readonly bytes?: number;\n}\n\nexport interface FramePreviewStats {\n readonly activeFrames: number;\n readonly observers: number;\n readonly rebuilds: number;\n readonly projectionRuns: number;\n}\n\nexport interface FramePreviewStore {\n /** Pure snapshot read. It never arms observers or performs a projection. */\n snapshot(frame: Entity): FramePreviewSnapshot;\n /** First subscriber activates; the last exact inverse removes every observer. */\n subscribe(frame: Entity, onChange: () => void): () => void;\n /** Re-arm active entries after a document import/reset invalidates reactivity. */\n rebind(): void;\n stats(): FramePreviewStats;\n dispose(): void;\n}\n\nexport interface FramePreviewStoreOpts {\n readonly world: World;\n readonly catalog: EngineCatalog;\n readonly session: () => {\n readonly documentEpoch: number;\n readonly store?: Pick<DurableStore, \"keyOf\">;\n };\n readonly diagnostics: () => readonly CanvasDiagnostic[];\n readonly budgets?: FramePreviewBudgets;\n readonly onFault?: (projectionId: string, error: unknown) => void;\n}\n\ntype Entry = {\n readonly frame: Entity;\n readonly listeners: Set<() => void>;\n snapshot: FramePreviewSnapshot;\n signature: string;\n revision: number;\n unsubs: (() => void)[];\n childUnsubs: (() => void)[];\n effectiveChildren: readonly Entity[];\n observedChildren: readonly Entity[];\n observedShape: string;\n scheduled: boolean;\n projectionFailed: string | undefined;\n};\n\nconst encoder = new TextEncoder();\nconst EMPTY_RECT: CanvasRect = Object.freeze({ x: 0, y: 0, width: 0, height: 0 });\nconst EMPTY_VIEW = Object.freeze({ x: 0, y: 0, zoom: 1 });\nconst EMPTY_FACETS: Readonly<Record<string, unknown>> = Object.freeze({});\nconst BASE_COMPONENTS: readonly Component[] = Object.freeze([\n Position,\n Size,\n PrefabId,\n]);\nconst MAX_OPAQUE_DURABLE_KEY_BYTES = 1024;\n\nfunction assertLoweredBudget(\n label: string,\n requested: number | undefined,\n fallback: number,\n minimum: number,\n hardMax: number,\n): number {\n const value = requested ?? fallback;\n if (!Number.isSafeInteger(value) || value < minimum || value > hardMax) {\n throw new Error(\n `ice: ${label} must be an integer between ${minimum} and ${hardMax}.`,\n );\n }\n return value;\n}\n\nfunction opaqueKey(\n store: Pick<DurableStore, \"keyOf\"> | undefined,\n documentEpoch: number,\n entity: Entity,\n): string {\n const durable = store?.keyOf(entity);\n if (durable === undefined) return `${documentEpoch}:${entity}`;\n const value = String(durable);\n // Keys are presentation-only and never accepted by mutation APIs. Avoid one\n // hostile/legacy durable key consuming the entire bounded snapshot.\n return encoder.encode(value).byteLength <= MAX_OPAQUE_DURABLE_KEY_BYTES\n ? value\n : `${documentEpoch}:${entity}`;\n}\n\nfunction emptySnapshot(frameKey: string): FramePreviewSnapshot {\n return Object.freeze({\n revision: 0,\n frameKey,\n bounds: EMPTY_RECT,\n resolvedView: EMPTY_VIEW,\n viewport: Object.freeze({ width: 0, height: 0 }),\n portal: EMPTY_RECT,\n totalChildren: 0,\n truncated: false,\n children: Object.freeze([]),\n facets: EMPTY_FACETS,\n });\n}\n\n/** Strict plain-data clone. Sorting keys makes its JSON encoding canonical. */\nfunction plain(value: unknown, seen = new Set<object>()): unknown {\n if (value === null || typeof value === \"string\" || typeof value === \"boolean\") return value;\n if (typeof value === \"number\") {\n if (!Number.isFinite(value)) throw new Error(\"projection output contains a non-finite number\");\n return value;\n }\n if (typeof value !== \"object\") {\n throw new Error(`projection output contains non-JSON value ${typeof value}`);\n }\n if (seen.has(value)) throw new Error(\"projection output contains a cycle\");\n const proto = Object.getPrototypeOf(value);\n if (proto !== Object.prototype && proto !== null && !Array.isArray(value)) {\n throw new Error(\"projection output contains a non-plain object\");\n }\n seen.add(value);\n try {\n if (Array.isArray(value)) {\n return Object.freeze(value.map((item) => plain(item, seen)));\n }\n const out: Record<string, unknown> = {};\n for (const key of Object.keys(value as Record<string, unknown>).sort()) {\n out[key] = plain((value as Record<string, unknown>)[key], seen);\n }\n return Object.freeze(out);\n } finally {\n seen.delete(value);\n }\n}\n\nfunction canonical(value: unknown): string {\n return JSON.stringify(value);\n}\n\nfunction bytes(value: unknown): number {\n return encoder.encode(canonical(value)).byteLength;\n}\n\nfunction parseJsonCell(value: unknown, fallback: string | undefined): unknown {\n if (typeof value !== \"string\") return null;\n try {\n return JSON.parse(value);\n } catch {\n try {\n return JSON.parse(fallback ?? \"null\");\n } catch {\n return null;\n }\n }\n}\n\nfunction uniqueComponents(projection: FrameProjection | undefined): readonly Component[] {\n const out: Component[] = [];\n const seen = new Set<Component>();\n for (const component of [...BASE_COMPONENTS, ...(projection?.reads ?? [])]) {\n if (seen.has(component)) continue;\n seen.add(component);\n out.push(component);\n }\n return out;\n}\n\nfunction validityFor(\n entity: Entity,\n diagnostics: readonly CanvasDiagnostic[],\n): FramePreviewValidity {\n let validity: FramePreviewValidity = \"valid\";\n for (const diagnostic of diagnostics) {\n if (diagnostic.entity !== entity) continue;\n if (\n diagnostic.code === \"malformed-parent\" ||\n diagnostic.code === \"child-of-cycle\" ||\n diagnostic.code === \"depth-limit\"\n ) {\n return \"malformed-parent\";\n }\n if (diagnostic.code === \"incompatible-placement\" || diagnostic.code === \"unknown-widget\") {\n validity = \"incompatible\";\n }\n }\n return validity;\n}\n\nexport function createFramePreviewStore(opts: FramePreviewStoreOpts): FramePreviewStore {\n const { world, catalog } = opts;\n const childBudget = assertLoweredBudget(\n \"frame preview child budget\",\n opts.budgets?.children,\n FRAME_PREVIEW_DEFAULT_CHILDREN,\n 1,\n FRAME_PREVIEW_MAX_CHILDREN,\n );\n const byteBudget = assertLoweredBudget(\n \"frame preview byte budget\",\n opts.budgets?.bytes,\n FRAME_PREVIEW_DEFAULT_BYTES,\n FRAME_PREVIEW_MIN_BYTES,\n FRAME_PREVIEW_MAX_BYTES,\n );\n const entries = new Map<Entity, Entry>();\n let disposed = false;\n let observerCount = 0;\n let rebuildCount = 0;\n let projectionRuns = 0;\n\n const reportProjectionFault = (id: string, error: unknown): void => {\n try {\n opts.onFault?.(id, error);\n } catch {\n // Reporting is never allowed to break silhouettes or later listeners.\n }\n };\n\n const identify = (entity: Entity): string => {\n const current = opts.session();\n return opaqueKey(current.store, current.documentEpoch, entity);\n };\n\n const definition = (frame: Entity) => {\n const typeId = world.get(frame, PrefabId)?.id;\n if (typeof typeId !== \"string\") return {};\n const widget = catalog.widget(typeId);\n const binding = widget?.container;\n if (binding === undefined) return {};\n return {\n typeId,\n binding,\n canvas: catalog.canvasForContainer(typeId),\n projection: catalog.frameProjectionForContainer(typeId),\n };\n };\n\n const isContainer = (entity: Entity): boolean => {\n const typeId = world.get(entity, PrefabId)?.id;\n return typeof typeId === \"string\" && catalog.widget(typeId)?.container !== undefined;\n };\n\n const relationRows = (\n frame: Entity,\n frameKey: string,\n children: readonly Entity[],\n keys: ReadonlyMap<Entity, string>,\n relation: Relation,\n ): readonly FrameProjectionRelationRow[] => {\n const scope = new Set<Entity>([frame, ...children]);\n const meta = schemaMeta.relation(relation);\n if (meta === undefined) return Object.freeze([]);\n const rows: FrameProjectionRelationRow[] = [];\n const key = (entity: Entity) => (entity === frame ? frameKey : keys.get(entity));\n for (const source of scope) {\n const targets =\n meta.arity === \"one\"\n ? (() => {\n const target = world.getRelation(source, relation);\n return target === undefined ? [] : [target];\n })()\n : world.getRelations(source, relation);\n for (const target of targets) {\n if (!scope.has(target)) continue;\n const sourceKey = key(source);\n const targetKey = key(target);\n if (sourceKey !== undefined && targetKey !== undefined) {\n rows.push(Object.freeze({ source: sourceKey, target: targetKey }));\n }\n }\n }\n rows.sort((a, b) => a.source.localeCompare(b.source) || a.target.localeCompare(b.target));\n return Object.freeze(rows);\n };\n\n const runProjection = (\n entry: Entry,\n projection: FrameProjection | undefined,\n frameKey: string,\n children: readonly Entity[],\n refs: readonly FrameProjectionChildRef[],\n keys: ReadonlyMap<Entity, string>,\n ): Readonly<Record<string, unknown>> => {\n if (projection === undefined || entry.projectionFailed === projection.id) return EMPTY_FACETS;\n const declared = new Set(projection.reads);\n const byKey = new Map<string, Entity>();\n for (const child of children) {\n const key = keys.get(child);\n if (key !== undefined) byKey.set(key, child);\n }\n const relations = new Map(\n projection.relations.map((relation) => [\n relation,\n relationRows(entry.frame, frameKey, children, keys, relation),\n ]),\n );\n try {\n projectionRuns += 1;\n const projected = projection.project({\n frameKey,\n children: refs,\n get(childKey, component) {\n if (!declared.has(component)) {\n throw new Error(`FrameProjection \"${projection.id}\" read an undeclared component.`);\n }\n const entity = byKey.get(childKey);\n return entity === undefined ? undefined : world.get(entity, component);\n },\n relations(relation) {\n const rows = relations.get(relation);\n if (rows === undefined) {\n throw new Error(`FrameProjection \"${projection.id}\" read an undeclared relation.`);\n }\n return rows;\n },\n });\n const normalized = plain(projected);\n if (\n normalized === null ||\n Array.isArray(normalized) ||\n typeof normalized !== \"object\"\n ) {\n throw new Error(\"projection output must be a plain facets record\");\n }\n if (bytes(normalized) > byteBudget) {\n throw new Error(`projection output exceeds the ${byteBudget}-byte portal budget`);\n }\n return normalized as Readonly<Record<string, unknown>>;\n } catch (error) {\n entry.projectionFailed = projection.id;\n reportProjectionFault(projection.id, error);\n return EMPTY_FACETS;\n }\n };\n\n const build = (entry: Entry): void => {\n if (disposed || entry.listeners.size === 0) return;\n rebuildCount += 1;\n const current = opts.session();\n const frameKey = opaqueKey(current.store, current.documentEpoch, entry.frame);\n const def = definition(entry.frame);\n const allChildren = entry.effectiveChildren;\n const scoped = allChildren.slice(0, childBudget);\n const keys = new Map<Entity, string>();\n const refs: FrameProjectionChildRef[] = [];\n const diagnostics = opts.diagnostics();\n const children: FramePreviewChild[] = [];\n for (let order = 0; order < scoped.length; order += 1) {\n const entity = scoped[order] as Entity;\n const widgetType = world.get(entity, PrefabId)?.id;\n if (typeof widgetType !== \"string\") continue;\n const key = opaqueKey(current.store, current.documentEpoch, entity);\n keys.set(entity, key);\n refs.push(Object.freeze({ key, widgetType, order }));\n const position = world.get(entity, Position) ?? { x: 0, y: 0 };\n const size = world.get(entity, Size) ?? { w: 0, h: 0 };\n children.push(\n Object.freeze({\n key,\n widgetType,\n rect: Object.freeze({ x: position.x, y: position.y, width: size.w, height: size.h }),\n order,\n validity: validityFor(entity, diagnostics),\n }),\n );\n }\n let facets = runProjection(\n entry,\n def.projection,\n frameKey,\n scoped,\n Object.freeze(refs),\n keys,\n );\n const view = resolveFrameView(world, entry.frame, def.canvas, { isContainer });\n const portal = resolvePortal(world, entry.frame, def.binding)?.local ?? EMPTY_RECT;\n const viewportResource = world.getResource(Viewport);\n const viewport = Object.freeze({\n width: viewportResource?.w ?? 0,\n height: viewportResource?.h ?? 0,\n });\n\n const fixedRecord = (value: Readonly<Record<string, unknown>>) => ({\n revision: entry.revision + 1,\n frameKey,\n bounds: view.bounds,\n resolvedView: view.camera,\n viewport,\n portal,\n totalChildren: allChildren.length,\n truncated: allChildren.length > children.length,\n children: [] as readonly FramePreviewChild[],\n facets: value,\n });\n let fixed = fixedRecord(facets);\n let used = bytes(fixed);\n if (used > byteBudget && facets !== EMPTY_FACETS && def.projection !== undefined) {\n const error = new Error(\n `projection output plus fixed record exceeds the ${byteBudget}-byte portal budget`,\n );\n entry.projectionFailed = def.projection.id;\n reportProjectionFault(def.projection.id, error);\n facets = EMPTY_FACETS;\n fixed = fixedRecord(facets);\n used = bytes(fixed);\n }\n const admitted: FramePreviewChild[] = [];\n for (const child of children) {\n const cost = bytes(child) + (admitted.length === 0 ? 0 : 1);\n if (used + cost > byteBudget) break;\n admitted.push(child);\n used += cost;\n }\n const value = {\n frameKey,\n bounds: Object.freeze({ ...view.bounds }),\n resolvedView: Object.freeze({ ...view.camera }),\n viewport,\n portal: Object.freeze({ ...portal }),\n totalChildren: allChildren.length,\n truncated: allChildren.length > admitted.length,\n children: Object.freeze(admitted),\n facets,\n };\n const signature = canonical(value);\n if (signature === entry.signature) return;\n entry.signature = signature;\n entry.revision += 1;\n entry.snapshot = Object.freeze({ revision: entry.revision, ...value });\n for (const listener of [...entry.listeners]) {\n try {\n listener();\n } catch {\n // One UI subscriber cannot block another or poison the projection job.\n }\n }\n };\n\n const schedule = (entry: Entry): void => {\n if (disposed || entry.listeners.size === 0 || entry.scheduled) return;\n entry.scheduled = true;\n queueMicrotask(() => {\n entry.scheduled = false;\n if (disposed || entry.listeners.size === 0) return;\n rewireChildren(entry);\n build(entry);\n });\n };\n\n const observe = (entry: Entry, subscribe: () => () => void): void => {\n entry.unsubs.push(subscribe());\n observerCount += 1;\n };\n\n const clearChildObservers = (entry: Entry): void => {\n for (const unsub of entry.childUnsubs.splice(0)) {\n unsub();\n observerCount -= 1;\n }\n };\n\n const rewireChildren = (entry: Entry): void => {\n if (!world.isAlive(entry.frame)) {\n if (entry.observedChildren.length > 0) {\n clearChildObservers(entry);\n entry.observedChildren = Object.freeze([]);\n }\n entry.effectiveChildren = Object.freeze([]);\n entry.observedShape = \"\";\n return;\n }\n const def = definition(entry.frame);\n const effective = resolveFrameChildren(world, entry.frame, { isContainer }).filter(\n (entity) => world.get(entity, PrefabId) !== undefined,\n );\n entry.effectiveChildren = effective;\n const next = effective.slice(0, childBudget);\n const shape = `${def.projection?.id ?? \"\"}@${def.projection?.version ?? 0}|${next\n .map((entity) => world.get(entity, PrefabId)?.id ?? \"\")\n .join(\"\\u0000\")}`;\n if (\n shape === entry.observedShape &&\n next.length === entry.observedChildren.length &&\n next.every((entity, index) => entity === entry.observedChildren[index])\n ) {\n return;\n }\n clearChildObservers(entry);\n entry.observedChildren = Object.freeze(next);\n entry.observedShape = shape;\n for (const entity of next) {\n const components = [...uniqueComponents(def.projection)];\n for (const component of components) {\n entry.childUnsubs.push(world.reactive.observeValue(entity, component, () => schedule(entry)));\n observerCount += 1;\n }\n if (!isContainer(entity)) {\n const membership = defineQuery([PrefabId, Related(ChildOf, entity)]);\n entry.childUnsubs.push(\n world.reactive.observeQuery(membership, () => schedule(entry), { cols: [] }),\n );\n observerCount += 1;\n }\n }\n };\n\n const deactivate = (entry: Entry): void => {\n clearChildObservers(entry);\n for (const unsub of entry.unsubs.splice(0)) {\n unsub();\n observerCount -= 1;\n }\n entry.observedChildren = Object.freeze([]);\n entry.effectiveChildren = Object.freeze([]);\n entry.observedShape = \"\";\n entry.scheduled = false;\n };\n\n const activate = (entry: Entry): void => {\n const def = definition(entry.frame);\n entry.projectionFailed = undefined;\n // Arm the order stamp before the initial pull, matching sibling-order's\n // membership/reorder contract.\n if (world.isAlive(entry.frame)) world.orderStamp(entry.frame, ChildOf);\n const membership = defineQuery([PrefabId, Related(ChildOf, entry.frame)]);\n observe(entry, () => world.reactive.observeQuery(membership, () => schedule(entry), { cols: [] }));\n for (const relation of def.projection?.relations ?? []) {\n const relationWake = defineQuery([Related(relation)]);\n observe(entry, () =>\n world.reactive.observeQuery(relationWake, () => schedule(entry), { cols: [] }),\n );\n }\n observe(entry, () => world.reactive.observeValue(entry.frame, Position, () => schedule(entry)));\n observe(entry, () => world.reactive.observeValue(entry.frame, Size, () => schedule(entry)));\n observe(entry, () => world.reactive.observeValue(entry.frame, PrefabId, () => schedule(entry)));\n observe(entry, () => world.reactive.observeResource(Viewport, () => schedule(entry)));\n observe(entry, () => world.reactive.observeResource(CameraLimits, () => schedule(entry)));\n observe(entry, () => world.reactive.observeResource(CanvasSession, () => schedule(entry)));\n rewireChildren(entry);\n build(entry);\n };\n\n const getEntry = (frame: Entity): Entry => {\n const existing = entries.get(frame);\n if (existing !== undefined) return existing;\n const entry: Entry = {\n frame,\n listeners: new Set(),\n snapshot: emptySnapshot(identify(frame)),\n signature: \"\",\n revision: 0,\n unsubs: [],\n childUnsubs: [],\n effectiveChildren: Object.freeze([]),\n observedChildren: Object.freeze([]),\n observedShape: \"\",\n scheduled: false,\n projectionFailed: undefined,\n };\n entries.set(frame, entry);\n return entry;\n };\n\n return {\n snapshot(frame) {\n return getEntry(frame).snapshot;\n },\n subscribe(frame, onChange) {\n if (disposed) return () => {};\n const entry = getEntry(frame);\n const wasInactive = entry.listeners.size === 0;\n // A unique wrapper preserves subscription multiplicity even when two\n // consumers happen to pass the same callback identity.\n const listener = () => onChange();\n entry.listeners.add(listener);\n if (wasInactive) activate(entry);\n let active = true;\n return () => {\n if (!active) return;\n active = false;\n entry.listeners.delete(listener);\n if (entry.listeners.size === 0) deactivate(entry);\n };\n },\n rebind() {\n if (disposed) return;\n for (const entry of entries.values()) {\n if (entry.listeners.size === 0) continue;\n deactivate(entry);\n activate(entry);\n }\n },\n stats: () => ({\n activeFrames: [...entries.values()].filter((entry) => entry.listeners.size > 0).length,\n observers: observerCount,\n rebuilds: rebuildCount,\n projectionRuns,\n }),\n dispose() {\n if (disposed) return;\n disposed = true;\n for (const entry of entries.values()) deactivate(entry);\n entries.clear();\n },\n };\n}\n","/**\n * Epoch-keyed presentation retention for cut-first nested-canvas navigation.\n *\n * Core owns only timing, identity, and exact release. DOM/GL/Ground adapters\n * synchronously capture their already-presented state in `prepare`; they never\n * receive a World and cannot delay or veto the authority cut.\n */\nimport type { Entity, World } from \"@vibecook/strata-ecs\";\nimport type { CameraState, PortalAffine } from \"@ice/kernel\";\nimport { Camera } from \"../catalog\";\nimport type { Engine } from \"../engine/engine\";\nimport { FrameInfo } from \"../engine/frame-info\";\nimport { departedCameraOf, NavTransition } from \"../systems/nav-flight\";\n/**\n * The ONE presentation plane (design-015 §1, D5b). Until D5b this was\n * `\"ground\" | \"dom\" | \"gl\"` — a DOM widget needed the `dom` plane's adapter to\n * prepare its outgoing hosts and a GL island the `gl` plane's — and\n * `presentationPlanesOf(widget)` said which a type needed. Everything under the\n * camera is the desk's now, so a flight prepares `ground` and nothing else; the\n * type stays a union of one so the coordinator's plane ownership keeps its shape.\n */\nexport type PresentationPlane = \"ground\";\nexport type PresentationReleaseReason =\n | \"settled\"\n | \"interrupted\"\n | \"superseded\"\n | \"detached\"\n | \"fault\"\n | \"timeout\"\n | \"cancelled\";\n\nexport interface FrameSwitchDescriptor {\n readonly kind: \"enter\" | \"exit\";\n readonly documentEpoch: number;\n readonly fromFrame: Entity;\n readonly toFrame: Entity;\n readonly fromTypeId: string;\n readonly toTypeId: string;\n readonly fromCamera: CameraState;\n readonly toCamera: CameraState;\n readonly affine: PortalAffine;\n /** Geometry and caller policy permit motion; adapter completeness is evaluated later. */\n readonly requestedMotion: boolean;\n /** Cross-program motion may proceed only when every required plane prepared. */\n readonly requiresFullT2: boolean;\n readonly requiredPlanes: readonly PresentationPlane[];\n}\n\n/** Geometry/identity assembled by core navigation before policy adds plane requirements. */\nexport type FrameSwitchRequest = Omit<\n FrameSwitchDescriptor,\n \"requiresFullT2\" | \"requiredPlanes\"\n>;\n\nexport type PresentationMotion = \"flight\" | \"crossfade\" | \"fast-fade\";\n\nexport interface PresentationTransitionFrame {\n readonly epoch: number;\n readonly descriptor: FrameSwitchDescriptor;\n readonly motion: PresentationMotion;\n readonly camera: CameraState;\n readonly outgoingCamera: CameraState;\n readonly progress: number;\n readonly outgoingOpacity: number;\n readonly incomingOpacity: number;\n readonly frozen: boolean;\n}\n\nexport interface PresentationRetainer {\n update(frame: PresentationTransitionFrame): void;\n /** Exact and idempotent on the adapter side. */\n release(reason: PresentationReleaseReason): void;\n}\n\nexport interface PresentationTransitionAdapter {\n readonly id: string;\n readonly plane: PresentationPlane;\n /** `null` means this plane has no outgoing visual but prepared successfully. */\n prepare(descriptor: FrameSwitchDescriptor): PresentationRetainer | null;\n}\n\nexport interface PreparedFrameSwitch {\n readonly complete: boolean;\n readonly allowFlight: boolean;\n commit(): void;\n /**\n * Release a preparation that will not commit. `cancelled` is reserved for a\n * rollback before navigation authority changes; callers that already\n * mutated authority must pass the actual terminal reason (normally\n * `fault`).\n */\n cancel(reason?: PresentationReleaseReason): void;\n}\n\nexport interface PresentationTransitionStats {\n readonly active: boolean;\n readonly epoch: number;\n readonly motion?: PresentationMotion;\n readonly retainers: number;\n readonly adapters: number;\n readonly reducedMotion: boolean;\n}\n\nexport interface PresentationTransitionCoordinator {\n register(adapter: PresentationTransitionAdapter): () => void;\n /**\n * The id of the adapter that owns `plane`, or `undefined` when the plane is\n * free (D-C4.6). A plane is single-owner and {@link register} THROWS on a\n * second claim — inside a `useEffect` that unmounts the React tree — so a\n * host that may be mounted twice on one engine asks here first.\n */\n ownerOf(plane: PresentationPlane): string | undefined;\n prepare(descriptor: FrameSwitchDescriptor): PreparedFrameSwitch;\n abort(reason?: PresentationReleaseReason): void;\n setReducedMotion(value: boolean): void;\n reducedMotion(): boolean;\n stats(): PresentationTransitionStats;\n dispose(): void;\n}\n\ntype ActiveTransition = {\n readonly epoch: number;\n readonly descriptor: FrameSwitchDescriptor;\n readonly retainers: Map<string, PresentationRetainer>;\n motion: PresentationMotion;\n readonly startedAtMs: number;\n elapsedMs: number;\n fadeElapsedMs: number;\n fadeFrom: number;\n lastOutgoingOpacity: number;\n};\n\ntype PendingTransition = {\n finish(reason: PresentationReleaseReason): void;\n /**\n * Release just one adapter's retainer, for an adapter that unregistered\n * while this preparation was still in flight. `finish` is all-or-nothing and\n * belongs to the navigation; this is the single-plane detach.\n */\n detach(id: string): void;\n};\n\nconst CROSSFADE_MS = 160;\nconst FAST_FADE_MS = 150;\nconst HOLD_CEILING_MS = 2_000;\n/** Adapters prepare in plane order (one plane since D5b; the DOM plane used to go first). */\nconst PREPARE_ORDER: Readonly<Record<PresentationPlane, number>> = Object.freeze({\n ground: 0,\n});\n\nconst clamp01 = (value: number): number => Math.min(1, Math.max(0, value));\nconst smooth = (value: number): number => {\n const x = clamp01(value);\n return x * x * (3 - 2 * x);\n};\nconst ramp = (value: number, from: number, to: number): number =>\n to <= from ? (value >= to ? 1 : 0) : smooth((value - from) / (to - from));\n\nfunction opacityAt(\n kind: \"enter\" | \"exit\",\n progress: number,\n frozen: boolean,\n): { outgoing: number; incoming: number } {\n if (frozen) {\n return {\n outgoing: 1 - ramp(progress, 0.05, 0.45),\n incoming: ramp(progress, 0.3, 0.7),\n };\n }\n return {\n outgoing:\n kind === \"enter\" ? 1 - ramp(progress, 0.3, 0.75) : 1 - ramp(progress, 0.85, 1),\n incoming: 1,\n };\n}\n\nexport function createPresentationTransitionCoordinator(\n world: World,\n engine: Engine,\n opts: { readonly onFault?: (adapterId: string, error: unknown) => void } = {},\n): PresentationTransitionCoordinator {\n const adapters = new Map<string, PresentationTransitionAdapter>();\n let active: ActiveTransition | undefined;\n let pending: PendingTransition | undefined;\n let prepareSequence = 0;\n let prefersReducedMotion = false;\n let disposed = false;\n\n const reportFault = (id: string, error: unknown): void => {\n try {\n opts.onFault?.(id, error);\n } catch {\n // Presentation diagnostics cannot interrupt authority or exact release.\n }\n };\n\n const release = (reason: PresentationReleaseReason): void => {\n const current = active;\n active = undefined;\n if (current === undefined) return;\n for (const [id, retainer] of current.retainers) {\n try {\n retainer.release(reason);\n } catch (error) {\n reportFault(id, error);\n }\n }\n current.retainers.clear();\n };\n\n const update = (current: ActiveTransition): void => {\n const transition = world.getResource(NavTransition);\n if (transition === undefined || transition.epoch !== current.epoch) {\n release(\"superseded\");\n return;\n }\n const frameInfo = world.getResource(FrameInfo);\n const dt = Math.max(0, frameInfo?.dt ?? 16);\n current.elapsedMs += dt;\n const wallElapsedMs = Math.max(\n current.elapsedMs,\n frameInfo === undefined ? 0 : frameInfo.now - current.startedAtMs,\n );\n if (wallElapsedMs >= HOLD_CEILING_MS) {\n release(\"timeout\");\n return;\n }\n\n const cameraCell = world.getResource(Camera);\n const camera: CameraState = cameraCell ?? current.descriptor.toCamera;\n let progress = clamp01(transition.p);\n let outgoingOpacity: number;\n let incomingOpacity: number;\n let shouldRelease = false;\n let releaseReason: PresentationReleaseReason = \"settled\";\n\n if (current.motion === \"crossfade\") {\n current.fadeElapsedMs += dt;\n progress = clamp01(current.fadeElapsedMs / CROSSFADE_MS);\n outgoingOpacity = 1 - smooth(progress);\n incomingOpacity = smooth(progress);\n shouldRelease = progress >= 1;\n } else if (current.motion === \"fast-fade\") {\n current.fadeElapsedMs += dt;\n progress = clamp01(current.fadeElapsedMs / FAST_FADE_MS);\n outgoingOpacity = current.fadeFrom * (1 - smooth(progress));\n incomingOpacity = 1;\n shouldRelease = progress >= 1;\n releaseReason = \"interrupted\";\n } else {\n const opacity = opacityAt(current.descriptor.kind, progress, transition.frozen);\n outgoingOpacity = opacity.outgoing;\n incomingOpacity = opacity.incoming;\n if (!transition.active) {\n if (transition.p >= 1) {\n shouldRelease = true;\n } else {\n current.motion = \"fast-fade\";\n current.fadeElapsedMs = 0;\n current.fadeFrom = outgoingOpacity;\n }\n }\n }\n current.lastOutgoingOpacity = outgoingOpacity;\n const frame: PresentationTransitionFrame = Object.freeze({\n epoch: current.epoch,\n descriptor: current.descriptor,\n motion: current.motion,\n camera,\n // the ONE rule every presenter of the departed frame reads (B7): the pre-cut camera itself at p = 0 and while frozen\n outgoingCamera: departedCameraOf(transition, camera),\n progress,\n outgoingOpacity,\n incomingOpacity,\n frozen: transition.frozen,\n });\n for (const [id, retainer] of [...current.retainers]) {\n try {\n retainer.update(frame);\n } catch (error) {\n current.retainers.delete(id);\n try {\n retainer.release(\"fault\");\n } catch (releaseError) {\n reportFault(id, releaseError);\n }\n reportFault(id, error);\n }\n }\n if (shouldRelease) release(releaseReason);\n };\n\n const removeReflector = engine.registerReflector({\n name: \"presentation-transition\",\n always: true,\n flush: () => {\n if (active !== undefined) update(active);\n },\n });\n\n // One lookup, two callers: the throw below and the public question a host\n // asks before it registers (D-C4.6). `dispose()` clears the map, so a\n // disposed coordinator answers `undefined` for every plane.\n const ownerOf = (plane: PresentationPlane): string | undefined =>\n [...adapters.values()].find((candidate) => candidate.plane === plane)?.id;\n\n return {\n register(adapter) {\n if (disposed) throw new Error(\"ice: presentation transition coordinator is disposed.\");\n const planeOwner = ownerOf(adapter.plane);\n if (adapter.id.length === 0 || adapters.has(adapter.id) || planeOwner !== undefined) {\n throw new Error(\n planeOwner !== undefined\n ? `ice: presentation transition plane \"${adapter.plane}\" is already owned by \"${planeOwner}\".`\n : `ice: presentation transition adapter id \"${adapter.id}\" is empty or already registered.`,\n );\n }\n adapters.set(adapter.id, adapter);\n let live = true;\n return () => {\n if (!live) return;\n live = false;\n if (adapters.get(adapter.id) === adapter) adapters.delete(adapter.id);\n // A preparation in flight holds its OWN retainer map — `active` is\n // only the committed one — and that map is finished by the caller's\n // commit/cancel, which may be arbitrarily later or never. Sweeping\n // only `active` left a detached adapter's retainer to be committed\n // into a transition it can no longer serve, and its `release` (the\n // DOM plane's is what hands the mount store's retention back) unrun.\n pending?.detach(adapter.id);\n const retained = active?.retainers.get(adapter.id);\n if (retained === undefined) return;\n active?.retainers.delete(adapter.id);\n try {\n retained.release(\"detached\");\n } catch (error) {\n reportFault(adapter.id, error);\n }\n };\n },\n ownerOf,\n prepare(descriptor) {\n const sequence = ++prepareSequence;\n const deadPrepared = (): PreparedFrameSwitch => ({\n complete: false,\n allowFlight: false,\n commit: () => {},\n cancel: () => {},\n });\n pending?.finish(\"superseded\");\n // Adapter release can synchronously run application callbacks. If one\n // starts a newer navigation, this invocation has already lost ownership.\n if (sequence !== prepareSequence) return deadPrepared();\n release(\"superseded\");\n if (sequence !== prepareSequence) return deadPrepared();\n const expectedEpoch = (world.getResource(NavTransition)?.epoch ?? 0) + 1;\n const retainers = new Map<string, PresentationRetainer>();\n const successfulPlanes = new Set<PresentationPlane>();\n let finished = false;\n const pendingTransition: PendingTransition = {\n finish(reason) {\n if (finished) return;\n finished = true;\n if (pending === pendingTransition) pending = undefined;\n for (const [id, retainer] of retainers) {\n try {\n retainer.release(reason);\n } catch (error) {\n reportFault(id, error);\n }\n }\n retainers.clear();\n },\n detach(id) {\n const retainer = retainers.get(id);\n if (retainer === undefined) return;\n retainers.delete(id);\n try {\n retainer.release(\"detached\");\n } catch (error) {\n reportFault(id, error);\n }\n },\n };\n pending = pendingTransition;\n if (descriptor.requestedMotion) {\n const orderedAdapters = [...adapters].sort(\n ([idA, a], [idB, b]) =>\n PREPARE_ORDER[a.plane] - PREPARE_ORDER[b.plane] || idA.localeCompare(idB),\n );\n for (const [id, adapter] of orderedAdapters) {\n try {\n const retainer = adapter.prepare(descriptor);\n if (finished || sequence !== prepareSequence) {\n if (retainer !== null) {\n try {\n retainer.release(\"superseded\");\n } catch (error) {\n reportFault(id, error);\n }\n }\n break;\n }\n // An adapter can unregister from INSIDE its own `prepare`: the DOM\n // one blurs focus and notifies the mount store's subscribers there,\n // both user-code boundaries, and one of them can tear down the\n // mount that owns this adapter. Banking that retainer would put it\n // in `pending` a moment after the unregister swept it — so release\n // it here and let the plane count as unprepared, which is what it\n // is. `continue`, not `break`: the other planes are still ours.\n if (adapters.get(id) !== adapter) {\n if (retainer !== null) {\n try {\n retainer.release(\"detached\");\n } catch (error) {\n reportFault(id, error);\n }\n }\n continue;\n }\n successfulPlanes.add(adapter.plane);\n if (retainer !== null) retainers.set(id, retainer);\n } catch (error) {\n reportFault(id, error);\n if (finished || sequence !== prepareSequence) break;\n }\n }\n }\n const ownsPreparation = !finished && sequence === prepareSequence;\n const complete =\n ownsPreparation &&\n descriptor.requiredPlanes.every((plane) => successfulPlanes.has(plane));\n const allowFlight =\n ownsPreparation &&\n descriptor.requestedMotion &&\n !prefersReducedMotion &&\n (!descriptor.requiresFullT2 || complete);\n const cancelPrepared = (reason: PresentationReleaseReason = \"cancelled\"): void => {\n if (finished) return;\n pendingTransition.finish(reason);\n };\n return {\n complete,\n allowFlight,\n commit() {\n if (finished) return;\n if (!descriptor.requestedMotion || retainers.size === 0) {\n cancelPrepared();\n return;\n }\n const transition = world.getResource(NavTransition);\n const identityMatches =\n transition !== undefined &&\n transition.epoch === expectedEpoch &&\n transition.documentEpoch === descriptor.documentEpoch &&\n transition.fromFrame === descriptor.fromFrame &&\n transition.toFrame === descriptor.toFrame &&\n transition.fromTypeId === descriptor.fromTypeId &&\n transition.toTypeId === descriptor.toTypeId;\n if (!identityMatches) {\n pendingTransition.finish(\"superseded\");\n return;\n }\n finished = true;\n if (pending === pendingTransition) pending = undefined;\n active = {\n epoch: transition.epoch,\n descriptor,\n retainers,\n motion: allowFlight ? \"flight\" : \"crossfade\",\n startedAtMs: world.getResource(FrameInfo)?.now ?? 0,\n elapsedMs: 0,\n fadeElapsedMs: 0,\n fadeFrom: 1,\n lastOutgoingOpacity: 1,\n };\n update(active);\n },\n cancel: cancelPrepared,\n };\n },\n abort(reason = \"interrupted\") {\n pending?.finish(reason);\n release(reason);\n },\n setReducedMotion(value) {\n prefersReducedMotion = value;\n },\n reducedMotion: () => prefersReducedMotion,\n stats: () =>\n Object.freeze({\n active: active !== undefined,\n epoch: active?.epoch ?? 0,\n ...(active === undefined ? {} : { motion: active.motion }),\n retainers: active?.retainers.size ?? 0,\n adapters: adapters.size,\n reducedMotion: prefersReducedMotion,\n }),\n dispose() {\n if (disposed) return;\n disposed = true;\n pending?.finish(\"detached\");\n release(\"detached\");\n adapters.clear();\n removeReflector();\n },\n };\n}\n","/**\n * The widget equip system (design-005 §2 \"capability-tag stamping recipe\",\n * design-001 reconciled catalog).\n *\n * Capability tags are RUNTIME state — a restored/remote document carries only\n * durable cells, so every projected widget entity gets its type's tags stamped\n * here, once (`WidgetEquipped` makes the query zero-match at steady state:\n * row-filtered, nothing runs, nothing stamps). Runs in `derive`; new\n * projections from this frame's sync() are visible by then.\n *\n * This generalizes the graybox demo's equipSceneBoxes into the engine.\n *\n * RIDERS take the same path — session-local facts derivable from the widget\n * TYPE and needed on every peer's projection, including one that received the\n * widget over the wire or restored it from a file, neither of which ran a spawn\n * path (design-013 D4: never sync what every peer can compute from `PrefabId`):\n * the desk `Stratum` (design-015 §4.2, D2a-core) and the type's runtime\n * pre-attached behaviours (design-009 §6). Structural `ctx.addComponent` lands\n * at the derive flush like the tags. Until design-015 D5b the six presentation\n * facts (`SurfaceKind` … `TextureRef`, design-013 §5) rode here too; they left\n * with the DOM/GPU presentation choice — an object presents on the desk and\n * nowhere else, so there is no kind to name, no target to choose and no texture\n * to reserve.\n */\nimport { Not, defineQuery, defineSystem, type Component, type System, type World } from \"@vibecook/strata-ecs\";\nimport type { AnyBehaviorDef } from \"../behavior/types\";\nimport { STRATUM_BANDS, Stratum } from \"../catalog/desk\";\nimport { widgetTypeFor } from \"../canvas/engine-catalog\";\nimport { PrefabId } from \"../schema/prefab\";\nimport { WidgetEquipped } from \"./define-widget\";\n\n/** Defaults ∪ the declared pre-attach data, serialized for the cell. */\nfunction runtimeBehaviorCell(b: AnyBehaviorDef, data: Readonly<Record<string, unknown>>): Record<string, unknown> {\n const out: Record<string, unknown> = { ...(b.defaults as Record<string, unknown>) };\n for (const [k, v] of Object.entries(data)) {\n if (v === undefined) continue;\n out[k] = b.schema[k]?.kind === \"json\" ? JSON.stringify(v) : v;\n }\n return out;\n}\n\nconst unequippedQ = defineQuery([PrefabId, Not(WidgetEquipped)]);\n\nexport function createWidgetEquipSystem(world: World): 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\" ? widgetTypeFor(world, 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 // The desk stratum (design-015 §4.2): every object (a `things` unless\n // it declared otherwise) and any other widget that declared one. A\n // rider like the tags — derivable from the type, stamped on every\n // peer's projection, never synced.\n if (widget.stratum !== undefined) {\n ctx.addComponent(e, Stratum, { band: STRATUM_BANDS[widget.stratum] });\n }\n // RUNTIME pre-attached behaviors (design-009 §6) are riders, exactly\n // like capability tags: session-local, and needed on every peer's\n // projection — including one that received this widget over the wire\n // or restored it from a file, neither of which ran its spawn path.\n for (const entry of widget.behaviors) {\n if (entry.behavior.store !== \"runtime\") continue;\n ctx.addComponent(\n e,\n entry.behavior.component as Component<Record<string, unknown>>,\n runtimeBehaviorCell(entry.behavior, entry.data),\n );\n }\n }\n ctx.addTag(e, WidgetEquipped);\n }\n },\n { name: \"widgetEquip\" },\n );\n}\n","/**\n * setWidgetProps — the paved-road widget prop UPDATE op (2026-07-13 review:\n * spawn validated through each prop's Standard Schema, but the update path —\n * raw `useCommit` writes — bypassed bounds/enum/json-shape checks entirely).\n *\n * Mirrors `widgetSpawnInits` semantics exactly: unknown prop names throw,\n * each given value runs `spec[\"~standard\"].validate` (an invalid value throws\n * BEFORE anything is written), `p.json` values are validated as parsed shapes\n * then serialized into their string cell. Writes are whole-group absolute\n * values (the current cell merged with the validated updates — design-001\n * §5.2 conflict-group granularity), one guardedTransaction = one undo step.\n */\nimport type { Component, Entity, World } from \"@vibecook/strata-ecs\";\nimport type { DurableStore } from \"@vibecook/strata-ecs/durable\";\nimport { guardedTransaction, type GuardedTxOpts } from \"../guards/guarded-tx\";\nimport { widgetTypeFor } from \"../canvas/engine-catalog\";\nimport { PrefabId } from \"../schema/prefab\";\n\nexport function setWidgetProps(\n store: DurableStore,\n world: World,\n entity: Entity,\n props: Readonly<Record<string, unknown>>,\n opts?: GuardedTxOpts,\n): void {\n const type = world.get(entity, PrefabId)?.id;\n const widget = typeof type === \"string\" ? widgetTypeFor(world, type) : undefined;\n if (widget === undefined) {\n throw new Error(`ice: setWidgetProps — entity ${String(entity)} is not a defined widget.`);\n }\n for (const name of Object.keys(props)) {\n if (widget.propToGroup[name] === undefined) {\n throw new Error(`ice: setWidgetProps(\"${widget.type}\") — unknown prop \"${name}\".`);\n }\n }\n\n // Validate + serialize every touched group BEFORE the transaction opens, so\n // an invalid value can never leave a partial multi-group update behind.\n const groupWrites: [Component, Record<string, string | number | boolean>][] = [];\n for (const g of widget.groups) {\n const touched = Object.keys(props).some((name) => widget.propToGroup[name] === g.name);\n if (!touched) continue;\n const current = (world.get(entity, g.component) ?? {}) as Record<string, string | number | boolean>;\n const value = { ...current };\n for (const [name, spec] of Object.entries(g.fields)) {\n const given = props[name];\n if (given === undefined) continue;\n const result = spec[\"~standard\"].validate(given);\n if (\"issues\" in result) {\n throw new Error(\n `ice: setWidgetProps(\"${widget.type}\") prop \"${name}\" invalid — ${result.issues[0]?.message}`,\n );\n }\n value[name] = spec.kind === \"json\" ? JSON.stringify(given) : (given as string | number | boolean);\n }\n groupWrites.push([g.component as Component, value]);\n }\n\n guardedTransaction(\n store,\n world,\n (tx) => {\n for (const [component, value] of groupWrites) {\n tx.edit(entity).set(component, value);\n }\n },\n opts,\n );\n}\n","/**\n * The widget runtime: the CULL (design-004 §2, what survives of it at design-015 D5b).\n *\n * - `cullSystem` (derive): viewport test over equipped widgets' `Size`, overscan\n * scaled by zoom; flips Visible/Culled CHANGE-ONLY. GATED (2026-07-15, the\n * activeMembership playbook): a real `runIf` — camera/viewport window compare\n * as the `extra` trigger (full pass; the window moved under everyone) ∨ a\n * petition-7 collector on Position/Size + Active flips (delta pass —\n * drags/spawns re-test only the journaled entities). Idle frames skip; camera\n * frames stay O(active) by the widgetQ Active scope. `Visible`/`Culled` is the\n * desk renderer's WORKING SET: the builder walks the visible objects and the\n * pick source answers for them.\n *\n * GONE at design-015 D5b: the mount system, its keep-mounted LRU, the\n * `useSyncExternalStore` snapshot, `retainForTransition` and the post-notify\n * listener flush — every one of them existed so a DOM host or a GL island could\n * stay mounted-but-hidden and be held across a nav crossfade. An object has no\n * view to mount; the desk draws it from the world (design-015 §1). The\n * facade's `runtime.store` went with them.\n */\nimport { defineQuery, defineTickSystem, type Entity, type TickSystem, type World } from \"@vibecook/strata-ecs\";\nimport { screenToWorld } from \"@ice/kernel\";\nimport { Active, Camera, Culled, Position, Size, Viewport, Visible } from \"../catalog\";\nimport type { Engine } from \"../engine/engine\";\nimport { RUNTIME_BUDGETS } from \"../settings/defaults\";\nimport { WidgetEquipped } from \"./define-widget\";\nimport { createWidgetEquipSystem } from \"./equip\";\nimport { createBreakpointSystem } from \"../systems/chrome\";\nimport { createActiveMembership, currentNavFrame } from \"../nav/nested-canvas\";\nimport { makeChurnGuard } from \"../helpers/churn-guard\";\n\nconst widgetQ = defineQuery([Position, Size, WidgetEquipped, Active]);\n\nexport interface WidgetRuntime {\n readonly cullSystem: TickSystem;\n}\n\nexport function createWidgetRuntime(world: World): WidgetRuntime {\n // Camera/viewport window compare — the cull gate's `extra` trigger. Kept\n // outside the guard so the closure caches the last-seen window verbatim\n // (undefined-ness included: the headless posture compares equal and never\n // fires; the first real camera write fires a full pass).\n let lastWin: { x: number; y: number; zoom: number; w: number; h: number } | undefined | null = null;\n // NAV DEFERRAL (field bug 2026-07-17, the folder-zombie): on the tick a nav\n // op lands, activeMembership strips Active from the departing frame's\n // widgets IN THE SAME TICK cull's full pass runs — and tag flips flush at\n // the group boundary, so cull classifies against STALE Active tags and the\n // FLIGHT-START window (which can span the old frame's coords). A widget\n // culled at root then re-tags Visible while ¬Active is a ZOMBIE: rendered,\n // unpickable, repaired by nobody (membership sees no input churn; cull only\n // touches Active). So: the nav tick SKIPS classification entirely and the\n // NEXT tick runs a forced full pass against the flushed membership.\n let lastNavFrame: Entity | undefined;\n let navPrimed = false;\n let navSkipTick = false;\n let navHoldFull = false;\n const cullGuard = makeChurnGuard(\n world,\n { components: [Position, Size], tags: [Active], coarse: false },\n () => {\n const frame = currentNavFrame(world);\n if (!navPrimed || frame !== lastNavFrame) {\n navPrimed = true;\n lastNavFrame = frame;\n navSkipTick = true;\n navHoldFull = true;\n }\n const cam = world.getResource(Camera);\n const vp = world.getResource(Viewport);\n const win =\n cam === undefined || vp === undefined\n ? undefined\n : { x: cam.x, y: cam.y, zoom: cam.zoom, w: vp.w, h: vp.h };\n const changed =\n lastWin === null ||\n (win === undefined) !== (lastWin === undefined) ||\n (win !== undefined &&\n lastWin !== undefined &&\n lastWin !== null &&\n (win.x !== lastWin.x || win.y !== lastWin.y || win.zoom !== lastWin.zoom || win.w !== lastWin.w || win.h !== lastWin.h));\n lastWin = win;\n // Nav ticks fire the gate regardless: the skip tick must consume the\n // guard (dropping its delta is safe — the held full pass covers it) and\n // the following tick must run even if camera/journal are quiet.\n if (navSkipTick || navHoldFull) return true;\n return changed;\n },\n );\n\n const cullSystem = defineTickSystem(\n (ctx) => {\n const work = cullGuard.take();\n if (work === undefined) return;\n if (navSkipTick) {\n // The nav tick: membership's Active flips flush at this group's\n // boundary — classify next tick (navHoldFull), never against stale tags.\n navSkipTick = false;\n return;\n }\n const forcedFull = navHoldFull;\n navHoldFull = false;\n const cam = ctx.getResource(Camera);\n const vp = ctx.getResource(Viewport);\n if (cam === undefined || vp === undefined || vp.w === 0) return; // headless: everything stays unculled\n const over = RUNTIME_BUDGETS.cullOverscanWorldPerZoom / cam.zoom;\n const tl = screenToWorld(0, 0, cam);\n const br = screenToWorld(vp.w, vp.h, cam);\n const minX = tl.x - over;\n const minY = tl.y - over;\n const maxX = br.x + over;\n const maxY = br.y + over;\n const classifyAt = (e: Entity, x: number, y: number, w: number, h: number): void => {\n const inView = x + w >= minX && x <= maxX && y + h >= minY && 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 const classify = (e: Entity): void => {\n const p = ctx.read(e, Position);\n const s = ctx.read(e, Size);\n classifyAt(e, p.x, p.y, s.w, s.h);\n };\n if (work.full || forcedFull) {\n // The chunk's columns, read in place: a camera move walks every Active\n // widget, and a whole-component `read` builds an object a call (K7a —\n // the pan's allocation).\n ctx.query(widgetQ).each((b) => {\n const pos = b.col(Position);\n const size = b.col(Size);\n for (let i = 0; i < b.count; i++) {\n const r = b.rows[i] as number;\n classifyAt(b.entity(r), pos.x[r] as number, pos.y[r] as number, size.w[r] as number, size.h[r] as number);\n }\n });\n return;\n }\n for (const e of work.changed) {\n // The delta twin of widgetQ: equipped ∧ Active (membership already\n // parks non-Active in the canonical Culled state — never touch them).\n if (!ctx.isAlive(e) || !ctx.hasTag(e, Active)) continue;\n if (!world.hasTag(e, WidgetEquipped) || !ctx.has(e, Position) || !ctx.has(e, Size)) continue;\n classify(e);\n }\n },\n { name: \"cull\", access: { read: [Position, Size] }, runIf: cullGuard.runIf },\n );\n\n return { cullSystem };\n}\n\n/** Install membership → equip → cull → breakpoint on an engine. */\nexport function installWidgetRuntime(engine: Engine): WidgetRuntime & { uninstall(): void } {\n const runtime = createWidgetRuntime(engine.world);\n // equip → cull → breakpoint (equip's deferred tags land at the derive flush,\n // so a brand-new widget is classified one frame after projection — accepted\n // 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(engine.world),\n runtime.cullSystem,\n createBreakpointSystem(engine.world),\n );\n return {\n ...runtime,\n uninstall() {\n removeSystems();\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: two triggers, plus an initial arm.\n * - `DurableStore.subscribeOutbound` (durable-store.ts) fires SYNCHRONOUSLY on\n * each sealed LOCAL commit and never on remote imports.\n * - `DocSession.subscribeRemote` (doc-kit) fires after each successful\n * `applyRemote`. The original design left remote changes to \"whichever peer\n * originated them\" — but that peer persists to ITS storage, not this one's:\n * a joiner that received edits and closed restored a STALE local backup\n * (2026-07-13 review). Local autosave must reflect the last-seen document.\n * - Autosave starts DIRTY: state that predates startAutosave() (a seeded or\n * freshly-joined doc) reaches storage after the first debounce, not only\n * after the next edit (same review — a seeded doc could close unsaved).\n * No polling — the design's `store.exportSnapshot()` length/frontier poll is\n * the last-resort fallback and is not needed here.\n *\n * Clock and scheduler are injectable so tests are deterministic with NO real\n * timers; the design's `requestIdleCallback` optimization is just an alternate\n * `schedule` an app can pass. `flush()` forces an awaited save; `close()`\n * captures and durably serializes the final revision; `stop()` explicitly\n * discards pending state.\n *\n * RESTORE (`restoreAutosave`): reads storage → `openDocSession`. Incompatible or\n * corrupt bytes NEVER throw and NEVER brick boot (the M5 exit criterion) —\n * they come back as `{ status: \"quarantined\", reason, bytes }` so the app can\n * stash the bytes aside and start fresh.\n */\nimport type { World } from \"@vibecook/strata-ecs\";\nimport { isMidGesture } from \"../interaction/gesture-status\";\nimport { openDocSession, type DocSession, type DocSessionOpts } from \"./doc-kit\";\nimport type { DocVersionReport } from \"./version-gate\";\n\n/** The app-owned write side of storage (localStorage, IndexedDB, fs, cloud — WHERE is app-owned). */\nexport interface AutosaveStorageWrite {\n put(bytes: Uint8Array): Promise<void> | void;\n /** Optional opaque Loro-update journal. `put` replaces the checkpoint and\n * clears its journal; `append` durably extends the current checkpoint. */\n append?(bytes: Uint8Array): Promise<void> | void;\n}\n\n/** The app-owned read side of storage (restore path). */\nexport interface AutosaveStorageRead {\n get(): Promise<Uint8Array | undefined> | Uint8Array | undefined;\n}\n\n/** Cancels a scheduled callback (the return of an injected `schedule`). */\nexport type CancelScheduled = () => void;\n\nexport interface AutosaveOpts {\n readonly storage: AutosaveStorageWrite;\n /** The session's world — read for the gesture-deferral gate (never written). */\n readonly world: World;\n /** Quiet-period before a save (default 800 ms). */\n readonly debounceMs?: number;\n /** Hard ceiling from the first unsaved change to a forced save (default 10 s). */\n readonly maxWaitMs?: number;\n /** Wall-clock source; the engine never reads a clock itself (default `Date.now`). */\n readonly now?: () => number;\n /** Timer factory; return a canceller (default `setTimeout`/`clearTimeout`). */\n readonly schedule?: (fn: () => void, ms: number) => CancelScheduled;\n /** Compact after this many journal records (default 64). */\n readonly checkpointEvery?: number;\n /** Compact before the journal exceeds this many bytes (default 4 MiB). */\n readonly maxJournalBytes?: number;\n}\n\nexport type AutosaveStatus = \"idle\" | \"pending\" | \"deferred\" | \"saving\" | \"saved\" | \"error\";\n\nexport interface AutosaveState {\n readonly status: AutosaveStatus;\n /** Wall-clock ms of the last successful save (via the injected `now`), or undefined. */\n readonly lastSavedAt: number | undefined;\n /** True while there are unsaved changes (a timer is armed or deferred). */\n readonly pending: boolean;\n}\n\nexport interface Autosave {\n /** Force a save of the current document now and await it. Rejects when persistence fails. */\n flush(): Promise<void>;\n /**\n * Capture the final document synchronously, serialize it behind any in-flight\n * write, and stop only after storage acknowledges it. Rejects on failure and\n * may be retried; no document mutation should occur after close begins.\n */\n close(): Promise<void>;\n /** Discard pending state immediately. Idempotent; never use for a normal close. */\n stop(): void;\n /** A pull-based status read for a per-frame HUD (design demo). */\n state(): AutosaveState;\n}\n\nfunction defaultSchedule(fn: () => void, ms: number): CancelScheduled {\n const id = setTimeout(fn, ms);\n return () => clearTimeout(id);\n}\n\n/**\n * Begin autosaving `session` to `opts.storage`. Debounced with a max-wait\n * ceiling, deferred while a gesture (or `Camera.gesturing`) is live. Returns the\n * control surface; call `stop()` at teardown.\n */\nexport function startAutosave(session: DocSession, opts: AutosaveOpts): Autosave {\n const { storage, world } = opts;\n const debounceMs = opts.debounceMs ?? 800;\n const maxWaitMs = opts.maxWaitMs ?? 10_000;\n const now = opts.now ?? (() => Date.now());\n const schedule = opts.schedule ?? defaultSchedule;\n const checkpointEvery = opts.checkpointEvery ?? 64;\n const maxJournalBytes = opts.maxJournalBytes ?? 4 * 1024 * 1024;\n\n let dirty = false;\n let firstDirtyAt = 0;\n let cancelTimer: CancelScheduled | undefined;\n let saving = false;\n let lastSavedAt: number | undefined;\n let errored = false;\n let lastWriteError: unknown;\n let stopped = false;\n let closing = false;\n let closeBytes: Uint8Array | undefined;\n let closeSavedAt = 0;\n let closeInFlight: Promise<void> | undefined;\n let forceCheckpoint = true;\n let journalEntries = 0;\n let journalBytes = 0;\n let pendingUpdates: Uint8Array[] = [];\n // The serialized writer: at most ONE storage.put is ever in flight. A save\n // requested while a put runs does NOT start a second put — the running loop\n // re-runs with FRESHLY exported bytes once the current put settles. So two\n // puts never interleave and never land out of order; the newest document\n // always wins (latest-wins), and a slow put can never be clobbered by a\n // faster one started later. `writing` (a flag, not the promise) is the gate:\n // a run that finishes synchronously — e.g. a put that throws before any await\n // — must clear it WITHOUT racing the `writeInFlight = runWrites()` assignment.\n let writing = false;\n let writeInFlight: Promise<void> = Promise.resolve();\n\n const deferred = (): boolean => isMidGesture(world);\n\n const clearTimer = (): void => {\n if (cancelTimer !== undefined) {\n cancelTimer();\n cancelTimer = undefined;\n }\n };\n\n const arm = (): void => {\n clearTimer();\n if (stopped || closing) return;\n const elapsed = now() - firstDirtyAt;\n // Debounce, but never later than the max-wait ceiling from the first change.\n const delay = Math.max(0, Math.min(debounceMs, maxWaitMs - elapsed));\n cancelTimer = schedule(onTimer, delay);\n };\n\n function onTimer(): void {\n cancelTimer = undefined;\n if (stopped || !dirty) return;\n if (deferred()) {\n // Can't persist mid-gesture; poll again a debounce later. The gesture's own\n // JustEnded commit also re-arms us the moment it lands (subscribeOutbound).\n cancelTimer = schedule(onTimer, debounceMs);\n return;\n }\n requestWrite();\n }\n\n /**\n * Persist the LATEST document until nothing is dirty. One loop owns the sole\n * `storage.put` call site, so writes are strictly serialized; each iteration\n * re-exports, so a change that arrives mid-put is written on the next pass\n * (latest-wins) rather than lost under a stale in-flight put. This never\n * rejects: a throwing/rejecting put is caught, recorded as status \"error\",\n * and left dirty for the next change/flush to retry — a persistent failure\n * breaks out instead of spinning.\n */\n async function runWrites(): Promise<void> {\n try {\n while (dirty && !stopped && !closing) {\n const at = now();\n const nextUpdate = pendingUpdates[0];\n // Read the optional appender once per pass, bound to its storage object:\n // a method-shorthand optional does not narrow through the `canAppend`\n // alias, and an unbound extraction would break a `this`-using storage.\n const append = storage.append?.bind(storage);\n const canAppend =\n append !== undefined &&\n !forceCheckpoint &&\n nextUpdate !== undefined &&\n journalEntries < checkpointEvery &&\n journalBytes + nextUpdate.byteLength <= maxJournalBytes;\n if (canAppend) {\n pendingUpdates.shift();\n dirty = pendingUpdates.length > 0;\n saving = true;\n try {\n await append(nextUpdate);\n journalEntries += 1;\n journalBytes += nextUpdate.byteLength;\n lastSavedAt = at;\n errored = false;\n lastWriteError = undefined;\n } catch (err) {\n // The full current snapshot includes this update. A checkpoint is\n // both the recovery path and compaction, including lost-ACK cases.\n forceCheckpoint = true;\n dirty = true;\n lastWriteError = err;\n } finally {\n saving = false;\n }\n continue;\n }\n\n const bytes = session.exportEnvelope(at);\n pendingUpdates = [];\n dirty = false; // optimistic: a change during the await re-sets it\n saving = true;\n try {\n await storage.put(bytes);\n forceCheckpoint = false;\n journalEntries = 0;\n journalBytes = 0;\n lastSavedAt = at;\n errored = false;\n lastWriteError = undefined;\n } catch (err) {\n errored = true;\n lastWriteError = err;\n forceCheckpoint = true;\n dirty = true; // keep marked so a later change/flush retries\n break; // do not spin on a persistent failure\n } finally {\n saving = false;\n }\n }\n } finally {\n writing = false;\n }\n }\n\n /** Kick (or join) the serialized writer; returns the in-flight write promise. */\n function requestWrite(): Promise<void> {\n if (stopped || closing) return writeInFlight;\n if (!writing) {\n writing = true;\n writeInFlight = runWrites();\n }\n return writeInFlight;\n }\n\n const markDirty = (): void => {\n if (stopped || closing) return;\n if (!dirty) firstDirtyAt = now();\n dirty = true;\n arm();\n };\n\n const journal = (bytes: Uint8Array): void => {\n pendingUpdates.push(bytes.slice());\n markDirty();\n };\n const unsubOutbound = session.store.subscribeOutbound(journal);\n const unsubRemote = session.subscribeRemote(journal);\n // Start dirty: the document AS HANDED IN (seeded, opened, joined) is unsaved\n // state — without this, a doc with no post-start edits never reaches storage.\n markDirty();\n\n return {\n async flush(): Promise<void> {\n if (stopped) {\n await writeInFlight; // stop() semantics: nothing new persists after stop\n return;\n }\n clearTimer();\n // Force-write the current document even mid-gesture: the doc holds only\n // committed state (the in-flight gesture commits at JustEnded), so every\n // frame is a consistent one to persist. Serialized like every other save —\n // if a put is already running this joins it, and the queued dirty state is\n // written when that put settles. ALWAYS exports — a flush must never be a\n // silent no-op (2026-07-13 review: the beforeunload path relied on it).\n forceCheckpoint = true;\n dirty = true;\n requestWrite();\n await writeInFlight;\n if (lastWriteError !== undefined) throw lastWriteError;\n },\n close(): Promise<void> {\n if (stopped) return writeInFlight;\n if (!closing) {\n closing = true;\n clearTimer();\n unsubOutbound();\n unsubRemote();\n // Capture before the caller can detach/reset the world. This exact\n // envelope is serialized behind the current background write below.\n closeSavedAt = now();\n closeBytes = session.exportEnvelope(closeSavedAt);\n dirty = false;\n }\n if (closeInFlight !== undefined) return closeInFlight;\n const finalBytes = closeBytes;\n if (finalBytes === undefined) return Promise.reject(new Error(\"ice: autosave close lost its final envelope\"));\n closeInFlight = (async () => {\n await writeInFlight;\n try {\n await storage.put(finalBytes);\n lastSavedAt = closeSavedAt;\n lastWriteError = undefined;\n errored = false;\n stopped = true;\n } catch (err) {\n lastWriteError = err;\n errored = true;\n throw err;\n }\n })();\n void closeInFlight.catch(() => {\n // A caller may retry close() after recovering the storage path.\n closeInFlight = undefined;\n });\n return closeInFlight;\n },\n stop(): void {\n if (stopped) return;\n stopped = true;\n clearTimer();\n if (!closing) {\n unsubOutbound();\n unsubRemote();\n }\n // Semantics: a put already in flight runs to completion (a promise cannot\n // be cancelled); the writer loop's `!stopped` guard then DROPS any queued\n // newer write — nothing is persisted after stop() beyond the put already\n // awaiting. Call flush() before stop() to force a final save.\n },\n state(): AutosaveState {\n const status: AutosaveStatus = saving\n ? \"saving\"\n : errored\n ? \"error\"\n : dirty\n ? deferred()\n ? \"deferred\"\n : \"pending\"\n : lastSavedAt !== undefined\n ? \"saved\"\n : \"idle\";\n return { status, lastSavedAt, pending: dirty };\n },\n };\n}\n\n/** The outcome of a restore attempt — a tagged union; nothing here ever throws. */\nexport type RestoreResult =\n | { readonly status: \"restored\"; readonly session: DocSession }\n | { readonly status: \"empty\" }\n | {\n readonly status: \"quarantined\";\n readonly reason: string;\n readonly bytes: Uint8Array;\n readonly report?: DocVersionReport;\n };\n\n/**\n * Load the autosaved document into `world`. Missing/empty storage ⇒\n * `{ status: \"empty\" }` (the app creates fresh). A successful open ⇒\n * `{ status: \"restored\", session }` (may be read-only per the version gate).\n * Corrupt or incompatible bytes ⇒ `{ status: \"quarantined\", reason, bytes }` —\n * NEVER a throw, NEVER a bricked boot (M5 exit criterion): the app stashes the\n * bytes aside and starts fresh.\n */\nexport async function restoreAutosave(\n world: World,\n storage: AutosaveStorageRead,\n opts?: DocSessionOpts,\n): Promise<RestoreResult> {\n const bytes = await storage.get();\n if (bytes === undefined || bytes.length === 0) return { status: \"empty\" };\n\n const result = openDocSession(world, bytes, opts ?? {});\n if (result.ok) return { status: \"restored\", session: result.session };\n return {\n status: \"quarantined\",\n reason: result.reason,\n bytes,\n ...(result.report !== undefined ? { report: result.report } : {}),\n };\n}\n","/**\n * The dumb snapshot relay (design-005 §6.5 M5 stopgap; §6, decision \"relay is\n * dumb — inventory §1.3).\n *\n * M5 ONLY: broadcasts the WHOLE converged document on every local change and\n * imports whole documents it receives. Loro imports dedupe, so a full snapshot\n * is a valid (if wasteful) relay — this is deliberately the simplest thing that\n * converges two tabs. M9 REPLACES it with the transport/bootstrap protocol\n * (hello → addressed-snapshot base → increment stream); do not grow this into\n * that — it is the throwaway.\n *\n * CHANGE-SUBSCRIPTION SURFACE + FEEDBACK GUARD: rides the same\n * `DurableStore.subscribeOutbound` as the autosave kit, which fires ONLY on\n * sealed LOCAL commits (durable-store.ts `onLocalBatch` early-returns on\n * `origin !== \"local\"`). That origin filter IS the feedback-loop guard: applying\n * a peer's snapshot via `applyRemote` produces remote-origin batches, which do\n * NOT re-fire `subscribeOutbound`, so an imported change is never rebroadcast.\n * No `applying` flag is needed — the subscription tells us the origin.\n *\n * LATE-JOINER SEED: on attach we post our snapshot (best-effort seed) AND a\n * `hello`; peers answer a `hello` with their snapshot, so a tab opened second\n * converges up to the first. BroadcastChannel never delivers a message to the\n * instance that posted it, so hello/answer never self-loops.\n */\nimport type { DocSession } from \"./doc-kit\";\n\n/**\n * The minimal channel surface the relay needs — structurally satisfied by the\n * global `BroadcastChannel` and by test fakes. Anything carrying a `Uint8Array`\n * through `postMessage` works (design-005 §6.5).\n */\nexport interface RelayChannel {\n postMessage(message: unknown): void;\n addEventListener(type: \"message\", listener: (ev: { data: unknown }) => void): void;\n removeEventListener(type: \"message\", listener: (ev: { data: unknown }) => void): void;\n close?(): void;\n}\n\nexport interface BroadcastRelayOpts {\n /** Channel name; used to construct a `BroadcastChannel` when `channel` is absent. */\n readonly channelName: string;\n /** Injected channel (tests). When omitted, a `new BroadcastChannel(channelName)` is created and owned. */\n readonly channel?: RelayChannel;\n}\n\nexport interface BroadcastRelay {\n /** Unsubscribe from the store, detach the listener, and close an owned channel. Idempotent. */\n stop(): void;\n}\n\ntype RelayMessage =\n | { readonly kind: \"snapshot\"; readonly bytes: Uint8Array }\n | { readonly kind: \"hello\" };\n\nfunction asRelayMessage(data: unknown): RelayMessage | undefined {\n if (typeof data !== \"object\" || data === null) return undefined;\n const kind = (data as { kind?: unknown }).kind;\n if (kind === \"hello\") return { kind: \"hello\" };\n if (kind === \"snapshot\") {\n const bytes = (data as { bytes?: unknown }).bytes;\n if (bytes instanceof Uint8Array) return { kind: \"snapshot\", bytes };\n }\n return undefined;\n}\n\n/** Attach a dumb snapshot relay to `session` over a `BroadcastChannel` (or injected channel). */\nexport function attachBroadcastRelay(session: DocSession, opts: BroadcastRelayOpts): BroadcastRelay {\n const ownsChannel = opts.channel === undefined;\n const channel: RelayChannel = opts.channel ?? new BroadcastChannel(opts.channelName);\n\n const broadcastSnapshot = (): void => {\n channel.postMessage({ kind: \"snapshot\", bytes: session.exportSnapshot() } satisfies RelayMessage);\n };\n\n const onMessage = (ev: { data: unknown }): void => {\n const msg = asRelayMessage(ev.data);\n if (msg === undefined) return;\n if (msg.kind === \"hello\") {\n broadcastSnapshot(); // answer a late joiner with our converged document\n } else {\n // Remote import: dedupes in loro and does NOT re-fire subscribeOutbound\n // (remote origin), so no rebroadcast — the feedback guard is the origin.\n session.applyRemote(msg.bytes);\n }\n };\n\n channel.addEventListener(\"message\", onMessage);\n const unsub = session.store.subscribeOutbound(() => broadcastSnapshot());\n\n // Seed peers with our current document, and ask them for theirs.\n broadcastSnapshot();\n channel.postMessage({ kind: \"hello\" } satisfies RelayMessage);\n\n let stopped = false;\n return {\n stop(): void {\n if (stopped) return;\n stopped = true;\n unsub();\n channel.removeEventListener(\"message\", onMessage);\n if (ownsChannel) channel.close?.();\n },\n };\n}\n","/**\n * The 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 * Contained presence faults, host-routable (0.8.0 review): `\"outbound\"` — a\n * subscriber (canonically `ws.send` on a closing socket) threw and its bytes\n * were dropped for that subscriber; `\"leave\"` — the leave flush failed\n * during detach and remote peers will drop this peer at TTL instead of\n * immediately; `\"heal\"` — the reset-heal's leave failed and stale keys age\n * out at TTL. Every fault is contained either way — this is observability\n * (telemetry, a \"presence degraded\" UI state), never control flow. Default:\n * `console.error`.\n */\n readonly onFault?: (where: \"outbound\" | \"leave\" | \"heal\", error: unknown) => void;\n /**\n * A peer's presence ARRIVED or AGED OUT (the Loro store's imports and its TTL sweep — never this peer's own sets): it is\n * projected at the next `world.sync()`, so the host's next frame must come — the facade wakes a sleeping loop here (K7a).\n * Only for an event that carries keys (I43): the sweep's empty tick, every ttl/2 at rest, and an import that changed nothing\n * are no one's arrival.\n */\n readonly onRemote?: () => void;\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 /**\n * THE HOST'S AWAY (petition I42): `setAway(reason)` says this peer is away whatever its pointer does — a host whose own chrome\n * COVERS the desk (VibeField's covers) — and `setAway(null)` that it is back. The cursor facet's `away` is true while a reason\n * is held OR the local mouse is out of the host (`PointerOutside`); the publish writes it change-only, and an installed\n * session's publish writes it between frames at once (`installPresence`), so a peer hears it even with the frame gate parked.\n * The reason is the host's word (a name for \"why\", never on the wire); an unchanged one changes nothing.\n */\n setAway(reason: string | null): void;\n /** The host's away reason, or null (the pointer's own leave is the world's — `PointerOutside` — not this). */\n away(): string | null;\n /** Told when `setAway` changes the reason (the publish's door — installPresence). Returns an unsubscribe. */\n onAway(fn: (reason: string | null) => 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 const onFault =\n opts.onFault ??\n ((where: \"outbound\" | \"leave\" | \"heal\", error: unknown) => {\n const detail =\n where === \"outbound\"\n ? \"presence outbound subscriber threw — bytes dropped for that subscriber (transport handlers must not throw)\"\n : where === \"leave\"\n ? \"presence leave failed — tearing the binding down anyway (remote peers drop us at TTL instead of immediately)\"\n : \"presence reset-heal leave failed — rebinding anyway (stale keys age out at TTL)\";\n console.error(`[ice] ${detail}`, error);\n });\n\n const loro = new LoroEphemeralStore(ttlMs);\n const source = new LoroEphemeralSnapshot(loro);\n const onRemote = opts.onRemote;\n // Only an event that CARRIES KEYS is a peer's (I43): Loro's TTL sweep runs every ttl/2 while the store holds a key — our own\n // keepalive keeps one there — and emits `timeout` with all three arrays empty when nothing aged out (strata's adapter keys off\n // the same arrays, loro-ephemeral-snapshot.ts finding 4); a stale or repeated import is empty too. A sweep that REMOVED a\n // peer's key still fires: a peer aging out is the next frame's.\n const stopRemote =\n onRemote === undefined\n ? undefined\n : loro.subscribe((ev) => {\n if (ev.by !== \"local\" && (ev.added.length > 0 || ev.updated.length > 0 || ev.removed.length > 0)) onRemote();\n });\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 // Each subscriber is FAULT-ISOLATED (review finding 1, 0.8.0): the canonical\n // subscriber is `ws.send`, which throws on a CLOSING/CLOSED socket — exactly\n // the moment a host tears presence down — and an unguarded throw here rode\n // `eph.leave()` up through detach/close/dispose, aborting the whole teardown\n // (and one bad subscriber starved every later one of bytes). The join sugar\n // never saw it because its only subscriber is joinDoc's own guarded send.\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]) {\n try {\n fn(bytes);\n } catch (err) {\n onFault(\"outbound\", err);\n }\n }\n },\n });\n let attachment = attachEphemeral(world, eph);\n\n // Identity now; PresenceCursor/SelectionSummary are dynamic facets the publish\n // hook owns. `Local` is auto-applied by eph.spawn (§15.4) — never transmitted.\n const spawnLocalPeer = (): Entity =>\n eph.spawn({\n components: [[PresenceInfo, { name: opts.name, color: opts.color }]],\n tags: [PresencePeer],\n });\n let localPeer = spawnLocalPeer();\n\n let detached = false;\n // the host's away (I42): its reason, and who hears it change\n let awayReason: string | null = null;\n const awayHeard = new Set<(reason: string | null) => void>();\n // world.reset() (doc close / joinDoc's internal re-bootstrap) kills every\n // projected presence entity AND our minted local peer, while the loro store,\n // wire, and outbound timers all survive — leaving the binding pointing at\n // dead handles and remote keepalives unable to re-project (blob-diff cache\n // says \"unchanged\"). Self-heal by REBINDING: tombstone the orphaned minted\n // keys (peers drop the stale identity now, not at TTL), detach the stale\n // binding, re-attach (fresh blob-diff cache → the next keepalive ≤ ttl/2\n // re-projects every remote peer), and re-mint the local identity. Deferred a\n // microtask: attachEphemeral is illegal inside an observer emit.\n let healQueued = false;\n const stopResetHeal = world.observe({\n onReset: () => {\n if (detached || healQueued) return;\n healQueued = true;\n queueMicrotask(() => {\n healQueued = false;\n if (detached) return;\n try {\n eph.leave(); // needs the live seam + minted set — must precede detach\n } catch (err) {\n // A throw here escapes into a bare microtask and strands the heal\n // half-done — report and keep healing (stale keys age out at TTL).\n onFault(\"heal\", err);\n }\n attachment.detach();\n attachment = attachEphemeral(world, eph);\n localPeer = spawnLocalPeer(); // fresh key (the mint counter only moves forward)\n });\n },\n });\n\n return {\n peerId,\n eph,\n // A getter: the local peer is RE-MINTED after a world reset (see the\n // self-heal above) — consumers must read through, never capture.\n get localPeer() {\n return localPeer;\n },\n wire: source,\n onOutbound(fn) {\n outbound.add(fn);\n return () => {\n outbound.delete(fn);\n };\n },\n setAway(reason) {\n if (reason !== null && typeof reason !== \"string\") throw new Error(`ice: presence setAway — the reason is a string or null (got ${String(reason)})`);\n if (detached || reason === awayReason) return;\n awayReason = reason;\n for (const fn of [...awayHeard]) fn(reason);\n },\n away: () => awayReason,\n onAway(fn) {\n awayHeard.add(fn);\n return () => {\n awayHeard.delete(fn);\n };\n },\n detach() {\n if (detached) return;\n detached = true;\n stopResetHeal();\n // leave() needs the live seam + minted set, so it MUST precede detach:\n // it deletes our keys and flushes tombstones through `send` NOW (peers\n // despawn us immediately rather than waiting the TTL). detach() then\n // despawns projections + stops the timers; the minted set is already empty.\n // Teardown must never throw (the guests-sweep rule): `detached` is\n // already latched, so a throw escaping here would strand the binding,\n // its two timers, and the wasm store FOREVER — report and keep tearing.\n try {\n eph.leave();\n } catch (err) {\n onFault(\"leave\", err);\n }\n attachment.detach();\n outbound.clear();\n awayHeard.clear();\n stopRemote?.();\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 * With it (petition I42): `away` — the mouse is out of the host\n * (`PointerOutside`, a `leave` fact's) or the host said so\n * (`PresenceSession.setAway`) — and `canvas`, the canvas the coordinates\n * belong to (`presenceCanvasOf`: \"\" at the root, else the entered\n * container's durable key). The host's away and the canvas still move a\n * facet already published when there is no mouse to read.\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 BoardRoot,\n LocalPointer,\n Pointer,\n PointerOutside,\n PointerWorld,\n Position,\n PresenceCursor,\n Selected,\n SelectionSummary,\n Size,\n} from \"../catalog\";\nimport { currentNavFrame } from \"../nav/nested-canvas\";\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 away: boolean;\n canvas: string;\n}\n\n/**\n * The canvas a peer's cursor coordinates belong to, as `PresenceCursor.canvas` names it (petition I42; design-001 §5.1 — the\n * desk's coordinates are FRAME-LOCAL): \"\" at the root; the ENTERED container's durable key (`keyOf`, the doc session's\n * `store.keyOf`); a container no document keys (never committed) `~<peerId>/<entity>` — never \"\", and never another peer's, so a\n * receiver in it draws no one and no one draws its owner there. The publish writes it and a receiver compares its own to it.\n */\nexport function presenceCanvasOf(world: World, peerId: string, keyOf?: (e: Entity) => string | undefined): string {\n const frame = currentNavFrame(world);\n if (frame === undefined || frame === world.getResource(BoardRoot)?.root) return \"\";\n return keyOf?.(frame) ?? `~${peerId}/${frame}`;\n}\n\ninterface SummaryFacet {\n count: number;\n x: number;\n y: number;\n w: number;\n h: number;\n keys: string;\n}\n\n/**\n * Build the publish hook that maintains `session.localPeer`'s cursor + selection\n * facets. Register it with `engine.onPublish` (installPresence does this).\n */\nexport function createPresencePublish(\n world: World,\n session: PresenceSession,\n opts: PresencePublishOpts = {},\n): PublishHook {\n const { eph } = session;\n const keyOf = opts.keyOf;\n const cap = opts.maxKeys ?? SELECTION_KEY_CAP;\n\n let cursorPresent = false;\n let lastCursor: CursorFacet | undefined;\n let summaryPresent = false;\n let lastSummary: SummaryFacet | undefined;\n // `session.localPeer` is a GETTER — a world reset re-mints it (the\n // presence-kit self-heal). Read through per publish; when the identity\n // swaps, drop the change-suppression caches too: the fresh peer carries NO\n // facets, so an \"unchanged\" cursor must still be re-added.\n let localPeer = session.localPeer;\n\n // The engine hands the hook its world; it is `session`'s world by construction\n // (installPresence registers on the same engine), so we read the captured one.\n return () => {\n if (session.localPeer !== localPeer) {\n localPeer = session.localPeer;\n cursorPresent = false;\n lastCursor = undefined;\n summaryPresent = false;\n lastSummary = undefined;\n }\n publishCursor(world);\n publishSelection(world);\n };\n\n function publishCursor(w: World): void {\n // The local mouse pointer is the presence cursor. Collect during the walk,\n // mutate after (structural eph.* is illegal mid-iteration).\n let mouse: { x: number; y: number; outside: boolean } | undefined;\n w.query(localMouseQ).each((b) => {\n for (const r of b) {\n if (mouse !== 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 mouse = { x: pw.x, y: pw.y, outside: w.hasTag(e, PointerOutside) };\n }\n });\n\n // no local mouse ⇒ the facet's point stays as last published (none published: nothing to say); the host's away and the\n // canvas still move it (I42)\n const at = mouse ?? (cursorPresent ? lastCursor : undefined);\n if (at === undefined) return;\n const cursor: CursorFacet = {\n x: at.x,\n y: at.y,\n device: \"mouse\",\n away: mouse?.outside === true || session.away() !== null,\n canvas: presenceCanvasOf(w, session.peerId, keyOf),\n };\n if (cursorPresent && lastCursor !== undefined && cursorEquals(lastCursor, cursor)) {\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 const s = w.get(e, Size);\n const width = s?.w ?? 0;\n const height = 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 cursorEquals(a: CursorFacet, b: CursorFacet): boolean {\n return a.x === b.x && a.y === b.y && a.device === b.device && a.away === b.away && a.canvas === b.canvas;\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 \"remote cursors are\n * always custom nodes\" — the §7 PHASE language covers the LOCAL L4 cursor, not\n * this system).\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 * WHERE A PEER IS (petition I42): a peer whose cursor says `away`, or whose\n * `canvas` is not this receiver's own (`presenceCanvasOf` — its coordinates are\n * frame-local to a canvas this one is not in), has NO hand here: none is\n * spawned, and one already pooled is reaped — so `@ice/dom`'s remote-cursor\n * chips (drawn from these entities) hide it, and a host reading the hands sees\n * the same. The peer entity and its facet stay (a host drawing people itself\n * reads `away`/`canvas` there). A peer with neither field (an older peer) is\n * present, on the root.\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 system (in the `present` phase — presentation derivation, no in-tick\n * consumers), 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, presenceCanvasOf } 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\ninterface RemoteCursorsRig {\n readonly system: TickSystem;\n /**\n * Destroy every pooled cursor entity and forget the pool (between frames —\n * uninstall's slot). The tick body reaps a cursor when its PEER dies, but\n * removing the SYSTEM removes the reaper: detaching presence on a\n * still-open document (petition I18's inverse) would otherwise strand every\n * pooled cursor as a ghost frozen on canvas. The join path never saw this —\n * `docs.close()` follows its presence teardown with an in-place world reset\n * that killed the strands before anyone looked.\n */\n reap(): void;\n}\n\n/**\n * Where this receiver is, for a remote cursor's `canvas` to be compared with (petition I42): its own peer id (a keyless container's\n * name is per peer) and the doc session's `keyOf`. Absent: \"\" at the root and a keyless name inside — no remote peer is drawn in a\n * container then.\n */\nexport interface RemoteCursorsOpts {\n readonly keyOf?: (e: Entity) => string | undefined;\n readonly peerId?: string;\n}\n\n/** The pool + system + reap triple `installPresence` owns (pool lifetime = install lifetime). */\nfunction createRemoteCursorsRig(world: World, opts: RemoteCursorsOpts = {}): RemoteCursorsRig {\n const pool = new Map<Entity, PoolEntry>();\n\n const system = defineTickSystem(\n (ctx) => {\n const live = new Set<Entity>();\n const here = presenceCanvasOf(world, opts.peerId ?? \"\", opts.keyOf);\n ctx.query(remotePeerCursorsQ).each((b) => {\n for (const r of b) {\n const peer = b.entity(r);\n const pc = ctx.read(peer, PresenceCursor);\n if (pc.away || (pc.canvas ?? \"\") !== here) continue; // away, or in another canvas: no hand here (one pooled is reaped below)\n live.add(peer);\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, dropped its PresenceCursor facet, went away or is in another canvas.\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 // orderIndependent: every row this system writes is its OWN pool's\n // cursor entity (one per remote peer) — row-disjoint from any other\n // Position writer by construction. The attestation is what lets a\n // userland `present`-phase behavior that co-writes Position silence\n // strata's double-writer advisory from its own side: suppression is\n // conjunctive over ALL co-writers, so an un-attested engine system\n // would make the warning unsilenceable for authors doing it right\n // (0.8.0 review finding).\n access: { write: [Position, CursorVisual], orderIndependent: [Position] },\n },\n );\n\n return {\n system,\n reap() {\n for (const [, entry] of pool) {\n if (world.isAlive(entry.cursor)) world.destroy(entry.cursor);\n }\n pool.clear();\n },\n };\n}\n\n/**\n * The tick system that pools + reaps remote cursor entities — standalone\n * export for imperative rigs, which choose their own phase (`installPresence`\n * registers its own copy in `present`, and builds it through a rig so its\n * uninstall can reap the pool too).\n */\nexport function createRemoteCursorsSystem(world: World, opts: RemoteCursorsOpts = {}): TickSystem {\n return createRemoteCursorsRig(world, opts).system;\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 system (`present` phase). Returns an\n * uninstall that removes both AND destroys the system's pooled cursor\n * entities — uninstalling on a live document must not leave ghost cursors\n * (a between-frames call, like every teardown here). Does NOT own the\n * session's lifecycle — call `session.detach()` separately.\n *\n * THE HOST'S AWAY BETWEEN FRAMES (petition I42): `session.setAway` runs the\n * publish once more right after the call — a microtask, so never inside a step,\n * change-only as ever — so the facet reaches the room even while the loop\n * sleeps or the frame gate holds a park (a cover that freezes the desk and says\n * the peer is away, in either order).\n */\nexport function installPresence(\n engine: Engine,\n session: PresenceSession,\n opts: InstallPresenceOpts = {},\n): () => void {\n const publish = createPresencePublish(engine.world, session, opts);\n const removePublish = engine.onPublish(publish);\n let installed = true;\n const stopAway = session.onAway(() => {\n queueMicrotask(() => {\n if (installed && !engine.frame.stepping()) publish(engine.world);\n });\n });\n const rig = createRemoteCursorsRig(engine.world, { peerId: session.peerId, ...(opts.keyOf !== undefined ? { keyOf: opts.keyOf } : {}) });\n // \"present\", not \"derive\" (2026-08-16, with I18): cursor visuals are\n // presentation derivation with NO in-tick consumers — only reflectors read\n // them, post-notify, which sees present-phase writes the same frame. In\n // \"derive\" the late-installed system co-wrote Position after the stack's\n // readers/writers (selectionChrome, cull) and strata's access advisories\n // fired on every presence-attached facade engine — row-disjoint in truth,\n // but the read-before-write advisory has no attestation opt-out, and the\n // phase that matches the system's meaning is also the one with no\n // neighbours to misread it.\n const removeSystem = engine.addSystems(\"present\", rig.system);\n return () => {\n installed = false;\n stopAway();\n removePublish();\n removeSystem();\n rig.reap();\n };\n}\n","/**\n * The transport/bootstrap kit (design-005 §6.5) — the engine-provided join state\n * machine; the app provides the byte channel (channels.ts).\n *\n * `joinDoc` runs the LOCKED §6.5 protocol:\n * join = broadcast hello → buffer inbound → import addressed snapshot as causal\n * base → re-broadcast own base → drain buffer; ~800 ms silence ⇒ first peer ⇒\n * seed. Reconnect = the caller calls `joinDoc` again (streams are never\n * resumed). A strata `PendingImportError` on a live update ⇒ automatic internal\n * re-bootstrap (one retry, then surfaced via `onError`).\n *\n * ── THE FRAME PROTOCOL (1-byte kind + payload) ──\n * HELLO(1) payload = joinerId (UTF-8). \"I'm joining; send me a base.\"\n * SNAPSHOT_OFFER(2) payload = an ENVELOPE-framed doc snapshot (header + loro\n * bytes). An UNaddressed base broadcast — the post-import\n * \"re-broadcast own base\" step; a buffering peer OPENS it (the\n * gate runs), an active peer unwraps + merges it (dedupes).\n * SNAPSHOT(3) payload = idLen(u16 LE) ++ targetId(UTF-8) ++ ENVELOPE. An\n * addressed answer to a HELLO — only the peer whose id ==\n * targetId adopts it as its causal base (others unwrap/merge).\n * UPDATE(4) payload = a sealed local commit's incremental (raw) loro bytes.\n * PRESENCE(5) payload = ephemeral presence bytes — rides the same channel,\n * applied immediately (independent of the doc handshake).\n *\n * ── STATES ──\n * BUFFERING: helloed, no base yet. UPDATE frames are BUFFERED; the first snapshot\n * (offer, or addressed to us) triggers `becomeJoiner`; the hello-timeout triggers\n * `becomeSeeder`. PRESENCE flows immediately; HELLOs are ignored (nothing to offer).\n * ACTIVE: session live (either role). Answers HELLOs with an addressed snapshot,\n * merges snapshots/offers, applies updates, relays presence. Local commits ride\n * `store.subscribeOutbound` → UPDATE frames (remote-origin imports never re-fire it,\n * so an imported change is never rebroadcast — the origin IS the feedback guard).\n *\n * Two cold joiners with no existing doc BOTH time out and seed (split-brain) — the\n * design's \"first peer seeds\" assumes a joiner arrives after a seeder exists; a\n * simultaneous-cold-start tie-break is out of scope for M9 and noted here.\n */\nimport type { World } from \"@vibecook/strata-ecs\";\nimport { PendingImportError } from \"@vibecook/strata-ecs/durable\";\nimport type { ByteChannel } from \"./channels\";\nimport { createDocSession, openDocSession, type DocSession, type DocSessionOpts } from \"./doc-kit\";\nimport { decodeEnvelope } from \"./envelope\";\nimport type { PresenceSession } from \"../presence/presence-kit\";\n\nconst K_HELLO = 1;\nconst K_SNAPSHOT_OFFER = 2;\nconst K_SNAPSHOT = 3;\nconst K_UPDATE = 4;\nconst K_PRESENCE = 5;\n\nconst utf8 = new TextEncoder();\nconst fromUtf8 = new TextDecoder();\n\n/** Injectable timer surface (autosave's clock precedent) so the hello-timeout is deterministic in tests. */\nexport interface BootstrapClock {\n setTimeout(fn: () => void, ms: number): unknown;\n clearTimeout(handle: unknown): void;\n}\n\nconst defaultClock: BootstrapClock = {\n setTimeout: (fn, ms) => setTimeout(fn, ms),\n clearTimeout: (h) => clearTimeout(h as ReturnType<typeof setTimeout>),\n};\n\nexport interface JoinDocOpts {\n /** Passed to create/open (maxUndoSteps, etc.). */\n readonly docOpts?: DocSessionOpts;\n /** Version-gate override, forwarded to `openDocSession` (a non-\"ok\" verdict ⇒ a read-only joiner). */\n readonly onGate?: DocSessionOpts[\"onGate\"];\n /** Injected timer surface (tests). Default: global setTimeout/clearTimeout. */\n readonly clock?: BootstrapClock;\n /** Silence window before the lone/first peer seeds (design §6.5, default 800 ms). */\n readonly helloTimeoutMs?: number;\n /** Populate the fresh document — runs on the SEEDER path only, before it goes active. */\n readonly seed?: (session: DocSession) => void;\n /** Presence session to relay over the same channel (kind PRESENCE). Optional. */\n readonly presence?: PresenceSession;\n /** Surfaced when a re-bootstrap (after a PendingImportError) itself fails, or a base import fails post-join. */\n readonly onError?: (err: unknown) => void;\n /**\n * Abort the join: tears the room down (channel unsubscribed, session closed)\n * and rejects the promise if it hasn't resolved yet. The facade aborts its\n * pending join when another document supersedes it — a resolution-time check\n * alone cannot stop a mid-handshake join from attaching to the world.\n */\n readonly signal?: AbortSignal;\n /**\n * Live-session transitions: fired at every activation (including the first,\n * just before the promise resolves) and with `undefined` when an internal\n * re-bootstrap tears the quarantined session down. The facade re-targets its\n * forwarding sink here — without it, callers keep committing into a session\n * `rebootstrap()` already closed.\n */\n readonly onSession?: (session: DocSession | undefined) => void;\n}\n\nexport interface JoinResult {\n /** \"seeder\" = we created the doc (timed out); \"joiner\" = we imported a peer's base. */\n readonly role: \"seeder\" | \"joiner\";\n /** LIVE (a getter): after an internal re-bootstrap this is the replacement session. */\n readonly session: DocSession;\n /** Stop relaying, unsubscribe the channel, and close the session. Idempotent. */\n leave(): void;\n}\n\n/** Prefix `payload` with a 1-byte `kind`. */\nfunction frame(kind: number, payload?: Uint8Array): Uint8Array {\n const len = payload?.length ?? 0;\n const out = new Uint8Array(1 + len);\n out[0] = kind;\n if (payload !== undefined) out.set(payload, 1);\n return out;\n}\n\n/** Build an addressed SNAPSHOT frame: kind ++ idLen(u16 LE) ++ id ++ snapshot. */\nfunction frameSnapshot(targetId: string, snapshot: Uint8Array): Uint8Array {\n const id = utf8.encode(targetId);\n const out = new Uint8Array(1 + 2 + id.length + snapshot.length);\n out[0] = K_SNAPSHOT;\n out[1] = id.length & 0xff;\n out[2] = (id.length >> 8) & 0xff;\n out.set(id, 3);\n out.set(snapshot, 3 + id.length);\n return out;\n}\n\n/** Parse a SNAPSHOT payload (the bytes AFTER the kind byte) into its target id + snapshot. */\nfunction parseSnapshot(payload: Uint8Array): { targetId: string; snapshot: Uint8Array } {\n const idLen = (payload[0] ?? 0) | ((payload[1] ?? 0) << 8);\n const targetId = fromUtf8.decode(payload.subarray(2, 2 + idLen));\n const snapshot = payload.subarray(2 + idLen);\n return { targetId, snapshot };\n}\n\n/**\n * Re-offer this session's document to the room (design-005 §6.5 amendment,\n * 2026-07-20 — the lossy-transport repair). Broadcasts the base as an\n * UN-addressed SNAPSHOT_OFFER — exactly the frame a joiner broadcasts after\n * importing its base — so the protocol already defines every receiver's move:\n * an ACTIVE peer MERGES it (loro dedupes; increments the outage dropped are\n * subsumed by the full document), a BUFFERING peer OPENS it as its causal base.\n * Call it when a lossy transport BEHIND a still-live channel heals (an Electron\n * main's mesh link bounced; the IPC channel object never died). A channel that\n * itself died (a closed socket) needs a fresh `joinDoc` instead — offers ride\n * the channel, and a dead one drops them silently.\n */\nexport function offerBase(channel: ByteChannel, session: DocSession): void {\n channel.send(frame(K_SNAPSHOT_OFFER, session.exportEnvelope()));\n}\n\n/**\n * Join (or found) the room's document over `channel`. Resolves once we go active —\n * as a \"joiner\" (imported a peer's base) or a \"seeder\" (timed out and created one).\n */\nexport function joinDoc(world: World, channel: ByteChannel, opts: JoinDocOpts = {}): Promise<JoinResult> {\n const clock = opts.clock ?? defaultClock;\n const helloTimeoutMs = opts.helloTimeoutMs ?? 800;\n const joinerId = crypto.randomUUID();\n const docOpts: DocSessionOpts = {\n ...(opts.docOpts ?? {}),\n ...(opts.onGate !== undefined ? { onGate: opts.onGate } : {}),\n // SINGLE-WRITER LAW (petition 8, schema-migrate.ts): a live-room joiner is never the\n // document's sole occupant — structural/pack migration here would split-brain the room\n // (the peers keep writing the old shape; sync never re-gates). An old-schema doc joined\n // live attaches read-only; it migrates on its next SOLO open.\n migrate: false,\n };\n\n return new Promise<JoinResult>((resolve, reject) => {\n let session: DocSession | undefined;\n let active = false;\n let settled = false;\n let left = false;\n let timeoutHandle: unknown;\n let unsubOutbound: (() => void) | undefined;\n let rebootstrapAttempts = 0;\n\n // UPDATE frames that arrived while BUFFERING — drained after the base imports.\n const buffered: Uint8Array[] = [];\n // Channel + presence-relay unsubs (filled at wire-up; exists from the start\n // so teardown is safe on every path, including a pre-resolution abort).\n const roomSubs: (() => void)[] = [];\n\n // EVERY exit — leave(), abort, a failed base import, a throwing seed(), the\n // quarantine give-up — funnels through this one idempotent teardown, so no\n // path can leak the channel/presence/outbound subscriptions or the timer.\n const teardown = (): void => {\n if (left) return;\n left = true;\n clock.clearTimeout(timeoutHandle);\n opts.signal?.removeEventListener(\"abort\", onAbort);\n for (const unsub of roomSubs.splice(0)) unsub();\n unsubOutbound?.();\n unsubOutbound = undefined;\n session?.close();\n };\n\n /** Failure exit: teardown, then reject (pre-resolve) or surface via onError (post-resolve). */\n const fail = (err: unknown): void => {\n teardown();\n if (!settled) {\n settled = true;\n reject(err instanceof Error ? err : new Error(String(err)));\n } else {\n opts.onError?.(err);\n }\n };\n\n // EVERY channel write goes through this guard: a transport throw (a socket\n // flipping state between the readiness check and send) must fail the join,\n // not strand a half-attached session — and an outbound-subscription send\n // must never escape into the user's local transaction (2026-07-13 review).\n const send = (bytes: Uint8Array): void => {\n try {\n channel.send(bytes);\n } catch (err) {\n fail(err);\n }\n };\n\n // A post-resolve abort is the caller closing a live join — leave() semantics,\n // deliberately NOT routed to onError (fail() would report every normal close).\n const onAbort = (): void => {\n const wasSettled = settled;\n teardown();\n if (!wasSettled) {\n settled = true;\n const reason: unknown = opts.signal?.reason ?? new Error(\"ice: joinDoc aborted\");\n reject(reason instanceof Error ? reason : new Error(String(reason)));\n }\n };\n\n const armTimeout = (): void => {\n timeoutHandle = clock.setTimeout(() => {\n if (!active && !left) becomeSeeder();\n }, helloTimeoutMs);\n };\n\n const applyRemoteSafe = (bytes: Uint8Array): void => {\n if (session === undefined) return;\n try {\n session.applyRemote(bytes);\n } catch (err) {\n if (err instanceof PendingImportError) rebootstrap();\n else opts.onError?.(err); // corrupt bytes must not brick the channel\n }\n };\n\n // An active peer MERGES a snapshot/offer (envelope-framed) — unwrap to raw\n // loro bytes, then apply. A buffering peer instead OPENS it (openDocSession\n // decodes the envelope itself + runs the gate).\n const mergeSnapshotEnvelope = (envelope: Uint8Array): void => {\n let payload: Uint8Array;\n try {\n payload = decodeEnvelope(envelope).payload;\n } catch (err) {\n opts.onError?.(err); // a corrupt envelope must not brick the channel\n return;\n }\n applyRemoteSafe(payload);\n };\n\n const goActive = (s: DocSession, role: \"seeder\" | \"joiner\"): void => {\n session = s;\n active = true;\n // Local commits → UPDATE frames. Remote-origin imports never fire this\n // (durable's onLocalBatch origin filter), so an import is never rebroadcast.\n unsubOutbound = s.store.subscribeOutbound((bytes) => send(frame(K_UPDATE, bytes)));\n opts.onSession?.(s);\n if (!settled) {\n settled = true;\n resolve({\n role,\n // The getter tracks re-bootstrap: the resolved object never pins the\n // original session (callers would keep a quarantined one otherwise).\n get session() {\n return session as DocSession;\n },\n leave: teardown,\n });\n }\n };\n\n const becomeSeeder = (): void => {\n if (active || left) return;\n if (rebootstrapAttempts > 0) {\n // A re-bootstrap that finds no peer cannot recover the doc — re-seeding\n // here would present a fresh empty doc as if it were the recovered one.\n teardown();\n opts.onError?.(new Error(\"ice: re-bootstrap found no peer to rejoin from — document quarantined\"));\n return;\n }\n let s: DocSession | undefined;\n try {\n s = createDocSession(world, docOpts);\n opts.seed?.(s); // seed BEFORE going active — the state rides every future snapshot\n } catch (err) {\n // seed() runs inside the hello-timeout timer callback — uncaught, the\n // throw would escape the timer and the join promise would hang forever.\n s?.close();\n fail(err);\n return;\n }\n goActive(s, \"seeder\");\n };\n\n const becomeJoiner = (base: Uint8Array): void => {\n if (active || left) return;\n clock.clearTimeout(timeoutHandle);\n const result = openDocSession(world, base, docOpts);\n if (!result.ok) {\n // A corrupt/incompatible base — tear the room down and surface it\n // (reconnect = re-join; the channel must not stay subscribed).\n fail(new Error(`ice: bootstrap base import failed — ${result.reason}`));\n return;\n }\n const s = result.session;\n session = s; // BEFORE the send: a throwing transport must find it in teardown\n // §6.5: import base → re-broadcast own base → drain buffer. Go active before\n // draining so late live UPDATEs (post-drain) apply through the active path.\n send(frame(K_SNAPSHOT_OFFER, s.exportEnvelope())); // envelope-framed (a peer may OPEN it)\n if (left) return; // the offer send failed — teardown already closed s\n goActive(s, \"joiner\");\n const drained = buffered.splice(0);\n for (let i = 0; i < drained.length; i++) {\n const bytes = drained[i];\n if (bytes === undefined) continue;\n applyRemoteSafe(bytes);\n if (left || !active || session !== s) {\n // A PendingImportError mid-drain re-bootstrapped (or quarantined) the\n // session — the rest of these frames belong to the REPLACEMENT's\n // buffer (they may import cleanly once the fresh base lands), not to\n // the session that just closed under us.\n buffered.push(...drained.slice(i + 1));\n break;\n }\n }\n };\n\n const rebootstrap = (): void => {\n if (rebootstrapAttempts >= 1) {\n // Second quarantine: give up FOR REAL — leave the room (else every later\n // UPDATE re-fires this error against a session we know is dead) and tell\n // the session listener the doc is gone.\n teardown();\n opts.onSession?.(undefined);\n opts.onError?.(new Error(\"ice: re-bootstrap after PendingImportError failed — document quarantined\"));\n return;\n }\n rebootstrapAttempts++;\n // Tear the quarantined session down, return to BUFFERING, and re-hello. The\n // channel subscription + presence relay stay wired (presence is session-free).\n // `session` keeps pointing at the closed one so the result getter stays\n // non-undefined; `active=false` routes every frame to the buffering path.\n unsubOutbound?.();\n unsubOutbound = undefined;\n session?.close();\n active = false;\n buffered.length = 0;\n opts.onSession?.(undefined); // no live session until the re-join lands\n send(frame(K_HELLO, utf8.encode(joinerId)));\n armTimeout();\n };\n\n const onFrame = (bytes: Uint8Array): void => {\n if (bytes.length === 0) return;\n const kind = bytes[0];\n const payload = bytes.subarray(1);\n\n if (kind === K_PRESENCE) {\n try {\n opts.presence?.wire.apply(payload); // independent of the doc handshake\n } catch (err) {\n opts.onError?.(err);\n }\n return;\n }\n\n if (active) {\n if (kind === K_HELLO) {\n if (session !== undefined) {\n send(frameSnapshot(fromUtf8.decode(payload), session.exportEnvelope()));\n }\n } else if (kind === K_UPDATE) {\n applyRemoteSafe(payload); // raw loro increment\n } else if (kind === K_SNAPSHOT_OFFER) {\n mergeSnapshotEnvelope(payload);\n } else if (kind === K_SNAPSHOT) {\n mergeSnapshotEnvelope(parseSnapshot(payload).snapshot);\n }\n return;\n }\n\n // BUFFERING (joiner-in-progress / pre-seed).\n if (kind === K_SNAPSHOT_OFFER) {\n becomeJoiner(payload);\n } else if (kind === K_SNAPSHOT) {\n const { targetId, snapshot } = parseSnapshot(payload);\n if (targetId === joinerId) becomeJoiner(snapshot); // \"import ADDRESSED snapshot as causal base\"\n } else if (kind === K_UPDATE) {\n buffered.push(payload); // buffer then drain (order preserved)\n }\n // HELLO while buffering: ignore (we have nothing to offer yet).\n };\n\n // Abort wiring before anything opens: a pre-aborted signal never joins the room.\n if (opts.signal?.aborted === true) {\n onAbort();\n return;\n }\n opts.signal?.addEventListener(\"abort\", onAbort);\n\n roomSubs.push(channel.subscribe(onFrame));\n const unsubPresence = opts.presence?.onOutbound((b) => send(frame(K_PRESENCE, b)));\n if (unsubPresence !== undefined) roomSubs.push(unsubPresence);\n\n // Broadcast hello, buffer inbound, wait for a base (or the silence timeout).\n // A transport that reports readiness GATES both: arming the ~800 ms window\n // while a socket is still CONNECTING lets a slow connect elapse it and seed\n // a divergent second doc offline — whose seeded state (pre-outbound-\n // subscription) would never reach the existing room (2026-07-13 review).\n const begin = (): void => {\n if (left) return; // aborted while the transport was connecting\n send(frame(K_HELLO, utf8.encode(joinerId)));\n if (left) return; // the hello itself failed — already torn down\n armTimeout();\n };\n if (channel.ready !== undefined) {\n channel.ready().then(begin, (err: unknown) => fail(err));\n } else {\n begin();\n }\n });\n}\n","/**\n * Byte-channel adapters for the bootstrap kit (design-005 §6.5: \"provided\n * adapters for BroadcastChannel and WebSocket byte relays; anything carrying a\n * Uint8Array works\").\n *\n * A `ByteChannel` is the whole transport contract the bootstrap state machine\n * needs: `send(bytes)` out, `subscribe(fn)` in. The engine stays transport-free —\n * the app owns the socket lifecycle and hands the instance in.\n *\n * Both adapters interact through STRUCTURAL types (no DOM lib dependency beyond\n * what core already uses — the broadcast-relay precedent), so a test double or an\n * alternative runtime satisfies them without the platform's exact event types.\n */\n\n/** The transport contract: bytes out, bytes in. Structurally satisfied by both adapters + test fakes. */\nexport interface ByteChannel {\n send(bytes: Uint8Array): void;\n /** Deliver every inbound frame to `fn`. Returns an unsubscribe. */\n subscribe(fn: (bytes: Uint8Array) => void): () => void;\n /**\n * OPTIONAL readiness: resolves once the transport can actually transmit,\n * rejects if it never will. `joinDoc` gates its hello + the seed-silence\n * window on this — a queue-until-open transport otherwise lets a slow\n * connect elapse the window and seed a DIVERGENT second doc offline\n * (2026-07-13 review). Synchronous transports (BroadcastChannel, in-memory\n * buses) simply omit it.\n */\n ready?(): Promise<void>;\n}\n\n/** A `ByteChannel` that owns a resource (a BroadcastChannel) and can release it. */\nexport interface OwnedByteChannel extends ByteChannel {\n close(): void;\n}\n\n/** The slice of `BroadcastChannel` we use (structural — avoids the DOM event lib). */\ninterface BroadcastChannelLike {\n postMessage(message: unknown): void;\n addEventListener(type: \"message\", listener: (ev: { data: unknown }) => void): void;\n removeEventListener(type: \"message\", listener: (ev: { data: unknown }) => void): void;\n close(): void;\n}\n\n/** The slice of `WebSocket` we use (structural — the app supplies the instance). */\nexport interface WebSocketLike {\n binaryType: string;\n readyState: number;\n send(data: ArrayBufferLike | ArrayBufferView): void;\n addEventListener(type: string, listener: (ev: { data: unknown }) => void): void;\n removeEventListener(type: string, listener: (ev: { data: unknown }) => void): void;\n}\n\n/** WebSocket `readyState` OPEN. */\nconst WS_OPEN = 1;\n\n/** Coerce a received message payload to a `Uint8Array`, or undefined if it is neither bytes nor a buffer. */\nfunction toBytes(data: unknown): Uint8Array | undefined {\n if (data instanceof Uint8Array) return data;\n if (data instanceof ArrayBuffer) return new Uint8Array(data);\n return undefined;\n}\n\n/**\n * A `ByteChannel` over a `BroadcastChannel` (same-origin tab-to-tab). Uint8Array\n * is structured-cloneable, so it rides `postMessage` directly. A BroadcastChannel\n * never delivers a message to the instance that posted it, so a peer never hears\n * its own frames. `close()` releases the owned channel.\n */\nexport function broadcastChannelByteChannel(name: string): OwnedByteChannel {\n const bc: BroadcastChannelLike = new BroadcastChannel(name);\n const listeners = new Set<(bytes: Uint8Array) => void>();\n\n const onMessage = (ev: { data: unknown }): void => {\n const bytes = toBytes(ev.data);\n if (bytes === undefined) return;\n for (const fn of [...listeners]) fn(bytes);\n };\n bc.addEventListener(\"message\", onMessage);\n\n return {\n send(bytes) {\n bc.postMessage(bytes);\n },\n subscribe(fn) {\n listeners.add(fn);\n return () => {\n listeners.delete(fn);\n };\n },\n close() {\n bc.removeEventListener(\"message\", onMessage);\n bc.close();\n listeners.clear();\n },\n };\n}\n\n/**\n * A `ByteChannel` over a caller-supplied WebSocket. Sets `binaryType =\n * \"arraybuffer\"` (so inbound frames arrive as `ArrayBuffer`), and QUEUES outbound\n * frames until the socket is OPEN, flushing on the `open` event. The app owns the\n * socket (construction, reconnection, close).\n */\nexport function webSocketByteChannel(ws: WebSocketLike): ByteChannel {\n ws.binaryType = \"arraybuffer\";\n const listeners = new Set<(bytes: Uint8Array) => void>();\n const queue: Uint8Array[] = [];\n\n const flush = (): void => {\n if (ws.readyState !== WS_OPEN) return;\n for (const bytes of queue.splice(0)) ws.send(bytes);\n };\n ws.addEventListener(\"open\", flush);\n ws.addEventListener(\"message\", (ev) => {\n const bytes = toBytes(ev.data);\n if (bytes === undefined) return;\n for (const fn of [...listeners]) fn(bytes);\n });\n flush(); // already-open sockets flush immediately\n\n // Readiness (the ByteChannel.ready contract): a CONNECTING socket resolves on\n // \"open\" and rejects on \"close\"/\"error\" first — joinDoc must not start its\n // seed-silence window while frames are still queued behind the connect.\n const readyPromise = new Promise<void>((resolve, reject) => {\n if (ws.readyState === WS_OPEN) {\n resolve();\n return;\n }\n if (ws.readyState > WS_OPEN) {\n reject(new Error(\"ice: webSocketByteChannel — the socket is already closing/closed.\"));\n return;\n }\n ws.addEventListener(\"open\", () => resolve());\n ws.addEventListener(\"close\", () => reject(new Error(\"ice: webSocketByteChannel — the socket closed before opening.\")));\n ws.addEventListener(\"error\", () => reject(new Error(\"ice: webSocketByteChannel — the socket errored before opening.\")));\n });\n readyPromise.catch(() => {}); // pre-observed: no unhandled rejection when ready() is never called\n\n return {\n send(bytes) {\n if (ws.readyState === WS_OPEN) ws.send(bytes);\n else queue.push(bytes); // queue-until-open\n },\n subscribe(fn) {\n listeners.add(fn);\n return () => {\n listeners.delete(fn);\n };\n },\n ready: () => readyPromise,\n };\n}\n","/**\n * `createCanvasEngine` — THE published construction path (design-005 §4).\n *\n * Construction wires: world + engine + the FULL interaction stack + the\n * widget runtime + nested canvas + settings resources, doc-less. A document\n * attaches later through `engine.docs.*` (doc-attached remains the default\n * POSTURE: `docs.create()` is the first call of every editor app) — the\n * commit seam is a FORWARDING sink whose target swaps per session, so the\n * stack never rebuilds across doc open/close.\n *\n * `ops.*` is the catalog of engine-owned write paths (design-005 §4 table):\n * app handlers call ops between frames (design-002 §3); each op is one\n * transaction / one resource write / one tag sweep. Nothing here adds a\n * write path that didn't already exist — ops BIND existing primitives to\n * the current session.\n *\n * Budgets: the frame preview's (children, bytes). Port budgets remain reviewed\n * constants (RUNTIME_BUDGETS) in v1 — recorded. `keepMounted` and `fboBytes`\n * left at design-015 D5b with the mount LRU and the GL ledger.\n */\nimport type { Entity, Resource, World } from \"@vibecook/strata-ecs\";\nimport { createWorld, defineQuery } from \"@vibecook/strata-ecs\";\nimport { fitCamera, zoomAtPoint } from \"@ice/kernel\";\nimport {\n canvasIdentityOf,\n canvasPackId,\n type CanvasCatalogContribution,\n type CanvasType,\n} from \"../canvas/define-canvas-type\";\nimport {\n bindEngineCatalog,\n compileEngineCatalog,\n type EngineCatalog,\n} from \"../canvas/engine-catalog\";\nimport {\n createPlacementAuthority,\n type PlacementAuthority,\n} from \"../canvas/placement\";\nimport {\n CanvasIntentScope,\n CanvasSession,\n createCanvasSessionController,\n type CanvasSessionValue,\n} from \"../canvas/session\";\nimport type {\n CanvasRuntimeExtension,\n FrameBehavior,\n} from \"../canvas/extensions\";\nimport type { FrameProjection } from \"../canvas/frame-projection\";\nimport {\n installCanvasRuntimeExtensions,\n type CanvasRuntimeExtensionHost,\n} from \"../canvas/runtime-extension-host\";\nimport {\n installFrameBehaviors,\n type FrameBehaviorHost,\n} from \"../canvas/frame-behavior-host\";\nimport {\n collectCanvasDiagnostics,\n type CanvasDiagnostic,\n type CanvasDiagnosticSnapshot,\n} from \"../canvas/diagnostics\";\nimport {\n createFramePreviewStore,\n FRAME_PREVIEW_DEFAULT_BYTES,\n FRAME_PREVIEW_DEFAULT_CHILDREN,\n type FramePreviewStore,\n} from \"../canvas/frame-preview\";\nimport {\n createPresentationTransitionCoordinator,\n type PresentationPlane,\n type PresentationTransitionCoordinator,\n} from \"../canvas/presentation-transition\";\nimport type { CanvasCatalogSection } from \"../canvas/define-canvas-type\";\nimport {\n ActiveTool,\n BoardRoot,\n Camera,\n CameraLimits,\n ChildOf,\n ChromeSettings,\n Container,\n GestureSettings,\n InsertGhost,\n Locked,\n PointerSettings,\n Position,\n Selectable,\n Size,\n SnapConfig,\n StageMode,\n TransformTween,\n Viewport,\n Wire,\n ZoomThroughSettings,\n} from \"../catalog\";\nimport { Active, Visible } from \"../catalog/camera-derived\";\nimport {\n createBehaviorRuntime,\n type BehaviorPresence,\n type BehaviorRuntime,\n type BehaviorSession,\n} from \"../behavior/runtime\";\nimport type { AnyBehaviorDef } from \"../behavior/types\";\nimport { createEngine, type Engine } from \"../engine/engine\";\nimport type { FrameControl } from \"../engine/frame-control\";\nimport { isMidGesture } from \"../interaction/gesture-status\";\nimport type { CommitIntent, CommitSink } from \"../engine/commit-sink\";\nimport { guardedTransaction, retargetTweensToDoc } from \"../guards/guarded-tx\";\nimport { writeRuntimeResource } from \"../guards/resource-writer\";\nimport { installInteractionStack, type InteractionStack } from \"../interaction/install\";\nimport { createNestedCanvas, currentNavFrame, type NavOpts, type NestedCanvas } from \"../nav/nested-canvas\";\nimport { NavIntent } from \"../nav/nav-geometry\";\nimport { cancelActiveGestures } from \"../ops/gestures\";\nimport { Held, HeldIntent, HeldTool, HeldView, TrayIntent } from \"../catalog/desk\";\nimport { heldEntity } from \"../systems/held\";\nimport { arrangeWidgets, type ArrangeOpts } from \"../ops/arrange\";\nimport { insertByDrag, type InsertByDragOpts } from \"../ops/insert\";\nimport { cascadeDestroy } from \"../ops/cascade\";\nimport { clearSelection, selectedEntities, setSelection } from \"../ops/selection\";\nimport { closeTray, trayHung } from \"../ops/tray\";\nimport { installWidgetRuntime, type WidgetRuntime } from \"../widget/mount-store\";\nimport { spawnWidget, type SpawnWidgetOpts } from \"../widget/spawn\";\nimport { setWidgetProps } from \"../widget/set-props\";\nimport { trayTakeProps, WidgetEquipped, type WidgetType } from \"../widget/define-widget\";\nimport { readHeldToolState } from \"../widget/held-tools\";\nimport { registerBuiltinTools, 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 type { CommitExtender } from \"../doc/doc-commit-sink\";\nimport { gateVerdict } from \"../doc/version-gate\";\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 PresenceOpts, type PresenceSession } from \"../presence/presence-kit\";\nimport { installPresence } from \"../presence/remote-cursors\";\nimport type { EngineGpu } from \"../surface/gpu-device\";\nimport {\n CAMERA_DEFAULTS,\n CHROME_DEFAULTS,\n FIT_DEFAULTS,\n GESTURE_DEFAULTS,\n POINTER_DEFAULTS,\n SNAP_DEFAULTS,\n type WheelMode,\n type WheelZoomCurve,\n ZOOM_THROUGH_DEFAULTS,\n} from \"../settings/defaults\";\n\nexport interface CanvasEngineOpts {\n /** Registered widget types (definition happens at defineWidget; this list is validated). */\n readonly widgets?: readonly { readonly type: string }[];\n /** Preserve these schemas in old documents without loading their runtime or showing their objects. */\n readonly retiredWidgets?: readonly { readonly type: string }[];\n /** Registered tools (definition happens at defineTool; validated). */\n readonly tools?: readonly Tool[];\n /** Explicit Canvas SDK definitions. Supplying any typed field enables typed mode. */\n readonly canvasTypes?: readonly CanvasType[];\n /** New-document root only; existing documents retain their durable identity. */\n readonly rootCanvas?: CanvasType;\n /** Presentation-only fallback for unknown/incompatible document semantics. */\n readonly presentationFallback?: CanvasType;\n /** Presentation-only sections merged deterministically at compilation. */\n readonly catalogContributions?: readonly CanvasCatalogContribution[];\n /** Governed current-frame runtime definitions compiled by this engine. */\n readonly canvasRuntimeExtensions?: readonly CanvasRuntimeExtension[];\n /** Governed view-independent semantic frame definitions compiled by this engine. */\n readonly frameBehaviors?: readonly FrameBehavior[];\n /** Bounded read-only instance-preview projections compiled by this engine. */\n readonly frameProjections?: readonly FrameProjection[];\n /**\n * Behaviors this engine runs (design-009). Definition is the import\n * side-effect; listing them here COMPILES and installs them — a behavior that\n * is defined but never registered costs nothing and does nothing, which is\n * what makes \"a plugin declared it\" and \"this engine runs it\" separable.\n */\n readonly behaviors?: readonly AnyBehaviorDef[];\n /** Generic guest breaker routing for hosts that use the published facade. */\n readonly onGuestFault?: (id: string, error: unknown) => void;\n /**\n * A reflector that threw (design-015 D7): the flush contains it — that frame is skipped — and routes it here (default:\n * `console.error`). A host that counts its faults (apps/desk's `window.__desk.faults`, the rigs' \"no page errors\") passes it.\n */\n readonly onReflectorFault?: (name: string, error: unknown) => void;\n readonly onGuestNotice?: (message: string) => void;\n /** Behavior-specific routing preserves hook and entity provenance. The two\n * pairs are COMPLEMENTARY, not alternatives: a fault that also strikes the\n * breaker (a thenable hook; throws spanning instances) reaches BOTH the\n * behavior route and the guest route — pass both, or the guest half of\n * those events still lands on the console default. */\n readonly onBehaviorFault?: (\n behavior: string,\n hook: string,\n entity: Entity | undefined,\n error: unknown,\n ) => void;\n readonly onBehaviorLog?: (\n behavior: string,\n message: string,\n rest: readonly unknown[],\n ) => void;\n readonly budgets?: {\n /** Portal-preview limits may be lowered from 128 children / 256 KiB. */\n readonly framePreviewChildren?: number;\n readonly framePreviewBytes?: number;\n };\n readonly settings?: {\n /**\n * The CameraLimits clamp. The desk's is infinite: `{ min: 1e-8, max: 1e8 }`\n * (design-015 §9) — every camera path holds finite and invertible there.\n */\n readonly zoom?: { readonly min?: number; readonly max?: number };\n /**\n * GestureSettings seeds. `wheel` selects ordinary scroll pan (default)\n * or zoom. `wheelZoomCurve` selects pinch/modifier zoom independently.\n * Omitted curves preserve the initial wheel mode's legacy response.\n */\n readonly gestures?: Partial<Record<Exclude<keyof typeof GESTURE_DEFAULTS, \"wheel\" | \"wheelZoomCurve\">, number>> & {\n readonly wheel?: WheelMode;\n /** Pinch and modifier-wheel response; changing `wheel` never changes this curve. */\n readonly wheelZoomCurve?: WheelZoomCurve;\n };\n readonly pointers?: Partial<Record<keyof typeof POINTER_DEFAULTS, number>>;\n readonly snap?: { readonly enabled?: boolean; readonly thresholdPx?: number };\n /** Selection-chrome knob: liftScale = the app's visual drag-lift scale (the resize handles wrap it). */\n readonly chrome?: { readonly liftScale?: number };\n /**\n * Nav seeds (design-015 §9 — D2b). `zoomThrough`: a wheel zoom that leaves a container's\n * face covering the view by `in` CSS px cuts into it, one that leaves the current frame's\n * face `out` px short cuts back out — off unless `enabled` (the desk's is on); `gate` is the\n * face's short side (CSS px) across which a live inside comes in (a face enters only at 1).\n */\n readonly nav?: {\n readonly zoomThrough?: {\n readonly enabled?: boolean;\n readonly in?: number;\n readonly out?: number;\n readonly gate?: readonly [number, number];\n };\n };\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 /**\n * The engine's GPU device (design-012 §4; the device door since design-015 D5b): acquire it with\n * `acquireCompositorDevice()` before constructing the engine and pass it here. ONE device per engine\n * (D7): the desk's layer draws with it — `createDeskHost` hands it through the layer context — and never\n * acquires its own, so its `errors()` sees the desk's uncaptured GPU errors; the app owns its end of life.\n * Absent — the common case, and every headless engine — the desk acquires its own device.\n */\n readonly compositorDevice?: EngineGpu;\n}\n\nexport interface CanvasOps {\n /** cancel active gestures → switch (design-003 §8; the strata-example lesson). */\n setTool(id: string): void;\n spawnWidget(type: string, opts: SpawnWidgetOpts): Entity;\n /**\n * Tray adoption (2026-07-19): DRAFT-spawn a runtime ghost of `type` centered\n * under the pressing pointer and enqueue one synthetic down — the ordinary\n * drag stack takes over (lift, snap, drop targets, folder consume). Release\n * promotes it through ONE `create` tx (selected, one undo step); cancel or a\n * rejected drop flies it back to the tray press point and despawns it with\n * zero undo footprint. Call from the tray tile's `pointerdown` AFTER\n * `stopPropagation()` (the down must not double-land via the adapter).\n */\n insertByDrag(type: string, opts: InsertByDragOpts): Entity;\n /**\n * THE TRAY'S OWN TAKE, LAID (petition I37 — a host's keyboard path through the pegboard: its arrows move `focusTray`, its ⏎ lays):\n * what a specimen dragged off the board makes, with no drag — the type at its natural size, made with what its entry says one taken\n * carries (`trayTakeProps`), CENTRED on `at` (a world point of the current frame), in ONE transaction (one undo step), selected;\n * and the board folds as a handed take's does (`closeTray`). Only a type the board hangs now (`trayHung` — the frame takes it, the\n * renderer draws it, the drawer shows its category); refused (undefined) for any other and while an object is in hand. Throws as\n * `spawnWidget` does (no document, a read-only one). Laid in the current frame, never consumed by a container under the point —\n * a drop's consume is the drag's.\n */\n layFromTray(type: string, at: { readonly x: number; readonly y: number }): Entity | undefined;\n /** Validated prop update: Standard-Schema-checked, json serialized, ONE tx (2026-07-13 review). */\n setWidgetProps(entity: Entity, props: Readonly<Record<string, unknown>>): void;\n deleteSelection(): void;\n /** Twin spawns offset +16/+16; the clones become the selection. */\n duplicateSelection(): Entity[];\n setSelection(ids: readonly Entity[], mode?: \"replace\" | \"add\" | \"toggle\"): void;\n clearSelection(): void;\n selectAll(): void;\n /** Sibling-sequence sweep, one tx: the ids to the frame top/bottom (petition 8). */\n reorder(ids: readonly Entity[], mode: \"top\" | \"bottom\"): void;\n /**\n * Tape widgets down, or lift the tape (design-015 §5.1, *Marks on the Mat*\n * Q-e): writes the durable `Locked` tag on every id that is a widget of the\n * current frame whose state differs, in ONE transaction (one undo step; no\n * transaction at all when nothing changes). A taped widget is never moved or\n * resized by a gesture and the marquee passes over it; it stays selectable,\n * pickable and openable. Refuses on a read-only document like every write op.\n */\n setLocked(ids: readonly Entity[], locked: boolean): void;\n /**\n * Desktop-style Clean Up (kernel packLayout): tidy reading-order rows, one\n * undo step, 240ms glide (durationMs: 0 snaps). Scope: ids > selection ≥2 >\n * current nav frame. Returns the movers (empty = already tidy).\n */\n arrange(opts?: ArrangeOpts): Entity[];\n zoomToFit(ids?: readonly Entity[]): void;\n /**\n * The natural DEFAULT framing (2026-07-18): zoom-to-fit the current\n * frame's widgets inside the FIT_DEFAULTS band (never past 100%, never\n * below 50%, ∩ settings.zoom) — same band as the folder arrival camera.\n * Returns false (camera untouched) until a real viewport AND content\n * exist, so boot code can retry. zoomToFit stays the uncapped explicit\n * \"show me everything\".\n */\n frameContent(): boolean;\n zoomTo(zoom: number, anchor?: { x: number; y: number }): void;\n panTo(x: number, y: number): void;\n enterContainer(container: Entity, opts?: NavOpts): void;\n exitContainer(opts?: NavOpts): void;\n /** Pop several levels in ONE transition (breadcrumb jumps; design-006 §5). */\n exitTo(targetDepth: number, opts?: NavOpts): void;\n cancelActiveGestures(): void;\n /**\n * Pick an object up into the hand (design-015 §8, D4b): the ONE writer of the runtime `Held`\n * tag (with a fresh `HeldView`) — no camera moves, the renderer lifts the object to its reading\n * size and the desk behind goes out of focus. The object is selected as it is picked up (it\n * stays selected when put down, so ⏎ opens it again) and any live gesture is cancelled. Refused\n * — an Error, like `enterContainer` on a non-container — for an entity that is not a live object\n * of the current frame whose type declares `openable` (its kind has an `open` binding), and while\n * another object is held (put that one down first). Never a document write. The object's tool in\n * hand (`HeldTool`, D3t-a) comes with it: its type's `heldTool` of its props, else its first mode.\n */\n open(entity: Entity): void;\n /** Put the held object down (design-015 §8): `Held`, `HeldView` and `HeldTool` leave; the renderer flies it home. Nothing held: no-op. */\n putDown(): void;\n /**\n * Use a tool of the held bar (design-015 §8; D3t-a — widget/held-tools.ts): a `mode` becomes the held object's ACTIVE\n * tool (`HeldTool` — a runtime write, the user's fact; a `toggle` mode chosen again hands back the one before it), an\n * `action` runs its op once (its transaction, the document's undo or redo). False when nothing is held, the held type\n * names no such tool, the tool is declared only, or its kind says it is DISABLED now (petition I49 — its `state`: the\n * renderer's word through the pose seam, the tool's own where no renderer answers): nothing is written, nothing runs.\n */\n useHeldTool(id: string): boolean;\n /**\n * Run a SELECTION MENU act (design-016 §5 · K-L2, K8a — widget/menu-actions.ts): the act `id` of the selected objects' types, each\n * declaring type's `run` handed its own selected objects. False when nothing selected declares it (the menu shows an act only when\n * every selected object's type does; an app's key reaches the ones that do).\n */\n runMenuAction(id: string): boolean;\n}\n\nexport interface CanvasDocs {\n create(opts?: DocSessionOpts): DocSession;\n open(bytes: Uint8Array, opts?: DocSessionOpts): OpenDocResult;\n /**\n * §6.5 bootstrap + optional presence sugar over the same channel. `signal`/\n * `onSession` are facade-owned (supersede + re-bootstrap wiring) — track the\n * live session through `docs.current()`. Rejects if another document is\n * opened while the join is in flight.\n */\n join(\n channel: ByteChannel,\n opts?: Omit<JoinDocOpts, \"presence\" | \"signal\" | \"onSession\"> & {\n readonly presence?: { name: string; color: string };\n },\n ): Promise<JoinResult>;\n current(): DocSession | undefined;\n /**\n * A layer's word on a gesture's landing: `extend` runs INSIDE every gesture's committing transaction (a move, a consume,\n * a resize, a create…), after the gesture's own writes, with the intent that made them — so what it adds is the gesture's\n * undo step, not a second one (the desk sticks a note to a calendar's day this way: the pin and the slot land with the\n * move, one ⌘Z takes the whole drop back). A cancelled gesture commits nothing and so reaches no extender. Registered on\n * the engine, not a session: it serves every document this engine opens until the returned function is called.\n */\n extendCommits(extend: CommitExtender): () => void;\n /** Add compiled widget capability requirements before creating their content. */\n upgradeCapabilities(widgetTypeIds: readonly string[]): boolean;\n /**\n * Attach facade presence to an ALREADY-live document (petition I18) — for\n * hosts that own their document lifecycle (`create()`/`open()` + their own\n * transport) and therefore never call `join({presence})`. Creates the\n * session with the public `attachPresence(world, opts)`, installs the\n * presence publish + remote-cursor systems, and exposes it through\n * `docs.presence()` — which is also the seam the behavior runtime reads, so\n * a registered ephemeral behavior leaves dormancy on the next publish step.\n * The caller wires the transport itself: `presence().wire.apply(bytes)`\n * inbound, `presence().onOutbound(send)` outbound (transport-free core —\n * the standing `PresenceSession` contract). Refuses without a live document\n * and refuses while a presence session is already live (either sugar's).\n * Returns an idempotent, IDENTITY-BOUND inverse: it detaches THIS\n * attachment — leave tombstones flush through still-subscribed outbound\n * before wiring tears down (best-effort per subscriber: one that THROWS,\n * e.g. `ws.send` on a closing socket, forfeits its own delivery and those\n * peers fall back to TTL expiry; route `PresenceOpts.onFault` to observe) —\n * and cannot touch a replacement; `docs.close()` and engine disposal run\n * the same teardown automatically.\n */\n attachPresence(opts: PresenceOpts): () => void;\n /**\n * The live presence session (the `join({presence})` sugar's or\n * `attachPresence`'s), or undefined when doc-less / presence-less. An\n * INSPECTION seam — the devtools dock's ephemeral tab reads\n * `presence().eph` (DevtoolsOpts.presence) — never a sync path; same\n * contract as `DocSession.attachment`. Swaps with the doc lifecycle exactly\n * like `current()`: set by join/attach, cleared by close.\n */\n presence(): PresenceSession | undefined;\n close(): void;\n undo(): boolean;\n redo(): boolean;\n autosave(storage: AutosaveStorageWrite, opts?: Omit<AutosaveOpts, \"storage\" | \"world\">): Autosave;\n}\n\n/**\n * Stage presentation control (StageMode resource, 2026-07-19): app chrome\n * that covers/recedes the canvas takes a refcounted, NAMED background hold —\n * the disposer pattern makes overlay lifecycles leak-proof (release on\n * unmount), the name makes \"why isn't the canvas animating?\" answerable.\n * Rendering policy only — input/interactability stays the overlay's concern.\n */\nexport interface StageControl {\n /** Take a named background hold. Returns an IDEMPOTENT release. */\n background(name: string): () => void;\n isBackgrounded(): boolean;\n /** Live hold names, in take order (debug/devtools). */\n holds(): readonly string[];\n}\n\n/** Headless current-canvas surface consumed by trays, keymaps, and adapters. */\nexport interface CurrentCanvasScope {\n current(): CanvasSessionValue;\n type(): CanvasType;\n catalog(): readonly CanvasCatalogSection[];\n tools(): readonly Tool[];\n /** Stable, locally derived compatibility/policy diagnostics for the attached document. */\n diagnostics(): readonly CanvasDiagnostic[];\n subscribe(onChange: () => void): () => void;\n}\n\nexport interface CanvasEngine {\n readonly world: World;\n readonly engine: Engine;\n /** Immutable definition authority for this engine instance. */\n readonly catalog: EngineCatalog;\n /** The one semantic authority used by all local placement paths. */\n readonly placement: PlacementAuthority;\n /** Resource-backed current CanvasType/catalog/tool projection. */\n readonly canvas: CurrentCanvasScope;\n /** Demand-driven semantic projections for visible container previews. */\n readonly previews: FramePreviewStore;\n /**\n * The behavior runtime (design-009 §6): attach/detach/has/read for\n * runtime-class behaviors, plus `list()` for devtools and the doctor.\n * DURABLE attachment is deliberately absent — it is a document op and goes\n * through `tx.attach` inside a transaction, so it syncs and undoes.\n */\n readonly behaviors: BehaviorRuntime;\n readonly stack: InteractionStack;\n readonly runtime: WidgetRuntime & { uninstall(): void };\n /** Trusted cross-package retention seam for cut-first canvas transitions. */\n readonly transitions: PresentationTransitionCoordinator;\n readonly nav: NestedCanvas;\n readonly ops: CanvasOps;\n readonly docs: CanvasDocs;\n readonly stage: StageControl;\n /**\n * The frame gate (2026-08-04) — `stage`'s stricter sibling. A background\n * hold is presentation policy over a LIVE world; a freeze stops the host\n * loop outright. Reach for `stage` when chrome RECEDES the canvas, `frame`\n * when chrome COVERS it. Passthrough of `engine.frame`, so there is one gate\n * whether you hold the facade or the raw engine.\n */\n readonly frame: FrameControl;\n /**\n * The app-owned GPU device when the app passed one (design-012 §4); undefined\n * otherwise. `dispose()` deliberately does NOT destroy it: the device outlives\n * layers by design, and its owner is the app that acquired it.\n */\n readonly compositorDevice?: EngineGpu;\n readonly budgets: {\n readonly framePreviewChildren: number;\n readonly framePreviewBytes: number;\n };\n /** step(now) passthrough — the app's rAF loop drives this. */\n step(now: number): void;\n dispose(): void;\n}\n\n/** The value a resource declaration carries (the facade's own resource mirror). */\ntype ResourceValue<R> = R extends Resource<infer S> ? S : never;\n\n/** Sink whose target swaps per doc and stamps one generation-safe intent scope. */\nfunction createForwardingSink(\n world: World,\n current: () => CanvasSessionValue,\n): CommitSink & { target: CommitSink | undefined } {\n return {\n target: undefined,\n commit(intent: CommitIntent) {\n const session = current();\n if (session.state !== \"attached\" || this.target === undefined) return false;\n const captured = world.get(intent.gesture, CanvasIntentScope);\n const targetFrame = captured?.frame ?? session.frame;\n const normalized: CommitIntent = {\n ...intent,\n scope: intent.scope ?? {\n documentEpoch: captured?.documentEpoch ?? session.documentEpoch,\n canvasEpoch: captured?.canvasEpoch ?? session.epoch,\n },\n ...(intent.creates === undefined\n ? {}\n : {\n creates: intent.creates.map((create) => ({\n ...create,\n parent: create.parent ?? targetFrame,\n })),\n }),\n };\n return this.target.commit(normalized);\n },\n };\n}\n\n// Query singletons (module scope — defineQuery identity is the cache key).\nconst selectableWidgetsQ = defineQuery([Position, Size, Selectable, Active, WidgetEquipped]);\n/** The current frame's visible widgets — `prepareTransition` finds the objects (no mount entry) here. */\nconst visibleWidgetsQ = defineQuery([PrefabId, WidgetEquipped, Active, Visible]);\n/** Live glides — the history chokepoint's sweep set (petition I15). */\nconst tweenQ = defineQuery([Position, TransformTween]);\nconst insertGhostQ = defineQuery([InsertGhost]);\n\nexport function createCanvasEngine(opts: CanvasEngineOpts = {}): CanvasEngine {\n registerBuiltinTools();\n const catalog = compileEngineCatalog({\n ...(opts.widgets === undefined ? {} : { widgets: opts.widgets }),\n ...(opts.retiredWidgets === undefined ? {} : { retiredWidgets: opts.retiredWidgets }),\n ...(opts.tools === undefined ? {} : { tools: opts.tools }),\n ...(opts.canvasTypes === undefined ? {} : { canvasTypes: opts.canvasTypes }),\n ...(opts.rootCanvas === undefined ? {} : { rootCanvas: opts.rootCanvas }),\n ...(opts.presentationFallback === undefined\n ? {}\n : { presentationFallback: opts.presentationFallback }),\n ...(opts.catalogContributions === undefined\n ? {}\n : { catalogContributions: opts.catalogContributions }),\n ...(opts.canvasRuntimeExtensions === undefined\n ? {}\n : { canvasRuntimeExtensions: opts.canvasRuntimeExtensions }),\n ...(opts.frameBehaviors === undefined ? {} : { frameBehaviors: opts.frameBehaviors }),\n ...(opts.frameProjections === undefined ? {} : { frameProjections: opts.frameProjections }),\n });\n\n const world = createWorld();\n const unbindCatalog = bindEngineCatalog(world, catalog);\n let session: DocSession | undefined;\n const canvasSession = createCanvasSessionController(world);\n const packEnabled = (id: string, version: number): boolean =>\n session?.versionReport().docPacks[id] === version;\n const engine = createEngine(world, {\n ...(opts.onGuestFault === undefined ? {} : { onGuestFault: opts.onGuestFault }),\n ...(opts.onReflectorFault === undefined ? {} : { onReflectorFault: opts.onReflectorFault }),\n ...(opts.onGuestNotice === undefined ? {} : { onGuestNotice: opts.onGuestNotice }),\n });\n const runtimeExtensionHost: CanvasRuntimeExtensionHost = installCanvasRuntimeExtensions({\n world,\n engine,\n catalog,\n session: () => canvasSession.current(),\n });\n const frameBehaviorHost: FrameBehaviorHost = installFrameBehaviors({\n world,\n engine,\n catalog,\n session: () => session,\n onAvailabilityChange: () => {\n if (canvasSession.current().state === \"attached\") canvasSession.bumpCapabilities();\n },\n });\n const placement = createPlacementAuthority({\n world,\n catalog,\n rootCanvasTypeId: () => {\n const report = session?.versionReport();\n return report?.rootIssue === undefined ? report?.rootCanvas?.id : undefined;\n },\n packEnabled,\n canvasWritable: (canvasTypeId) => frameBehaviorHost.isCanvasWritable(canvasTypeId),\n });\n const sink = createForwardingSink(world, () => canvasSession.current());\n /** An object that OPENS (design-015 §8): a live, Active widget of the frame whose type declares `openable`. */\n const isOpenable = (entity: Entity): boolean => {\n if (!world.isAlive(entity) || !world.hasTag(entity, Active)) return false;\n const typeId = world.get(entity, PrefabId)?.id;\n return typeof typeId === \"string\" && catalog.widget(typeId)?.openable === true;\n };\n /** The object in hand, or undefined. */\n const heldNow = (): Entity | undefined => heldEntity(world);\n /** THE PUT-DOWN (design-015 §8): the fact and the user's view (and tool, D3t-a) leave together; the renderer's flux flies the object home. */\n const putDown = (): void => {\n const held = heldNow();\n if (held === undefined) return;\n if (world.isAlive(held)) {\n if (world.has(held, HeldView)) world.removeComponent(held, HeldView);\n if (world.has(held, HeldTool)) world.removeComponent(held, HeldTool);\n world.removeTag(held, Held);\n }\n };\n /** The held bar's tools of an entity's type (D3t-a) — empty for anything that does not open. */\n const heldToolsOf = (entity: Entity): WidgetType[\"heldTools\"] => {\n const typeId = world.get(entity, PrefabId)?.id;\n return typeof typeId === \"string\" ? (catalog.widget(typeId)?.heldTools ?? []) : [];\n };\n /** A widget's props as the world holds them now: its groups' cells, flat (D3t-a — what a held tool reads). */\n const propsOf = (entity: Entity): Record<string, unknown> => {\n const typeId = world.get(entity, PrefabId)?.id;\n const type = typeof typeId === \"string\" ? catalog.widget(typeId) : undefined;\n const props: Record<string, unknown> = {};\n for (const g of type?.groups ?? []) Object.assign(props, (world.get(entity, g.component) as Record<string, unknown> | undefined) ?? {});\n return props;\n };\n /** The mode in hand at a pick-up (D3t-a): the type's `heldTool` of the object's props, else its first mode, else none. */\n const firstHeldTool = (entity: Entity): string => {\n const typeId = world.get(entity, PrefabId)?.id;\n const type = typeof typeId === \"string\" ? catalog.widget(typeId) : undefined;\n if (type === undefined) return \"\";\n if (type.heldTool !== undefined) return type.heldTool(propsOf(entity));\n return type.heldTools.find((t) => t.kind === \"mode\")?.id ?? \"\";\n };\n const stack = installInteractionStack(engine, {\n sink,\n placement: {\n canIngress: (widgetTypeId, targetContainer) =>\n placement.canIngress(widgetTypeId, targetContainer).ok,\n canPlace: (widgetTypeId, targetFrame) => placement.canPlace(widgetTypeId, targetFrame).ok,\n },\n // the gesture's and the zoom-through's \"may this be entered\" — the nav's own test (design-015 §9)\n isContainer: (entity) => {\n if (!world.isAlive(entity) || !world.hasTag(entity, Container)) return false;\n const typeId = world.get(entity, PrefabId)?.id;\n return typeof typeId === \"string\" && catalog.widget(typeId)?.container !== undefined;\n },\n // the double-tap's \"may this be picked up\" (design-015 §8): its type declares an opening\n isOpenable: (entity) => isOpenable(entity),\n });\n const budgets = {\n framePreviewChildren:\n opts.budgets?.framePreviewChildren ?? FRAME_PREVIEW_DEFAULT_CHILDREN,\n framePreviewBytes: opts.budgets?.framePreviewBytes ?? FRAME_PREVIEW_DEFAULT_BYTES,\n };\n const runtime = installWidgetRuntime(engine);\n const transitions = createPresentationTransitionCoordinator(world, engine, {\n ...(opts.onGuestFault === undefined\n ? {}\n : {\n onFault: (id: string, error: unknown) =>\n opts.onGuestFault?.(`presentation-transition:${id}`, error),\n }),\n });\n const navIdentity = (\n frame: Entity | undefined,\n role: \"from\" | \"to\",\n ): { frame: Entity; typeId: string } => {\n const current = canvasSession.current();\n // An integrity pop may observe an already-cleared NavFrame edge. The\n // session still owns the exact departed entity/type until onSwitch runs.\n if (role === \"from\" && current.state === \"attached\") {\n if (frame === undefined || frame === current.frame) {\n return { frame: current.frame, typeId: current.typeId };\n }\n }\n if (frame === undefined) {\n return {\n frame: world.getResource(BoardRoot)?.root ?? (0 as Entity),\n typeId: session?.versionReport().rootCanvas?.id ?? \"\",\n };\n }\n const widgetTypeId = world.get(frame, PrefabId)?.id;\n return {\n frame,\n typeId:\n typeof widgetTypeId === \"string\"\n ? catalog.canvasForContainer(widgetTypeId)?.id ?? \"\"\n : \"\",\n };\n };\n const nav = createNestedCanvas(world, {\n index: stack.index,\n clearSpatialCaches: () => stack.clearCaches(),\n navGeometry: stack.navGeometry,\n isContainer: (entity) => {\n if (!world.isAlive(entity) || !world.hasTag(entity, Container)) return false;\n const typeId = world.get(entity, PrefabId)?.id;\n return typeof typeId === \"string\" && catalog.widget(typeId)?.container !== undefined;\n },\n beforeSwitch: () => {\n runtimeExtensionHost.invalidate();\n cancelActiveGestures(world);\n putDown(); // the hand lets go at a nav cut (design-015 §8, §9): the chrome belongs to the desk you are on\n stack.queue.drain();\n const ghosts: Entity[] = [];\n world.query(insertGhostQ).each((batch) => {\n for (const row of batch) ghosts.push(batch.entity(row));\n });\n for (const ghost of ghosts) world.destroy(ghost);\n clearSelection(world);\n },\n prepareTransition: (request) => {\n // A canvas type that DECLARES a ground (design-013 C2: a field declaration, not a program\n // id) requires the `ground` plane to prepare — the desk's layer registers the plane's\n // adapter, and without an owner every enter into a folder is a snap. So does a visible\n // OBJECT in the departing frame (design-015 §5.2): found in the world — pre-cut, `Active`\n // is still that frame's membership — each asks for `ground`, the one plane there is (D5b;\n // the `dom` and `gl` planes the mount store's snapshot used to ask for went with it).\n const fromGround = catalog.canvasType(request.fromTypeId)?.presentation?.ground;\n const toGround = catalog.canvasType(request.toTypeId)?.presentation?.ground;\n const required = new Set<PresentationPlane>();\n if (fromGround !== undefined || toGround !== undefined) required.add(\"ground\");\n const widgetOf = (entity: Entity): WidgetType | undefined => {\n const widgetTypeId = world.get(entity, PrefabId)?.id;\n return typeof widgetTypeId === \"string\" ? catalog.widget(widgetTypeId) : undefined;\n };\n if (!required.has(\"ground\")) {\n world.query(visibleWidgetsQ).each((batch) => {\n for (const row of batch) {\n if (widgetOf(batch.entity(row))?.object !== undefined) required.add(\"ground\");\n }\n });\n }\n return transitions.prepare(\n Object.freeze({\n ...request,\n requiresFullT2: request.fromTypeId !== request.toTypeId,\n requiredPlanes: Object.freeze([...required]),\n }),\n );\n },\n abortTransition: (reason) => transitions.abort(reason),\n transitionIdentity: (fromFrame, toFrame) => {\n const from = navIdentity(fromFrame, \"from\");\n const to = navIdentity(toFrame, \"to\");\n return {\n documentEpoch: canvasSession.current().documentEpoch,\n fromFrame: from.frame,\n toFrame: to.frame,\n fromTypeId: from.typeId,\n toTypeId: to.typeId,\n };\n },\n onSwitch: (frame, depth, restoreTool) => {\n cancelActiveGestures(world);\n const targetFrame = frame ?? world.getResource(BoardRoot)?.root;\n if (targetFrame === undefined || !world.isAlive(targetFrame)) {\n transitions.abort(\"detached\");\n canvasSession.detach();\n return;\n }\n const typeId =\n frame === undefined\n ? session?.versionReport().rootCanvas?.id ?? \"\"\n : (() => {\n const widgetTypeId = world.get(frame, PrefabId)?.id;\n return typeof widgetTypeId === \"string\"\n ? catalog.canvasForContainer(widgetTypeId)?.id ?? \"\"\n : \"\";\n })();\n canvasSession.switchFrame(targetFrame, typeId, depth);\n const legal = canvas.tools();\n const currentTool = world.getResource(ActiveTool)?.id ?? \"select\";\n const preferred = restoreTool ?? currentTool;\n const nextTool =\n legal.find((tool) => tool.id === preferred) ??\n legal.find((tool) => tool.id === catalog.defaultToolFor(typeId).id) ??\n legal.find((tool) => tool.id === \"select\") ??\n catalog.tool(\"select\");\n if (nextTool !== undefined && nextTool.id !== currentTool) {\n writeRuntimeResource(world, ActiveTool, { id: nextTool.id });\n }\n },\n });\n engine.addSystems(\"react\", nav.navIntegrity);\n\n /**\n * The nav op a system asked for INSIDE the tick (design-015 §9, D2b — the double-tap gesture,\n * the zoom-through; `NavIntent`), applied once the tick is over: the ops are structural and\n * run outside it. A `\"cut\"` states its own re-dressing fact (`NavRedress`) in the op.\n */\n let appliedIntent = 0;\n const applyNavIntent = (): void => {\n const intent = world.getResource(NavIntent);\n if (intent === undefined || intent.epoch === appliedIntent) return;\n appliedIntent = intent.epoch;\n const opts: NavOpts = { transition: intent.transition };\n if (intent.kind === \"enter\") {\n if (!world.isAlive(intent.target) || !world.hasTag(intent.target, Container)) return;\n const typeId = world.get(intent.target, PrefabId)?.id;\n if (typeof typeId !== \"string\" || catalog.widget(typeId)?.container === undefined) return;\n nav.enterContainer(intent.target, opts);\n } else if (currentNavFrame(world) !== undefined) {\n nav.exitContainer(opts);\n }\n };\n // on the ENGINE's own after-step hook, not a wrapper round `step`: a host loop (dom/loop.ts) may drive the raw engine\n const removeNavIntent = engine.afterStep(applyNavIntent);\n\n /**\n * The hand's request a system made INSIDE the tick (design-015 §8, D4b — the double-tap on an openable\n * object, the gesture ways back; `HeldIntent`), applied once the tick is over exactly as the nav's is:\n * `open` when the target still qualifies and nothing else is held, `putDown` whatever is held.\n */\n let appliedHeld = 0;\n const applyHeldIntent = (): void => {\n const intent = world.getResource(HeldIntent);\n if (intent === undefined || intent.epoch === appliedHeld) return;\n appliedHeld = intent.epoch;\n if (intent.kind === \"open\") {\n if (heldNow() !== undefined || !isOpenable(intent.target)) return;\n ops.open(intent.target);\n } else putDown();\n };\n const removeHeldIntent = engine.afterStep(applyHeldIntent);\n\n /**\n * The tray's HAND-OFF (design-017 §9; K5b — `TrayIntent`): a copy taken off the pegboard left the drawer inside the tick; once it is\n * over, `ops.insertByDrag` spawns the insert ghost under the same grab point (its `anchor` — no centre-snap), its synthetic down the\n * pointer's, flying home to the specimen's spot on a cancel — made with what the entry says one taken carries (`trayTakeProps`).\n * Refused (a read-only document, a frame that takes no such kind): nothing is spawned, and the renderer, seeing no ghost come, puts\n * the copy back.\n */\n let appliedTray = 0;\n const applyTrayIntent = (): void => {\n const intent = world.getResource(TrayIntent);\n if (intent === undefined || intent.epoch === appliedTray) return;\n appliedTray = intent.epoch;\n const type = intent.type ?? \"\";\n const entry = catalog.widget(type)?.tray;\n if (entry === undefined) return;\n const props = trayTakeProps(entry);\n try {\n ops.insertByDrag(type, {\n screenX: intent.x, screenY: intent.y, pointerId: intent.pointerId ?? \"mouse\", device: intent.device, buttons: intent.buttons,\n anchor: { u: intent.u, v: intent.v }, home: { x: intent.homeX, y: intent.homeY }, ...(props !== undefined ? { props } : {}),\n });\n } catch (err) {\n console.warn(`ice: the tray could not hand \"${type}\" to the desk —`, err instanceof Error ? err.message : err);\n }\n };\n const removeTrayIntent = engine.afterStep(applyTrayIntent);\n\n // Settings resources (design-005 §4): construction seeds; live-tunable after.\n //\n // THE FACADE OWNS THESE, NOT THE DOCUMENT (D-C4.5, Phase C review). A\n // document close runs `DocSession.close()` → strata `world.reset()`, whose\n // contract clears RESOURCES as well as entities — so every seed below has\n // to be written again on the far side of a close, or a mounted engine comes\n // out of a `docs.create()`/`open()` with no `Viewport` and no `Camera` and\n // neither ground host can build until the next ResizeObserver fire. The\n // values that come back are the LIVE ones, not the construction seeds: the\n // host's box and the user's view are not the document's, and the settings\n // are seeds that a host may have tuned since. `facadeResources` is that\n // mirror — it trails the world and only ever advances on a DEFINED read, so\n // a capture taken after a reset (`docs.join`'s re-bootstrap, where the reset\n // happens inside `joinDoc`) keeps the last good values instead of erasing\n // them.\n const st = opts.settings ?? {};\n const facadeResources: {\n camera: ResourceValue<typeof Camera>;\n viewport: ResourceValue<typeof Viewport>;\n activeTool: ResourceValue<typeof ActiveTool>;\n cameraLimits: ResourceValue<typeof CameraLimits>;\n gestures: ResourceValue<typeof GestureSettings>;\n pointers: ResourceValue<typeof PointerSettings>;\n snap: ResourceValue<typeof SnapConfig>;\n chrome: ResourceValue<typeof ChromeSettings>;\n zoomThrough: ResourceValue<typeof ZoomThroughSettings>;\n stage: ResourceValue<typeof StageMode> | undefined;\n } = {\n camera: { x: 0, y: 0, zoom: 1, gesturing: false },\n viewport: { w: 0, h: 0, dpr: 1 },\n // the ROOT canvas type's default tool is the one in hand at birth (design-015 D7, D-D7-C.2 — `select` when it names none): a\n // preset's root, like the desk's, is what `createCanvasEngine` makes, with no `setTool` after\n activeTool: { id: catalog.defaultToolFor(catalog.rootCanvas.id).id },\n cameraLimits: {\n minZoom: st.zoom?.min ?? CAMERA_DEFAULTS.minZoom,\n maxZoom: st.zoom?.max ?? CAMERA_DEFAULTS.maxZoom,\n },\n gestures: {\n ...GESTURE_DEFAULTS,\n ...st.gestures,\n // Preserve existing scroll-to-zoom consumers at construction. Once\n // seeded, changing the wheel mode cannot change the pinch response.\n wheelZoomCurve: st.gestures?.wheelZoomCurve ?? (st.gestures?.wheel === \"zoom\" ? \"exponential\" : GESTURE_DEFAULTS.wheelZoomCurve),\n },\n pointers: { ...POINTER_DEFAULTS, ...st.pointers },\n snap: {\n enabled: st.snap?.enabled ?? SNAP_DEFAULTS.enabled,\n thresholdPx: st.snap?.thresholdPx ?? SNAP_DEFAULTS.thresholdPx,\n },\n chrome: {\n liftScale: st.chrome?.liftScale ?? CHROME_DEFAULTS.liftScale,\n },\n zoomThrough: {\n enabled: st.nav?.zoomThrough?.enabled ?? ZOOM_THROUGH_DEFAULTS.enabled,\n in: st.nav?.zoomThrough?.in ?? ZOOM_THROUGH_DEFAULTS.in,\n out: st.nav?.zoomThrough?.out ?? ZOOM_THROUGH_DEFAULTS.out,\n gate0: st.nav?.zoomThrough?.gate?.[0] ?? ZOOM_THROUGH_DEFAULTS.gate[0],\n gate1: st.nav?.zoomThrough?.gate?.[1] ?? ZOOM_THROUGH_DEFAULTS.gate[1],\n },\n // StageMode's truth is the out-of-ECS `stageHolds` map below, so the\n // mirror starts ABSENT: at construction nothing holds and the resource is\n // legitimately unset (every reader defaults to 0). It is captured and\n // restored like the rest once a hold exists — a doc switch under a live\n // overlay must not silently un-freeze the background.\n stage: undefined,\n };\n /** Read the world into the mirror. MUST run before a `world.reset()`. */\n const captureFacadeResources = (): void => {\n facadeResources.camera = world.getResource(Camera) ?? facadeResources.camera;\n facadeResources.viewport = world.getResource(Viewport) ?? facadeResources.viewport;\n facadeResources.activeTool = world.getResource(ActiveTool) ?? facadeResources.activeTool;\n facadeResources.cameraLimits = world.getResource(CameraLimits) ?? facadeResources.cameraLimits;\n facadeResources.gestures = world.getResource(GestureSettings) ?? facadeResources.gestures;\n facadeResources.pointers = world.getResource(PointerSettings) ?? facadeResources.pointers;\n facadeResources.snap = world.getResource(SnapConfig) ?? facadeResources.snap;\n facadeResources.chrome = world.getResource(ChromeSettings) ?? facadeResources.chrome;\n facadeResources.zoomThrough = world.getResource(ZoomThroughSettings) ?? facadeResources.zoomThrough;\n facadeResources.stage = world.getResource(StageMode) ?? facadeResources.stage;\n };\n /** Write the mirror into the world: construction, and after every reset. */\n const seedFacadeResources = (): void => {\n world.setResource(Camera, facadeResources.camera);\n world.setResource(Viewport, facadeResources.viewport);\n world.setResource(ActiveTool, facadeResources.activeTool);\n world.setResource(CameraLimits, facadeResources.cameraLimits);\n world.setResource(GestureSettings, facadeResources.gestures);\n world.setResource(PointerSettings, facadeResources.pointers);\n world.setResource(SnapConfig, facadeResources.snap);\n world.setResource(ChromeSettings, facadeResources.chrome);\n world.setResource(ZoomThroughSettings, facadeResources.zoomThrough);\n if (facadeResources.stage !== undefined) world.setResource(StageMode, facadeResources.stage);\n };\n seedFacadeResources();\n\n const resolvedCanvasType = (): CanvasType => {\n const current = canvasSession.current();\n if (current.state === \"attached\") {\n const resolved = catalog.canvasType(current.typeId);\n if (\n resolved !== undefined &&\n packEnabled(canvasPackId(resolved.id), resolved.semanticVersion)\n ) {\n return resolved;\n }\n }\n return catalog.presentationFallback;\n };\n\n let diagnosticSnapshot: CanvasDiagnosticSnapshot = Object.freeze({\n diagnostics: Object.freeze([]),\n });\n let diagnosticsDirty = false;\n const refreshCanvasDiagnostics = (): boolean => {\n const previous = JSON.stringify(diagnosticSnapshot.diagnostics.map((d) => [d.key, d.code, d.message]));\n diagnosticSnapshot =\n session === undefined\n ? Object.freeze({ diagnostics: Object.freeze([]) })\n : collectCanvasDiagnostics({\n world,\n store: session.store,\n catalog,\n report: session.versionReport(),\n });\n diagnosticsDirty = false;\n const next = JSON.stringify(diagnosticSnapshot.diagnostics.map((d) => [d.key, d.code, d.message]));\n return previous !== next;\n };\n\n let effectiveSurfaceKey = \"\";\n let effectiveCatalog: readonly CanvasCatalogSection[] = Object.freeze([]);\n let effectiveTools: readonly Tool[] = Object.freeze([]);\n const rebuildEffectiveSurface = (): void => {\n const current = canvasSession.current();\n const key = `${current.documentEpoch}:${current.epoch}:${current.typeId}`;\n if (key === effectiveSurfaceKey) return;\n effectiveSurfaceKey = key;\n if (current.state !== \"attached\") {\n effectiveCatalog = Object.freeze([]);\n effectiveTools = Object.freeze(\n catalog\n .toolsFor(catalog.presentationFallback.id)\n .filter((tool) => tool.draw === undefined),\n );\n return;\n }\n const resolved = catalog.canvasType(current.typeId);\n if (resolved === undefined || resolved !== resolvedCanvasType()) {\n effectiveCatalog = Object.freeze([]);\n effectiveTools = Object.freeze(\n catalog\n .toolsFor(catalog.presentationFallback.id)\n .filter((tool) => tool.draw === undefined),\n );\n return;\n }\n effectiveCatalog = Object.freeze(\n catalog.catalogFor(resolved.id).map((section) =>\n Object.freeze({\n ...section,\n items: Object.freeze(\n section.items.filter((widget) =>\n packEnabled(widget.prefab.id, widget.prefab.version ?? 1),\n ),\n ),\n }),\n ),\n );\n effectiveTools = Object.freeze(\n catalog.toolsFor(resolved.id).filter((tool) => {\n const widget = tool.draw === undefined ? undefined : catalog.widget(tool.draw.widgetType);\n return widget === undefined || packEnabled(widget.prefab.id, widget.prefab.version ?? 1);\n }),\n );\n };\n\n const canvas: CurrentCanvasScope = {\n current: () => canvasSession.current(),\n type: resolvedCanvasType,\n catalog() {\n rebuildEffectiveSurface();\n return effectiveCatalog;\n },\n tools() {\n rebuildEffectiveSurface();\n return effectiveTools;\n },\n diagnostics() {\n return diagnosticSnapshot.diagnostics;\n },\n subscribe: (onChange) => world.reactive.observeResource(CanvasSession, onChange),\n };\n\n const removeDiagnosticPublish = engine.onPublish(() => {\n if (!diagnosticsDirty) return;\n const changed = refreshCanvasDiagnostics();\n if (changed && canvasSession.current().state === \"attached\") {\n canvasSession.bumpCapabilities();\n }\n });\n\n const previews = createFramePreviewStore({\n world,\n catalog,\n session: () => ({\n documentEpoch: canvasSession.current().documentEpoch,\n ...(session === undefined ? {} : { store: session.store }),\n }),\n diagnostics: () => diagnosticSnapshot.diagnostics,\n budgets: {\n children: budgets.framePreviewChildren,\n bytes: budgets.framePreviewBytes,\n },\n ...(opts.onGuestFault === undefined\n ? {}\n : {\n onFault: (id: string, error: unknown) =>\n opts.onGuestFault?.(`frame-projection:${id}`, error),\n }),\n });\n\n // --- doc lifecycle ---------------------------------------------------------\n let presence: PresenceSession | undefined;\n let sessionVersionUnsub: (() => void) | undefined;\n let uninstallPresence: (() => void) | undefined;\n let joined: JoinResult | undefined; // the room handle — closeDoc must LEAVE, not just close\n let joinAbort: AbortController | undefined; // kills an in-flight join on supersede\n const liveAutosaves = new Set<Autosave>(); // facade-created; stopped at closeDoc\n\n const requireSession = (op: string): DocSession => {\n if (session === undefined) {\n throw new Error(`ice: ops.${op} needs a document — call engine.docs.create()/open()/join() first.`);\n }\n return session;\n };\n\n // Read-only is enforced at every SANCTIONED write surface, not only the\n // gesture sink (2026-07-13 review: the sink swap alone let facade ops and\n // undo/redo edit — and broadcast — a version-gated document).\n const requireWritable = (op: string): DocSession => {\n const s = requireSession(op);\n if (\n s.readOnly ||\n gateVerdict(s.versionReport()) !== \"ok\" ||\n diagnosticsDirty ||\n diagnosticSnapshot.authorityIssue !== undefined\n ) {\n throw new Error(`ice: ops.${op} — the document is read-only (version gate); writes are disabled.`);\n }\n return s;\n };\n\n const requireCurrentFrame = (op: string): Entity => {\n const current = canvasSession.current();\n if (\n current.state !== \"attached\" ||\n !world.isAlive(current.frame) ||\n current.typeId.length === 0\n ) {\n throw new Error(`ice: ops.${op} needs an attached, semantically resolved CanvasSession.`);\n }\n return current.frame;\n };\n\n const assertEditablePlacement = (entity: Entity, op: string): Entity => {\n if (!world.isAlive(entity) || !world.hasTag(entity, Active)) {\n throw new Error(`ice: ops.${op} only accepts entities in the current active CanvasFrame.`);\n }\n const parent = world.getRelation(entity, ChildOf);\n if (parent === undefined) {\n throw new Error(`ice: ops.${op} — entity has no direct CanvasFrame parent.`);\n }\n placement.assertReparent(entity, parent, `ops.${op}`);\n return parent;\n };\n const inCurrentSelectionScope = (entity: Entity): boolean =>\n world.isAlive(entity) &&\n (world.hasTag(entity, Active) || world.hasTag(entity, Wire));\n\n const versionScope = Object.freeze({\n localPacks: catalog.localPacks(),\n initialPacks: catalog.initialPacks(),\n packDependencies: catalog.packDependencies(),\n });\n\n const rejectCommit = (message: string): undefined => {\n opts.onGuestNotice?.(`Canvas placement rejected: ${message}`);\n return undefined;\n };\n\n const commitGuard = (intent: CommitIntent): CommitIntent | undefined => {\n const current = canvasSession.current();\n if (current.state !== \"attached\") return rejectCommit(\"no CanvasSession is attached\");\n if (\n intent.scope === undefined ||\n intent.scope.documentEpoch !== current.documentEpoch ||\n intent.scope.canvasEpoch !== current.epoch\n ) {\n return rejectCommit(\"the intent belongs to a stale CanvasSession epoch\");\n }\n if (\n session === undefined ||\n session.readOnly ||\n gateVerdict(session.versionReport()) !== \"ok\" ||\n diagnosticsDirty ||\n diagnosticSnapshot.authorityIssue !== undefined\n ) {\n return rejectCommit(\"the document capability gate is not writable\");\n }\n const root = world.getResource(BoardRoot)?.root;\n const interactiveTarget = (target: Entity): boolean =>\n target === current.frame ||\n (world.hasTag(target, Active) && world.getRelation(target, ChildOf) === current.frame);\n for (const create of intent.creates ?? []) {\n if (create.parent === undefined) return rejectCommit(\"create has no explicit target frame\");\n if (!interactiveTarget(create.parent)) {\n return rejectCommit(\"create target is outside the gesture's active CanvasFrame\");\n }\n const decision =\n create.parent === root\n ? placement.canPlace(create.type, create.parent)\n : placement.canIngress(create.type, create.parent);\n if (!decision.ok) return rejectCommit(decision.message);\n }\n for (const reparent of intent.reparents ?? []) {\n if (!interactiveTarget(reparent.container)) {\n return rejectCommit(\"reparent target is outside the gesture's active CanvasFrame\");\n }\n const decision = placement.validateReparent(reparent.entity, reparent.container);\n if (!decision.ok) return rejectCommit(decision.message);\n }\n for (const order of intent.orders ?? []) {\n if (order.parent !== current.frame) {\n return rejectCommit(\"sibling order target is not the gesture's active CanvasFrame\");\n }\n const decision = placement.validateReparent(order.entity, order.parent);\n if (!decision.ok) return rejectCommit(decision.message);\n }\n const checked = new Set<Entity>();\n for (const write of intent.writes) {\n if (checked.has(write.entity) || world.get(write.entity, PrefabId) === undefined) continue;\n checked.add(write.entity);\n if (!world.hasTag(write.entity, Active)) {\n return rejectCommit(\"edited widget is no longer active in the gesture's CanvasFrame\");\n }\n const parent = world.getRelation(write.entity, ChildOf);\n if (parent === undefined) return rejectCommit(\"edited widget has no direct frame parent\");\n const decision = placement.validateReparent(write.entity, parent);\n if (!decision.ok) return rejectCommit(decision.message);\n }\n return intent;\n };\n\n // The layers' word on a gesture's landing (`docs.extendCommits`): every session this facade opens fans its gesture\n // transactions through the extenders registered here — a registration outlives the session it was made under.\n const commitExtenders = new Set<CommitExtender>();\n const commitExtend: CommitExtender = (intent, tx) => {\n for (const extend of [...commitExtenders]) extend(intent, tx);\n };\n\n const scopedDocOpts = (o: DocSessionOpts | undefined): DocSessionOpts => ({\n ...o,\n versionScope,\n rootCanvas: canvasIdentityOf(catalog.rootCanvas),\n commitGuard,\n commitExtend,\n canvasCatalog: catalog,\n });\n\n const adoptSession = (next: DocSession): DocSession => {\n const alreadyAdopted = session === next;\n session = next;\n sink.target = next.sink;\n if (alreadyAdopted) return next;\n sessionVersionUnsub?.();\n let versionSignature = JSON.stringify(next.versionReport());\n const versionUnsub = next.subscribeRemote(() => {\n // a peer's change lands at the next `world.sync()`: that frame must come (K7a — the loop may be asleep)\n engine.frame.wake(\"doc\");\n diagnosticsDirty = true;\n const report = next.versionReport();\n const signature = JSON.stringify(report);\n if (signature === versionSignature || session !== next) return;\n versionSignature = signature;\n const current = canvasSession.current();\n if (current.state !== \"attached\") return;\n if (current.depth === 0) {\n canvasSession.switchFrame(current.frame, report.rootCanvas?.id ?? \"\", 0);\n } else {\n canvasSession.bumpCapabilities();\n }\n const legal = canvas.tools();\n const activeId = world.getResource(ActiveTool)?.id ?? \"select\";\n if (!legal.some((tool) => tool.id === activeId)) {\n const fallback = legal.find((tool) => tool.id === \"select\") ?? legal[0];\n if (fallback !== undefined) writeRuntimeResource(world, ActiveTool, { id: fallback.id });\n }\n });\n // …and a LOCAL commit made outside a step (a transaction, an undo, a redo — strata's values land at once, the structure at\n // the next sync): the outbound wire hears every one\n const outboundUnsub = next.store.subscribeOutbound(() => engine.frame.wake(\"doc\"));\n sessionVersionUnsub = () => {\n versionUnsub();\n outboundUnsub();\n };\n const root = world.getResource(BoardRoot)?.root;\n if (root === undefined || !world.isAlive(root)) {\n canvasSession.detach();\n } else {\n canvasSession.attach(root, next.rootCanvas?.id ?? \"\");\n }\n refreshCanvasDiagnostics();\n previews.rebind();\n return next;\n };\n\n // ONE presence acquisition + ONE teardown, shared by the two doors (the\n // `join({presence})` sugar and `docs.attachPresence`, petition I18) — the\n // assignment is what the behavior runtime's forwarding reads per publish, so\n // both doors activate ephemeral behaviors identically. Teardown order is\n // load-bearing: systems out FIRST (no publish hook stages a facet into a\n // session mid-leave; the uninstall also reaps the derived remote cursors —\n // ghosts, on a still-open doc), THEN detach (leave tombstones flush through\n // still-subscribed outbound before the session's wiring dies).\n const acquirePresence = (o: PresenceOpts): PresenceSession => {\n // a peer's cursor arriving or aging out is the next frame's (K7a — a sleeping loop wakes for it)\n const p = attachPresence(world, { ...o, onRemote: () => { o.onRemote?.(); engine.frame.wake(\"presence\"); } });\n presence = p;\n uninstallPresence = installPresence(engine, p, {\n keyOf: (e) => session?.store.keyOf(e),\n });\n return p;\n };\n\n // NEVER throws (review findings 1+4, 0.8.0): teardown must not stop\n // teardown. The fields clear FIRST so the seam pair can't desynchronize\n // under a throw and reentrant close/inverse calls see a settled state; each\n // half is then contained on its own — a host transport throwing inside the\n // leave flush must not abort the room leave, the session close, or the rest\n // of engine disposal behind it.\n const releasePresence = (): void => {\n const uninstall = uninstallPresence;\n const p = presence;\n uninstallPresence = undefined;\n presence = undefined;\n try {\n uninstall?.();\n } catch (err) {\n console.error(\"[ice] presence uninstall threw — teardown continues\", err);\n }\n try {\n p?.detach();\n } catch (err) {\n console.error(\"[ice] presence detach threw — teardown continues\", err);\n }\n };\n\n const closeDoc = (): void => {\n // BEFORE the close below resets the world: the facade's own resources are\n // not the document's (D-C4.5), so read the live values out first.\n captureFacadeResources();\n // A pending join dies here — left to resolve, it would attach a stale\n // session over whatever the caller opens next.\n joinAbort?.abort(new Error(\"ice: docs.join superseded — another document was opened while joining.\"));\n joinAbort = undefined;\n for (const a of [...liveAutosaves]) a.stop(); // before close: no export of a detached session\n liveAutosaves.clear();\n transitions.abort(\"detached\");\n releasePresence();\n sessionVersionUnsub?.();\n sessionVersionUnsub = undefined;\n if (session !== undefined || joined !== undefined) {\n runtimeExtensionHost.invalidate();\n canvasSession.detach();\n }\n joined?.leave(); // leaves the ROOM: channel + outbound unsubs, then closes the session\n joined = undefined;\n session?.close(); // idempotent — a no-op when leave() above already closed it\n session = undefined;\n diagnosticsDirty = false;\n diagnosticSnapshot = Object.freeze({ diagnostics: Object.freeze([]) });\n sink.target = undefined;\n // DocSession.close/reset clears resources; the engine-owned monotone\n // counters live outside ECS and must be republished immediately, and the\n // facade's own seeds re-written with the values captured above (D-C4.5) —\n // a mounted engine keeps its viewport, its camera, its tool, its tuned\n // settings and its stage holds straight through the switch.\n canvasSession.republish();\n previews.rebind();\n seedFacadeResources();\n };\n\n /**\n * Undo/redo + THE HISTORY CHOKEPOINT (petition I15). Undo does not pass\n * through `guardedTransaction` — it is strata's own local batch — so a glide\n * in flight when ⌘Z lands would otherwise complete at the PRE-undo target and\n * strand the cell: runtime ≠ baseline with nothing banked, divergence that\n * never reconciles and poisons the cell against later remote updates. After\n * the history step, every live tween is retargeted onto its doc truth, so the\n * glide finishes on the undone value and the cell reconverges by landing.\n */\n const historyStep = (which: \"undo\" | \"redo\"): boolean => {\n const s = session;\n if (s === undefined) return false;\n const ok = which === \"undo\" ? s.store.undo() : s.store.redo();\n if (!ok) return false;\n const tweening: Entity[] = [];\n world.query(tweenQ).each((b) => {\n for (const r of b) tweening.push(b.entity(r));\n });\n if (tweening.length > 0) {\n retargetTweensToDoc(world, tweening, (e) => {\n const v = s.store.getComponent(e, Position);\n return v === undefined ? undefined : { x: v.x, y: v.y };\n });\n }\n return true;\n };\n\n const gatePolicy: DocSessionOpts[\"onGate\"] =\n opts.policy?.versionGate === undefined\n ? undefined\n : (_report, verdict) => (verdict === \"migrate\" ? (opts.policy?.versionGate ?? verdict) : verdict);\n\n const docs: CanvasDocs = {\n extendCommits(extend) {\n commitExtenders.add(extend);\n return () => {\n commitExtenders.delete(extend);\n };\n },\n create(o) {\n closeDoc();\n return adoptSession(createDocSession(world, scopedDocOpts(o)));\n },\n open(bytes, o) {\n closeDoc();\n const result = openDocSession(world, bytes, {\n ...(gatePolicy !== undefined ? { onGate: gatePolicy } : {}),\n ...o,\n ...scopedDocOpts(undefined),\n });\n if (result.ok) adoptSession(result.session);\n else canvasSession.republish();\n return result;\n },\n async join(channel, o = {}) {\n closeDoc();\n const ac = new AbortController();\n joinAbort = ac;\n const { presence: presenceOpts, docOpts: requestedDocOpts, ...joinOpts } = o;\n if (presenceOpts !== undefined) {\n acquirePresence({ name: presenceOpts.name, color: presenceOpts.color });\n }\n let result: JoinResult;\n try {\n result = await joinDoc(world, channel, {\n docOpts: scopedDocOpts({\n ...(gatePolicy !== undefined ? { onGate: gatePolicy } : {}),\n ...requestedDocOpts,\n }),\n ...(presence !== undefined ? { presence } : {}),\n ...joinOpts,\n signal: ac.signal,\n // Re-bootstrap swaps the session inside joinDoc (PendingImportError\n // recovery) — re-target the forwarding sink or ops keep committing\n // into the quarantined session.\n onSession: (s) => {\n if (joinAbort !== ac) return; // superseded — a newer doc owns the sink\n if (s !== undefined) {\n adoptSession(s);\n } else {\n transitions.abort(\"detached\");\n canvasSession.detach();\n sessionVersionUnsub?.();\n sessionVersionUnsub = undefined;\n session = undefined; // joinDoc already closed it\n sink.target = undefined;\n canvasSession.republish();\n // That close was a `world.reset()` INSIDE joinDoc, so the\n // facade's own resources are gone here too (D-C4.5). The mirror\n // only advances on a defined read, so it still carries the\n // values from before the re-bootstrap.\n seedFacadeResources();\n }\n },\n });\n } catch (err) {\n // A REJECTED join must not strand the presence session it acquired\n // (review finding 3, 0.8.0): the behavior runtime's seam reads\n // `presence`, not `session`, so a leftover would keep ephemeral\n // behaviors publishing into a room joinDoc already unsubscribed —\n // on a doc-less engine, with no inverse the caller ever received.\n // Release ONLY if this join still owns the flow: on a supersede the\n // newer door's closeDoc released ours already and may own a fresh one.\n if (joinAbort === ac) {\n joinAbort = undefined;\n releasePresence();\n }\n throw err;\n }\n // The await gap: user code in the same task may have opened another doc\n // after our resolve was queued — that newer doc owns the engine now.\n if (joinAbort !== ac) {\n result.leave();\n throw new Error(\"ice: docs.join superseded — another document was opened while joining.\");\n }\n joined = result;\n adoptSession(result.session);\n return result;\n },\n current: () => session,\n upgradeCapabilities(widgetTypeIds) {\n const s = requireWritable(\"upgradeCapabilities\");\n if (joined !== undefined) {\n throw new Error(\n \"ice: docs.upgradeCapabilities is unavailable during a live room until peer capability negotiation is attached.\",\n );\n }\n const packs: Record<string, number> = {};\n for (const typeId of widgetTypeIds) {\n const requirements = catalog.requirementsForWidget(typeId);\n if (requirements === undefined) {\n throw new Error(`ice: docs.upgradeCapabilities — unknown widget type \"${typeId}\".`);\n }\n Object.assign(packs, requirements);\n }\n const changed = s.upgradePacks(packs);\n if (changed) {\n refreshCanvasDiagnostics();\n canvasSession.bumpCapabilities();\n }\n return changed;\n },\n attachPresence(o) {\n if (session === undefined) {\n throw new Error(\n \"ice: docs.attachPresence needs a live document — call docs.create()/open()/join() first.\",\n );\n }\n if (presence !== undefined) {\n throw new Error(\n \"ice: docs.attachPresence — a presence session is already live (join({presence}) or a prior attach); detach it (its inverse, or docs.close()) before attaching another.\",\n );\n }\n const mine = acquirePresence(o);\n let done = false;\n return () => {\n if (done) return; // idempotent\n done = true;\n // Identity-bound: after close/dispose (which already released) or a\n // replacement attachment, this inverse owns nothing — a stale inverse\n // must never detach someone else's live session.\n if (presence !== mine) return;\n releasePresence();\n };\n },\n presence: () => presence,\n close: closeDoc,\n // Read-only documents must not mutate through history either — undo/redo\n // write the store exactly like an op does.\n undo: () =>\n session === undefined ||\n session.readOnly ||\n gateVerdict(session.versionReport()) !== \"ok\" ||\n diagnosticsDirty ||\n diagnosticSnapshot.authorityIssue !== undefined\n ? false\n : historyStep(\"undo\"),\n redo: () =>\n session === undefined ||\n session.readOnly ||\n gateVerdict(session.versionReport()) !== \"ok\" ||\n diagnosticsDirty ||\n diagnosticSnapshot.authorityIssue !== undefined\n ? false\n : historyStep(\"redo\"),\n autosave(storage, o) {\n const s = requireSession(\"autosave\");\n const inner = startAutosave(s, { storage, world, ...o });\n // Track facade-created autosaves: an untracked one outlives closeDoc and\n // its next timer exports the DETACHED old session over the new document's\n // storage (2026-07-13 review).\n const handle: Autosave = {\n flush: () => inner.flush(),\n close: async () => {\n await inner.close();\n liveAutosaves.delete(handle);\n },\n state: () => inner.state(),\n stop: () => {\n liveAutosaves.delete(handle);\n inner.stop();\n },\n };\n liveAutosaves.add(handle);\n return handle;\n },\n };\n\n // --- the behavior runtime ---------------------------------------------------\n // The session seam is FORWARDING, exactly like the commit sink above: a\n // behavior's `ctx.commit` and its divergence-guarding live writer both have\n // to follow the document across open/close, and the runtime itself must\n // survive that (its instances are per-generation, not per-engine).\n const behaviors = createBehaviorRuntime({\n world,\n engine,\n session: () => session as BehaviorSession | undefined,\n // Presence attaches with `docs.join({presence})` OR `docs.attachPresence`\n // (petition I18) and detaches with the document / the attach inverse, so\n // this reads through per publish: an ephemeral behavior installed before\n // there is a presence session simply lies dormant until there is a peer\n // for it to be — and goes dormant again if the session detaches under it.\n presence: () => presence as BehaviorPresence | undefined,\n ...(opts.onBehaviorFault === undefined ? {} : { onFault: opts.onBehaviorFault }),\n ...(opts.onBehaviorLog === undefined ? {} : { onLog: opts.onBehaviorLog }),\n });\n // The engine registered its own three kind behaviours here first (design-013 D7's\n // `ice:surface.*`, the DOM/GPU choice) until design-015 D5b; an object presents on the\n // desk and nowhere else, so the app's are the only behaviours there are.\n for (const b of opts.behaviors ?? []) behaviors.register(b);\n\n // --- ops catalog -------------------------------------------------------------\n const widgetQuery = (): Entity[] => {\n const out: Entity[] = [];\n world.query(selectableWidgetsQ).each((b) => {\n for (const r of b) out.push(b.entity(r));\n });\n return out;\n };\n\n const ops: CanvasOps = {\n setTool(id) {\n const legal = canvas.tools();\n if (!legal.some((tool) => tool.id === id)) {\n throw new Error(`ice: ops.setTool — tool \"${id}\" is not legal in the current CanvasType.`);\n }\n cancelActiveGestures(world);\n writeRuntimeResource(world, ActiveTool, { id });\n },\n spawnWidget(type, o) {\n const s = requireWritable(\"spawnWidget\");\n const targetFrame = o.parent ?? requireCurrentFrame(\"spawnWidget\");\n placement.assertPlace(type, targetFrame, \"ops.spawnWidget\");\n const spawned = spawnWidget(s.store, world, type, { ...o, parent: targetFrame });\n // `Active` is DERIVED — `createActiveMembership` (nav/nested-canvas.ts)\n // stamps it inside the tick, and ops run outside the tick, so a widget\n // spawned into the open frame carries no membership until the next\n // `step()`. Every scope-filtered op (setSelection, deleteSelection) would\n // silently drop it in that window, and design-011 §16's `Selected ⇒\n // Active` makes membership the right thing to establish rather than the\n // filter the right thing to loosen. Stamp what the tick would compute for\n // THIS spawn — the entity is a member of `targetFrame` by construction —\n // and leave a spawn into a FOREIGN frame (an explicit `parent`) unstamped\n // so it stays correctly out of scope. `nested-canvas.cutVisibility` writes\n // these same tags from an op for the same reason; the next membership\n // pass re-derives and corrects either way.\n const current = canvasSession.current();\n if (\n current.state === \"attached\" &&\n targetFrame === current.frame &&\n !world.hasTag(spawned, Active)\n ) {\n world.addTag(spawned, Active);\n }\n return spawned;\n },\n layFromTray(type, at) {\n if (typeof at?.x !== \"number\" || typeof at.y !== \"number\" || !Number.isFinite(at.x) || !Number.isFinite(at.y)) {\n throw new Error(`ice: ops.layFromTray — the point is ${JSON.stringify(at) ?? String(at)}: { x, y }, a world point of the current frame, two finite numbers.`);\n }\n if (heldNow() !== undefined || !trayHung(world).includes(type)) return undefined;\n const widget = catalog.widget(type);\n const entry = widget?.tray;\n if (widget === undefined || entry === undefined) return undefined;\n // what the drag-off's create carries (l3-behave's promote of the insert ghost): the type, its natural size, the take's props\n const { w, h } = widget.defaultSize;\n const props = trayTakeProps(entry);\n const laid = ops.spawnWidget(type, { x: at.x - w / 2, y: at.y - h / 2, w, h, ...(props !== undefined ? { props } : {}) });\n ops.setSelection([laid]);\n closeTray(world);\n return laid;\n },\n insertByDrag(type, o) {\n // Writable-session gate UP FRONT: the ghost drag would otherwise run\n // beautifully and silently drop its create at commit (read-only sink).\n requireWritable(\"insertByDrag\");\n const targetFrame = requireCurrentFrame(\"insertByDrag\");\n placement.assertPlace(type, targetFrame, \"ops.insertByDrag\");\n return insertByDrag(world, stack.queue, type, o);\n },\n setWidgetProps(entity, props) {\n const s = requireWritable(\"setWidgetProps\");\n assertEditablePlacement(entity, \"setWidgetProps\");\n setWidgetProps(s.store, world, entity, props);\n },\n deleteSelection() {\n const s = requireWritable(\"deleteSelection\");\n const doomed = selectedEntities(world).filter(\n (e) => inCurrentSelectionScope(e) && s.store.keyOf(e) !== undefined,\n );\n if (doomed.length === 0) return;\n s.store.transaction((tx) => {\n for (const e of doomed) cascadeDestroy(tx, world, e);\n });\n },\n duplicateSelection() {\n const s = requireWritable(\"duplicateSelection\");\n const sources = selectedEntities(world).filter(\n (e) => world.hasTag(e, Active) && s.store.keyOf(e) !== undefined,\n );\n if (sources.length === 0) return [];\n for (const source of sources) assertEditablePlacement(source, \"duplicateSelection\");\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\" ? catalog.widget(type) : undefined;\n if (widget === undefined) continue;\n const pos = world.get(src, Position) ?? { x: 0, y: 0 };\n const size = world.get(src, Size);\n const overrides: [unknown, unknown][] = [\n [Position, { x: pos.x + 16, y: pos.y + 16 }],\n ...(size !== undefined ? [[Size, { ...size }] as [unknown, unknown]] : []),\n ];\n for (const g of widget.groups) {\n const v = world.get(src, g.component);\n if (v !== undefined) overrides.push([g.component, { ...(v as Record<string, unknown>) }]);\n }\n const clone = tx.spawnPrefab(widget.prefab, overrides as never);\n // The clone joins its source's sequence right above it (petition 8;\n // the +16/+16 twin reads as \"on top of\" its source — and an edge-less\n // clone would be unordered entirely, the pre-flip latent bug). A\n // source without an edge (legacy doc) has nothing to inherit.\n const parent = world.getRelation(src, ChildOf);\n if (parent !== undefined) {\n placement.assertPlace(widget.type, parent, \"ops.duplicateSelection\");\n tx.setRelation(clone, ChildOf, parent, { after: src });\n }\n clones.push(clone);\n }\n });\n // The clones land at the next sync; select them once alive.\n setSelection(world, clones.filter((e) => world.isAlive(e)), \"replace\");\n return clones;\n },\n setSelection(ids, mode = \"replace\") {\n setSelection(\n world,\n ids.filter(inCurrentSelectionScope),\n mode,\n );\n },\n clearSelection() {\n clearSelection(world);\n },\n selectAll() {\n setSelection(world, widgetQuery(), \"replace\");\n },\n reorder(ids, mode) {\n const s = requireWritable(\"reorder\");\n // Sibling-sequence sweep, one tx (petition 8): \"top\" appends each id to\n // its sequence tail — painted last = topmost, so later ids finish higher;\n // \"bottom\" prepends, later ids finish lower. Exactly the legacy\n // fractional-z sweep's outcome, keyed on sequence position instead.\n // TODO(design-005): relative modes (\"above\"/\"below\" an anchor) are a\n // {before}/{after} moveRelation away — deferred until the public ops\n // table names them.\n guardedTransaction(s.store, world, (tx) => {\n for (const e of ids) {\n if (s.store.keyOf(e) === undefined) continue;\n if (!world.hasTag(e, Active)) continue;\n assertEditablePlacement(e, \"reorder\");\n // No ChildOf edge (legacy doc) — no sequence to move within.\n if (world.getRelation(e, ChildOf) === undefined) continue;\n tx.moveRelation(e, ChildOf, mode === \"top\" ? \"last\" : \"first\");\n }\n });\n },\n setLocked(ids, locked) {\n const s = requireWritable(\"setLocked\");\n // The tape (design-015 §5.1): the durable `Locked` tag, this op its one\n // writer. Scoped like `reorder` — doc-keyed widgets of the current frame —\n // and CHANGE-ONLY against the world every facade op reads (a transaction\n // lands there at the next sync): an id already in the asked state writes\n // nothing, and when none differs no transaction opens (no empty undo\n // step). Placement is asserted before the transaction, so a refusal writes\n // nothing at all.\n const targets: Entity[] = [];\n for (const e of new Set(ids)) {\n if (!world.isAlive(e) || !world.hasTag(e, Active) || s.store.keyOf(e) === undefined) continue;\n const typeId = world.get(e, PrefabId)?.id;\n if (typeof typeId !== \"string\" || catalog.widget(typeId) === undefined) continue;\n if (world.hasTag(e, Locked) === locked) continue;\n assertEditablePlacement(e, \"setLocked\");\n targets.push(e);\n }\n if (targets.length === 0) return;\n guardedTransaction(s.store, world, (tx) => {\n for (const e of targets) {\n if (locked) tx.addTag(e, Locked);\n else tx.removeTag(e, Locked);\n }\n });\n },\n arrange(opts) {\n const s = requireWritable(\"arrange\");\n const scoped =\n opts?.ids === undefined\n ? opts\n : {\n ...opts,\n ids: opts.ids.filter(\n (entity) => world.isAlive(entity) && world.hasTag(entity, Active),\n ),\n };\n return arrangeWidgets(s.store, s.liveWriter, world, scoped);\n },\n zoomToFit(ids) {\n const targets = ids !== undefined && ids.length > 0 ? [...ids] : widgetQuery();\n let minX = Number.POSITIVE_INFINITY;\n let minY = Number.POSITIVE_INFINITY;\n let maxX = Number.NEGATIVE_INFINITY;\n let maxY = Number.NEGATIVE_INFINITY;\n for (const e of targets) {\n const p = world.get(e, Position);\n const s = world.get(e, Size);\n if (p === undefined || s === undefined) continue;\n minX = Math.min(minX, p.x);\n minY = Math.min(minY, p.y);\n maxX = Math.max(maxX, p.x + s.w);\n maxY = Math.max(maxY, p.y + s.h);\n }\n const vp = world.getResource(Viewport);\n if (!Number.isFinite(minX) || vp === undefined || vp.w === 0) return;\n const lim = world.getResource(CameraLimits) ?? CAMERA_DEFAULTS;\n const pad = 80;\n const zoom = Math.min(\n lim.maxZoom,\n Math.max(lim.minZoom, Math.min(vp.w / (maxX - minX + pad * 2), vp.h / (maxY - minY + pad * 2))),\n );\n writeRuntimeResource(world, Camera, {\n x: minX - (vp.w / zoom - (maxX - minX)) / 2,\n y: minY - (vp.h / zoom - (maxY - minY)) / 2,\n zoom,\n gesturing: false,\n });\n },\n frameContent() {\n const targets = widgetQuery();\n const vp = world.getResource(Viewport);\n if (targets.length === 0 || vp === undefined || vp.w === 0) return false;\n let minX = Number.POSITIVE_INFINITY;\n let minY = Number.POSITIVE_INFINITY;\n let maxX = Number.NEGATIVE_INFINITY;\n let maxY = Number.NEGATIVE_INFINITY;\n let any = false;\n for (const e of targets) {\n const p = world.get(e, Position);\n const 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 any = true;\n }\n if (!any) return false;\n const lim = world.getResource(CameraLimits) ?? CAMERA_DEFAULTS;\n const cam = fitCamera({ x: minX, y: minY, width: maxX - minX, height: maxY - minY }, vp.w, vp.h, {\n pad: FIT_DEFAULTS.pad,\n // Band ∩ hard limits; on no overlap the hard limit wins (arrival rule).\n minZoom: Math.min(Math.max(FIT_DEFAULTS.minZoom, lim.minZoom), lim.maxZoom),\n maxZoom: Math.max(Math.min(FIT_DEFAULTS.maxZoom, lim.maxZoom), lim.minZoom),\n });\n writeRuntimeResource(world, Camera, { ...cam, gesturing: false });\n return true;\n },\n zoomTo(zoom, anchor) {\n const cam = world.getResource(Camera) ?? { x: 0, y: 0, zoom: 1, gesturing: false };\n const vp = world.getResource(Viewport);\n const lim = world.getResource(CameraLimits) ?? CAMERA_DEFAULTS;\n const z = Math.min(lim.maxZoom, Math.max(lim.minZoom, zoom));\n const a = anchor ?? { x: (vp?.w ?? 0) / 2, y: (vp?.h ?? 0) / 2 };\n const next = zoomAtPoint(cam, a.x, a.y, z);\n writeRuntimeResource(world, Camera, { ...next, gesturing: false });\n },\n panTo(x, y) {\n const cam = world.getResource(Camera) ?? { x: 0, y: 0, zoom: 1, gesturing: false };\n writeRuntimeResource(world, Camera, { x, y, zoom: cam.zoom, gesturing: false });\n },\n enterContainer: (c, opts) => nav.enterContainer(c, opts),\n exitContainer: (opts) => nav.exitContainer(opts),\n exitTo: (d, opts) => nav.exitTo(d, opts),\n cancelActiveGestures: () => cancelActiveGestures(world),\n open(entity) {\n // THE OPEN (design-015 §8): the one writer of `Held`. Runtime riders only — a free write from an op, as the\n // selection is; the document never learns what is in whose hand.\n if (!isOpenable(entity)) throw new Error(\"ice: open — the target is not a live object of this frame whose kind opens (its type declares no `openable`).\");\n const held = heldNow();\n if (held !== undefined) {\n if (held === entity) return;\n throw new Error(\"ice: open — another object is in hand; put it down first (at most one object is held).\");\n }\n cancelActiveGestures(world);\n setSelection(world, [entity], \"replace\");\n world.addComponent(entity, HeldView, { zoom: 1, panX: 0, panY: 0 });\n const tool = firstHeldTool(entity);\n world.addComponent(entity, HeldTool, { id: tool, prev: tool });\n world.addTag(entity, Held);\n },\n putDown,\n useHeldTool(id) {\n // THE HELD BAR (design-015 §8, D3t-a): a mode becomes the tool in hand — a runtime write, the user's fact, as the selection\n // is; an action runs its op, whose writes are the document's (its own transaction, or a step of the document's history)\n const held = heldNow();\n if (held === undefined || !world.isAlive(held)) return false;\n const tool = heldToolsOf(held).find((t) => t.id === id);\n if (tool === undefined || tool.kind === undefined) return false;\n // a tool its kind says is DISABLED now does nothing (petition I49): the renderer's word where there is one — it reads the\n // tool's `state` with the kind's state on its desk — else the tool's own, with no desk state\n const pose = stack.heldPose.current;\n const state = pose?.toolState !== undefined ? pose.toolState(held, id) : readHeldToolState(tool, { world, entity: held, props: () => propsOf(held), local: undefined });\n if (state?.enabled === false) return false;\n if (tool.kind === \"mode\") {\n const cur = world.get(held, HeldTool) ?? { id: \"\", prev: \"\" };\n const next = cur.id !== id ? { id, prev: cur.id } : tool.toggle === true ? { id: cur.prev, prev: id } : undefined;\n if (next === undefined) return true;\n if (world.has(held, HeldTool)) world.edit(held).set(HeldTool, next);\n else world.addComponent(held, HeldTool, next);\n return true;\n }\n /** The session an action may write through, or undefined on a read-only document (the write ops' own test). */\n const writable = (): DocSession | undefined => {\n const s = session;\n return s === undefined || s.readOnly || gateVerdict(s.versionReport()) !== \"ok\" || diagnosticsDirty || diagnosticSnapshot.authorityIssue !== undefined ? undefined : s;\n };\n tool.run?.({\n world,\n entity: held,\n undo: () => docs.undo(),\n redo: () => docs.redo(),\n transact(fn, o) {\n const s = writable();\n if (s === undefined) return false;\n guardedTransaction(s.store, world, fn, o?.undoable === false ? { undoable: false } : undefined);\n return true;\n },\n props: () => propsOf(held),\n setProps(props, o) {\n const s = writable();\n if (s === undefined) return false;\n setWidgetProps(s.store, world, held, props, o?.undoable === false ? { undoable: false } : undefined);\n return true;\n },\n });\n return true;\n },\n runMenuAction(id) {\n // THE SELECTION MENU'S ACTS (K8a): each type that declares `id` runs it once over its own selected objects\n const byType = new Map<WidgetType, Entity[]>();\n for (const e of selectedEntities(world)) {\n const typeId = world.isAlive(e) ? world.get(e, PrefabId)?.id : undefined;\n const type = typeof typeId === \"string\" ? catalog.widget(typeId) : undefined;\n if (type === undefined || !type.menu.some((a) => a.id === id)) continue;\n const list = byType.get(type);\n if (list === undefined) byType.set(type, [e]);\n else list.push(e);\n }\n if (byType.size === 0) return false;\n /** The session an act may write through, or undefined on a read-only document (the write ops' own test). */\n const writable = (): DocSession | undefined => {\n const s = session;\n return s === undefined || s.readOnly || gateVerdict(s.versionReport()) !== \"ok\" || diagnosticsDirty || diagnosticSnapshot.authorityIssue !== undefined ? undefined : s;\n };\n for (const [type, entities] of byType) {\n type.menu.find((a) => a.id === id)?.run({\n world,\n entities,\n props: (e) => propsOf(e),\n setProps(e, props, o) {\n const s = writable();\n if (s === undefined || !world.isAlive(e)) return false;\n setWidgetProps(s.store, world, e, props, o?.undoable === false ? { undoable: false } : undefined);\n return true;\n },\n transact(fn, o) {\n const s = writable();\n if (s === undefined) return false;\n guardedTransaction(s.store, world, fn, o?.undoable === false ? { undoable: false } : undefined);\n return true;\n },\n });\n }\n return true;\n },\n };\n\n // --- stage holds (StageMode mirror; tokens live HERE, out-of-ECS) ---------\n const stageHolds = new Map<symbol, string>();\n const syncStage = (): void => {\n writeRuntimeResource(world, StageMode, { backgroundHolds: stageHolds.size });\n };\n const stage: StageControl = {\n background(name) {\n const token = Symbol(name);\n stageHolds.set(token, name);\n syncStage();\n let released = false;\n return () => {\n if (released) return; // idempotent — double-release must not eat another hold\n released = true;\n stageHolds.delete(token);\n syncStage();\n };\n },\n isBackgrounded: () => stageHolds.size > 0,\n holds: () => [...stageHolds.values()],\n };\n\n // --- frame freeze wiring (the gate lives on the engine; these are its two\n // stack-level consequences, installed once at construction) ---------------\n //\n // A gesture may not be left in flight across a freeze: its runtime edits are\n // uncommitted until the recognizer reaches JustEnded, and a parked loop never\n // gets there. So a freeze CANCELS between frames and the reporter below keeps\n // the settle walking until the recognizers are terminal — cancellation is a\n // one-tick resource the ctl:spawn sweep acts on NEXT tick, so this is a walk,\n // never a single frame.\n engine.frame.settleWhile(\"gestures\", () => isMidGesture(world));\n engine.frame.onChange(() => {\n if (engine.frame.isFrozen()) {\n cancelActiveGestures(world);\n return;\n }\n // Thaw. The adapters never stopped enqueuing, so the queue holds facts\n // about a canvas nobody could interact with, stamped with a `tMs` that is\n // now minutes stale — replaying them would hand recognizers a burst of\n // impossible history. Drop them, exactly as the adapter drops a pointer\n // across a window blur (design-003 §8).\n stack.queue.drain();\n });\n\n return {\n world,\n engine,\n catalog,\n placement,\n canvas,\n previews,\n behaviors,\n stack,\n runtime,\n transitions,\n nav,\n ops,\n docs,\n stage,\n frame: engine.frame,\n // exactOptionalPropertyTypes: a `compositorDevice: undefined` property is\n // NOT the same as an absent one, and the optional field refuses the former.\n ...(opts.compositorDevice !== undefined ? { compositorDevice: opts.compositorDevice } : {}),\n budgets,\n step: (now) => engine.step(now),\n dispose() {\n removeNavIntent();\n removeHeldIntent();\n removeTrayIntent();\n previews.dispose();\n closeDoc();\n transitions.dispose();\n // Behaviors before guests: their dispose hooks may still want a live\n // world, and their breaker rows live in the guest registry that the next\n // line tears down.\n behaviors.dispose();\n removeDiagnosticPublish();\n runtimeExtensionHost.dispose();\n frameBehaviorHost?.dispose();\n // Guests first: their dispose may touch doc/runtime state, and a\n // suspended-but-registered guest still holds an instance to tear down.\n engine.disposeGuests();\n runtime.uninstall();\n stack.uninstall();\n unbindCatalog();\n },\n };\n}\n","/** Current-frame CanvasRuntimeExtension dispatcher and fault/output governor. */\nimport {\n Related,\n defineQuery,\n valueEquals,\n type ChangeCollector,\n type Component,\n type Entity,\n type Relation,\n type Resource,\n type Tag,\n type World,\n} from \"@vibecook/strata-ecs\";\nimport { ChildOf, Position } from \"../catalog/scene\";\nimport type { Engine } from \"../engine/engine\";\nimport { PrefabId } from \"../schema/prefab\";\nimport { schemaMeta } from \"../schema/meta\";\nimport type { CanvasSessionValue } from \"./session\";\nimport type { EngineCatalog } from \"./engine-catalog\";\nimport type {\n CanvasReadFacet,\n CanvasRuntimeExtension,\n CanvasRuntimeExtensionContext,\n} from \"./extensions\";\n\ninterface Facets {\n readonly components: Set<Component>;\n readonly tags: Set<Tag>;\n readonly relations: Set<Relation>;\n readonly resources: Set<Resource>;\n}\n\ninterface PriorOutput {\n readonly present: boolean;\n readonly value: unknown;\n}\n\ninterface Activation {\n readonly extension: CanvasRuntimeExtension;\n readonly facets: Facets;\n readonly collector: ChangeCollector;\n readonly controller: AbortController;\n readonly unsubs: (() => void)[];\n readonly prior: Map<Component, Map<Entity, PriorOutput>>;\n full: boolean;\n externalDirty: boolean;\n}\n\nexport interface CanvasRuntimeExtensionHost {\n /** Force output teardown at the synchronous authority cut. */\n invalidate(): void;\n dispose(): void;\n}\n\nfunction partition(facets: readonly CanvasReadFacet[]): Facets {\n const components = new Set<Component>();\n const tags = new Set<Tag>();\n const relations = new Set<Relation>();\n const resources = new Set<Resource>();\n for (const facet of facets) {\n if (schemaMeta.component(facet as Component) !== undefined) components.add(facet as Component);\n else if (schemaMeta.tagName(facet as Tag) !== undefined) tags.add(facet as Tag);\n else if (schemaMeta.relation(facet as Relation) !== undefined) relations.add(facet as Relation);\n else if (schemaMeta.resource(facet as Resource) !== undefined) resources.add(facet as Resource);\n }\n return { components, tags, relations, resources };\n}\n\nfunction sessionKey(session: CanvasSessionValue): string {\n return `${session.documentEpoch}:${session.epoch}`;\n}\n\nexport function installCanvasRuntimeExtensions(opts: {\n readonly world: World;\n readonly engine: Engine;\n readonly catalog: EngineCatalog;\n readonly session: () => CanvasSessionValue;\n}): CanvasRuntimeExtensionHost {\n const { world, engine, catalog } = opts;\n const used = new Map<string, CanvasRuntimeExtension>();\n for (const canvas of catalog.canvasTypeDefs()) {\n for (const extension of catalog.runtimeExtensionsFor(canvas.id)) {\n used.set(extension.id, extension);\n }\n }\n if (used.size === 0) return { invalidate() {}, dispose() {} };\n\n const driven = new Map(\n [...used.values()].map((extension) => [\n extension.id,\n engine.guests.addDriven({\n id: `canvas-runtime:${extension.id}`,\n ...(extension.budgetMs === undefined ? {} : { budgetMs: extension.budgetMs }),\n }),\n ] as const),\n );\n let activeKey = \"\";\n let activations: Activation[] = [];\n let disposed = false;\n\n const restoreOutputs = (activation: Activation): void => {\n for (const [component, entities] of activation.prior) {\n for (const [entity, prior] of entities) {\n if (!world.isAlive(entity)) continue;\n if (prior.present) {\n const current = world.get(entity, component);\n if (current === undefined || !valueEquals(component, current, prior.value)) {\n world.edit(entity).set(component, prior.value);\n }\n } else if (world.has(entity, component)) {\n world.removeComponent(entity, component);\n }\n }\n }\n activation.prior.clear();\n };\n\n const deactivate = (): void => {\n for (const activation of activations) {\n restoreOutputs(activation);\n activation.collector.dispose();\n for (const unsub of activation.unsubs) unsub();\n activation.controller.abort();\n }\n activations = [];\n activeKey = \"\";\n };\n\n const makeActivation = (extension: CanvasRuntimeExtension): Activation => {\n const facets = partition(extension.reads);\n const components = [...new Set<Component>([PrefabId, Position, ...facets.components])];\n const activation: Activation = {\n extension,\n facets,\n collector: world.changes.collect({\n components,\n ...(facets.tags.size === 0 ? {} : { tags: [...facets.tags] }),\n coarse: false,\n }),\n controller: new AbortController(),\n unsubs: [],\n prior: new Map(),\n full: true,\n externalDirty: false,\n };\n for (const relation of facets.relations) {\n const query = defineQuery([Related(relation)]);\n activation.unsubs.push(\n world.reactive.observeQuery(query, () => {\n activation.externalDirty = true;\n }),\n );\n }\n for (const resource of facets.resources) {\n activation.unsubs.push(\n world.reactive.observeResource(resource, () => {\n activation.externalDirty = true;\n }),\n );\n }\n return activation;\n };\n\n const ensureSession = (): (CanvasSessionValue & { readonly state: \"attached\" }) | undefined => {\n const current = opts.session();\n const key = sessionKey(current);\n if (key === activeKey) {\n return current.state === \"attached\"\n ? (current as CanvasSessionValue & { readonly state: \"attached\" })\n : undefined;\n }\n deactivate();\n activeKey = key;\n if (current.state !== \"attached\") return undefined;\n activations = catalog.runtimeExtensionsFor(current.typeId).map(makeActivation);\n return current as CanvasSessionValue & { readonly state: \"attached\" };\n };\n\n const removeDepartedOutputs = (activation: Activation, scope: ReadonlySet<Entity>): void => {\n for (const [component, entities] of activation.prior) {\n for (const [entity, prior] of [...entities]) {\n if (scope.has(entity)) continue;\n entities.delete(entity);\n if (!world.isAlive(entity)) continue;\n if (prior.present) world.edit(entity).set(component, prior.value);\n else if (world.has(entity, component)) world.removeComponent(entity, component);\n }\n }\n };\n\n const runActivation = (\n activation: Activation,\n session: CanvasSessionValue & { readonly state: \"attached\" },\n ): void => {\n const delta = activation.collector.drain();\n const children = world\n .getReverse(session.frame, ChildOf)\n .filter((entity) => world.isAlive(entity) && world.get(entity, PrefabId) !== undefined);\n const scope = new Set<Entity>([session.frame, ...children]);\n removeDepartedOutputs(activation, scope);\n const changed = delta.changed.filter((entity) => scope.has(entity));\n const full = activation.full || delta.reset || delta.coarse.length > 0;\n const shouldRun = full || activation.externalDirty || changed.length > 0 || delta.removed.length > 0;\n activation.full = false;\n activation.externalDirty = false;\n if (!shouldRun) return;\n\n const { extension, facets } = activation;\n const assertEntity = (entity: Entity): void => {\n if (!scope.has(entity) || !world.isAlive(entity)) {\n throw new Error(\n `ice: CanvasRuntimeExtension \"${extension.id}\" addressed an entity outside the active direct frame.`,\n );\n }\n };\n const context: CanvasRuntimeExtensionContext = {\n session,\n frame: session.frame,\n children: Object.freeze([...children]),\n changes: { full, changed: Object.freeze([...changed]), removed: Object.freeze([...delta.removed]) },\n signal: activation.controller.signal,\n read(entity, component) {\n assertEntity(entity);\n if (!facets.components.has(component)) {\n throw new Error(`ice: CanvasRuntimeExtension \"${extension.id}\" read an undeclared component.`);\n }\n return world.read(entity, component);\n },\n get(entity, component) {\n assertEntity(entity);\n if (!facets.components.has(component)) {\n throw new Error(`ice: CanvasRuntimeExtension \"${extension.id}\" read an undeclared component.`);\n }\n return world.get(entity, component);\n },\n hasTag(entity, tag) {\n assertEntity(entity);\n if (!facets.tags.has(tag)) {\n throw new Error(`ice: CanvasRuntimeExtension \"${extension.id}\" read an undeclared tag.`);\n }\n return world.hasTag(entity, tag);\n },\n getRelation(entity, relation) {\n assertEntity(entity);\n if (!facets.relations.has(relation)) {\n throw new Error(`ice: CanvasRuntimeExtension \"${extension.id}\" read an undeclared relation.`);\n }\n const target = world.getRelation(entity, relation);\n return target !== undefined && scope.has(target) ? target : undefined;\n },\n getRelations(entity, relation) {\n assertEntity(entity);\n if (!facets.relations.has(relation)) {\n throw new Error(`ice: CanvasRuntimeExtension \"${extension.id}\" read an undeclared relation.`);\n }\n return world.getRelations(entity, relation).filter((target) => scope.has(target));\n },\n getReverse(entity, relation) {\n assertEntity(entity);\n if (!facets.relations.has(relation)) {\n throw new Error(`ice: CanvasRuntimeExtension \"${extension.id}\" read an undeclared relation.`);\n }\n return world.getReverse(entity, relation).filter((source) => scope.has(source));\n },\n getResource(resource) {\n if (!facets.resources.has(resource)) {\n throw new Error(`ice: CanvasRuntimeExtension \"${extension.id}\" read an undeclared resource.`);\n }\n return world.getResource(resource);\n },\n set(entity, component, value) {\n assertEntity(entity);\n if (!extension.writesRuntime.includes(component)) {\n throw new Error(`ice: CanvasRuntimeExtension \"${extension.id}\" wrote an undeclared output.`);\n }\n let entities = activation.prior.get(component);\n if (entities === undefined) {\n entities = new Map();\n activation.prior.set(component, entities);\n }\n if (!entities.has(entity)) {\n entities.set(entity, {\n present: world.has(entity, component),\n value: world.get(entity, component),\n });\n }\n const current = world.get(entity, component);\n if (current !== undefined && valueEquals(component, current, value)) return;\n if (current === undefined) world.addComponent(entity, component, value);\n else world.edit(entity).set(component, value);\n },\n remove(entity, component) {\n assertEntity(entity);\n if (!extension.writesRuntime.includes(component)) {\n throw new Error(`ice: CanvasRuntimeExtension \"${extension.id}\" removed an undeclared output.`);\n }\n if (world.has(entity, component)) world.removeComponent(entity, component);\n },\n };\n const returned: unknown = extension.run(context);\n if (typeof (returned as { then?: unknown } | null | undefined)?.then === \"function\") {\n throw new Error(`ice: CanvasRuntimeExtension \"${extension.id}\" returned a thenable.`);\n }\n };\n\n const removeDispatcher = engine.guests.add({\n id: \"canvas-runtime:dispatcher\",\n make: () => ({\n run() {\n const session = ensureSession();\n if (session?.state !== \"attached\") return;\n for (const activation of activations) {\n const breaker = driven.get(activation.extension.id);\n const ok = breaker?.run(() => runActivation(activation, session)) ?? false;\n if (!ok) {\n // A failed run rolled its outputs back, but `runActivation` already\n // drained the collector and cleared full/externalDirty BEFORE the\n // body threw — so the next dispatch would see an empty delta and\n // skip, leaving the reverted outputs stale until some unrelated\n // input changed. RE-ARM: the next dispatch recomputes from scratch.\n //\n // Not a hot loop. A throwing extension re-runs at most\n // GUEST_BUDGET.consecutiveThrows times before the breaker suspends\n // it — that ladder is the point (design-011 §13.3: clear outputs,\n // breaker suspension, diagnostic). Once SUSPENDED, `breaker.run`\n // short-circuits false without entering the body, restoreOutputs is\n // a no-op over the already-cleared `prior`, and this flag simply\n // stays armed — which is also how `guests.resume(id)` gets a full\n // recompute on the first dispatch after it lets the guest back in.\n restoreOutputs(activation);\n activation.full = true;\n }\n }\n },\n dispose: deactivate,\n }),\n });\n\n return {\n invalidate: deactivate,\n dispose() {\n if (disposed) return;\n disposed = true;\n removeDispatcher();\n deactivate();\n for (const breaker of driven.values()) breaker.remove();\n driven.clear();\n },\n };\n}\n","/** View-independent, dirt-routed semantic FrameBehavior host. */\nimport {\n Related,\n defineQuery,\n valueEquals,\n type ChangeCollector,\n type Component,\n type Entity,\n type Relation,\n type Resource,\n type Tag,\n type World,\n} from \"@vibecook/strata-ecs\";\nimport { BoardRoot, ChildOf, Position } from \"../catalog/scene\";\nimport type { DocSession } from \"../doc/doc-kit\";\nimport { gateVerdict } from \"../doc/version-gate\";\nimport type { Engine } from \"../engine/engine\";\nimport { guardedTransaction } from \"../guards/guarded-tx\";\nimport { PrefabId } from \"../schema/prefab\";\nimport { schemaMeta } from \"../schema/meta\";\nimport { canvasPackId } from \"./define-canvas-type\";\nimport type { EngineCatalog } from \"./engine-catalog\";\nimport {\n frameBehaviorPackId,\n type CanvasReadFacet,\n type FrameBehavior,\n type FrameBehaviorWriteContext,\n} from \"./extensions\";\n\nconst durableQ = defineQuery([PrefabId]);\n\ninterface Facets {\n readonly components: Set<Component>;\n readonly tags: Set<Tag>;\n readonly relations: Set<Relation>;\n readonly resources: Set<Resource>;\n}\n\ntype FrameOp =\n | { readonly kind: \"set\"; readonly entity: Entity; readonly component: Component; readonly value: unknown }\n | { readonly kind: \"remove\"; readonly entity: Entity; readonly component: Component }\n | { readonly kind: \"set-relation\"; readonly entity: Entity; readonly relation: Relation; readonly target: Entity }\n | { readonly kind: \"remove-relation\"; readonly entity: Entity; readonly relation: Relation; readonly target?: Entity };\n\ninterface BehaviorState {\n readonly behavior: FrameBehavior;\n readonly canvasIds: ReadonlySet<string>;\n readonly facets: Facets;\n readonly collector: ChangeCollector;\n readonly unsubs: (() => void)[];\n readonly pending: Set<Entity>;\n readonly ownerByEntity: Map<Entity, Entity>;\n externalDirty: boolean;\n full: boolean;\n faulted: boolean;\n}\n\nexport interface FrameBehaviorHost {\n isCanvasWritable(canvasTypeId: string): boolean;\n dispose(): void;\n}\n\nfunction partition(facets: readonly CanvasReadFacet[]): Facets {\n const components = new Set<Component>();\n const tags = new Set<Tag>();\n const relations = new Set<Relation>();\n const resources = new Set<Resource>();\n for (const facet of facets) {\n if (schemaMeta.component(facet as Component) !== undefined) components.add(facet as Component);\n else if (schemaMeta.tagName(facet as Tag) !== undefined) tags.add(facet as Tag);\n else if (schemaMeta.relation(facet as Relation) !== undefined) relations.add(facet as Relation);\n else if (schemaMeta.resource(facet as Resource) !== undefined) resources.add(facet as Resource);\n }\n return { components, tags, relations, resources };\n}\n\nfunction canvasForFrame(\n world: World,\n catalog: EngineCatalog,\n session: DocSession,\n frame: Entity,\n): string | undefined {\n const root = world.getResource(BoardRoot)?.root;\n if (frame === root) return session.versionReport().rootCanvas?.id;\n const typeId = world.get(frame, PrefabId)?.id;\n return typeof typeId === \"string\" ? catalog.canvasForContainer(typeId)?.id : undefined;\n}\n\nfunction validFrame(world: World, catalog: EngineCatalog, frame: Entity): boolean {\n if (!world.isAlive(frame)) return false;\n if (frame === world.getResource(BoardRoot)?.root) return true;\n const typeId = world.get(frame, PrefabId)?.id;\n return typeof typeId === \"string\" && catalog.widget(typeId)?.container !== undefined;\n}\n\nfunction stableFrames(store: DocSession[\"store\"], frames: Iterable<Entity>): Entity[] {\n return [...new Set(frames)].sort((a, b) => {\n const ka = String(store.keyOf(a) ?? a);\n const kb = String(store.keyOf(b) ?? b);\n return ka.localeCompare(kb);\n });\n}\n\nexport function installFrameBehaviors(opts: {\n readonly world: World;\n readonly engine: Engine;\n readonly catalog: EngineCatalog;\n readonly session: () => DocSession | undefined;\n readonly onAvailabilityChange?: () => void;\n}): FrameBehaviorHost {\n const { world, engine, catalog } = opts;\n const used = new Map<string, { behavior: FrameBehavior; canvasIds: Set<string> }>();\n for (const canvas of catalog.canvasTypeDefs()) {\n for (const behavior of catalog.frameBehaviorsFor(canvas.id)) {\n const entry = used.get(behavior.id) ?? { behavior, canvasIds: new Set<string>() };\n entry.canvasIds.add(canvas.id);\n used.set(behavior.id, entry);\n }\n }\n if (used.size === 0) return { isCanvasWritable: () => true, dispose() {} };\n\n const states = new Map<string, BehaviorState>();\n const breakers = new Map<string, ReturnType<Engine[\"guests\"][\"addDriven\"]>>();\n\n for (const { behavior, canvasIds } of used.values()) {\n const facets = partition(behavior.reads);\n const state: BehaviorState = {\n behavior,\n canvasIds,\n facets,\n collector: world.changes.collect({\n components: [...new Set<Component>([PrefabId, Position, ...facets.components])],\n ...(facets.tags.size === 0 ? {} : { tags: [...facets.tags] }),\n coarse: false,\n }),\n unsubs: [],\n pending: new Set(),\n ownerByEntity: new Map(),\n externalDirty: false,\n full: true,\n faulted: false,\n };\n for (const relation of facets.relations) {\n state.unsubs.push(\n world.reactive.observeQuery(defineQuery([Related(relation)]), () => {\n state.externalDirty = true;\n }),\n );\n }\n for (const resource of facets.resources) {\n state.unsubs.push(\n world.reactive.observeResource(resource, () => {\n state.externalDirty = true;\n }),\n );\n }\n states.set(behavior.id, state);\n breakers.set(\n behavior.id,\n engine.guests.addDriven({\n id: `frame-behavior:${behavior.id}`,\n budgetMs: behavior.budget.ms,\n busy: () => state.pending.size > 0 || state.full || state.faulted,\n }),\n );\n }\n\n const markAllFrames = (state: BehaviorState, session: DocSession): void => {\n const root = world.getResource(BoardRoot)?.root;\n if (\n root !== undefined &&\n state.canvasIds.has(session.versionReport().rootCanvas?.id ?? \"\")\n ) {\n state.pending.add(root);\n }\n world.query(durableQ).each((batch) => {\n for (const row of batch) {\n const entity = batch.entity(row);\n const typeId = world.read(entity, PrefabId).id;\n const canvasId = typeof typeId === \"string\" ? catalog.canvasForContainer(typeId)?.id : undefined;\n if (canvasId !== undefined && state.canvasIds.has(canvasId)) state.pending.add(entity);\n const parent = world.getRelation(entity, ChildOf);\n if (parent !== undefined) state.ownerByEntity.set(entity, parent);\n }\n });\n };\n\n const routeEntity = (state: BehaviorState, session: DocSession, entity: Entity): void => {\n if (!world.isAlive(entity)) {\n const prior = state.ownerByEntity.get(entity);\n if (prior !== undefined) state.pending.add(prior);\n state.ownerByEntity.delete(entity);\n return;\n }\n const parent = world.getRelation(entity, ChildOf);\n if (parent !== undefined) {\n const previous = state.ownerByEntity.get(entity);\n if (previous !== undefined && previous !== parent) state.pending.add(previous);\n state.ownerByEntity.set(entity, parent);\n if (validFrame(world, catalog, parent)) state.pending.add(parent);\n }\n if (validFrame(world, catalog, entity)) {\n const canvasId = canvasForFrame(world, catalog, session, entity);\n if (canvasId !== undefined && state.canvasIds.has(canvasId)) state.pending.add(entity);\n }\n };\n\n const drainState = (state: BehaviorState, session: DocSession): void => {\n const delta = state.collector.drain();\n if (state.full || state.externalDirty || delta.reset || delta.coarse.length > 0) {\n markAllFrames(state, session);\n state.full = false;\n state.externalDirty = false;\n }\n for (const entity of delta.changed) routeEntity(state, session, entity);\n for (const entity of delta.removed) routeEntity(state, session, entity);\n };\n\n const planFrame = (\n state: BehaviorState,\n session: DocSession,\n frame: Entity,\n canvasTypeId: string,\n ): FrameOp[] => {\n const children = world\n .getReverse(frame, ChildOf)\n .filter((entity) => world.isAlive(entity) && world.get(entity, PrefabId) !== undefined);\n if (children.length > state.behavior.budget.entities) {\n throw new Error(\n `ice: FrameBehavior \"${state.behavior.id}\" frame exceeds its ` +\n `${state.behavior.budget.entities}-entity budget.`,\n );\n }\n const scope = new Set<Entity>([frame, ...children]);\n const ops: FrameOp[] = [];\n const assertEntity = (entity: Entity): void => {\n if (!scope.has(entity) || !world.isAlive(entity)) {\n throw new Error(\n `ice: FrameBehavior \"${state.behavior.id}\" addressed an entity outside its direct frame.`,\n );\n }\n };\n const context: FrameBehaviorWriteContext = {\n canvasTypeId,\n frame,\n children: Object.freeze([...children]),\n read(entity, component) {\n assertEntity(entity);\n if (!state.facets.components.has(component)) {\n throw new Error(`ice: FrameBehavior \"${state.behavior.id}\" read an undeclared component.`);\n }\n return world.read(entity, component);\n },\n get(entity, component) {\n assertEntity(entity);\n if (!state.facets.components.has(component)) {\n throw new Error(`ice: FrameBehavior \"${state.behavior.id}\" read an undeclared component.`);\n }\n return world.get(entity, component);\n },\n hasTag(entity, tag) {\n assertEntity(entity);\n if (!state.facets.tags.has(tag)) {\n throw new Error(`ice: FrameBehavior \"${state.behavior.id}\" read an undeclared tag.`);\n }\n return world.hasTag(entity, tag);\n },\n getRelation(entity, relation) {\n assertEntity(entity);\n if (!state.facets.relations.has(relation)) {\n throw new Error(`ice: FrameBehavior \"${state.behavior.id}\" read an undeclared relation.`);\n }\n const target = world.getRelation(entity, relation);\n return target !== undefined && scope.has(target) ? target : undefined;\n },\n getRelations(entity, relation) {\n assertEntity(entity);\n if (!state.facets.relations.has(relation)) {\n throw new Error(`ice: FrameBehavior \"${state.behavior.id}\" read an undeclared relation.`);\n }\n return world.getRelations(entity, relation).filter((target) => scope.has(target));\n },\n getReverse(entity, relation) {\n assertEntity(entity);\n if (!state.facets.relations.has(relation)) {\n throw new Error(`ice: FrameBehavior \"${state.behavior.id}\" read an undeclared relation.`);\n }\n return world.getReverse(entity, relation).filter((source) => scope.has(source));\n },\n getResource(resource) {\n if (!state.facets.resources.has(resource)) {\n throw new Error(`ice: FrameBehavior \"${state.behavior.id}\" read an undeclared resource.`);\n }\n return world.getResource(resource);\n },\n set(entity, component, value) {\n assertEntity(entity);\n if (entity === world.getResource(BoardRoot)?.root) {\n throw new Error(\"ice: FrameBehavior cannot add mutable state to BoardRoot.\");\n }\n if (!state.behavior.writesDurable.includes(component)) {\n throw new Error(`ice: FrameBehavior \"${state.behavior.id}\" wrote an undeclared component.`);\n }\n ops.push({ kind: \"set\", entity, component, value });\n },\n remove(entity, component) {\n assertEntity(entity);\n if (!state.behavior.writesDurable.includes(component)) {\n throw new Error(`ice: FrameBehavior \"${state.behavior.id}\" removed an undeclared component.`);\n }\n ops.push({ kind: \"remove\", entity, component });\n },\n setRelation(entity, relation, target) {\n assertEntity(entity);\n if (!scope.has(target) || !state.behavior.writesRelations.includes(relation)) {\n throw new Error(`ice: FrameBehavior \"${state.behavior.id}\" wrote an undeclared/cross-frame relation.`);\n }\n ops.push({ kind: \"set-relation\", entity, relation, target });\n },\n removeRelation(entity, relation, target) {\n assertEntity(entity);\n if (\n !state.behavior.writesRelations.includes(relation) ||\n (target !== undefined && !scope.has(target))\n ) {\n throw new Error(`ice: FrameBehavior \"${state.behavior.id}\" removed an undeclared/cross-frame relation.`);\n }\n ops.push({ kind: \"remove-relation\", entity, relation, ...(target === undefined ? {} : { target }) });\n },\n };\n const returned: unknown = state.behavior.run(context);\n if (typeof (returned as { then?: unknown } | null | undefined)?.then === \"function\") {\n throw new Error(`ice: FrameBehavior \"${state.behavior.id}\" returned a thenable.`);\n }\n return ops;\n };\n\n const applyOps = (state: BehaviorState, session: DocSession, ops: readonly FrameOp[]): void => {\n const effective = ops.filter((op) => {\n switch (op.kind) {\n case \"set\": {\n const current = world.get(op.entity, op.component);\n return current === undefined || !valueEquals(op.component, current, op.value);\n }\n case \"remove\":\n return world.has(op.entity, op.component);\n case \"set-relation\":\n return world.getRelation(op.entity, op.relation) !== op.target;\n case \"remove-relation\":\n return op.target === undefined\n ? world.getRelation(op.entity, op.relation) !== undefined\n : world.getRelations(op.entity, op.relation).includes(op.target);\n }\n });\n if (effective.length === 0) return;\n guardedTransaction(\n session.store,\n world,\n (tx) => {\n for (const op of effective) {\n switch (op.kind) {\n case \"set\":\n if (world.has(op.entity, op.component)) tx.edit(op.entity).set(op.component, op.value);\n else tx.addComponent(op.entity, op.component, op.value);\n break;\n case \"remove\":\n tx.removeComponent(op.entity, op.component);\n break;\n case \"set-relation\":\n tx.setRelation(op.entity, op.relation, op.target);\n break;\n case \"remove-relation\":\n tx.removeRelation(op.entity, op.relation, op.target);\n break;\n }\n }\n },\n {\n undoable: false,\n live: session.liveWriter,\n keyOf: (entity) => session.store.keyOf(entity) as string | undefined,\n meta: { origin: `frame-behavior:${state.behavior.id}` },\n },\n );\n };\n\n const availabilityChanged = (state: BehaviorState, next: boolean): void => {\n if (state.faulted === next) return;\n state.faulted = next;\n opts.onAvailabilityChange?.();\n };\n\n const removeDispatcher = engine.guests.add({\n id: \"frame-behavior:dispatcher\",\n make: () => ({\n run() {\n const session = opts.session();\n if (\n session === undefined ||\n session.readOnly ||\n gateVerdict(session.versionReport()) !== \"ok\"\n ) {\n for (const state of states.values()) state.full = true;\n return;\n }\n // Canvas-local topological order is already compiled. Iterating the\n // catalog order here means a downstream behavior drains after an\n // upstream behavior's same-frame guarded transaction.\n const ordered: BehaviorState[] = [];\n const seen = new Set<string>();\n for (const canvas of catalog.canvasTypeDefs()) {\n for (const behavior of catalog.frameBehaviorsFor(canvas.id)) {\n if (seen.has(behavior.id)) continue;\n seen.add(behavior.id);\n const state = states.get(behavior.id);\n if (state !== undefined) ordered.push(state);\n }\n }\n for (const state of ordered) {\n drainState(state, session);\n const frames = stableFrames(session.store, state.pending);\n for (const frame of frames) {\n if (!validFrame(world, catalog, frame)) {\n state.pending.delete(frame);\n continue;\n }\n const canvasId = canvasForFrame(world, catalog, session, frame);\n if (canvasId === undefined || !state.canvasIds.has(canvasId)) {\n state.pending.delete(frame);\n continue;\n }\n const report = session.versionReport();\n const canvas = catalog.canvasType(canvasId);\n if (\n canvas === undefined ||\n report.docPacks[canvasPackId(canvasId)] !== canvas.semanticVersion ||\n report.docPacks[frameBehaviorPackId(state.behavior.id)] !== state.behavior.version\n ) {\n continue;\n }\n const breaker = breakers.get(state.behavior.id);\n const ok = breaker?.run(() => {\n const ops = planFrame(state, session, frame, canvasId);\n applyOps(state, session, ops);\n }) ?? false;\n if (ok) {\n state.pending.delete(frame);\n availabilityChanged(state, false);\n } else {\n availabilityChanged(state, true);\n break;\n }\n }\n }\n },\n dispose() {\n for (const state of states.values()) {\n state.collector.clear();\n state.pending.clear();\n state.ownerByEntity.clear();\n state.full = true;\n }\n },\n busy: () => [...states.values()].some((state) => state.pending.size > 0),\n }),\n });\n\n return {\n isCanvasWritable(canvasTypeId) {\n for (const behavior of catalog.frameBehaviorsFor(canvasTypeId)) {\n const state = states.get(behavior.id);\n const breaker = breakers.get(behavior.id);\n if (state?.faulted === true || breaker?.suspended() === true) return false;\n }\n return true;\n },\n dispose() {\n removeDispatcher();\n for (const state of states.values()) {\n state.collector.dispose();\n for (const unsub of state.unsubs) unsub();\n }\n for (const breaker of breakers.values()) breaker.remove();\n states.clear();\n breakers.clear();\n },\n };\n}\n","/**\n * insertByDrag — the tray-adoption op (2026-07-19, James: the widget tray).\n *\n * Called from the app's tray-tile `pointerdown` (which `stopPropagation`s the\n * native down — the sanctioned widget-content boundary, design-002 §8). Two\n * event-time moves, then the ENGINE owns everything:\n *\n * 1. DRAFT-spawn the ghost (design-001 §3; instantiate `{ draft: true }`) —\n * a runtime instance of the widget prefab centered under the pointer,\n * equipped + Active + top-of-frame IMMEDIATELY (the equip system runs in\n * `derive`, AFTER this tick's pick — the down below must find the ghost\n * indexed and topmost in the SAME tick, so the op stamps what equip\n * would). Two capability tags are deliberately withheld:\n * - `LongPressDrag`: a tray insert is always instant-drag — nobody holds\n * 500ms over a palette;\n * - `SweepsContained`: a comment ghost at the tray's world point must not\n * sweep the widgets resting under the tray into the insert.\n * And one is always GIVEN (K5b, design-017 §9): `Movable` — the adoption\n * drag is core's whatever the kind's own carry (a print is not core-movable:\n * its carry is its physics), so every kind taken off the tray runs the\n * ordinary drag to its drop.\n * The projected twin gets the FULL tag set from the equip system.\n *\n * 2. Enqueue ONE synthetic un-flagged `down` (Law 2 — this op is an adapter\n * here, it only enqueues; the GL router precedent). Next tick: spatialSync\n * indexes the ghost, targeting resolves it topmost, the Drag recognizer\n * captures it — and the ordinary L0–L4 stack runs the whole drag: lift,\n * snap, drop targets, folder consume. moveBehavior's ghost terminals\n * promote (one `create` tx) or fly the ghost home and reap it.\n */\nimport type { Entity, World } from \"@vibecook/strata-ecs\";\nimport { screenToWorld, type CameraState } from \"@ice/kernel\";\nimport { Camera, ChildOf, InsertGhost, LongPressDrag, Movable, SweepsContained } from \"../catalog\";\nimport { Active } from \"../catalog/camera-derived\";\nimport { widgetTypeFor } from \"../canvas/engine-catalog\";\nimport { instantiate } from \"../engine/instantiate\";\nimport { NO_MODS, type InputQueue } from \"../input/queue\";\nimport { WidgetEquipped } from \"../widget/define-widget\";\nimport { widgetSpawnInits } from \"../widget/spawn\";\nimport { frameParent } from \"./sibling-order\";\n\nconst IDENTITY_CAM: CameraState = { x: 0, y: 0, zoom: 1 };\n\nexport interface InsertByDragOpts {\n /** The press point in canvas-container CSS px (the kernel screen space). */\n readonly screenX: number;\n readonly screenY: number;\n /** Prop overrides for the eventual create (validated by widgetSpawnInits). */\n readonly props?: Readonly<Record<string, unknown>>;\n /** Adapter pointer id of the pressing pointer (default \"mouse\"). */\n readonly pointerId?: string;\n readonly device?: \"mouse\" | \"touch\" | \"pen\";\n /** PointerEvent.buttons at the press (default 1 = primary). */\n readonly buttons?: number;\n /**\n * Fly-back HOME in screen px (default: the press point). Apps that adopt\n * the drag AWAY from the tray (the deferred-spawn proxy pattern — the ghost\n * spawns at the tray-EXIT point) aim the cancel/reject return at the\n * persistent chrome (the toolbar) instead of a spot in open canvas.\n */\n readonly home?: { readonly x: number; readonly y: number };\n /**\n * Proportional GRAB POINT (0–1 within the widget rect; default center).\n * The grab point is the drag's INVARIANT (2026-07-19 polish): the spot\n * under the finger in the tray tile stays the same spot of the spawned\n * widget — the proxy→widget morph then composes as a pure scale about the\n * cursor, with no re-anchoring snap.\n */\n readonly anchor?: { readonly u: number; readonly v: number };\n}\n\nexport function insertByDrag(\n world: World,\n queue: InputQueue,\n type: string,\n opts: InsertByDragOpts,\n): Entity {\n const widget = widgetTypeFor(world, type);\n if (widget === undefined) throw new Error(`ice: insertByDrag — unknown widget type \"${type}\".`);\n\n const cam = world.getResource(Camera) ?? IDENTITY_CAM;\n const wp = screenToWorld(opts.screenX, opts.screenY, cam);\n const w = widget.defaultSize.w;\n const h = widget.defaultSize.h;\n // The pointer pins the ANCHOR point (proportional; default center — the\n // Figma/FigJam palette behavior). Grab latches the offset at claim, and\n // the ghost's zero dead zone (l2) keeps it pinned from the first move.\n const u = opts.anchor?.u ?? 0.5;\n const v = opts.anchor?.v ?? 0.5;\n const { prefab, overrides } = widgetSpawnInits(type, {\n x: wp.x - u * w,\n y: wp.y - v * h,\n w,\n h,\n ...(opts.props !== undefined ? { props: opts.props } : {}),\n }, widget);\n\n const ghost = instantiate(prefab, { into: \"world\", world }, { draft: true, overrides });\n world.addComponent(ghost, InsertGhost, {\n type,\n props: JSON.stringify(opts.props ?? {}),\n screenX: opts.home?.x ?? opts.screenX,\n screenY: opts.home?.y ?? opts.screenY,\n });\n for (const tag of widget.capabilityTags) {\n if (tag === LongPressDrag || tag === SweepsContained) continue;\n world.addTag(ghost, tag);\n }\n if (!world.hasTag(ghost, Movable)) world.addTag(ghost, Movable);\n world.addTag(ghost, WidgetEquipped);\n world.addTag(ghost, Active);\n const parent = frameParent(world);\n if (parent !== undefined) world.setRelation(ghost, ChildOf, parent, \"last\"); // topmost — the pick must hit IT\n\n queue.enqueue({\n kind: \"down\",\n pointerId: opts.pointerId ?? \"mouse\",\n device: opts.device ?? \"mouse\",\n screenX: opts.screenX,\n screenY: opts.screenY,\n buttons: opts.buttons ?? 1,\n mods: NO_MODS,\n });\n return ghost;\n}\n","/**\n * THE ENGINE'S DEVICE (design-012 §4 \"Device\"; kept as the device door at design-015 D5b, slimmed at D7): ONE device\n * per engine. An app that wants the device before the desk mounts — to read its uncaptured errors, to share it with\n * work of its own — acquires it here and passes it to `createCanvasEngine({ compositorDevice })`; the desk's layer then\n * DRAWS WITH IT (`createDeskHost` hands it through the layer context) instead of acquiring a device of its own, so\n * `errors()` sees the desk's uncaptured GPU errors. Absent — the common case, and every headless engine — the desk\n * acquires its own. The engine never destroys it: the app that acquired it owns its end of life.\n *\n * The error log subscribes with `addEventListener('uncapturederror')`, never the `onuncapturederror` property, so no\n * other holder of the device can disconnect it; it is armed HERE, before any consumer exists, so no error goes unseen.\n * (The three.js creation rules this module carried for the GL islands — no compatibility adapter, every advertised\n * feature — left with three at D7; `hasCoreFeatures`, three's compatibility-mode signal, with them.) ONE feature is asked\n * for whenever the adapter has it (design-016 §4, K2): `timestamp-query`, the GPU profiler's clock — a feature cannot be\n * added to a device once it is made, and one left unused costs nothing, so every engine's device can be profiled.\n *\n * Headless-safe: WebGPU is not DOM (it exists in workers), so naming it here does not breach core's wall. The only\n * environmental touch is reading `navigator.gpu`, and its absence is a clean typed failure, never a throw from deep\n * inside a layer. TYPES: `@webgpu/types` is the ONE entry in `tsconfig.base.json`'s `types` array, and a runtime-free\n * dependency of `@vibecook/ice`, so the published `.d.ts` resolves for consumers.\n */\n\nexport interface GpuUncapturedError {\n /** `performance.now()` at capture, or 0 where the clock is unavailable. */\n readonly at: number;\n readonly type: string;\n readonly message: string;\n}\n\n/** The engine's GPU facts. Reached as `engine.compositorDevice` — undefined unless the app passed one (the desk then acquires its own). */\nexport interface EngineGpu {\n readonly adapter: GPUAdapter;\n readonly device: GPUDevice;\n /** Features actually enabled on the device (not merely adapter-advertised). */\n readonly enabled: readonly string[];\n /** `timestamp-query` is on the device — asked for whenever the adapter has it (the GPU profiler's clock, design-016 §4). */\n readonly hasTimestampQuery: boolean;\n /** Uncaptured GPU errors since acquisition, newest last. */\n errors(): readonly GpuUncapturedError[];\n /** Release the device. The ENGINE NEVER CALLS THIS — nor does the desk's layer that drew with it: the app that acquired it owns its end of life. */\n destroy(): void;\n}\n\nexport interface AcquireDeviceOpts {\n /** Defaults to \"high-performance\" — the desk is the frame's fill cost. */\n readonly powerPreference?: GPUPowerPreference;\n /** Features to enable where the adapter has them, beside `timestamp-query` (always asked for where the adapter has it; the desk's drawing needs none). */\n readonly requiredFeatures?: readonly GPUFeatureName[];\n /** Cap the retained error log (defaults to 64). */\n readonly maxErrors?: number;\n}\n\nexport class GpuUnavailableError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"GpuUnavailableError\";\n }\n}\n\nconst now = (): number =>\n typeof performance !== \"undefined\" && typeof performance.now === \"function\" ? performance.now() : 0;\n\n/** The profiler's clock (design-016 §4, K2): asked for on every device the adapter can give it to. */\nconst PROFILER_FEATURES: readonly GPUFeatureName[] = [\"timestamp-query\"];\n\n/** What a device is asked for: the caller's features and the profiler's, each once, where the adapter has them. */\nfunction deviceFeatures(adapter: Pick<GPUAdapter, \"features\">, requested: readonly GPUFeatureName[] = []): GPUFeatureName[] {\n return [...new Set([...requested, ...PROFILER_FEATURES])].filter((f) => adapter.features.has(f));\n}\n\n/**\n * Acquire the engine's device. Called by the APP before `createCanvasEngine({ compositorDevice })`; the desk's layer\n * receives it from there. Throws {@link GpuUnavailableError} rather than returning a half-state.\n */\nexport async function acquireCompositorDevice(opts: AcquireDeviceOpts = {}): Promise<EngineGpu> {\n const gpu = (globalThis.navigator as { gpu?: GPU } | undefined)?.gpu;\n if (gpu == null) {\n throw new GpuUnavailableError(\"navigator.gpu is undefined — no WebGPU in this context\");\n }\n\n const adapter = await gpu.requestAdapter({\n powerPreference: opts.powerPreference ?? \"high-performance\",\n });\n if (adapter === null) throw new GpuUnavailableError(\"requestAdapter returned null\");\n const device = await adapter.requestDevice({\n label: \"ice\",\n requiredFeatures: deviceFeatures(adapter, opts.requiredFeatures),\n });\n\n // armed BEFORE any consumer, and via addEventListener so no later holder can disconnect it\n const maxErrors = opts.maxErrors ?? 64;\n const errors: GpuUncapturedError[] = [];\n device.addEventListener(\"uncapturederror\", (event) => {\n const err = (event as GPUUncapturedErrorEvent).error as { message?: string } | undefined;\n const entry: GpuUncapturedError = {\n at: now(),\n type: err?.constructor?.name ?? \"GPUError\",\n message: err?.message ?? \"unknown\",\n };\n errors.push(entry);\n if (errors.length > maxErrors) errors.splice(0, errors.length - maxErrors);\n console.error(\"[ice] uncaptured GPU error\", entry.type, entry.message);\n });\n\n return {\n adapter,\n device,\n enabled: [...device.features].sort(),\n hasTimestampQuery: device.features.has(\"timestamp-query\"),\n errors: () => errors,\n destroy: () => device.destroy(),\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 */\n// Informational only; must track packages/ice/package.json version on publish.\nexport const CORE_VERSION = \"0.11.0\";\n\nexport { defineSchemaOnce, hmrInvalidateOnSchemaChange } from \"./boot/hmr\";\n\n// Strata surface re-exported for downstream packages: dom/react/desk reach\n// strata ONLY through core (design-002 §6 — strata is core's sole runtime\n// dependency; the import walls make a direct dep a CI failure).\nexport {\n All,\n Any,\n Not,\n Related,\n createWorld,\n defineQuery,\n defineSystem,\n defineTickSystem,\n enumOf,\n field,\n // Query-only for apps (`Not(Local)` = remote presence peers); strata-owned,\n // auto-applied by the ephemeral store on spawn, never transmitted.\n Local,\n} from \"@vibecook/strata-ecs\";\nexport type {\n Batch,\n Component,\n Condition,\n Entity,\n OrderPlace,\n Pipeline,\n Query,\n Relation,\n Resource,\n System,\n SystemCtx,\n Tag,\n TickSystem,\n World,\n} from \"@vibecook/strata-ecs\";\n\n// Schema wrappers (record metadata, delegate to strata) + registries.\nexport {\n defineComponent,\n defineRelation,\n defineResource,\n defineTag,\n schemaMeta,\n type ComponentMeta,\n type RawSchema,\n type RelationMeta,\n type ResourceMeta,\n} from \"./schema/meta\";\n\n// Prefabs — sovereignty at the entity level (design-001 §2).\n// (__resetPrefabsForTests is deliberately NOT re-exported — test-only, import from the module.)\nexport {\n definePrefab,\n init,\n PrefabId,\n prefabs,\n type ComponentInit,\n type FieldWrite,\n type Prefab,\n type PrefabClass,\n type PrefabDef,\n} from \"./schema/prefab\";\n\n// Spawn routing (the class IS the spawn path).\nexport { instantiate, type EphSpawner, type SpawnTarget } from \"./engine/instantiate\";\n\n// The frame contract (design-002): FrameInfo clock, phase-group pipeline,\n// reflector registry, and the engine facade that owns step(now).\nexport { FrameInfo, setFrameInfo } from \"./engine/frame-info\";\nexport { createPipelineRegistry, PHASE_GROUPS, type AnySystem, type PhaseGroup, type PipelineRegistry } from \"./engine/pipeline\";\nexport {\n createReflectorRegistry,\n type ReflectorDef,\n type ReflectorObserve,\n type ReflectorQuerySpec,\n type ReflectorRegistry,\n} from \"./engine/reflectors\";\nexport {\n createEngine,\n type Engine,\n type EngineOpts,\n type FrameTelemetry,\n type PublishHook,\n type SystemRunRecord,\n} from \"./engine/engine\";\nexport { createFrameControl, SETTLE_CAP, SLEEP_TAIL, type FrameControl, type SleepStats } from \"./engine/frame-control\";\nexport { interactionPending } from \"./interaction/wakes\";\n// The guest runtime (petition I14): the named frame slot for work the engine\n// did not write, under a circuit breaker. The behavior framework compiles onto\n// it (design-009); hosts reach it as `engine.guests`.\nexport {\n createGuestRegistry,\n GUEST_BUDGET,\n type GuestFactory,\n type GuestFrame,\n type GuestGeneration,\n type GuestInstance,\n type GuestLedgerRecord,\n type GuestRegistry,\n type GuestRegistryOpts,\n type GuestRun,\n type GuestSpec,\n type GuestStatus,\n} from \"./engine/guests\";\n\n// --- The behavior framework (design-009): ICE's SECOND product surface -------\n// `defineWidget` (faces) · `defineBehavior` (logic + state) · `defineTool`\n// (input policy). `store:` routes everything — where data lives, who sees it,\n// what survives, which write vocabulary the hooks receive, at which cadence.\nexport { behaviors, defineBehavior, describeBehavior } from \"./behavior/define-behavior\";\n// The runtime itself, for IMPERATIVE hosts (2026-09-06, design-013 D7).\n// `createCanvasEngine` builds one and registers the app's behaviours into it,\n// so a facade app never names this; a host that drives the raw engine — the\n// rigs, a headless trace — needs the factory to have a runtime to register\n// into at all.\nexport { createBehaviorRuntime } from \"./behavior/runtime\";\nexport type {\n BehaviorPresence,\n BehaviorRegistrationOptions,\n BehaviorRuntime,\n BehaviorRuntimeOpts,\n BehaviorSession,\n} from \"./behavior/runtime\";\nexport {\n BEHAVIOR_DEFAULT_PHASE,\n BEHAVIOR_PHASES,\n type AnyBehaviorAttachSpec,\n type AnyBehaviorDef,\n type BehaviorAttachSpec,\n type BehaviorChanges,\n type BehaviorCtxBase,\n type BehaviorCtxFor,\n type BehaviorDescription,\n type BehaviorFrame,\n type BehaviorHandle,\n type BehaviorHookName,\n type BehaviorHooks,\n type BehaviorPhase,\n type BehaviorPropDescription,\n type BehaviorQuery,\n type BehaviorQuerySpec,\n type BehaviorRead,\n type BehaviorReadDescription,\n type BehaviorSchema,\n type BehaviorSpec,\n type BehaviorStore,\n type BehaviorTx,\n type BehaviorWorld,\n type DataOf,\n type DurableBehaviorCtx,\n type EphemeralBehaviorCtx,\n type PeerFacet,\n type RuntimeBehaviorCtx,\n} from \"./behavior/types\";\nexport { compileBehavior, isDurableEligible, type CompiledBehavior } from \"./behavior/compile\";\nexport {\n behaviorMarkerKey,\n classifyBehaviorVersion,\n docBehaviorVersion,\n stampBehaviorMarker,\n BEHAVIOR_MARKER_PREFIX,\n type BehaviorMeta,\n type BehaviorVerdict,\n} from \"./behavior/migrate\";\n// The testing rig ships WITH the framework, not after it (design-009 §7).\nexport {\n createBehaviorHarness,\n type BehaviorHarness,\n type BehaviorHarnessOpts,\n type HarnessCommit,\n} from \"./behavior/harness\";\n\n// Write-path guards.\nexport { devGuardsEnabled, setDevGuards } from \"./guards/dev\";\nexport { createLiveWriter, type LiveWriter, type LiveWriterOpts } from \"./guards/live-writer\";\nexport { guardedTransaction, type GuardedTx, type GuardedTxOpts } from \"./guards/guarded-tx\";\nexport { writeRuntimeResource } from \"./guards/resource-writer\";\n\n// The component/tag/relation/resource catalog (design-001 §5, faithful transcription).\nexport * from \"./catalog\";\n\n// Engine helpers: PhaseSet + Just* markers (design-003 §4.2), version stamps (design-002 §4).\nexport * from \"./helpers/phase-set\";\nexport * from \"./helpers/version-stamps\";\n// The drain-in-runIf idiom (petition I15): a change-collector gate that stashes\n// its delta for the body, so a skipped system stamps NOTHING (design-002 §4's\n// guard rule). Engine-internal since M6; exported because every derived\n// consumer outside core — plugin systems, and the behavior framework's own\n// delivery loop — needs exactly this and would otherwise hand-roll it.\nexport * from \"./helpers/churn-guard\";\n// Catalog-adjacent ops (app-handler write paths).\nexport * from \"./ops/arrange\";\nexport * from \"./ops/selection\";\nexport * from \"./ops/cascade\";\nexport * from \"./ops/claims\";\nexport * from \"./ops/gestures\";\nexport * from \"./ops/point-pick\";\n// Sibling order (petition 8): THE per-frame stacking source — frame parent,\n// pull-based ordinal cache, and the one comparator paint/pick/drop share.\nexport * from \"./ops/sibling-order\";\n// Port-schema → kernel PortSlot resolution (2026-07-16: exported for a wires\n// pass — rendered and picked anchors agree by construction).\nexport { portSlots, portSlotOf } from \"./ops/port-geometry\";\n\n// The interaction stack (design-003): input queue, commit seam, install.\nexport { createInputQueue, NO_MODS, type InputEvent, type InputEventKind, type InputMods, type InputQueue } from \"./input/queue\";\nexport {\n createRecordingCommitSink,\n type CommitIntent,\n type CommitCreate,\n type CommitOrder,\n type CommitReparent,\n type CommitSink,\n type CommitWrite,\n} from \"./engine/commit-sink\";\nexport {\n ensureCanvasSurface,\n installInteractionCore,\n installInteractionStack,\n type InteractionCore,\n type InteractionCoreOpts,\n type InteractionStack,\n} from \"./interaction/install\";\nexport { anyGestureNonTerminal, isMidGesture } from \"./interaction/gesture-status\";\nexport type { MarqueeBuffer } from \"./systems/l3-marquee\";\nexport { DEFAULT_SPAWN_PROFILES, type SingleKindName, type SpawnProfiles } from \"./systems/l2-recognize\";\nexport { createCursorSync } from \"./systems/l4-cursor\";\n// M8 node-editor core (design-004 §6, design-003 §5.8): wire sync, port\n// materialization, connect gesture + its out-of-ECS preview buffer.\nexport { createWireSync, type WireSyncSystem } from \"./systems/l1-wires\";\nexport { createPortMaterialize } from \"./systems/l3-ports\";\nexport {\n createConnectSystems,\n type ConnectSystems,\n type WirePreviewBuffer,\n} from \"./systems/l3-connect\";\n\n// The doc kit (design-001 §6, design-005 §6): envelope, version gate, sessions.\nexport {\n ENGINE_SCHEMA_VERSION,\n ENVELOPE_MAGIC,\n ENVELOPE_VERSION,\n EnvelopeError,\n decodeEnvelope,\n encodeEnvelope,\n type EnvelopeHeader,\n} from \"./doc/envelope\";\nexport {\n gateVerdict,\n readEnvelopeVersionReport,\n readDocVersionReport,\n stampEngineMeta,\n type DocVersionScope,\n type DocVersionReport,\n type GateVerdict,\n} from \"./doc/version-gate\";\nexport { type CommitExtender, 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, the cull.\nexport { p, type JsonShape, type PropSpec, type PropsDecl, type StandardSchemaV1 } from \"./widget/props\";\nexport {\n WidgetEquipped,\n defineWidget,\n renames,\n widgets,\n type WidgetDef,\n type WidgetGroup,\n type WidgetInteraction,\n type WidgetContainerDef,\n type WidgetContainerEntry,\n type WidgetPortalInsets,\n type WidgetPortDecl,\n type WidgetBehaviorDecl,\n type WidgetBehaviorEntry,\n type WidgetRename,\n type WidgetRenameEntry,\n type WidgetType,\n type TrayEntry,\n trayTakeProps,\n} from \"./widget/define-widget\";\n// design-015 §8 (D3t-a): the held bar's tools — a mode (`HeldTool`, the tool in hand) or an action (an op), with its keys\nexport { type HeldGlyph, type HeldToolApi, type HeldToolDef, type HeldToolState, type HeldToolStateContext, isHeldGlyph, type KeyChord, keyMatches, matchHeldTool, readHeldToolState } from \"./widget/held-tools\";\nexport { type MenuActionApi, type MenuActionDef, menuActionsFor } from \"./widget/menu-actions\";\n\n// --- Canvas SDK: typed frame definitions, engine authority, and placement ---\nexport {\n DefaultCanvasType,\n ROOT_CANVAS_META_KEY,\n canvasIdentityOf,\n canvasPackId,\n canvasTypes,\n contributeCanvasCatalog,\n defineCanvasType,\n encodeCanvasIdentity,\n parseCanvasIdentity,\n sameCanvasIdentity,\n type CanvasCatalogSection,\n type CanvasCatalogContribution,\n type CanvasPlacementDef,\n type CanvasType,\n type CanvasTypeDef,\n type CanvasTypeIdentity,\n} from \"./canvas/define-canvas-type\";\nexport {\n defineContainer,\n type ContainerDef,\n type ContainerIngressDef,\n} from \"./canvas/define-container\";\nexport {\n bindEngineCatalog,\n compileEngineCatalog,\n dataPrefabFor,\n durablePrefabFor,\n engineCatalogFor,\n resolveToolFor,\n toolTypeFor,\n widgetTypeFor,\n type EngineCatalog,\n type EngineCatalogCompileOpts,\n} from \"./canvas/engine-catalog\";\nexport {\n createPlacementAuthority,\n type PlacementAuthority,\n type PlacementAuthorityOpts,\n type PlacementDecision,\n type PlacementReason,\n} from \"./canvas/placement\";\nexport {\n CanvasIntentScope,\n CanvasSession,\n createCanvasSessionController,\n type CanvasSessionController,\n type CanvasSessionValue,\n} from \"./canvas/session\";\nexport {\n collectCanvasDiagnostics,\n type CanvasDiagnostic,\n type CanvasDiagnosticCode,\n type CanvasDiagnosticSnapshot,\n} from \"./canvas/diagnostics\";\nexport {\n resolveFrameChildren,\n resolveFrameView,\n resolvePortal,\n type CanvasRect,\n type FrameChildrenOpts,\n type ResolvedFrameView,\n type ResolvedPortal,\n} from \"./canvas/frame-view\";\nexport {\n defineFrameProjection,\n frameProjections,\n type CanvasPreviewDeclaration,\n type FrameProjection,\n type FrameProjectionChildRef,\n type FrameProjectionContext,\n type FrameProjectionDef,\n type FrameProjectionRelationRow,\n} from \"./canvas/frame-projection\";\nexport {\n createFramePreviewStore,\n FRAME_PREVIEW_DEFAULT_BYTES,\n FRAME_PREVIEW_DEFAULT_CHILDREN,\n FRAME_PREVIEW_MAX_BYTES,\n FRAME_PREVIEW_MAX_CHILDREN,\n FRAME_PREVIEW_MIN_BYTES,\n type FramePreviewBudgets,\n type FramePreviewChild,\n type FramePreviewSnapshot,\n type FramePreviewStats,\n type FramePreviewStore,\n type FramePreviewStoreOpts,\n type FramePreviewValidity,\n} from \"./canvas/frame-preview\";\nexport {\n createPresentationTransitionCoordinator,\n type FrameSwitchDescriptor,\n type FrameSwitchRequest,\n type PreparedFrameSwitch,\n type PresentationMotion,\n type PresentationPlane,\n type PresentationReleaseReason,\n type PresentationRetainer,\n type PresentationTransitionAdapter,\n type PresentationTransitionCoordinator,\n type PresentationTransitionFrame,\n type PresentationTransitionStats,\n} from \"./canvas/presentation-transition\";\nexport {\n canvasRuntimeExtensions,\n defineCanvasRuntimeExtension,\n defineFrameBehavior,\n frameBehaviorPackId,\n frameBehaviors,\n type CanvasReadFacet,\n type CanvasRuntimeChanges,\n type CanvasRuntimeExtension,\n type CanvasRuntimeExtensionContext,\n type CanvasRuntimeExtensionDef,\n type CanvasScopedReader,\n type CanvasSemanticMigration,\n type CanvasSemanticMigrationContext,\n type ExistingPlacementPosture,\n type FrameBehavior,\n type FrameBehaviorDef,\n type FrameBehaviorWriteContext,\n} from \"./canvas/extensions\";\nexport { createWidgetEquipSystem } from \"./widget/equip\";\nexport { attachSpawnBehaviors, attachSpawnParent, spawnWidget, widgetSpawnInits, type SpawnWidgetOpts } from \"./widget/spawn\";\n// The frame pick source (design-014, B3b): the ground layer's hit test on the interaction stack — and what the stack's exact pick\n// out of the tick answers (`InteractionStack.pickAt`, petition I27).\nexport type { FramePickSlot, FramePickSource, PointPick } from \"./systems/l1-pick\";\nexport { setWidgetProps } from \"./widget/set-props\";\nexport { createWidgetRuntime, installWidgetRuntime, type WidgetRuntime } from \"./widget/mount-store\";\n\n// Reviewed default constants (citations point at the owning design sections).\nexport * from \"./settings/defaults\";\n// (The ground-layer pass configs — GridConfig, WiresConfig, SnapGuidesConfig, GridMagnetConfig and their\n// DEFAULT_*s — left at design-015 D7: nothing read them after D5b; the desk's grid is its own, `@ice/desk`'s GridConfig.)\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.\n// `WheelZoomStep` (design-015 §9, D2a-core): this frame's wheel zoom, for the\n// systems after cameraControl (D2b's zoom-through).\nexport { CameraInertia, CameraZoomStep, WheelZoomStep, 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// --- chrome + breakpoints (design-004 §5 chrome, §8 LOD; measurement left at design-015 D5b) ---\nexport { createBreakpointSystem, createSelectionChromeSystem } from \"./systems/chrome\";\n\n// --- M8 nested canvas (design-004 §7): membership, nav ops, integrity ---\nexport {\n createActiveMembership,\n createNestedCanvas,\n currentNavEntry,\n currentNavFrame,\n type NavOpts,\n type NestedCanvas,\n type NestedCanvasOpts,\n} from \"./nav/nested-canvas\";\n// design-015 §9 (D2b): the nav geometry seam — the renderer's word on a container's DRAWN face\n// (`stack.navGeometry`), core's fallback, the in-tick nav request and the re-dressing fact.\nexport {\n defaultArrivalCamera,\n fallbackNavFace,\n type NavFace,\n type NavGeometrySlot,\n type NavGeometrySource,\n NavIntent,\n NavRedress,\n resolveNavFace,\n smoothstep,\n staticFace,\n} from \"./nav/nav-geometry\";\nexport { createNavTap, NavTapMemo, type NavTapOpts } from \"./systems/nav-tap\";\n// design-015 §8 (D4b): the held input — the pose seam (`stack.heldPose`), the hand's numbers, the held object.\nexport { createHeldInput, heldEntity, HOLD_INPUT, type HeldPoseSlot, type HeldPoseSource, type HeldScreenFrame } from \"./systems/held\";\nexport { createPressWheel } from \"./systems/press-wheel\";\n// design-017 (K3): the pegboard tray's input — the pose seam (`stack.trayPose`), its numbers, the band's arithmetic — and its ops;\n// design-018 §6 (R2): its category (the filter) and the categories its frame hangs.\nexport { createTrayInput, createTrayLay, hungTypes, scrollBy, specimensOf, TRAY_INPUT, type TrayPoseSlot, type TrayPoseSource, type TrayScreenFrame } from \"./systems/tray\";\nexport { closeTray, ensureTray, focusTray, openTray, scrollTray, setTrayCategory, toggleTray, trayCategories, trayCategory, type TrayCategory, trayEntity, trayEntryCount, trayFocus, type TrayFocusMove, trayHung, trayOpen } from \"./ops/tray\";\nexport { createZoomThrough, type ZoomThroughOpts } from \"./systems/zoom-through\";\n// design-006 T1: the flight resource (T2's reflector consumes it) + system factory.\nexport {\n abortNavFlight,\n createNavFlight,\n departedCameraOf,\n type DepartedCameraInputs,\n navFlightActive,\n NavTransition,\n publishNavCut,\n startNavFlight,\n type NavTransitionIdentity,\n} from \"./systems/nav-flight\";\n\n// --- M9 presence layer (design-005 §6.5, design-001 §5.6) ---\nexport {\n attachPresence,\n createPresencePublish,\n createRemoteCursorsSystem,\n DEFAULT_PRESENCE_TTL_MS,\n installPresence,\n presenceCanvasOf,\n type InstallPresenceOpts,\n type PresenceOpts,\n type PresencePublishOpts,\n type PresenceSession,\n type RemoteCursorsOpts,\n} from \"./presence\";\n\n// --- M9 transport/bootstrap kit (design-005 §6.5): join protocol + byte channels ---\nexport {\n joinDoc,\n offerBase,\n type BootstrapClock,\n type JoinDocOpts,\n type JoinResult,\n} from \"./doc/bootstrap\";\nexport {\n broadcastChannelByteChannel,\n webSocketByteChannel,\n type ByteChannel,\n type OwnedByteChannel,\n type WebSocketLike,\n} from \"./doc/channels\";\n\n// --- M10 published facade (design-005 §3-§4): tools + createCanvasEngine ---\nexport {\n createDrawTool,\n defineTool,\n tools,\n type CanvasDragRoute,\n type Tool,\n type ToolDef,\n type ToolGates,\n type ToolRoute,\n type WidgetDragRoute,\n} from \"./tools/define-tool\";\nexport {\n createCanvasEngine,\n type CanvasDocs,\n type CanvasEngine,\n type CanvasEngineOpts,\n type CurrentCanvasScope,\n type StageControl,\n type CanvasOps,\n} from \"./facade/create-canvas-engine\";\nexport { createDrawBehavior } from \"./systems/l3-draw\";\n\n// --- the GPU device door (design-012 §4, slimmed at design-015 D5b and D7) ---\n// `acquireCompositorDevice` is the one WebGPU touch in core: the engine's device,\n// passed as `createCanvasEngine({ compositorDevice })`, the desk draws with. The\n// surface vocabulary, the infra trio (Band · Demand · Residency), the residency\n// module, three's backend-texture read and the three standard surface\n// behaviours that used to follow it here left with the DOM/GPU presentation\n// choice (design-015 §1: nothing presents anywhere but the desk).\nexport {\n acquireCompositorDevice,\n GpuUnavailableError,\n type AcquireDeviceOpts,\n type EngineGpu,\n type GpuUncapturedError,\n} from \"./surface/gpu-device\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAQO,SAAS,iBAAoB,KAAaA,QAAmB;AAClE,QAAM,IAAI;AACV,IAAE,iBAAiB,oBAAI,IAAqB;AAC5C,QAAM,MAAM,EAAE;AACd,MAAI,CAAC,IAAI,IAAI,GAAG,EAAG,KAAI,IAAI,KAAKA,OAAM,CAAC;AACvC,SAAO,IAAI,IAAI,GAAG;AACpB;AAEO,SAAS,4BAA4B,KAA+C;AACzF,OAAK,WAAW;AAClB;;;ACRA;AAAA,EACE,mBAAmB;AAAA,EACnB,kBAAkB;AAAA,EAClB,kBAAkB;AAAA,EAClB,aAAa;AAAA,OAMR;AA0BP,IAAM,gBAAgB,oBAAI,IAA8B;AACxD,IAAM,sBAAsB,oBAAI,IAAuB;AACvD,IAAM,WAAW,oBAAI,IAAiB;AACtC,IAAM,eAAe,oBAAI,IAA4B;AACrD,IAAM,eAAe,oBAAI,IAA4B;AAErD,SAAS,WAAW,OAA4B;AAC9C,MAAI,UAAU,MAAO,QAAO;AAC5B,SACE,OAAO,UAAU,YACjB,UAAU,QACT,MAA6B,SAAS;AAE3C;AAEA,SAAS,WAAW,OAA4B;AAG9C,SAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,aAAa;AACrE;AAEO,SAAS,gBACd,MACA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,mBAAmB,OAAO,SAAS,IAAI,iBAAiB;AAAA,IACxD,QAAQ,MAAM;AAAA,IACd,SAAS,MAAM,OAAO,QAAQ;AAAA,EAChC;AACF;;;AClGA;AAAA,EACE;AAAA,EACA,OAAAE;AAAA,EACA,OAAAC;AAAA,EACA,WAAAC;AAAA,EACA,eAAAC;AAAA,EACA,eAAAC;AAAA,EACA,gBAAAC;AAAA,EACA,oBAAAC;AAAA,EACA,UAAAC;AAAA,EACA,SAAAC;AAAA,EAGA,SAAAC;AAAA,OACK;AAkPP,SAAS,yBAAyB;AAvQ3B,IAAM,eAAe;","names":["build","now","field","field","now","record","frame","ms","frame","now","enumOf","field","field","enumOf","phase","next","field","field","enumOf","field","enumOf","field","field","field","enumOf","field","enumOf","field","field","field","enumOf","field","field","enumOf","enumOf","field","field","enumOf","field","field","next","defineQuery","defineTickSystem","enumOf","field","field","enumOf","defineQuery","frame","defineTickSystem","p","defineQuery","defineQuery","now","validate","field","enumOf","registry","field","enumOf","phase","fail","bytes","registry","registry","tools","field","enumOf","registry","strataFieldOf","field","enumOf","fail","why","given","p","registry","uniqueStrings","registry","next","p","init","live","defineQuery","defineSystem","defineTickSystem","p","defineTickSystem","defineQuery","defineSystem","Not","defineQuery","valueEquals","build","byComponent","Not","defineQuery","defineQuery","Not","defineQuery","Not","now","p","frame","valueEquals","bytes","frame","field","enumOf","frame","field","enumOf","defineQuery","defineTickSystem","defineQuery","frame","defineTickSystem","deepest","defineQuery","frame","defineQuery","defineQuery","defineTickSystem","defineQuery","defineTickSystem","enumOf","field","field","enumOf","frame","Any","Not","defineQuery","defineSystem","defineQuery","defineQuery","p","defineQuery","Any","Not","pinchQ","P","defineSystem","now","p","down","defineQuery","defineQuery","next","defineQuery","defineSystem","defineTickSystem","P","defineQuery","defineSystem","defineTickSystem","defineQuery","defineTickSystem","defineQuery","connectDragQ","compatible","defineTickSystem","now","p","dist","defineQuery","defineTickSystem","p","selectedQ","defineQuery","defineTickSystem","idx","defineQuery","defineSystem","P","defineQuery","defineSystem","defineQuery","defineSystem","P","defineQuery","p","defineSystem","defineQuery","defineSystem","heldQ","defineQuery","localPointerQ","defineSystem","now","p","frame","gs","next","defineQuery","defineSystem","defineQuery","defineSystem","p","watchers","defineQuery","defineSystem","defineTickSystem","trayQ","defineQuery","localPointerQ","p","next","defineSystem","frame","now","ended","defineTickSystem","t","defineQuery","trayQ","defineQuery","next","presentOf","defineQuery","defineSystem","field","field","defineQuery","defineSystem","gs","now","defineQuery","defineTickSystem","defineQuery","defineTickSystem","frame","defineQuery","Any","defineQuery","defineSystem","P","anyKindQ","defineQuery","Any","defineSystem","defineQuery","defineSystem","defineTickSystem","pointerQ","defineQuery","defineSystem","defineTickSystem","defineQuery","defineSystem","defineTickSystem","Not","IDENTITY_CAM","defineQuery","trayQ","Not","pointerQ","p","defineTickSystem","next","ordinals","defineSystem","cur","Any","Not","defineQuery","defineSystem","defineTickSystem","P","defineQuery","Any","Not","isTerminal","defineTickSystem","defineSystem","defineQuery","defineSystem","defineQuery","defineSystem","defineQuery","defineSystem","p","P","tapRecognizedQ","defineQuery","IDENTITY_CAM","defineSystem","defineQuery","defineSystem","P","defineQuery","p","defineSystem","defineQuery","defineTickSystem","P","IDENTITY_CAM","canvasSurfaceQ","defineQuery","longPressQ","next","defineTickSystem","defineQuery","defineSystem","P","defineQuery","defineSystem","defineQuery","defineTickSystem","defineQuery","defineTickSystem","enabled","defineQuery","defineSystem","P","defineQuery","isTerminal","defineSystem","canvasSurfaceQ","defineQuery","behaviors","bytes","version","defineQuery","defineQuery","next","PACK_PREFIX","p","defineQuery","valueEquals","PACK_PREFIX","defineQuery","frame","valueEquals","defineQuery","PACK_PREFIX","RENAMED_PREFIX","allDurableQ","defineQuery","Any","defineQuery","RENAMED_PREFIX","defineQuery","Any","watchers","defineQuery","SCHEMA_PREFIX","PACK_PREFIX","allDurableQ","defineQuery","bytes","defineQuery","bytes","defineQuery","defineQuery","defineQuery","wireQ","p","next","Any","defineQuery","defineQuery","Any","P","fail","frame","defineQuery","durableQ","defineQuery","frame","Related","defineQuery","frame","build","value","next","defineQuery","Related","frame","Not","defineQuery","defineSystem","defineQuery","Not","defineSystem","defineQuery","defineTickSystem","defineQuery","frame","defineTickSystem","p","now","bytes","bytes","bytes","defineQuery","defineQuery","frame","p","Not","defineQuery","defineTickSystem","Local","defineQuery","Not","Local","defineTickSystem","utf8","fail","bytes","bytes","createWorld","defineQuery","Related","defineQuery","valueEquals","valueEquals","defineQuery","Related","Related","defineQuery","valueEquals","durableQ","defineQuery","partition","frame","validFrame","Related","planFrame","applyOps","valueEquals","next","IDENTITY_CAM","defineQuery","tweenQ","createWorld","frame","opts","next","write","p","bytes","behaviors","now","Any","Not","Related","createWorld","defineQuery","defineSystem","defineTickSystem","enumOf","field","Local"]}