# Plethora Bit SDK

Context version: plethora-agent-context-2026-10-22.1

**Fetch the current context first, every time.** At the start of every new Bit, and again right before every upload, fetch https://agent.plethora.studio/v1/agent/context.md and note its Version (also `contextVersion` in https://agent.plethora.studio/v1/agent/context.json). Do not build from an SDK, context, schema, template, skill or memory kept from an earlier chat or an earlier Bit: the contract changes, and Plethora only publishes full-screen Bits (`"display": "fullscreen"`). Send the version you built against as `agentFeedback.contextVersion`; an upload built against an older context is refused with 409 `context_outdated` and nothing is saved.

**Deliver:** pair with the creator (https://agent.plethora.studio/v1/agent/start.md), then upload the Bit as a draft (https://agent.plethora.studio/v1/agent/upload.md).

The complete public SDK in one read. Follow [creation](https://agent.plethora.studio/v1/agent/creation.md) and [fundamentals](https://agent.plethora.studio/v1/agent/fundamentals.md) for the process and environment. Topic pages are focused projections, not additional hidden APIs. If a tool truncates this response, retrieve the missing chapters before claiming complete coverage.

## Contract Source Of Truth

This section is generated from the executable bit contract. If it disagrees with `/v1/agent/schema.json`, stop and report contract drift.

- Runtime: plethora-bit@2
- SDK version: 1.8.0
- Manifest schema version: 1
- Runtime global: `window.plethoraBit`
- Entry default: `main.js`
- Package size limit: 2097152 bytes
- Packaged assets: max 0
- Approved library host: libs.plethora.studio
- Permissions: `audio`, `backgroundMusic`, `camera`, `haptics`, `microphone`, `motion`, `storage`
- Memory families: `local`, `records`, `tallies`, `worlds`
- Game progress: optional `manifest.game.progress`, max 8 channels, 8192 bytes per saved state
- Creator tuning: optional `manifest.tuning`, max 32 knobs and 8 curves
- First-use onboarding: required for new Bits, optional for legacy compatibility; `immersive`, `one_line`, `guided`, or `briefing`
- Display: `manifest.display` (`"fullscreen"`) is required to publish, for a first publish and every new version: every Bit declares `"fullscreen"`, gets the whole screen and lays out text and controls from `ctx.contentSafeArea ?? ctx.safeArea`. A draft without it is still saved (with the `display_not_fullscreen` notice), but publishing refuses it with 422 `display_fullscreen_required`. Bits published before this rule keep playing in the legacy safe frame. Any other value, null included, is rejected with a 400 (`E_MANIFEST_DISPLAY`)


## SDK Reference

SDK 1.8.0; runtime plethora-bit@2; manifest schema 1.

Entry: `window.plethoraBit = { meta?, async init(ctx) {} }`. Compatibility global: `window.scrollerApp`.

This complete reference includes public calls, options, return handles, lifecycle and failure behavior. Focused topic pages project the same capability entries. Compatibility aliases are retained; unavailable and host-restricted surfaces are labeled explicitly.

### Contents

- [Runtime Metadata and Readiness](#sdk-runtime)
- [DOM, Canvas and Surface Composition](#sdk-surfaces)
- [Visual Feedback and Transitions](#sdk-fx)
- [Palettes, Kits, Textures, Materials and Sprites](#sdk-visual)
- [Creator Tuning](#sdk-tune)
- [First-Use Onboarding](#sdk-onboarding)
- [Pointers, Gestures and Input Helpers](#sdk-input)
- [Loops, Timers, State Machines, Scores and Progress](#sdk-game)
- [Math, Random, Noise and Color](#sdk-math)
- [Geometry, Paths and Spatial Queries](#sdk-geometry)
- [Platform Lifecycle and Haptics](#sdk-lifecycle)
- [Pulse Completion and Sharing](#sdk-pulse)
- [Events, Frames, Timers and Cleanup](#sdk-eventsandframes)
- [Libraries, Fonts and Verified Resources](#sdk-libraries)
- [Music and Sound](#sdk-audio)
- [Camera, Microphone and Audio Reactivity](#sdk-media)
- [Camera Availability and Placement](#sdk-camera)
- [Microphone Privacy and Permissions](#sdk-microphone)
- [Synchronous Storage and Raw Sensor Compatibility](#sdk-storageandmotion)
- [Local Storage Boundaries](#sdk-storage)
- [Motion, Calibration and Sensor Events](#sdk-motion)
- [Local Memory, Records, Tallies and Shared Worlds](#sdk-memory)
- [Unavailable Packaged Assets](#sdk-assets)
- [Legacy Anti-Patterns and Safety Reminders](#sdk-antipatterns)

### Applicable SDK Rules

- Treat this SDK reference as the complete public surface. Do not invent ctx methods, manifest fields, endpoints, or response keys.
- Prefer ctx.input for pointer/touch/click-like interaction. Use ctx.listen as the raw escape hatch for unusual DOM/library events, but keep cleanup owned by ctx. Do not assume complex interactions are impossible; advanced collision, physics, raycasting, spatial indexes, and library-specific controls remain creator/library territory.
- Prefer ctx.game.loop for custom continuous motion, fixed-step physics/collisions, stable dt-based animation, timers, cooldowns, and tiny state machines. Library-owned tickers are still fine when a renderer owns the loop; do not run raw recursive requestAnimationFrame loops.
- For numeric run state, prefer ctx.game.score. Mutate it locally during play and submit one declared record only at a meaningful result or checkpoint; do not write records from every tap, frame, or collision.
- For resumable games, declare manifest.game.progress and use ctx.game.progress. Save only at meaningful checkpoints such as level changes, generated puzzle seed, inventory/room transitions, or chapter unlocks; never save from an animation frame or ordinary every-tap path. This is viewer-private Continue Playing state, not shared-device/pass-and-play party state.
- Use ctx.math for common scalar/vector/random/noise/easing work and ctx.geometry for common 2D shape/path work. These are helpers, not capability ceilings: serious physics, CAD, 3D raycasting, shader systems, renderer controls, and library-specific systems remain available through creator code or approved libraries.
- Use ctx.visual.palette/kit for color and style tokens, ctx.visual.texture for deterministic procedural surface detail, ctx.visual.material for renderer-neutral surface recipes, and ctx.visual.sprite for reusable local procedural sprite handles. For kit style, prefer categorical style axes plus numeric axes over a lone mood preset; mood is only shorthand. These helpers are optional craft tools, not a house style, asset system, renderer, scene graph, or replacement for custom art direction.
- Use ctx.onResize(layout, { immediate: true }) for resize/orientation-safe layout. Raw resize listeners through ctx.listen are still available for unusual library interop, but normal layout should use the cleanup-owned SDK hook.
- Use ctx.pulse.complete(options?) when a game, puzzle, level, or achievement should create an implicit Pulsegraph completion post. Use ctx.platform.complete(payload?) only for lifecycle/analytics unless payload.pulse explicitly opts in.

<a id="sdk-runtime"></a>

### Runtime Metadata and Readiness

- ctx.container -> HTMLElement owned by Plethora. Read-only target; prefer ctx.createRoot/createCanvas2D/createCanvas instead of appending directly.
- ctx.width, ctx.height -> current container size in CSS pixels. Use them for CSS-coordinate layout/drawing. canvas.width/canvas.height are raw backing-store dimensions and may differ when maxDpr is set on a Canvas2D surface.
- ctx.dpr and ctx.nativeDpr -> runtime/browser DPR metadata. A Canvas2D maxDpr opt-in can cap one canvas backing store below either value.
- manifest.display: "fullscreen" is required to publish (a first publish and every new version): every Bit declares it. It gives the Bit the whole screen: its container covers the phone screen edge to edge (402x874 on an iPhone 17 Pro) and Plethora's logo button floats over the bottom centre. A draft saved without it is kept, but publishing refuses it with 422 display_fullscreen_required (E_DISPLAY_FULLSCREEN_REQUIRED in the package contract). Two cases still play in the legacy safe frame between the camera cutout and the home indicator, with the legacy ctx.safeArea: Bits published before this rule, and any Bit on an app version from before full-screen support, so keep the fallbacks below. Any other display value, null included, is rejected: the upload answers 400 bad_request, saying Manifest display must be "fullscreen" when present (E_MANIFEST_DISPLAY in the package contract).
- ctx.safeArea -> { top, right, bottom, left } in CSS pixels. In a full-screen Bit these are the phone's own insets: camera cutout or Dynamic Island, home indicator, Android cutouts and navigation bar, e.g. { top: 62, right: 0, bottom: 34, left: 0 } on an iPhone 17 Pro. In a safe-frame Bit ctx.safeArea is the fixed { top: 0, right: 0, bottom: 120, left: 0 }. Treat ctx.safeArea, ctx.contentSafeArea and ctx.logoArea as read-only: in a full-screen Bit they are frozen live values the host replaces when the insets change, so assigning to them does nothing (and throws in strict-mode code).
- ctx.contentSafeArea -> { top, right, bottom, left } in CSS pixels, full-screen Bits only: ctx.safeArea moved in past the controls Plethora draws over the Bit, so the bottom also clears the logo button (e.g. bottom 108.5 on an iPhone 17 Pro, 130.5 on Android with 3-button navigation) and, in the web player, the top clears its back arrow. Keep text, scores and controls inside it. It is undefined in a safe-frame Bit, so always read const area = ctx.contentSafeArea ?? ctx.safeArea;
- ctx.logoArea -> { x, y, width, height } of the logo button in container CSS pixels, or null; undefined in a safe-frame Bit. Never put a control behind it. contentSafeArea.bottom clears it across the whole width; a Bit that uses the bottom corners beside the logo keeps just this rect free.
- Full-screen layout: paint the background edge to edge (a canvas or root that fills ctx.width x ctx.height); keep text, scores and controls inside ctx.contentSafeArea ?? ctx.safeArea; avoid drag zones along the bottom inset and the side edges, where the phone takes system swipes. Size canvases from ctx.width/ctx.height at init as usual.
- CSS insets: a full-screen document sets --plethora-safe-top, --plethora-safe-right, --plethora-safe-bottom, --plethora-safe-left and the matching --plethora-content-safe-* variables (px) on :root, with viewport-fit=cover. Safe-frame Bits get none, so always give a fallback, e.g. padding: var(--plethora-content-safe-top, 0px) var(--plethora-content-safe-right, 0px) var(--plethora-content-safe-bottom, 120px) var(--plethora-content-safe-left, 0px). Never 0px at the bottom: the logo still covers the bottom of a safe-frame Bit.
- ctx.manifest -> normalized plethora.json manifest.
- ctx.runtime -> { version: "plethora-bit@2", schemaVersion: 1 }. It carries no SDK version: the SDK version (1.8.0) is the docs' and the agent context's, for reporting what a Bit was built against.
- ctx.capabilities -> booleans for audio, backgroundMusic, camera, haptics, microphone, motion, storage.
- ctx.markVisualReady(reason?) -> tells host that the Bit has produced a visible first frame.
- ctx.onResize(callback, { immediate?, debounceMs? }?) -> cleanup. callback receives { width, height, dpr, nativeDpr, safeArea }, plus contentSafeArea and logoArea in a full-screen Bit, where it also fires when the insets change. In a safe-frame Bit the callback's own safeArea is all zeros, so read insets as ctx.contentSafeArea ?? ctx.safeArea inside the callback. Use this for resize/orientation-safe layout; values are CSS-pixel viewport data unless you deliberately read canvas backing pixels.
- window.plethoraBit.meta.keyboardBehavior -> optional "auto" | "avoid" | "none". Default auto lifts focused visible text inputs above the iOS keyboard; none opts out for self-managed layouts.
- ctx.viewer -> host-supplied viewer metadata, with username (empty string when unavailable). This is display context, not an authentication token, stable account ID, or authority to access another viewer.
- ctx.viewer.username can change: people can rename themselves (once every 30 days). Show it, but never key saved data, scores or lists by it, or a rename splits or loses them. Keep per-person state in ctx.memory or ctx.game, which the host keeps per viewer by their account (or ctx.storage for this device only), never under the username.
- Capability booleans reflect declaration/host policy, not a guarantee of hardware, OS consent, audio unlock, successful acquisition, or support in an older installed client. Synchronous permission-gated calls can throw NotAllowedError; asynchronous acquisition rejects. Handle capability denial and runtime availability separately.
- All ctx handles belong to the current init lifetime. Keep external renderer teardown in ctx.onDestroy and fence late asynchronous UI work after destruction. Host suspension is not a new init or a reason to replace healthy surfaces.

<a id="sdk-surfaces"></a>

### DOM, Canvas and Surface Composition

- ctx.createRoot({ className?, touchAction?, style?: string, layer?, order?, zIndex?, input?, pointerEvents? }?) -> HTMLElement absolutely filling the bit container. Prefer CSS text appended to cssText. SDK 1.6.3 also honors legacy plain CSS property maps with string/number values; no React Native style arrays or implicit numeric units.
- ctx.createCanvas2D({ touchAction?, maxDpr?, coordinateSpace?, scaleToCssPixels?, alpha?, desynchronized?, willReadFrequently?, layer?, order?, zIndex?, input? }?) -> HTMLCanvasElement for Canvas2D. Omitted maxDpr keeps a legacy-safe CSS-size backing store. maxDpr alone raises backing resolution but leaves normal raw canvas.width/canvas.height drawing space for compatibility.
- Use coordinateSpace:"css" or scaleToCssPixels:true only when all drawing, clearing, layout, and hit tests use ctx.width/ctx.height or getBoundingClientRect() CSS pixels. Without that opt-in, code that sets maxDpr should draw against raw canvas.width/canvas.height. alpha:false is only for a fully opaque canvas. desynchronized defaults to false. desynchronized:true is an optional latency hint that can bypass normal DOM composition; avoid it for transparent or layered canvases and verify Android and iOS before opting in. Unsupported WebViews may ignore it.
- In coordinateSpace:"css" mode, the runtime keeps the DPR transform installed. Later identity setTransform(1,0,0,1,0,0) or resetTransform() calls are restored to CSS-pixel scale and warn once. Use coordinateSpace:"backing-store" or omit coordinateSpace when you want raw physical-pixel drawing.
- willReadFrequently is only for repeated getImageData/putImageData work. Canvas pixels remain local to the WebView.
- willReadFrequently does not read, persist, upload, or grant pixel access; it is only a local Canvas2D context hint.
- ctx.createCanvas({ touchAction?, layer?, order?, zIndex?, input? }?) -> HTMLCanvasElement for WebGL, WebGL2, Three, Pixi, OGL, regl, Babylon, Phaser, and custom renderers.
- Placement: layer is "background" | "content" | "overlay" | "modal" with background < content < overlay < modal. order is a bounded finite integer inside its named layer. A finite zIndex is an advanced explicit override and wins over named lanes.
- input:"passthrough" maps to pointer-events:none so a full-screen surface cannot steal touches. input:"auto" makes that surface hit-testable. pointerEvents:"none" and pointerEvents:"auto" are accepted CSS aliases for legacy/agent-authored code, but prefer input for new work. Without layer/order/zIndex/input/pointerEvents, factories preserve legacy append/source-order stacking and native interactivity.
- ctx.surface.place(surface, { layer?, order?, zIndex?, input?, pointerEvents? }) -> surface. Moves an existing surface without reparenting or replacing it.
- surface may be an HTMLElement/HTMLCanvasElement or a common wrapper handle that resolves to one: { current }, { ref: { current } }, { canvas }, { element }, { domElement }, { domNode }, { view }, { renderer: { domElement } }, { getCanvas() }, or { getRenderingCanvas() }. Unrelated plain objects still fail clearly.
- ctx.surface.getPlacement(surface) -> placement snapshot or null. ctx.surface.enableInput(surface) -> surface; use this only when wiring custom events manually.
- ctx.input.track/on/activate explicitly enable their passed target. ctx.listen and ctx.input.delegate preserve hit testing on managed surfaces, including inline and stylesheet pointer-events:none. Ordinary child listeners retain legacy auto-enablement unless inline pointerEvents is none. For delegated controls inside a passthrough HUD, set CSS pointer-events:auto or call ctx.surface.enableInput(child). Never enable the entire HUD merely to delegate child events.
- Surface layers are visual composition only. They do not select a renderer, restrict DOM nesting, change permissions, or limit approved libraries. Complex DOM, Three/WebGL scenes, renderer-specific layering, and library-owned composition remain creator/library territory.
- Canvas2D helpers are not a ceiling; WebGL, Three, Pixi, Phaser, and custom renderers remain available through ctx.createCanvas() / approved libraries.
- Surface returns are DOM nodes, not drawing contexts: const canvas = ctx.createCanvas2D(); const g = canvas.getContext("2d"); or ctx.createCanvas().getContext("webgl2"). A browser may return null for an unsupported context; distinguish that from dependency or renderer failure.
- All factories are synchronous and cleanup-owned. Raw createCanvas backing dimensions use the runtime DPR; a library renderer may manage its own pixel ratio/size. Recompute layout in onResize without remounting the canvas or renderer. Surface placement does not change drawing coordinates.
- ctx.surface.getPlacement(surface) returns { layer, order, zIndex, input, computedZIndex } when managed, otherwise null. order rounds/clamps to -999999..999999; zIndex rounds finite input; invalid layer/input normalize to null. Invalid surface handles or use after cleanup throw synchronously. enableInput changes pointer hit testing, not permission or keyboard focus.
- Host-restricted: ctx.chrome may be undefined. It is supplied for first-party Bits only, not a general creator theme/control API. When present, ctx.chrome.mode is "browse" | "play" | null, ctx.chrome.layout is a host layout snapshot, and ctx.chrome.events lists admitted event names. Any full-screen Bit finds the logo button in ctx.logoArea and the space clear of it in ctx.contentSafeArea; do not wait for ctx.chrome to lay out around the logo.
- ctx.chrome.on(name, handler, options?) -> cleanup for "mode", "layout", or "action", with { immediate:true } supported for available mode/layout snapshots. Mode events contain { mode, cause }; action events contain { action, source }. Subscribe only to advertised events; no chrome setter is public.
- Chrome layout, when available, contains logo/card rectangles and actions/targets maps of rectangles; each rectangle is {x,y,width,height} in host-provided layout coordinates, or null when absent. Do not substitute canvas backing pixels or infer an ordinary creator capability from a first-party host signal.

<a id="sdk-fx"></a>

### Visual Feedback and Transitions

- ctx.fx.impact(options?), burst(options?), ripple(options?), flash(options?), floatText(options?) -> FxHandle. These are short-lived screen-space visual feedback effects, not audio, haptics, gameplay rules, physics, or a scene graph.
- Common effect options: durationMs (or compatibility alias duration), color, x/y, normalizedX/Y, ndcX/Y, and anchor. impact also accepts strength/radius/count; burst accepts count/spread/radius; ripple accepts radius/width; flash accepts opacity/blend; floatText accepts text/size/rise/stack; trail accepts color/width/lifeMs/spacing; pulse accepts scale; shake accepts amount/frequency/axis.
- FxHandle -> { active, cancel(reason?), finish(), pause(), resume(), done: Promise<void> }. Effects share a capped scheduler, are cleanup-owned, pause with the host, and respect reduced-motion preferences.
- Coordinates are target-local CSS pixels. Pass { x, y }, normalizedX/normalizedY, ndcX/ndcY, an input pointer, or anchor/target element where that effect accepts a position. FX handles DPR and overlay placement; do not use canvas backing-store pixels.
- ctx.fx.trail(inputOrOptions?, options?) -> FxTrail with add(point), follow(inputOrPointer), pause(), resume(), clear(), destroy(). Use it for short finger trails; it is bounded and never owns a new loop per pointer event.
- ctx.fx.pulse(target, options?) and ctx.fx.shake(target?, options?) -> FxHandle for short visual response. They preserve existing target transforms when safe and otherwise fall back without corrupting DOM or library animation.
- ctx.fx.transition({ kind: "fade" | "wipe" | "iris", color?, outMs?, inMs? }) -> FxTransition. The Bit owns its state: await transition.cover(); scene = "results"; await transition.reveal(); The helper never chooses or mutates scene/router state.
- ctx.fx.clear(options?) settles effects in that FX context. ctx.fx.create({ layer?, order?, anchor? }?) -> bounded child FxContext for deliberate layered composition; child contexts share the Bit-wide scheduler and resource caps.
- Default feedback is a lazy input:"passthrough" overlay; transitions use the input-transparent modal lane. FX never steals touch, re-parents creator surfaces, or selects a renderer.
- ctx.fx.emitter() does not exist. Use ctx.fx for bounded feedback; build a custom Canvas2D/WebGL/Three/DOM system or approved-library effect when the idea genuinely needs a particle engine, scene system, or renderer-specific control.
- Effect timing is milliseconds, clamped to 16..5000. FxHandle.done resolves when finished or cancelled (including cleanup/cap pressure), not only on a successful visible animation; cancellation does not reject it. cancel(reason?), finish(), pause(), resume() return whether their state transition applied. No effect grants audio/haptics permission.
- FxTransition exposes transition.active, transition.cover() -> Promise<void>, reveal() -> Promise<void>, transition.cancel(reason?), finish(), pause(), resume(), transition.done. Default outMs:160, inMs:180; wipe direction may be "left" (default), "right", "up", or "down". reveal waits for cover if necessary. A new transition supersedes the previous one; cancellation settles waiters, so guard scene mutation against destroyed/changed attempts.
- Trail follow(input) adds one point now; it does not subscribe to input or start following automatically. Call add(point)/follow(input) from your existing loop as needed. Both return whether a point was added; spacing suppresses too-close samples. clear empties the trail; destroy is terminal. lifeMs defaults 360 (80..2000), width 3 (1..24 CSS px), spacing 1 (1..48 CSS px); maxAge is a compatibility lifeMs alias.
- Effect defaults: impact/burst/ripple/floatText positions resolve in CSS coordinates from anchor/target/pointer data. ripple width also accepts lineWidth. pulse scale defaults 1.08 (1.01..1.5); shake amount defaults 8 CSS px (1..48), frequency 18 (1..60), axis "x" or "y". floatText text is limited to 96 characters, size 10..48 CSS px, rise 4..120 CSS px; stack:"none" disables automatic offsets.
- ctx.fx.create returns another public FxContext with the same effect methods and clear/create. Its clear affects that context; resource caps remain shared with the Bit. ctx.fx.clear() ignores options and returns void. Internal scheduler, resource registries and installer APIs are not creator controls.

<a id="sdk-visual"></a>

### Palettes, Kits, Textures, Materials and Sprites

- ctx.visual.palette.from(input?, options?) -> frozen palette roles. Input may be a seed string, CSS color, partial role object, or options object. Options include mode, mood, style, medium, material, era, geometry, composition, lighting, texture, motion, finish, harmony, contrast, seed, axes, energy, saturation, warmth, depth, glow, softness, weirdness, density, polish, and role overrides.
- Palette roles: bg, bg2, surface, surface2, ink, muted, line, accent, accent2, accent3, focus, success, warning, danger. Roles are ordinary CSS colors. Use them in DOM, Canvas2D, SVG, WebGL uniforms, Three materials, or any approved library.
- Returned palette methods: palette.ramp(roleOrColor, steps, options?), gradient(a, b, steps), contrast(fg, bg), isReadable(fg, bg, options?), ensureReadable(fg, bg, options?), cssVars(prefix?), toJSON(). pair(base, options?), mix(a, b, t), and harmonize(color, base, options?) live on the ctx.visual.palette namespace, not on returned palette handles. ramp also accepts a full palette request object such as { mood, style, axes, harmony, seed } and uses accent by default; override with { role: "bg" | "surface" | "accent2" }.
- ctx.visual.palette.roles(input?, options?) is an alias of from and returns the same frozen role-and-method handle. Use palette.toJSON() for just the roles. ctx.visual.palette.pair/contrast/isReadable/ensureReadable/mix/harmonize/ramp/gradient are also available as stateless helpers.
- ctx.visual.kit(input?, options?) -> frozen renderer-neutral token kit with colors, ramps, type, surface, shape, stroke, glow, shadow, fx, and materialHints groups. Input may be a mood string such as "arcade", "glass", "botanical", "noir", "pixel", "crystalline", "bauhaus", "destijl", "swiss", "brutalist", "constructivist", "memphis", "cyberpunk", "vaporwave", "synthwave", "y2k", "risograph", "ukiyoe", "artdeco", "artnouveau", "midcentury", "material", "lofi", "kawaii", "cottagecore", "outrun", or an options object.
- Preferred kit shape: ctx.visual.kit({ mood, style: { medium, material, era, geometry, composition, lighting, texture, motion, finish }, axes: { energy, saturation, warmth, depth, glow, softness, weirdness, density, polish }, harmony, seed }). Categorical style choices may use ctx.visual.catalog.styles options or custom one-word/open strings; known options add recipes, unknown strings are preserved as creator intent. Numeric axes are 0..1 and override recipe defaults. Use style axes first; use mood as a shorthand starting point, not the whole art direction.
- Style axes are categorical: medium = screen/canvas/paper/ink/marker/chalk/watercolor/oil-paint/gouache/collage/photography/clay/glass/metal/plastic/fabric/neon/hologram/pixel/voxel/low-poly/wireframe/shader/terminal/blueprint/comic/poster/instrument/diagram/sticker/toy/ceramic/liquid/crystal/shadow/light; material = matte/paper/ink/clay/glass/chrome/metal/neon/hologram/liquid/plastic/ceramic/fabric/wood/stone/light/rubber/foam/paperboard/enamel/carbon-fiber/pearl/gel/wax; era = contemporary/timeless/retro-arcade/y2k/bauhaus/art-deco/midcentury/cyberpunk/solarpunk/vaporwave/brutalist/folk/futuristic/memphis/retro-futurist/space-age/victorian/medieval/storybook/constructivist/swiss/postmodern; geometry = rounded/sharp/blocky/organic/isometric/grid/sketchy/ornamental/modular/minimal/maximal/wireframe/low-poly/radial/fractal/biomorphic/tiled; composition = centered/full-bleed/layered/tiled/radial/split/board/hud/poster/diorama; lighting = flat/soft-glow/hard-shadow/spotlight/neon-bloom/ambient/dusk/luminous/rim-light/backlit/golden-hour/noir/studio/volumetric/overcast/candlelit; texture = clean/grain/halftone/paper-fiber/scanline/dither/worn/fabric/noise/glossy/brush/watercolor-wash/stipple/glitch/linen/embossed/frosted/pixel-dither; motion = calm/bouncy/snappy/floaty/jittery/liquid/mechanical/elastic/springy/inertial/breathing/cinematic/clockwork/orbiting/wavy/chaotic; finish = handmade/polished/toy-like/luxurious/rough/dreamy/tactical/sticker/editorial/premium/playful/clinical/industrial/mystical/cozy/sporty.
- Kit methods: kit.cssVars(prefix?), kit.applyCssVars(root?, options?), kit.toJSON(). applyCssVars is explicit; ctx.visual never mutates global CSS unless the Bit calls it.
- ctx.visual.texture(kind, options?) and named helpers ctx.visual.texture.grain/paper/halftone/grid/dots/scanlines/hatch/noise/clouds/marble/fabric/brushed(options?) -> frozen procedural texture handle. Handles expose cssBackground/cssBackgroundSize when CSS gradients can represent the texture, draw(ctx2d, rect?), pattern(ctx2d), sample(x,y), toDataURL(), toJSON(), and dispose().
- Texture output is deterministic by seed, local-only, asset-free, network-free, lazily rasterized, cached, and bounded. Prefer small repeated textures; never generate high-DPR texture pixels every frame. Texture helpers are polish tools, not a replacement for custom shader/material systems.
- ctx.visual.material(kind, options?) and named helpers ctx.visual.material.matte/paper/ink/clay/glass/chrome/metal/neon/hologram/liquid/plastic/ceramic/fabric(options?) -> frozen renderer-neutral material handle with colors, opacity, roughness, metalness, transmission, glow, stroke, texture, css, canvas, svg, three, pixi, and toJSON().
- Material adapters return plain data only. The SDK does not import Three/Pixi/Babylon or create renderer objects; creators still construct new THREE.MeshStandardMaterial(material.three), use material.canvas in Canvas2D, or override everything for custom art direction.
- ctx.visual.sprite(kind, options?) and named helpers ctx.visual.sprite.orb/blob/coin/star/spark/gem/ship/projectile/pickup/hazard/tile/button/badge(options?) -> frozen procedural sprite handle. Handles expose width, height, frames, static, animated, anchor, bounds, source, shapes, canvas(frame?, state?), draw(ctx2d, x, y, options?), pattern(ctx2d, options?), frameAt(timeMs, options?), hitShape(), toDataURL(), toJSON(), and dispose().
- ctx.visual.sprite.compose({ width, height, shapes, seed?, frames?, anchor?, kit?, palette? }) builds a reusable cached shape graph. Supported shape kinds include circle, ellipse, rect, roundRect, line, arc, polygon, regularPolygon, star, path, text, group, repeat, and mirror. Shapes can use fills, strokes, gradients, shadows, glow, texture handles, and material handles.
- ctx.visual.sprite.custom({ width, height, frames?, draw(g, frame, state, info) }) keeps renderer power open for hand-authored Canvas2D sprite authoring. sprite.sheet(...) is a convenience alias for composed or custom multi-frame sprites. Sprite helpers are not assets, do not load files, and are not a renderer prison; draw handles into Canvas2D when useful, or use toJSON()/shape data as authoring/caching input for SVG, DOM, WebGL, Three, Pixi, Phaser, shaders, or approved libraries.
- ctx.visual.catalog lists moods, media, styleAxes, styles, harmonies, axes, palette roles, textures, materials, and sprites so agents can choose honestly instead of inventing presets. Reference-backed moods use curated swatch anchors, but semantic seed + style axes + harmony + numeric axes vary the final kit. Override color, hue, colors, texture, material params, sprite shapes, or any token when the idea needs custom art direction.
- ctx.visual is optional. It does not generate assets, create packaged assets, remote images, meshes, audio, physics, renderer objects, scene graphs, or a house style. Advanced shaders, hand-authored Canvas2D, Three/Pixi/Phaser styles, imported approved libraries, and custom visual systems remain creator/library territory.
- Palette return shapes: contrast(fg,bg) -> contrast ratio; isReadable(fg,bg,{minTextContrast?}?) -> boolean; ensureReadable(fg,bg,{minTextContrast?}?) -> CSS color. Default minimum text contrast is 4.5. Palette creation also accepts brightness, neutrals, minTextContrast, and safety:{minTextContrast?,repair?}; repair:false disables automatic text-role adjustment. cssVars(prefix="--bit") returns a property map without applying it; palette.toJSON() returns the role map.
- Stateless palette helpers: ctx.visual.palette.ramp(input,steps=5,{spread?:0.34,role?,...paletteOptions}?) returns 1..24 CSS colors; gradient(a,b,steps=5) returns 1..32 CSS colors. pair(base,{harmony?,seed?}?) returns {a,b} harmonized CSS colors, not a contrast-tested text/background pair; mix(a,b,t) returns a CSS color; harmonize(color,base,{amount?:0.32}?) adjusts hue. Returned palette methods accept role names as well as CSS colors. Palette and kit default seeds incorporate the Bit identity/title/description/tags; pass seed explicitly for reproducible independent output.
- Kit exposes id, mood, medium, style, axes, harmony, seed as well as token groups; kit.cssVars(prefix="--bit") returns a map, kit.applyCssVars(root,{prefix?}?) applies it to the supplied root and returns the same property map, kit.toJSON() returns serializable token data. Supply a real root explicitly; with no root applyCssVars only returns the map and does not mutate global CSS.
- Texture options: seed, kit, palette, color/colors, size (default 256), width/height, maxSize (default 512, capped 1024), maxDpr (default 1, 0.5..2), scale, density, opacity, contrast, softness, rotation, spacing. Size/width/height are local pixels. density/opacity/contrast/softness are normalized 0..1. Texture handles expose id, kind, seed, width, height, pixelRatio, static:true, animated:false, colors, cssBackground, cssBackgroundSize.
- texture.canvas() -> cached HTMLCanvasElement|null (CSS-only textures return null); texture.cssVars(prefix="--bit-texture") -> map; pattern(ctx2d,repetition="repeat") -> CanvasPattern|null; draw(ctx2d,{x?,y?,width?,height?,w?,h?}?,{opacity?}?) -> boolean; sample(x,y) -> procedural sample; toDataURL(type="image/png",quality?) -> string|null; toJSON() -> descriptor; dispose() evicts its raster cache. ctx.visual.texture.catalog lists names; ctx.visual.texture.clearCache() clears shared texture cache. Rasterization can be unavailable without a Canvas2D context.
- Material options: kit, palette, seed, color/colors, opacity, roughness, metalness, transmission, thickness, ior, clearcoat, sheen, iridescence, emissive, emissiveIntensity, glow, stroke, lineWidth, texture, normalTexture. Normalized material strengths use 0..1, thickness is nonnegative, ior clamps 1..2.5. Handle metadata also includes id, kind, thickness, ior, clearcoat, emissive, shadow and material.normal (from normalTexture), plus named renderer adapter data. ctx.visual.material.catalog lists supported kinds; unknown kind falls back to matte.
- Sprite options: kind, seed, size (default 64), width/height, maxSize (default 256, capped 512), maxDpr (default 1, 0.5..2), frames (1..64), anchor ("center" default, "topLeft", "top", "bottom", or normalized {x,y}), kit, palette, color/fill, material, texture, glow. compose(spec,options?) and custom(spec,options?) merge options; sheet(spec,options?) chooses custom when draw is supplied, otherwise compose. ctx.visual.sprite.catalog lists kinds.
- Sprite draw options: { frame?, state?, scale?, scaleX?, scaleY?, alpha?, rotation?, flipX?, flipY?, composite?, blendMode? }; rotation is radians. frameAt(timeMs,{fps?:12,loop?:true}?) returns a frame index; canvas(frame=0,state={}) lazily caches it; pattern(ctx2d,{frame?,state?,repetition?}?) returns CanvasPattern|null. toDataURL(frame=0,{state?,type?,quality?}?) returns string|null. hitShape() is an anchor-relative rectangle, not alpha-pixel collision. draw returns boolean; custom draw errors render a fallback. dispose clears cached frames.
- Compatibility/unavailable visual output: sprite.svg() returns null; it does not export SVG markup. Use shapes/toJSON with creator rendering if needed. Texture/sprite handles are local cached helpers, not persistent assets; release obsolete handles and avoid generating unique cache states every frame.
- Unavailable: ctx.visual.background is not exported. Build layered backgrounds with managed surface placement, palette/kit colors, texture.cssBackground/cssBackgroundSize or texture.draw, and creator-owned DOM/Canvas2D/WebGL rendering. The SDK does not provide a dedicated background scene API.

<a id="sdk-tune"></a>

### Creator Tuning

- ctx.tune reads manifest.tuning defaults and draft-time overrides. Published playback uses frozen manifest defaults. Tuning is for creator-editable parameters, not hidden player settings or arbitrary persistence.
- Declare manifest.tuning.groups, knobs, curves, and presets. Supported knob types: number, integer, boolean, choice, multi_choice, color, range, point2, vec2, seed, duration_ms, percent. Supported apply modes: live and restart.
- Typed getters: ctx.tune.get(id), number(id), integer(id), boolean(id), choice(id), multiChoice(id), color(id), range(id), point2(id), vec2(id), seed(id), durationMs(id), percent(id). Declared knobs return safe normalized values. Undeclared knobs return undefined, so `ctx.tune.number("speed") ?? 240` works as expected.
- Curves: ctx.tune.curve(id) -> { id, domain, range, points, easing, at(x), toJSON() }. Use for difficulty ramps, spawn pacing, visual intensity, audio density, or progress-based feel changes.
- Change hooks: ctx.tune.onChange(idOrIds, fn) -> cleanup. Use for live values that require rebuilding local objects, music settings, palette/materials, or cached sprites. Restart knobs should be read during init/new run.
- Utilities: ctx.tune.has(id) tells whether a knob or curve is declared; ctx.tune.snapshot() returns a cloned value map; ctx.tune.meta(id) returns declared knob/curve metadata; ctx.tune.applyPreset(id) applies a declared preset in draft/runtime when available; ctx.tune.reset(id?) returns values to manifest defaults.
- Good default: expose 5-15 meaningful controls such as player_speed, spawn_rate, difficulty_ramp, arena_style, accent_color, music_intensity, shake_amount, or particle_density. Do not expose raw magic numbers the creator cannot understand.
- Use tuning with ctx.game.loop, ctx.game.score, ctx.visual, ctx.fx, and ctx.music. Tuning changes must not send bridge messages every frame, create network/storage access, or replace creator/library rendering power.
- All tune reads are synchronous, permission-free copies or immutable handles. number/integer/durationMs/percent return numbers, boolean returns boolean, choice/color/seed return declared scalar values, multiChoice/range return arrays, point2/vec2 return vector objects. Unknown IDs return undefined (curve returns a safe empty evaluator). percent is a normalized value, durationMs is milliseconds; ranges/units come from each manifest declaration.
- ctx.tune.meta(id) returns knob/curve metadata or undefined. onChange accepts one ID or an ID array and returns cleanup. reset(id?) and applyPreset(id) return changed-ID arrays; unknown presets return []. These operate on runtime tuning values, not saved user progress or a publish request. Creator code cannot call internal configure/update/destroy methods.
- Change callback signature: fn(value,{id,revision}), where value is a cloned normalized value for that changed ID. Curve handles snapshot points at retrieval; obtain a new curve in onChange after edits. No immediate callback is promised on subscription.

<a id="sdk-onboarding"></a>

### First-Use Onboarding

- manifest.onboarding is the first-use entry contract. Every new Bit must choose one: immersive, one_line, guided, or briefing. It is optional only for legacy compatibility; do not omit it from new work. Do not use the same generic instruction panel for every Bit.
- Common fields: { kind, version, replayable? }. version is a positive integer and participates in the per-device completion key. Increase it only when a changed first-use experience should be shown again.
- immersive: { kind: "immersive", version: 1 }. No runtime overlay. Use when the first action is self-evident, discovery is deliberate, or the Bit authors its own visual first-use interaction.
- one_line: { kind: "one_line", version: 1, message: "Drag to steer through the light." }. Use one pointer under about 60 characters. The runtime presents it near the top of the Bit, away from bottom controls, and clears it on the first ctx.platform.interact() or confirmation.
- For non-obvious puzzles or unfamiliar mechanics, prefer a tiny interactive example in the Bit: show the real visual language, ask for one meaningful tap/drag, respond visibly, then let the player continue or Skip. Keep each cue to one short action. Avoid a repeated text-card template across Bits; fit the guide to the mechanic and art direction.
- guided: { kind: "guided", version: 1, steps: [{ id, title, body, advance?: "continue" | "interaction" }] }. Existing managed text-card mode; keep for compatible Bits or cases where its short pointers genuinely fit. advance:"interaction" moves forward on the next ctx.platform.interact(); call ctx.onboarding.advance("stepId") after a specific success when generic interaction is too broad.
- briefing: { kind: "briefing", version: 1, pages: [{ title?, body }] }. Existing managed text-page mode; not the default for puzzles. Use only when an interactive example cannot convey essential rules, with brief pointers rather than paragraphs.
- A Bit-authored guide owns its own Next, Play, Skip, first-use persistence, replay affordance when useful, and cleanup. Place its text and controls inside ctx.contentSafeArea ?? ctx.safeArea; do not cover the actual play controls after the guide closes. Managed guided and briefing overlays also support Skip on compatible clients.
- ctx.onboarding.state() -> { kind, version, active, completed, currentIndex, currentStepId, replayable }. ctx.onboarding.replay() reopens a replayable current onboarding without clearing its completion memory.
- ctx.onboarding.start({ force?: true }), next(), advance(stepId?), complete(), dismiss(), focus(targetOrRect), and clearFocus() manage a declared first-use experience. focus accepts a DOM element or { x, y, width, height } in bit-local CSS pixels; it is a visual guide, not a collision/renderer API.
- The runtime owns these behaviors only for managed one_line/guided/briefing declarations. With immersive, it renders no overlay and the Bit can own a bespoke visual walkthrough using its DOM, Canvas2D, WebGL, Three, or approved libraries. Starter prompts and action buttons stay inside ctx.contentSafeArea ?? ctx.safeArea, clear of the logo button.
- The post-play long-press Bit World tips are separate. They are optional quick-reference pointers, not first-use onboarding, not long descriptions, and not numbered walkthroughs by default.
- Onboarding methods are synchronous and return booleans for whether the requested action applied; state() returns a frozen snapshot. next()/advance(stepId?) return false while inactive or when step identity does not match. complete()/dismiss() mark managed first use complete; replay() requires replayable and does not erase the saved completion.
- focus(targetOrRect) returns false without active onboarding, a valid target or positive width/height. clearFocus() removes only the highlight. Missing managed support produces inert false-returning methods and an immersive inactive snapshot; do not infer that immersive means the creator-authored tutorial ran. There is no public reset, destroy, ready or notifyInteraction method on ctx.onboarding.

<a id="sdk-input"></a>

### Pointers, Gestures and Input Helpers

- ctx.input.track(target, options?) -> input tracker for canvas, WebGL canvas, DOM roots, controls, fidgets, games, and interactive UI. No manifest permission is required.
- Default behavior is target-aware: canvases/WebGL canvases prevent scroll and use pointer capture by default; buttons, links, inputs, textareas, selects, and contenteditable DOM keep native behavior unless you override options.
- Options: { preventDefault?, touchAction?, pointerCapture?: "auto" | true | false, multitouch?, passive?, tapMaxMs?, tapMaxDistance?, doubleTapMaxMs?, holdMs?, swipeMinDistance?, swipeMinVelocity?, dragMinDistance? }.
- Primary shortcuts for simple bits: input.x, y, dx, dy, startX, startY, down, pressed, released, tap, doubleTap, dragging, durationMs, distance, velocityX, velocityY, vector, swipe, hold(ms). pressed/released/tap/doubleTap/swipe are one-frame flags; call input.frameDone() after consuming if you use manual frame bookkeeping.
- Full pointer data: input.primary and input.pointers expose { id, isPrimary, pointerType, pressure, width, height, x, y, dx, dy, startX, startY, clientX, clientY, pageX, pageY, screenX, screenY, normalizedX, normalizedY, ndcX, ndcY, down, pressed, released, cancelled, tap, doubleTap, dragging, durationMs, distance, velocityX, velocityY, vector, swipe }.
- Coordinate contract: x/y are target-local CSS pixels; normalizedX/Y are 0..1 in the target; ndcX/Y are -1..1 for Three/WebGL raycasting; client/page/screen coordinates are also preserved for DOM/library interop.
- Gestures: ctx.input.on(target, "tap" | "doubleTap" | "dragStart" | "drag" | "dragEnd" | "hold" | "swipe" | "pinch" | "rotate", handler, options?) -> cleanup function. Prefer this for simple gesture events instead of manual pointer math.
- Pinch/rotate: input.pinch -> { active, scale, delta, centerX, centerY, distance, startDistance, pointers }; input.rotate -> { active, angle, delta, centerX, centerY, pointers }. Use these for zoom, 3D object spin, kaleidoscopes, and map-like toys.
- Zones: input.zone(zones), ctx.input.zone(inputOrPointer, zones), and ctx.input.zones(inputOrPointer, zones) test simple rectangular/circular/polygon zones. Zones are for controls, lanes, regions, and affordances; complex collision/raycasting remains creator/library code.
- Hit helpers: ctx.input.hitCircle(inputOrPointer, x, y, r), hitRect(inputOrPointer, x, y, w, h), hitPolygon(inputOrPointer, points), nearest(inputOrPointer, points). These are convenience helpers for touch affordances, not a full collision engine.
- DOM helpers: ctx.input.activate(target, handler, options?) handles click plus keyboard activation for DOM controls. ctx.input.delegate(root, selector, gestureOrEvent, handler, options?) handles delegated controls when lists are dynamic.
- Motion helpers tied to input: ctx.input.follow(inputOrPointer, options?), spring(inputOrPointer, options?), inertia(inputOrPointer, options?), fling(inputOrPointer). They return small state/helpers for finger-follow, slingshots, tossed cards, magnetic dots, and tactile fidgets.
- ctx.listen(target, eventName, handler, options?) remains available for raw pointer/touch/mouse/keyboard/custom/library events. Use it when ctx.input is not the right abstraction; do not mount or listen on document.body for core interaction.
- Tracker lifecycle: input.on(name, handler) -> unsubscribe; input.pointer(id) -> pointer snapshot (empty inactive pointer when absent); input.destroy() removes listeners/hold timers; input.frameDone() clears transient flags. ctx cleanup destroys trackers automatically. Gesture events also include down, move, up, cancel, holdStart, holdEnd; cancelled input must not count as a completed action.
- Gesture payloads include pointer data and target; pinch/rotate add their gesture shape. Delegated gestures add delegateTarget; delegated ordinary DOM events give { event, target, delegateTarget }. activate passes the original event and supports click, Enter and Space. Use actual focusable DOM controls for keyboard access.
- Tracker options/defaults: tapMaxMs:250, tapMaxDistance:12, doubleTapMaxMs:280, holdMs:500, swipeMinDistance:36, swipeMinVelocity:0.35, dragMinDistance:8, multitouch:true; preventDefault defaults true on canvas and false on ordinary controls, passive defaults to !preventDefault, pointerCapture defaults "auto" on canvas and false elsewhere, touchAction defaults "none" on canvas. Threshold distances are CSS pixels, velocities are CSS pixels per millisecond, times are milliseconds, rotate angles are radians.
- input.vector is { x, y, angle, distance, velocity, direction }; swipe is null or a gesture vector. ctx.input.nearest(inputOrPointer, points) returns the nearest candidate with x/y/distance or null for no points. zone returns the first { id, zone, x, y, pointer } match or null; zones returns all matches. Rect zones use x/y/w/h; circle zones use cx/cy/r; polygon zones use points. Width/height/radius aliases are not accepted by these input zones.
- ctx.input.follow(source, { smoothing?, maxSpeed?, snapDistance? }?) -> follow; follow.update() and getters x/y/vx/vy advance toward the current source. Default smoothing is 0.2; maxSpeed is CSS pixels per second. ctx.input.spring(source, { stiffness?, damping?, mass? }?) has the same shape, default stiffness:180, damping:22, mass:1.
- ctx.input.inertia(source, { friction?, minSpeed? }?) -> inertia with inertia.update(), x/y/vx/vy. Default friction:0.92; during press it follows the pointer and after release continues with decaying velocity. These kinematic helpers use the runtime clock (not a dtMs argument) and even getter reads advance state; sample update() once and reuse its state when consistency matters. They create no timer and have no release/destroy method. ctx.input.fling(source) returns { vx, vy, speed, angle } once, in CSS pixels per second and radians.

<a id="sdk-game"></a>

### Loops, Timers, State Machines, Scores and Progress

- ctx.game.loop(options) -> cleanup-owned stable time loop for custom games, fidgets, simulations, rhythm toys, particles, and continuous animation. Use this instead of raw recursive requestAnimationFrame for Bit-owned loops.
- Options: { fps?, fixedHz?, maxDeltaMs?, maxSubsteps?, timeScale?, input?, autoFrameDone?, autoStart?, update?, fixedUpdate?, render?, resetOnResume? }. fps caps rendering for intentionally lighter bits; fixedHz gives deterministic simulation steps.
- Callbacks: update(dtMs, state), fixedUpdate(stepMs, state), render(alpha, state). state is the creator-supplied options.state object (default {}), not injected timing metadata. Read frame, elapsedMs, timeScale, isRunning, isPaused, and stats from the returned loop. stats contains fps, frameMs, updateMs, renderMs, droppedFrames, clampedDeltas, and substeps.
- Movement rule: scale custom motion by dtMs or use fixedUpdate. Do not assume 60 FPS; Android and iOS frame pacing can differ, and touch activity can wake a throttled WebView.
- Controls: loop.pause(), resume(), stop(), destroy(), step(ms?), resetClock(), setFps(fps|null), setTimeScale(value), stats. ctx cleanup destroys the loop automatically.
- Input integration: pass input: ctx.input.track(canvas) so one-frame input flags are cleared after render. Set autoFrameDone:false only if the bit manually calls input.frameDone().
- Helpers: ctx.game.timer(ms), cooldown(ms), every(ms, fn), sequence(steps), stateMachine(def), clamp(value,min,max), lerp(a,b,t), approach(value,target,amount), wrap(value,min,max), bounds(shape), random(seed).
- ctx.game.stopwatch({ elapsedMs?, onChange? }?) -> cleanup-owned active-play clock (SDK 1.8.0). Each stopwatch starts paused, including restored snapshots. Methods: start(), pause(), reset(elapsedMs=0), snapshot(), destroy(). Read-only elapsedMs, running and active; snapshot() returns {elapsedMs,running,active}. running is creator intent; active additionally requires an eligible visible foreground unpaused host and visible document. Host resume preserves running intent but never starts a creator-paused clock. reset sets elapsed time and pauses. Mutators return whether state changed; destroyed mutators return false. At most 32 live clocks per document; manual destroy releases its slot and ctx cleanup destroys remaining clocks.
- stopwatch elapsedMs uses a monotonic clock, not frame counts, clamped simulation dt, or Date.now()-savedStart. It schedules no frames or timers and counts slow foreground frames in full. Start on the actual puzzle/play view; pause on menus, colour changes, manual pause and completion. Thinking while the selected puzzle remains visible still counts. Plethora handles background, offscreen and host pause independently. Clock boundaries follow host lifecycle delivery, not an OS-level precision guarantee; this is not anti-cheat or authoritative server timing. Calendar edition/day/countdown logic still uses calendar time, not this stopwatch.
- stopwatch onChange(snapshot) fires only on real start/pause/reset/host-activity transitions, never each frame or read. Observer errors are reported without stopping other clocks. Keep callbacks small; render elapsedMs on your existing low-frequency HUD tick. Persist only elapsedMs plus versioned game state through acknowledged ctx.game.progress or ctx.memory.local checkpoints. Restoring elapsedMs never adds the gap or restores running intent. Save at meaningful boundaries and a bounded coalesced cadence during long play; a last background/disposal callback may be too late for a new cloud write. Pending/unacknowledged saves can be lost on process death. No per-frame network/storage writes; never treat failed hydration as empty state. Feature-detect and catch unsupported host errors, asking for an app update rather than using wall time as a fake equivalent.
- Active-play sequence: after validated hydration, create const clock = ctx.game.stopwatch({elapsedMs:savedElapsedMs}). Call clock.start() when opening the actual play view, and clock.pause() before leaving it or completing the puzzle. Read clock.snapshot().elapsedMs and persist it with game state without blocking replay. For a fastest-time record, submit only a completed valid solution; unfinished short times are not results.
- Independent colour/level/difficulty challenges need declared record dimensions or separate channels. Submit, rank and leaderboard must use the same channel, period and dimensions (for example {colour:"amber"}); display separate selected boards. Preserve published channel keys, epochs, ordering and dimensions. A new measurement such as active time versus old whole-set wall time needs a new channel; keep old records readable, never reinterpret them. Legacy timestamps cannot reconstruct per-colour active durations: preserve old progress but mark unmeasured attempts ineligible for the new board. Daily periods currently bucket by server UTC acceptance, not metadata.edition; prevent delayed previous-edition submissions locally and do not promise authoritative puzzle editions until that platform contract exists.
- ctx.game.score(idOrOptions?, options?) -> one cleanup-owned local numeric track. ctx.game.score() creates the default "score" track; ctx.game.score("combo", options?) creates a named track. Options are { initial?, min?, max?, primary? }. The default score is primary; named tracks are secondary unless primary:true. Only one primary track may exist.
- Track state and mutation: score.id, value, previous, delta, lowest, highest, initial, primary; score.set(value, { reason? }), add(amount, { reason? }), reset({ reason? }), flush(), and onChange(listener). Values must be finite and are clamped by min/max. Track state is local and immediate, so update DOM/canvas/WebGL/Three however the Bit needs.
- The primary track coalesces primary host score updates at at most 12 Hz. It does not write to the server or rerender native UI for every local change. Plethora flushes the final score before complete, fail, host pause, and cleanup; call score.flush() only when you need an earlier host update.
- score.submit(recordChannelId, { label?, dimensions?, metadata? }?) -> Promise<record result>. It flushes first, then explicitly submits through the existing manifest.memory.records channel and resolves server acceptance, not just local queuing. Only submit a durable record at a meaningful result or checkpoint. isPersonalBest means this all-time best_per_user record improved; do not infer a rank from that boolean. The optional standing is an acceptance-time standing snapshot: use its board identity, scope, period, dimensions and rankComputedAt together. Idempotent receipt replay preserves that snapshot; rank() or leaderboard() gets fresh standing for the selected board. Legacy receipts may omit standing.
- score.checkpoint(recordChannelId, { label?, dimensions?, metadata? }?) -> Promise<{ queued:true, checkpointId, submitted:false }> in published playback. Supports best_per_user only; latest_per_user and all_entries require explicit submit. Snapshots this track value into the authenticated host-owned bounded buffer; queued locally, not server acceptance. It does not upload every frame. Draft preview applies the same validated record locally and may return submitted:true; it never writes the public board.
- score.rank(recordChannelId, { scope?, period?, dimensions? }?) -> Promise<standing>. Uses the same leaderboard read with limit:1; returns viewerRank (nullable), totalRanked and board identity/freshness metadata without top rows. It is a server snapshot, not a prediction or a rank computed from top ten.
- score.checkpointStatus(recordChannelId, { dimensions? }?) -> Promise<{ pending, failed, lastFailure }>. Reads the host buffer for this Bit/channel/dimensions and current attempt only; it does not enqueue or retry a score. rank/leaderboard also include checkpointStatus. A pending drain can reject with checkpoint_pending; keep cached rows and offer refresh. A board with checkpointStatus.failed > 0 contains accepted scores, not proof that the failed checkpoint saved: show an honest warning and inspect lastFailure before offering an explicit retry.
- score.leaderboard(recordChannelId, { scope?, period?, dimensions?, limit? }?) -> Promise<leaderboard>. scopes, periods, and dimensions must be declared by that record channel. Plethora renders the standard long-press Bit World leaderboard with board, scope, period, and dimension controls.
- Leaderboard and rank reads wait for already-issued same-channel/dimensions writes in this run; the host drains pending checkpoints before reading. Failed writes remain failures, not optimistic rank success. This waits only inside the result promise: Never await leaderboard work before replay, navigation, first paint, or the game loop. Keep cached rows visible with Updating status and replace score/rank together on success.
- Call ctx.platform.start() for every new attempt, including replay; complete/fail marks the outcome, not the next attempt. Keep an attempt counter and disposed flag in result callbacks. Old run/document observers reject with runtime_attempt_changed/runtime_destroyed and cannot deliver fresh success into the next result screen; pending host writes are not cancelled by replay.
- score.flush() is host synchronization only, not a durable checkpoint or server write. For long games, checkpoint only a valid ready-to-save best_per_user result at meaningful progress boundaries. For ascending best-time boards, an unfinished short timer is not a valid winning result. Keep metadata and dimensions with the same score snapshot. latest_per_user and all_entries require explicit submit: strongest-value coalescing would corrupt latest-value or event-history semantics.
- ctx.platform.setScore and score.flush only synchronize live host score; neither is a saved leaderboard receipt. In authenticated published app playback, a checkpoint receipt with queued:true and submitted:false means pending device-buffered delivery, not cloud acceptance. The buffer is bounded, account-scoped and subject to retry/period expiry; reinstall cannot restore never-delivered bytes. Show pending/failed separately from the accepted best and observe explicit submit or an authoritative board read before claiming saved. Simulated submit/checkpoint success in draft preview or shared-web play is not account acceptance.
- For long best_per_user games, call score.checkpoint(channelId, { dimensions, metadata }) only for already-valid improvements at bounded milestones or a coalesced cadence, never every frame/tap. Keep the current run score local and never seed it with an old personal best. Cover continued play after a win: keep checkpointing valid improvements and explicitly submit the final valid result even if an earlier win was submitted. An unfinished asc timer is not a valid score. Handle rejection in a detached attempt/lifetime-guarded task; silent .catch(() => {}) is not a save strategy. Preserve unresolved status and follow the documented retry/identity rules instead of fabricating acceptance or issuing unbounded retries.
- ctx.game.progress.load(channelId?) -> Promise<progress>. Reads retained viewer-private state for a declared manifest.game.progress channel. channelId defaults to "main". Restore only when saved.resumeEligible === true; resumeIneligibleReason explains empty, completed, abandoned, expired, package_mismatch, scope_mismatch, or state_schema_mismatch. Completed and expired state remains readable but is not resumable. Eligibility means compatible unfinished checkpoint, not proof that the game restored successfully; creator code owns restoration and calls complete/abandon explicitly.
- For older servers without resumeEligible, use a conservative fallback: require saved.status === "in_progress", saved.stateSchemaVersion === the declared stateSchemaVersion, an absent expiresAt or Date.parse(saved.expiresAt) > Date.now(), and creator-owned validation of the state shape and compatibility. Older responses cannot prove current package/scope identity: if compatibility is uncertain, start fresh. Never infer resumability from nonempty JSON. Respect an explicit resumeEligible === false even when state is retained.
- ctx.game.progress.save(channelIdOrValue?, valueOrOptions?, options?) -> Promise<progress result>. Save payload shape is { state, label?, percent?, dimensions?, metadata?, stateSchemaVersion? }. Use at checkpoints, level unlocks, generated puzzle seed, room/inventory transitions, or chapter changes; never call from every frame, collision, or ordinary tap.
- ctx.game.progress.complete(channelIdOrOptions?, options?) and abandon(channelIdOrOptions?, options?) -> Promise<progress result>. Use complete when the run/story/puzzle is finished and should leave Continue Playing; use abandon for restart/new-run flows.
- Progress powers the viewer personal Continue Playing shelf. It is private per signed-in viewer and not a leaderboard, tally, shared world, analytics event, or pass-and-play/shared-device player state. Use ctx.memory.local or ctx.storage for hidden local settings that should not appear in Continue Playing; use in-bit player selection/local state for couch multiplayer on one phone.
- State machines are for readable mode flow such as menu/play/gameOver/replay. They are not a full engine; advanced physics, collisions, ECS, pathfinding, raycasting, shaders, and renderer-specific loops remain creator/library territory.
- ctx.onFrame remains available for tiny one-callback animations and library interop. Prefer ctx.game.loop when the bit has gameplay timing, collision, timers, replay state, or custom simulation.
- Loop defaults: fps:"display" (also null/undefined), maxDeltaMs:80, maxSubsteps:4, timeScale:1, autoStart:true, autoFrameDone:true, resetOnResume:true. fixedHz defaults to 60 when fixedUpdate exists, otherwise no fixed stepping; null/false disables it. dtMs/stepMs/elapsedMs are milliseconds; render alpha is interpolation fraction [0,1). Excess fixed-step backlog is dropped, not simulated without bound.
- Additional loop options: state, onStart(state), onPause(state), onResume(state), onStop(state), onDestroy(state), onError(error, phase). Callback failures go to onError when supplied, otherwise are rethrown asynchronously; this is not a promise-returning loop. loop.start() starts/restarts a stopped loop; resume() only resumes a paused running loop. destroy() is terminal. step(ms=1000/60) runs one manual update/render. resetClock() resets the frame clock/accumulator, not creator state or elapsed totals.
- ctx.game.timer(ms, { elapsedMs?, repeat? }?) -> timer. timer.update(dtMs), reset(nextMs?), durationMs, elapsedMs, remainingMs, progress (0..1), done. It advances only when you call update, not via a hidden wall-clock timer; repeat wraps elapsed time modulo duration.
- ctx.game.cooldown(ms, { remainingMs? }?) -> cooldown. cooldown.update(dtMs), ready() -> boolean, cooldown.trigger(nextMs?), reset(), durationMs, remainingMs, progress. New cooldowns are ready unless remainingMs is supplied. trigger starts the countdown; reset makes it immediately ready.
- ctx.game.every(ms, fn, { maxCallsPerUpdate? }?) -> every. every.update(dtMs), reset(), destroy(), active, elapsedMs, progress. Callback receives { count, intervalMs, overflowMs }; count is within this update. Default maxCallsPerUpdate is 8; excess backlog is discarded. It needs explicit update calls.
- ctx.game.sequence(steps, { context? }?) -> sequence. Steps accept { durationMs, enter(context, info)?, update(elapsedMs, context, info)?, exit(context, info)? }; info includes index and step, plus progress for update. sequence.update(dtMs), reset(), index, done, elapsedMs, progress, context. At most one step advances per update; excess delta is not carried into the next step. No automatic scheduling or next() method.
- ctx.game.stateMachine({ initial?, context?, states }) -> machine. machine.send(event, payload?), is(name), update(dtMs), render(alpha), value, context, states. Each state accepts enter(context, transition), exit(context, transition), update(dtMs, context), render(alpha, context), on:{ event: targetName | function(context,payload) | { target, guard?, action? } }. A false guard or missing/unknown target leaves state unchanged. Initial enter runs synchronously; the creator drives update/render.
- ctx.game.bounds(shape) -> { contains(point), clampPoint(point) }. This lightweight compatibility helper is not ctx.geometry.bounds; circle clampPoint returns the input point unchanged. ctx.game.random(seed) -> callable nextRandom() in [0,1), unlike the richer object returned by ctx.math.random(seed). clamp(value,min,max), lerp(a,b,t), approach(value,target,amount), wrap(value,min,max) are synchronous scalar helpers.
- Score set/add/reset/flush return the same score handle for chaining; onChange(listener) returns cleanup and receives { id, value, previous, delta, lowest, highest, reason?, source }. Reopening a track ID with conflicting options, non-finite values, a second primary track or use after destruction throws. Submit/checkpoint/rank/leaderboard return promises and may reject independently of local score state. Track listeners, loops and score flushing are cleanup-owned; timer/cooldown/every/sequence/state-machine helpers are plain local objects driven by your loop.
- Progress response fields: channel, status (empty/in_progress/completed/abandoned), state, label, percent, dimensions, metadata, stateSchemaVersion, updatedAt, lastSavedAt, completedAt, abandonedAt, expiresAt, resumeEligible, resumeIneligibleReason. Empty state/timestamps may be null; timestamps are serialized dates, not frame time. Progress percent is 0..1. Complete/abandon retain saved state unless a new state is explicitly supplied; they change resumability, not the Bit score.
- Progress overloads: save(payload) or save(channelId,payload), save(rawState,options) or save(channelId,rawState,options). A payload is {state,label?,percent?,dimensions?,metadata?,stateSchemaVersion?}; legacy value is accepted as a state alias. complete(options?) / complete(channelId,options?) and abandon use the same optional metadata/state form. Missing declaration throws synchronously; host validation, auth, limits or transport failures reject the returned promise.
- In authenticated published app playback, ctx.game.progress is cloud-backed per-account retained state, not ctx.storage. Acknowledged progress can survive reinstall on the same account/scope, subject to expiry, schema and package eligibility; pending saves are not receipts. This excludes draft preview and shared-web play: shared-web progress uses page-local simulation even for published Bits, not account-cloud persistence. A failed load is not a new game: do not save default state or call complete/abandon to recover from a network error. Hydrate and validate before enabling writes, retain the working view on failure, and ignore stale load/save completions after replay, disposal or account change. For private unlocks/settings that should not enter Continue Playing, use declared ctx.memory.local instead.

<a id="sdk-math"></a>

### Math, Random, Noise and Color

- ctx.math -> pure scalar, angle, vector, quaternion, deterministic random/noise, easing, timing-curve, envelope, and color helpers. No manifest permission is required.
- Scalars: ctx.math.clamp, clamp01/saturate, lerp, invLerp/unlerp, remap(value, inMin, inMax, outMin, outMax, { clamp?, easing? }), approach, wrap, pingPong, deadzone, snap, roundTo, signNonZero, mod, smoothstep, smootherstep, smoothDamp, spring.
- Angles: ctx.math.angle.normalize, normalizePositive, delta, lerp, toRad, toDeg, turnDirection. Angle values are radians except explicit toRad/toDeg conversions.
- Vectors: ctx.math.vec2 and ctx.math.vec3 provide create, set, copy, add, sub, scale, length, normalize, distance, dot, lerp, clampLength; vec2 also provides mul/div, angle, angleBetween, fromAngle, rotate, perp, project, reflect; vec3 also provides cross. Helpers accept plain objects and optional out objects.
- Quaternions: ctx.math.quat.identity, fromEuler(alpha,beta,gamma), multiply, invert, rotateVec3, slerp. Euler inputs use radians. Use for lightweight 3D orientation work; renderer-specific transforms remain valid when a library owns the scene.
- Determinism: ctx.math.random(seed) returns float, range, int, pick, chance, shuffle, sign, unitVec2, insideCircle, onCircle, weighted, gaussian. Same seed means same sequence. ctx.math.noise(seed) exposes value1/value2/value3, simplex2/simplex3, perlin2/perlin3, noise2D/noise3D, fbm2/fbm3, fbm2D/fbm3D, ridged2, turbulence2, cellular2, domainWarp2, curl2/curl2D, and field2. Static helpers ctx.math.noise.value2/fbm2/curl2/field2(seed, ...) are also available.
- Style/time: ctx.math.ease has linear, quad/cubic/back/elastic/bounce variants; ctx.math.curve(points, { interpolation? }).at(x) makes timing/value curves; ctx.math.envelope({ attackMs, decayMs, sustain, releaseMs }).at(timeMs, releasedAtMs?) makes ADSR-like values.
- Color: ctx.math.color.rgb, hsl, hex, lerp, toCss. Use these for procedural palettes, not as a replacement for renderer/library color systems.
- Scalar signatures: clamp(value,min=0,max=1), clamp01(value), saturate(value), lerp(a,b,t), invLerp(a,b,value), unlerp(a,b,value), approach(value,target,maxDelta), wrap(value,min=0,max=1), pingPong(value,length=1), deadzone(value,amount=0), snap(value,step=1), roundTo(value,step=1), signNonZero(value), mod(value,divisor), smoothstep(min,max,value), smootherstep(min,max,value). lerp/invLerp are not clamped; remap clamps only when requested. Degenerate inverse ranges return 0. snap/roundTo round to multiples, not decimal places.
- ctx.math.smoothDamp(current,target,velocity,smoothTime=0.2,maxSpeed=Infinity,deltaTime=1/60) -> { value, velocity }. ctx.math.spring(value,target,velocity=0,{ stiffness=180, damping=20, mass=1, deltaTime=1/60 }?) -> { value, velocity }. Both deltaTime and smoothTime are seconds, unlike game.loop milliseconds: pass dtMs/1000 and retain returned velocity.
- ctx.math.angle.normalize(radians) wraps to [-PI,PI); normalizePositive(radians) to [0,2PI); delta(a,b) gives signed shortest difference; lerp(a,b,t) follows that difference; turnDirection(a,b) returns -1/0/1. toRad(degrees) and toDeg(radians) are explicit conversions.
- Vector signatures: create(x=0,y=0[,z=0]), set(out,x,y[,z]), copy(a,out?), add(a,b,out?), sub(a,b,out?), scale(a,amount,out?), length(a), normalize(a,out?), distance(a,b), dot(a,b), lerp(a,b,t,out?), clampLength(a,min=0,max=Infinity,out?). vec2 has mul(a,b,out?), div(a,b,out?), angle(a), angleBetween(a,b), fromAngle(radians,length?,out?), rotate(a,radians,out?), perp(a,out?), project(a,onto,out?), reflect(a,normal,out?); vec3.cross(a,b,out?) computes the cross product. Values are plain {x,y} or {x,y,z}; optional out is written and returned.
- Compatibility vector aliases: ctx.math.vec2.len/lenSq/lengthSq/norm/dist/distSq/distanceSq; ctx.math.vec2.lenSq(a) is squared length, distSq(a,b) is squared distance. vec3 supports len/lenSq/lengthSq/norm/dist but no squared-distance helper. Zero-length normalization yields a zero vector.
- Quaternion signatures: identity(out?), fromEuler(alpha,beta,gamma,out?), multiply(a,b,out?), invert(q,out?), rotateVec3(q,vector,out?), slerp(a,b,t,out?). They accept/return plain {x,y,z,w} quaternions or {x,y,z} rotated vectors; angles are radians and these do not own a renderer transform.
- Random handle signatures: float() -> [0,1), range(min=0,max=1), int(min=0,max=1) inclusive, pick(items), chance(probability=0.5), shuffle(items) -> copied array, sign() -> -1|1, unitVec2(), insideCircle(radius=1), onCircle(radius=1), weighted(items,weights), gaussian(mean=0,deviation=1). Empty picks/weighted choices return undefined. No cryptographic randomness guarantee.
- ctx.math.noise(seed, options?) -> noise handle. Defaults/options: scale:1, amplitude:1, normalize?, range?:[min,max], frequency:1, octaves:4, lacunarity:2, gain:0.5; each sampler also takes options. value1(x), value2(x,y), value3(x,y,z), fbm2(x,y), fbm3(x,y,z) produce bounded noise, normally -1..1; normalize/range remap output. simplex2/perlin2/noise2D alias value2, simplex3/perlin3/noise3D alias value3, and fbm2D/fbm3D alias fbm2/fbm3: these names do not promise distinct simplex/Perlin implementations.
- Noise recipes: ridged2(x,y,options?), turbulence2(x,y,options?) normally 0..1; cellular2(x,y,{mode?:"edge",scale?,frequency?}?) -> 0..1; domainWarp2(x,y,{warp?:0.75,...noiseOptions}?) -> scalar; curl2/curl2D(x,y,{epsilon?:0.01,...noiseOptions}?) -> {x,y}. field2({width?:16,height?:16,scale?:0.05,sample?}?) -> { width, height, values, at(x,y), toJSON() }; each dimension clamps to 1..512, at clamps/floors indices. Static ctx.math.noise.value2/fbm2/curl2 take seed first, then coordinates/options; field2(seed,options?) makes the same field handle.
- Exact easing names (each takes t): linear, inQuad, outQuad, inOutQuad, inCubic, outCubic, inOutCubic, outBack, inOutBack, outElastic, outBounce. Most clamp input t to 0..1; back/elastic can overshoot. No unlisted inElastic/inBounce aliases are exported.
- Curve handle exposes points and at(x); points accept [x,y] pairs or {x,y}, sorted by x, with interpolation:"linear" (default) or "step". Outside endpoints it returns the nearest endpoint value; empty curves return 0. Envelope exposes attackMs, decayMs, sustain (0..1), releaseMs, at(timeMs,releasedAtMs?); sustain defaults 1, other durations 0. These are pure evaluators, not scheduled animations.
- Color signatures: rgb(r=0,g=0,b=0,a=1) clamps RGB to 0..255 and alpha to 0..1; hsl(h=0,s=0,l=0,a=1) uses hue degrees and saturation/lightness 0..100; hex(text) parses 3/4/6/8 hex digits to RGBA (invalid input becomes black). color.lerp(a,b,t) interpolates parsed color objects, toCss(color) returns a CSS color string.

<a id="sdk-geometry"></a>

### Geometry, Paths and Spatial Queries

- ctx.geometry -> lightweight 2D shape, bounds, hit, collision-info, intersection, projection, path, curve-position, sampling, transform, and spatial-grid helpers. No manifest permission is required.
- Shapes use plain objects: point { x, y }, rect { x, y, w, h }, circle { cx, cy, r }, ellipse { cx, cy, rx, ry, rotation? }, segment { a, b }, ray { origin, direction }, and point arrays for triangles/polygons. Common width/height/radius aliases are normalized.
- Constructors/helpers: ctx.geometry.point(x?, y?), segment(a, b), ray(origin, direction), normalize(shape), typeOf(shape), bounds(shape). rect, circle, ellipse, triangle, and polygon are helper namespaces, not callable constructors; construct their plain shape objects directly. rect.fromCenter(cx, cy, w, h) constructs a rectangle. Bounds expose left/right/top/bottom/center plus contains, clampPoint, expand, inset, union, intersection.
- Hits and simple response: ctx.geometry.hit.circlePoint, ctx.geometry.hit.rectPoint, ctx.geometry.hit.ellipsePoint, ctx.geometry.hit.pointPolygon, ctx.geometry.hit.pointTriangle, ctx.geometry.hit.circleCircle, ctx.geometry.hit.rectRect, ctx.geometry.hit.circleRect, ctx.geometry.hit.segmentCircle, ctx.geometry.hit.segmentRect, ctx.geometry.hit.segmentSegment. ctx.geometry.collision.circleCircle/rectRect/circleRect/segmentSegment return compact hit, point, normal, depth, t data.
- Intersections and nearest points: ctx.geometry.intersection.lineLine/segmentSegment/raySegment/lineCircle/segmentCircle/segmentRect/circleCircle; ctx.geometry.distance.*; nearestPointOnSegment; projectPointOnLine/Segment/Ray; heading; pointFromHeading.
- Polygons/paths: ctx.geometry.polygon area/centroid/bounds/containsPoint/isClockwise/reverse/translate/scale/rotate; ctx.geometry.triangle area/centroid/containsPoint/barycentric/bounds; ctx.geometry.path(points) with length, pointAt, tangentAt, normalAt, segmentAt, closestPoint, sample, plus path static helpers.
- Curves, sampling, transforms: ctx.geometry.bezier quadratic/cubic/tangents; arc.pointAt/toPolyline; sample circle/onCircle/ellipse/onEllipse/rect/polygon/path; transform point/points/rect/circle/polygon plus translate/scale/rotate/compose.
- ctx.geometry.spatialGrid({ cellSize }) is a tiny predictable insert/remove/query helper for simple nearby checks. It is not a physics broad-phase promise. Advanced physics, CAD, pathfinding, polygon clipping, or 3D raycasting remain creator/library territory.
- Geometry is synchronous and permission-free. Use a consistent coordinate space throughout; no automatic CSS/DPR conversion. Angles/rotations are radians; curve/path t is clamped 0..1. Point-returning functions accept an optional final out object when listed. Empty/degenerate input generally yields zero shapes or no hit; this is not robust CAD/polygon validation.
- Rect namespace: rect.fromCenter(cx,cy,w,h), center(rect,out?), corners(rect), inflate(rect,amount), inset(rect,amount), union(a,b), intersection(a,b), clampPoint(rect,point,out?). Circle namespace: circle.pointAt(circle,angle,out?), fromDiameter(a,b), circumference(circle), area(circle). Ellipse: ellipse.pointAt(ellipse,angle,out?), area(ellipse), bounds(ellipse). These return plain shapes, points, numeric areas/lengths, or null for an empty rectangle intersection.
- Bounds handle: x,y,w,h,left,right,top,bottom,center; contains(point), clampPoint(point,out?), expand(amount), inset(amount), union(other), intersection(other). Static ctx.geometry.bounds.union(a,b), intersection(a,b), overlaps(a,b), containsPoint(bounds,point) operate on axis-aligned bounds.
- Triangle namespace signatures: area(a,b,c), centroid(a,b,c,out?), containsPoint(a,b,c,point), barycentric(a,b,c,point), bounds(a,b,c). Polygon namespace: area(points), centroid(points,out?), bounds(points), containsPoint(points,point), isClockwise(points), reverse(points), translate(points,dx,dy), scale(points,sx,sy?,origin?), rotate(points,angle,origin?). These are not callable triangle/polygon factories.
- Hit signatures: hit.circlePoint(circle,point), rectPoint(rect,point), ellipsePoint(ellipse,point), pointPolygon(point,points), pointTriangle(point,a,b,c), circleCircle(a,b), rectRect(a,b), circleRect(circle,rect), segmentCircle(a,b,circle), segmentRect(a,b,rect), segmentSegment(a,b,c,d) -> boolean. Segment helpers take endpoint arguments, not two segment wrapper objects.
- Collision signatures: collision.circleCircle(a,b), rectRect(a,b), circleRect(circle,rect) -> {hit:false} or {hit:true,point,normal,depth}; collision.segmentSegment(a,b,c,d) -> {hit:false} or {hit:true,point,t}. Intersections: lineLine(a,b,c,d), segmentSegment(a,b,c,d), raySegment(origin,direction,a,b), lineCircle(a,b,circle), segmentCircle(a,b,circle), segmentRect(a,b,rect), circleCircle(a,b) -> {hit,points,point?,t?,u?}. Parallel/collinear line helpers return no hit rather than overlap segments.
- ctx.geometry.distance.pointPath(point,pathOrPoints), pointPoint(a,b), pointLine(point,a,b), pointRay(point,origin,direction), pointSegment(point,a,b), pointRect(point,rect), pointCircle(point,circle), pointPolygon(point,points) -> scalar distance. nearestPointOnSegment(point,a,b,out?), projectPointOnLine(point,a,b,out?), projectPointOnSegment(point,a,b,out?), projectPointOnRay(point,origin,direction,out?) return points. heading(a,b) returns radians; pointFromHeading(origin,heading,distance,out?) returns a point.
- Path handle: points, length (number), pointAt(t,out?), tangentAt(t,out?), normalAt(t,out?), segmentAt(t) -> {index,a,b,length}|null, closestPoint(point,out?), sample(count=2) -> points. Static ctx.geometry.path.length(points), pointAt(points,t,out?), closestPoint(points,point,out?), resample(points,count=2), simplify(points,tolerance=1) are also public. Path positions use accumulated arc length, not equal time per segment.
- Bezier signatures: bezier.quadratic(a,b,c,t,out?), cubic(a,b,c,d,t,out?), tangentQuadratic(a,b,c,t,out?), tangentCubic(a,b,c,d,t,out?) -> point/vector; tangents are derivatives, not normalized directions. arc.pointAt(center,radius,startAngle,endAngle,t,out?), arc.toPolyline(center,radius,startAngle,endAngle,segments=16) -> point/points.
- Sampling: sample.circle(circle,rng?,out?), onCircle(circle,rng?,out?), ellipse(ellipse,rng?,out?), onEllipse(ellipse,rng?,out?), rect(rect,rng?,out?), polygon(points,rng?,out?), path(points,rng?,out?) -> point. rng is an object with float(), such as ctx.math.random(seed); omitted rng uses Math.random. Polygon sampling uses an anchor fan, so do not assume arbitrary concave polygon triangulation.
- Transform description: { translate:{x,y}, scale:{x,y}, rotate:radians, origin:{x,y} }. transform.point(point,transform,out?), points(points,transform,outArray?), polygon(points,transform,outArray?), rect(rect,transform), circle(circle,transform). Rect returns transformed axis-aligned bounds; circle uses the larger absolute axis scale. Helpers translate(dx=0,dy=0), scale(sx=1,sy=sx,origin?), rotate(angle=0,origin?), compose(...transforms) return descriptions. compose combines components, not general matrix multiplication.
- Spatial grid handle: grid.cellSize (default 64, minimum 1), grid.insert(id,shape) -> id (replaces existing id), remove(id) -> boolean, query(rect) -> matching ID array, clear() -> void. Query uses axis-aligned bounding rectangles; retain your own ID-to-object map. There is no update() method: reinsert after motion. No loop or cleanup is needed for this local data structure.

<a id="sdk-lifecycle"></a>

### Platform Lifecycle and Haptics

- ctx.platform.ready(payload?) -> hide loader and notify host. Call after first visible render, not before drawing.
- ctx.platform.start(payload?) -> begins a new attempt from a real user gesture. Call when play begins and on every replay; complete/fail do not begin the next attempt.
- ctx.platform.interact(payload?) -> meaningful action such as tap, drag, choice, vote, score, mutation, replay.
- ctx.platform.setScore(score, payload?) -> low-level compatibility escape hatch for current host score. It does not create, mutate, or submit a ctx.game.score track; prefer ctx.game.score for new numeric run state.
- ctx.platform.setProgress(value, payload?) -> 0..1 progress for finite experiences.
- ctx.platform.milestone(name, payload?) -> named moment such as level_clear, combo, ten_seconds.
- ctx.platform.complete(payload?) -> natural ending/win/survey submitted/finished state for lifecycle/analytics. Add payload.pulse = true only when it should become an implicit Pulse; prefer ctx.pulse.complete().
- ctx.platform.fail(payload?) -> failure/game-over state.
- ctx.platform.error(payload?) -> recoverable runtime issue visible to host/analytics.
- ctx.platform.emit(name, payload?) -> custom analytics event.
- ctx.platform.haptic('light' | 'medium' | 'heavy' | 'success' | 'warning' | 'error') -> requires haptics permission.
- Platform methods are synchronous notifications returning void, not server persistence receipts. payload is a small serializable object; do not send secrets, source, raw sensor streams or media. start resets attempt ownership; complete/fail flush the host score. setProgress is a transient 0..1 host signal, not a save to Continue Playing. Haptic delivery depends on device/user settings even with the declaration.

<a id="sdk-pulse"></a>

### Pulse Completion and Sharing

- ctx.pulse.complete(options?) -> marks a game/puzzle/level/achievement completion and asks Plethora to create an implicit milestone Pulse on the timeline.
- Completion options may include timeMs, durationMs, timeSeconds, timeLabel, level, mode, score, result, text/explicitText, implicitText, and captureMode: "none". By default Plethora captures the current runtime screen for the Pulse image.
- Use this at the exact result screen you want screenshotted, after the visible win/completion state has rendered. Do not call it repeatedly from an animation loop.
- ctx.share(options?) -> void. Requests host scene sharing with { sceneId?, title?, text?, implicitText?, captureMode?, imageRole?, payload? }. sceneId defaults "default" (max 96 chars), title max 200, text max 2000, implicitText max 500, imageRole defaults "runtime" (max 48); payload is an object. captureMode:"none" disables capture; otherwise the host uses runtime_snapshot. This is a request, not a delivered-share receipt or permission to auto-publish a Pulse.
- ctx.pulse.complete and ctx.platform.complete return nothing. They flush current host score and notify the host, not durable record acceptance. Render the result first; use record/progress APIs independently when those outcomes need persistence.

<a id="sdk-eventsandframes"></a>

### Events, Frames, Timers and Cleanup

- ctx.listen(target, eventName, handler, options?) -> addEventListener plus automatic remove on cleanup. Use this for raw events and library interop; prefer ctx.input for normal pointer/touch/gesture handling.
- ctx.onFrame((dtMs, timeMs) => void) -> persistent runtime-owned frame callback. Register once during init, never inside itself.
- ctx.raf(cb) -> legacy alias for ctx.onFrame; avoid for new code.
- ctx.timeout(fn, ms) and ctx.interval(fn, ms) -> cleanup-owned timer helpers.
- ctx.onDestroy(fn) -> cleanup hook for external renderers, custom audio, or library teardown.
- Do not call ctx.cleanup() manually; Plethora owns unload cleanup.
- ctx.listen returns a removal function; ctx.onResize returns cleanup and optionally invokes immediately. onResize debounceMs is milliseconds. ctx.onFrame and legacy ctx.raf register persistent callbacks and return nothing, not an animation request ID or cancel function. Runtime suspension gates managed frame delivery.
- ctx.timeout(fn, ms) and ctx.interval(fn, ms) return nothing, not timer IDs or cancellation functions; runtime cleanup cancels them automatically. For independently cancellable timing use a driven game timer/every helper or guard the callback. ctx.onDestroy(fn) returns nothing; callbacks run on teardown, not on every host pause. Never call cleanup yourself.

<a id="sdk-libraries"></a>

### Libraries, Fonts and Verified Resources

- ctx.loadScript(name, version) -> Promise<void>. Loads classic script dependencies from declared Plethora Library Registry pins.
- ctx.importModule(name, version) -> Promise<module>. Imports ES module dependencies from declared Plethora Library Registry pins.
- High-leverage approved script pins include tone@15.1.22 for custom synths, sequenced music, and deeper audio-reactive music systems; declare audio/backgroundMusic as appropriate and microphone only when reading mic analysis; howler@2.2.4 for simple sound effects and short loops when ctx.audio handles are not expressive enough; declare audio; matter-js@0.20.0 for approachable rigid-body arcade physics for balls, collisions, slingshots, pinball, and falling-object games; planck@1.5.0 for precise Box2D-style 2D physics when stable joints, contacts, and deterministic simulation matter; gsap@3.15.0 for timeline animation, tween choreography, and polished DOM/SVG/numeric transitions; roughjs@4.6.6 for sketchy hand-drawn Canvas/SVG visuals without hand-authoring every imperfect stroke; canvas-confetti@1.9.4 for small celebratory particle bursts for wins, unlocks, votes, streaks, and completion moments.
- ctx.loadFont(family, name, version, options?) -> Promise<FontFace>. Loads approved font files from the Plethora Font Registry.
- ctx.registry.resources(name, version) -> Promise<resourceBundle>. Loads verified non-executable sidecar files such as wasm/model files. resourceBundle.locateFile(file) returns a runtime-local blob URL.
- ctx.mediapipe.hands(version?) -> Promise<{ Hands, HAND_CONNECTIONS, locateFile, resources }>. Requires manifest dependency mediapipe-hands@0.4.1675469240 and loads the approved MediaPipe Hands script plus verified wasm/model sidecars.
- Compatibility overloads ctx.loadScript(url), ctx.importModule(url), ctx.loadFont(family, url, options?), and ctx.registry.resources(url) accept exact libs.plethora.studio registry URLs. All registry loader inputs may be assembled in normal local code from literals, variables, lookup tables, destructuring, or helpers. The runtime verifies the final value against the declared dependency, expected asset kind, and exact registry descriptor; public CDNs and raw HTTP calls are never allowed.
- ctx.fetch(url, options?) -> Promise<Response|undefined>. Compatibility helper for data/blob/about URLs only; http/https network egress is denied. Runtime cleanup aborts the request and the helper resolves undefined on AbortError; check for a response before reading it.
- No networkFetch permission exists. Registry libraries are authorized by exact manifest dependencies; fonts must match fontRegistry entries exactly.
- Inline SVG markup is allowed for small self-contained vector shapes; remote SVG/image URLs are still remote assets and blocked.
- Fetch /v1/agent/libraries.json before choosing pins. Do not guess paths, versions, filenames, or global names.
- Font options: { style?, weight?, display? } are FontFace descriptors. family is your local CSS family name; name/version select the exact approved font registry entry. Font availability, wrong pin/kind, missing declaration, integrity verification and load failures reject; await a font before measuring text that relies on it.
- Resource handle: resourceBundle.entries contains approved registry descriptors; resourceBundle.urls maps filenames, paths and registry URLs to verified runtime-local blob URLs. resourceBundle.get(file), url(file), and locateFile(file) are synchronous aliases that throw for an unknown file; there is no arbitrary network fallback. URLs belong to runtime ownership; do not revoke or persist them for another document.
- MediaPipe result also exposes VERSION and url(file), alongside Hands, HAND_CONNECTIONS, locateFile and resources. These are registry-library constructors/constants, not a camera permission grant. The creator owns library instance setup, results callbacks and close/disposal; keep camera acquisition in ctx.camera and register library teardown with ctx.onDestroy.
- loadScript resolves void and its approved global is described by the registry; importModule resolves the module namespace, not a script global. Never assume a failed loader means WebGL is disabled. Preserve the original error and distinguish unavailable pin, integrity/load failure and renderer initialization failure.
- ctx.fetch uses its own cleanup-owned AbortController and replaces options.signal. It forwards other fetch options for local URL handling; it is not an escape hatch for external HTTP or a guarantee that aborted work rejects.

<a id="sdk-audio"></a>

### Music and Sound

- ctx.music.presets -> string[] currently including ambient, pulse, arcade, drift, sparkle, techno, house, chiptune, drone, lofi, synthwave, jungle, cozy, spooky, triumph, bubble.
- ctx.music.scales -> string[] currently including major, minor, pentatonic, minorPentatonic, blues, dorian, lydian, wholeTone, hirajoshi, chromatic.
- ctx.music.stings -> string[] currently including tap, coin, success, fail, danger, powerup, win, lose.
- ctx.music.unlock() -> Promise<state>. Call it inside the first tap/press before or after ctx.music.play() so mobile WebViews unlock audio reliably.
- ctx.music.play(optionsOrPreset) / ctx.music.start(optionsOrPreset) -> music handle. Requires backgroundMusic permission; call from a user gesture when possible.
- Music options: { preset?, id?, volume?, tempo?, fadeInMs?, intensity?, density?, swing?, scale?, root?, transpose?, pattern?, chords?, chordPattern?, drums?, drumPattern?, drumGain?, filterCutoff? }. Values are clamped by runtime.
- Music handle: stop(opts?), pause(), resume(), unlock(), setVolume(value, opts?), setPreset(name, opts?), setTempo(bpm, opts?), setIntensity(value, opts?), setScale(nameOrFreqs, opts?), setPattern(pattern), duck(amount, ms), sting(nameOrOpts, opts?), state(), details(), error(), ready(), playing, preset.
- ctx.music.stop({ fadeOutMs? }), pause(), resume(), unlock(), setVolume(value, { fadeMs? }), setPreset(), setTempo(), setIntensity(), setScale(), setPattern(), duck(), sting(), state(), details(), error(), ready(), playing, preset are also available on ctx.music.
- ctx.music.sting(nameOrOptions) plays small musical event cues. Good names: tap, coin, success, fail, danger, powerup, win, lose. It returns a Promise and should be called from/after a user gesture.
- ctx.music.duck(amount, ms) briefly lowers the music bed. Use before loud action moments; amount is 0..0.95.
- ctx.music.state() returns locked, ready, playing, paused, or stopped. ctx.music.details() returns preset, presets, scales, stings, tempo, volume, intensity, density, swing, filterCutoff, error. ctx.music.error() returns { message, code, name } or null. host_paused means the Bit is inactive/backgrounded and Plethora intentionally blocked audio.
- Plethora automatically pauses/gates all Bit audio when the Bit is not the active foreground runtime, including app background/lock, Android focus loss, and runtime swaps. Do not build background playback or audio keepalive behavior.
- ctx.audio.play(url, { volume? }?) -> sound handle. ctx.audio.loop(url, { volume? }?) -> looping sound handle. Requires audio permission.
- Audio handle: stop(), pause(), resume(), paused, volume get/set. ctx.audio.stopAll() stops all ctx.audio elements.
- new Audio(url), AudioContext, and webkitAudioContext are permission-guarded; prefer ctx.music/ctx.audio unless custom synthesis is truly needed.
- Audio URLs must be local data/blob/about URLs, not remote files. Approved registry HTTP URLs are accepted only by registry loader APIs, not by ctx.audio or new Audio; use verified runtime-local resource URLs when applicable.
- Start audio after a user gesture so mobile autoplay rules do not mute the Bit. Prefer ctx.music for background beds instead of custom WebAudio unless the bit needs bespoke synthesis.
- Music ranges/units: tempo 40..220 BPM; volume 0..0.9; intensity/density 0..1; swing 0..0.42; drumGain 0..2; filterCutoff 220..12000 Hz. fadeInMs/fadeOutMs/fadeMs and duck duration are milliseconds. Scale may be a catalog name or frequency array in Hz; root is Hz and transpose is semitones. Additional supported sound options include bass (frequency array) and wave (oscillator waveform). Unknown preset falls back to ambient.
- Setter details: setPreset(name,{...musicOptions,fadeMs?,filterQ?,keepStep?}?), setTempo(bpm,{keepSchedule?}?), setIntensity(value,{volumeFollows?,fadeMs?}?), setScale(nameOrFreqs,{root?,transpose?}?), setPattern(pattern), setVolume(value,{fadeMs?}?). Patterns contain scale-degree indices and rests; drums use kick/snare/hat arrays. Setters affect the current bed; they do not acquire microphone input.
- sting(nameOrOptions, options?) accepts { name?, root?, wave?, volume?, intervals?, durations? }; volume clamps 0..0.5, root 40..1600 Hz, intervals are semitone offsets and durations are seconds. It needs backgroundMusic permission and an unlocked active runtime. stop({fadeOutMs?,close?}?) defaults to a 400 ms fade; close also closes the music context.
- Music play/start returns a control handle immediately, not a Promise of audible playback. handle.ready()/ctx.music.ready() returns the current readiness promise; unlock(), resume(), and sting() are asynchronous. Inspect state()/error() for failure; a handle existing is not proof of OS audio unlock. ctx.audio play/loop similarly return immediately and suppress autoplay rejection internally; paused is observable but not a durable success receipt.
- Sound handles: volume defaults 1 and clamps 0..1; stop() pauses and rewinds, pause() retains position, resume() requests playback, all returning void. stopAll() clears owned media sources. No ended/error callback or exposed media element is part of this handle.

<a id="sdk-media"></a>

### Camera, Microphone and Audio Reactivity

- ctx.camera.start({ facing?: "user" | "environment" | "front" | "back", width?, height?, preview?: { opacity?, layer?, order?, zIndex?, objectFit?, mirror? } }) -> Promise<HTMLVideoElement>. preview configures the SDK-owned video layer; layer/order follow normal surfaces, zIndex is the advanced override, objectFit is cover/contain/fill/none/scale-down, and mirror flips it horizontally. Requires camera permission and user OS grant.
- ctx.camera.stop(), pause(), resume(), flip() -> camera lifecycle. flip() returns Promise<HTMLVideoElement|null> and toggles user/environment.
- ctx.camera.snapshot() -> HTMLCanvasElement|null from latest video frame.
- ctx.camera.zoom(level) -> best-effort hardware zoom when supported.
- ctx.camera.ready, width, height, facing -> camera state getters.
- ctx.microphone.start({ fftSize?, smoothing? }) -> Promise<microphoneHandle>. Requires microphone permission and user OS grant. Audio permission is not needed for analysis; request audio separately only for playback or raw Web Audio.
- Microphone handle: sampleRate, fftSize get/set, smoothing get/set, analyser, getFrequencyData(), getTimeDomainData(), getFeatures() -> { level, peak, bass, lowMid, mid, treble, beat, spectrum }.
- ctx.microphone.stop() -> stop mic stream and close audio context.
- Camera/microphone starts are single-flight. stop() cancels pending acquisition as well as active media; cancelled starts reject with AbortError. Ignore intentional cancellation in error UI, and do not use a retired ctx after restart. Camera flip preserves the returned video; calls during acquisition join the current request.
- ctx.audio.reactive.start(options) and stop() reuse the same managed microphone analysis stream; never create a second getUserMedia stream for visual audio reactivity.
- If camera or microphone permission is denied, show a graceful fallback instead of a blank screen.
- ctx.audio.reactive.start(options?) -> Promise<microphoneHandle>, exactly the same managed analyser handle as ctx.microphone.start; reactive.stop() stops that shared microphone stream. It needs microphone, not audio/backgroundMusic. No separate beat callback or reactive event bus exists: poll microphoneHandle.getFeatures() in your render loop.
- Microphone options default fftSize:2048 and smoothing:0. FFT sizes must satisfy the browser AnalyserNode power-of-two constraints (32..32768); smoothing is 0..1. Invalid settings may reject setup or throw on assignment. sampleRate is Hz; getFrequencyData returns a reused Uint8Array (0..255 bins), getTimeDomainData a reused Float32Array. Copy arrays only when retaining samples across reads.
- microphoneHandle.getFeatures() returns level/peak and bass/lowMid/mid/treble normalized to 0..1, beat as a heuristic boolean, and spectrum as the reused frequency array. Band names describe fixed FFT-bin fractions, not calibrated frequency cutoffs; beat is not a tempo tracker. After stop, getFeatures returns empty/zero features; do not call the raw frequency/time getters on a stopped handle.
- Camera and microphone start promises reject for missing declaration, denied OS access, unavailable hardware/WebView support, setup failure or AbortError cancellation. Stop is idempotent and disposes late acquisitions; start after stop acquires a new lifetime. Keep fallback controls available and do not retain analysis/video across ctx destruction.

<a id="sdk-camera"></a>

### Camera Availability and Placement

- Camera is supported in native builds. Use it only when the camera is the actual interaction surface, not as decoration.
- Permission: camera. Prompt should happen from a user gesture where possible.
- Use facing "user" for selfie/face bits and "environment" for rear-camera filters.
- Keep the returned video in its SDK-owned DOM layer; configure visual placement through start({ preview }) instead of reparenting it. Use preview.layer/order to place it beneath or above other surfaces; use zIndex only for an intentional advanced override.
- Never assume camera exists. Check ctx.capabilities.camera and handle rejected start().
- start(options?) defaults to facing:"user"; width/height are ideal capture resolution hints in pixels, not layout size guarantees. front maps to user, back/rear map to environment. The promise waits for a playable first frame, rejecting camera_frame_timeout after the readiness deadline, camera_frame_error on media failure or camera_play_failed if playback is blocked.
- Preview defaults: opacity:0.001, objectFit:"cover", mirror:false, zIndex:0 and input passthrough. Request preview.opacity:1 explicitly when the video itself should be visible; using video as a renderer input does not require a full-opacity preview. Capture width/height getters report video pixels; ctx.width/height remain viewport CSS pixels.
- pause()/resume() control preview playback and return void; pause is not a privacy stop and does not stop the acquired track. stop() cancels acquisition, stops tracks and removes preview. flip() returns the existing preview after switching stream or null before start; unavailable preferred facing may fall back to the default camera. zoom(level) clamps to hardware capability, returns void and suppresses unsupported/constraint failure; do not claim zoom succeeded without device evidence.
- snapshot() synchronously returns a new local canvas at capture resolution or null without a ready frame. It is not a saved file, automatic upload or permission to transmit camera pixels. Do not treat start success as continuous device availability.

<a id="sdk-microphone"></a>

### Microphone Privacy and Permissions

- Microphone analysis is supported in native builds. Use it only when audio is central to the interaction.
- Permission: microphone. It is sufficient for SDK microphone analysis; audio is a separate permission for playback or custom synthesis. Plethora exposes analysis data only; do not record or upload audio.
- Use getFrequencyData() for spectrum/reactive visuals and getTimeDomainData() for waveform/amplitude.
- Never assume microphone exists. Check ctx.capabilities.microphone and handle rejected start().

<a id="sdk-storageandmotion"></a>

### Synchronous Storage and Raw Sensor Compatibility

- ctx.storage.get(key) -> parsed JSON value or null. Requires storage permission.
- ctx.storage.set(key, value), remove(key), clear() -> viewer-local storage scoped to this Bit. Requires storage permission.
- ctx.storage is synchronous; get returns the value or null; set/remove/clear return nothing, so don't await them or chain .then/.catch.
- ctx.sensors is the raw/advanced compatibility surface. ctx.sensors.start() -> Promise<boolean>, snapshot, tilt, acceleration, accelerationIncludingGravity, accelerometer, gyroscope, magnetometer, rotation, rotationRate, orientation, onChange(listener), and active expose native bridge fields.
- Compatibility raw sensors: ctx.sensors.available reflects motion permission; start() sets active and resolves true but does not promise a fresh sample or request browser sensor consent. onChange(listener) returns cleanup for raw native sensor snapshots. There is no raw sensors.stop/pause/resume API; prefer ctx.motion for acquisition, calibration and lifecycle.

<a id="sdk-storage"></a>

### Local Storage Boundaries

- Use ctx.storage only for viewer-local convenience. For platform leaderboards/tallies/shared worlds, use ctx.memory.
- Do not store secrets. Values should be small JSON-serializable state.
- Storage get returns null for absent, malformed or inaccessible data after the permission check. set/remove/clear swallow underlying serialization/storage failures and return void; there is no durable write acknowledgement. Missing storage permission throws synchronously. clear removes only this Bit namespace, not all browser storage; use declared memory APIs when server acceptance matters.
- ctx.storage is synchronous device-only WebView storage, not account-owned cloud memory. Keep it for disposable convenience, never the sole store for personal bests, unlocks or progress that must survive reinstall. In authenticated published app playback, read accepted bests from the existing record standing and use declared ctx.memory.local or ctx.game.progress for durable personal state. A record declaration does not restore an authored BEST label automatically. This cloud guarantee excludes draft preview and shared-web play: shared-web memory uses page-local simulation even for published Bits, not account-cloud persistence.
- Reinstall cannot recover never-delivered local bytes. Legacy storage is namespaced by Bit, not by signed-in account: do not treat an unattributed old device value as a proven account score or upload it into competitive records. Account switch must not inherit another viewer's cached best/progress. Neither storage API requires adding camera, microphone or motion permissions.

<a id="sdk-motion"></a>

### Motion, Calibration and Sensor Events

- ctx.motion.start(options?) -> Promise<true>. Requires motion permission and should be called from a real tap/press; it prefers the native sensor bridge and falls back to browser motion events.
- Native and browser events are separate streams: fresh native data wins before callback throttling. Raw snapshot.tilt remains native radians or browser degrees; control and tiltControl normalize both into degree-based steering and preserve circular calibration. snapshot.tiltAtMs is the last orientation measurement, not the last gyro/acceleration transport; ignore duplicate tiltAtMs when applying a steering sample. Never add a second source filter or recalibrate because one animation frame was slow.
- State/getters: available, active, permission ("granted" | "denied" | "prompt" | "unavailable"), error, snapshot, tilt, control, acceleration, accelerationIncludingGravity, gravity, rotationRate, gyroscope, magnetometer, orientation, quaternion. Legacy accel remains an alias for accelerationIncludingGravity.
- snapshot shape: { atMs, source: "native" | "browser" | "none", orientation, tilt:{x,y,z}, control:{x,y}, acceleration, accelerationIncludingGravity, gravity, rotationRate:{alpha,beta,gamma}, gyroscope, magnetometer, quaternion:{x,y,z,w}, calibrated, permission }. Missing values are finite zero vectors, not undefined traps.
- Calibration/filtering: ctx.motion.calibrate(options?), resetCalibration(), setSmoothing(value), setDeadzone(value), setAxisMapping({ invertX?, invertY? }). Calibration captures current neutral tilt; settings are additive and cleanup-owned.
- ctx.motion.tiltControl({ maxAngle?, deadzone?, smoothing?, invertX?, invertY?, calibrate? }) -> { x, y, angle, strength, raw, destroy() }. x/y are normalized -1..1 and are useful for marble mazes, balance toys, steering, parallax, and gravity painting.
- ctx.motion.shake({ threshold?, cooldownMs?, smoothing? }) -> { active, strength, count, vector, destroy() }. ctx.motion.impulse({ threshold?, cooldownMs?, smoothing?, decayMs? }) -> { active, strength, vector, ageMs, destroy() }. Use impulse for short tactile bursts, not for claimed world-space tracking.
- Events: ctx.motion.on("shake" | "tilt" | "flip" | "faceUp" | "faceDown" | "orientationChange" | "impulse" | "impact" | "change", handler) and ctx.motion.onChange(handler, { throttleHz? }) return cleanup functions. flip fires only when gravity-derived face orientation changes.
- Lifecycle: ctx.motion.stop(), pause(), resume(). Plethora stops it on runtime cleanup and pauses it with the host. Do not collect hidden/background motion data.
- Always support non-motion fallback controls. ctx.motion describes device sensors only; object animation belongs in ctx.game.loop/ctx.math/ctx.geometry or renderer/library code. It does not track real-world phone position.
- start options: { smoothing?, deadzone?, calibrate?:true|{alpha?,beta?,gamma?} }. setSmoothing clamps 0..1; setDeadzone clamps 0..0.99; setAxisMapping accepts invertX/invertY. calibrate({alpha?,beta?,gamma?}?) and resetCalibration() return snapshot copies. Calibration override angles use the current source units, so prefer capture-current calibration over invented unit conversions.
- Snapshot also contains snapshot.tiltAtMs, the orientation sample timestamp. atMs is transport/sample time in milliseconds; neither timestamp is game elapsed time. Raw native rotation/tilt and browser rotation/tilt retain source units. tiltControl.maxAngle defaults to 28 degrees; its angle getter is radians, strength is 0..1, raw contains the normalized steering target.
- shake/impulse handles both expose active, strength, count, vector, ageMs, destroy(). Defaults: shake threshold:1.4 and cooldownMs:450; impulse threshold:1.2, cooldownMs:120, decayMs:260. Thresholds compare the delivered acceleration magnitude, not a guaranteed world-space displacement. Recipes require started motion; creating a handle alone does not acquire sensors.
- on(event,handler) returns cleanup; onChange(handler,{throttleHz?}) receives a cloned snapshot with bounded subscriber cadence, not every native transport packet. Shake/impulse events include { type, strength, vector, count, atMs, snapshot }; tilt/orientation/face events reflect current sensor data. Stop detaches sensor delivery; destroy each recipe when it is no longer used.

<a id="sdk-memory"></a>

### Local Memory, Records, Tallies and Shared Worlds

- Use ctx.game.progress, not ctx.memory.local, for game state that should make Plethora show the Bit in Continue Playing.
- ctx.memory.local(channelId).get() and set(value) -> Promise<{ value, updatedAt }>. An empty get returns value:null and updatedAt:null; read result.value rather than treating the result as bare saved JSON. Channel must be declared in manifest.memory.local.
- In authenticated published app playback, ctx.memory.local is cloud-backed per-account state: local means private to the viewer, not device-only. An acknowledged set survives reinstall on the same account and channel scope. This excludes draft preview and shared-web play: draft memory is isolated simulation; shared-web memory uses page-local simulation even for published Bits, not account-cloud persistence. Simulated memory/record success is not an account save receipt; the separate web score-claim flow does not make memory cloud-backed. Hydrate and validate result.value before enabling saves. A failed read is not empty state: retain the working view, show unavailable/retry, and do not overwrite cloud state with defaults. Fence late loads/saves to the current lifetime/account and serialize or coalesce bounded saves so an older completion cannot replace newer state.
- ctx.memory.record(channelId).submit(value, { label?, dimensions?, metadata? }?) -> Promise<result>. Raw record access remains available for custom flows, but use ctx.game.score(...).submit(channelId, options?) for normal live numeric scores. The channel declaration label names the leaderboard column; submit label is only an optional formatted value such as "950 pts", never "High Score".
- Submit the score at the end of every run: every game over or loss, including a game over that comes after a win when play continues (keep going, tap to continue). Never gate the game-over submit behind a won or completed flag: every final score after the win is then lost, and the board keeps the score from the moment of the win. Leave a run out only on purpose, such as an assisted or practice run, or a record that only exists on a win (a clear time, a win streak).
- ctx.memory.record(channelId).checkpoint(value, { label?, dimensions?, metadata? }?) -> Promise<queue receipt>. value must be a finite number representing an already-valid result. Supports best_per_user only; latest_per_user and all_entries require explicit submit and checkpoint rejects with invalid_checkpoint. Uses memory.record.checkpoint with the same payload as submit; the host owns persistence/coalescing/retry, not an independent WebView uploader. Published receipt is { queued:true, checkpointId, submitted:false }; use submit when server acceptance must be observed.
- ctx.memory.record(channelId).leaderboard({ scope?, period?, dimensions?, limit? }?) -> Promise<leaderboard>. Returns rows and nullable viewerRank with totalRanked and board metadata. Plethora owns standard global/following leaderboard UI. After submit/checkpoint, same-run reads wait for pending writes rather than racing them.
- ctx.memory.record(channelId).rank({ scope?, period?, dimensions? }?) -> Promise<standing>. Same read as leaderboard with limit:1, omitting rows; preserve viewerRank, totalRanked and metadata together. No separate route or rank algorithm. Empty boards/viewers return viewerRank:null, not rank zero.
- ctx.memory.record(channelId).checkpointStatus({ dimensions? }?) -> Promise<{ pending, failed, lastFailure }>. Inspect buffered work and errors for this Bit/channel/dimensions and current attempt without blocking gameplay. Returned rank/leaderboard metadata also carries checkpointStatus; render failed checkpoint status separately from the currently accepted board, never as a saved-score success.
- Memory failures retain code/status/retryable. A timeout may have an indeterminate write outcome, so never blindly resend an explicit submit with a new identity. Handle failures in a detached result task; use an attempt token plus ctx.onDestroy guard for both success and error UI callbacks.
- Record declarations control order (desc high score or asc best time), dedupe (best_per_user, latest_per_user or all_entries), periods, scopes, and named dimensions such as mode or arena. There is no separate score manifest namespace.
- For a durable personal BEST in authenticated published app playback, read the existing best_per_user record with rank({ scope:"global", period:"all_time", dimensions }) and use viewerRank.value when viewerRank is non-null. Select the declared all_time period and exact dimensions for the displayed mode; preserve channel key/epoch, dedupe and order. The server applies desc for highest score or asc for lowest valid result; do not combine modes, use a daily rank as lifetime best, or compute a competing best in device storage. Null means no accepted standing, not a numeric zero. Keep accepted best, rank and board metadata together; pending local improvements are separate.
- Detached accepted-best example for authenticated published app playback, inside init(ctx). This assumes an existing high_score best_per_user record with global/all_time and mode:"classic" declared; substitute the actual channel/dimensions, never rename a live board to fit the example. renderBest is your own UI patch function, not an SDK API: on error retain the previous best/standing and show unavailable; on success display checkpointStatus.pending/failed separately from accepted values. Call startAttempt from each real play/replay gesture, and refreshBest only at bounded result/refresh boundaries, never each frame. Paint and enable replay without awaiting this read.

```javascript
const record = ctx.memory.record("high_score");
const dimensions = { mode: "classic" };
let attempt = 0;
let read = 0;
let disposed = false;
ctx.onDestroy(() => { disposed = true; });

function refreshBest() {
  const owner = attempt;
  const request = ++read;
  void record.rank({ scope: "global", period: "all_time", dimensions })
    .then(result => {
      if (disposed || owner !== attempt || request !== read) return;
      renderBest({
        best: result.viewerRank === null ? null : result.viewerRank.value,
        standing: result,
        error: null
      });
    })
    .catch(error => {
      if (disposed || owner !== attempt || request !== read) return;
      renderBest({ error });
    });
}

function startAttempt() {
  attempt += 1;
  ctx.platform.start();
  refreshBest();
}
```
- Several leaderboards are allowed: each manifest.memory.records key is its own board (records, tallies, worlds and local channels together are at most 16), and Plethora's leaderboard shows a board picker when a Bit has two or more. A challenge (a player sends their score for others to beat) puts a progress ring on the logo that fills with the live score only when the Bit has exactly one leaderboard and higher scores win (order "desc"); with two or more boards, or a lower-wins board, the ring shows but does not follow the score.
- Leaderboards carry over to every new version, whatever changed: a board is its record key plus epoch, and Plethora keeps the live epoch, so code, visuals, audio, difficulty, tuning or scoring changes and any epoch in your files all keep the board and its scores. Only the maker can start a game's leaderboards over, by choosing it when they publish (the app and dashboard publish screens; the publish API takes leaderboardReset: "reset", anything else keeps). It clears everyone's scores and places on that game, and challenges against old scores, so Plethora recommends keeping the leaderboard: do not suggest a reset or ask the maker for one.
- Rows are also keyed by record key, dimensions and period, so once a game is live keep each record's key, dimension names and values, periods, dedupe and order the same. Renaming a key, changing dimensions or periods, or moving from all_entries to a per-user best shows players a board without the old scores; flipping order ranks old and new scores by different rules.
- ctx.memory.tally(channelId).choose(value) -> Promise<result>. ctx.memory.tally(channelId).results(options?) -> Promise<results>. Use for polls, ratings, reactions, votes.
- ctx.memory.world(channelId).get(options?) -> Promise<snapshot>. ctx.memory.world(channelId).mutate(mutation) -> Promise<result>. Use for bounded co-creation.
- World mutations are semantic and bounded. pixel_grid: { x, y, color }. points: { id, x, y, ... } or { id, delete: true }. objects: prefer { id, object } or { id, op: "delete" } for per-object updates; legacy/small board patches like { notes: [...] } are accepted but field worlds are cleaner for whole-state patches. sequencer_grid: { x, y, value }. field: object patch.
- Declare memory channels in plethora.json first. Bits cannot create ad hoc channels at runtime.
- Respect declared rules/rate limits. Design UI for rejected writes or unchanged state.
- Memory handles are synchronous channel selectors; undeclared channel IDs throw before any request. Their methods return promises of host responses, not raw HTTP Response objects. Published memory requires the current signed-in viewer and matching package/channel authority; draft preview uses isolated local simulation and never proves a public write succeeded. Memory channel declarations are separate from the storage permission.
- Record submit result: { submitted:true, eventId, value, displayLabel, updatedPeriods, isPersonalBest, improvedBest, standing, pulseCapture, challenges }. Older receipts may omit newer fields. standing is nullable acceptance-time board evidence, not necessarily current after later writes; pulseCapture/challenges are host outcome metadata, not APIs to call or authorization to publish.
- Leaderboard result: { channel, scope, period, dimensions, rows, viewerRank, standing, rankStatus, rankComputedAt, totalRanked, boardKey, boardVersion, checkpointStatus? }. viewerRank is a nullable ranked-row object, not a numeric rank; inspect its rank field. The nested standing carries rank/userId/value/displayLabel/achievedAt, totalRanked, period/periodStart, dimensions, scope, channel/scopeKey and board identity/freshness. rank() returns the same response without rows.
- Leaderboard options select declared scope (global/following), period and dimensions; limit defaults 25 and clamps 1..100 in current server reads. Do not infer a missing rank from limited rows. checkpointStatus lastFailure is optional failure detail, not an accepted-score receipt. Keep scope/period/dimensions and rankComputedAt with cached rows.
- Tally choose(value) accepts only the answer form declared by that channel and resolves { submitted:true, eventId, answer, answerKey }. results(options?) resolves { channel, results:[{answerKey,count}], viewerResponse:{answer,answerKey,updatedAt}|null }. Current server results has no pagination/filter option; an options parameter is not a promise of arbitrary queries.
- World get(options?) resolves { channel, state, version, updatedAt }; current server get returns the bounded snapshot without cursor/filter semantics. mutate(mutation) resolves { mutated:true, eventId, snapshot } with the resulting state/version. No world subscribe/list/delete-channel method exists. Use only declared bounded semantic mutations; normal rejection/rate-limit errors must not blank the working view.

<a id="sdk-assets"></a>

### Unavailable Packaged Assets

- ctx.assets.url/image/audio/json/text exist only to fail clearly in the public runtime while maxAssets is 0.
- Do not include packaged bit assets in zips. Generate visuals/audio procedurally, use inline data for tiny sounds if appropriate, or use approved registry libraries.
- Unavailable behavior: ctx.assets.url(path) throws synchronously. ctx.assets.image(path), audio(path), json(path), and text(path) return rejected promises. These are failure stubs for compatibility, not asset-loading capabilities or permission requests.

<a id="sdk-antipatterns"></a>

### Legacy Anti-Patterns and Safety Reminders

- No document.body mounting, manual script tags, public CDN URLs, latest/range dependencies, workers, sockets, arbitrary fetches, or hidden network calls.
- No blank first frame. Draw something immediately, then call ctx.platform.ready() or ctx.markVisualReady(reason).
- No text under the camera cutout or Dynamic Island and no control behind the logo button. Lay out text, scores and controls inside ctx.contentSafeArea ?? ctx.safeArea; only the background and passive scenery go edge to edge.
- No undeclared permissions. If source uses camera/microphone/audio/backgroundMusic/haptics/motion/storage, manifest.permissions must include it.
- No defaulting to camera, microphone, or motion mechanics; they need explicit creator intent plus fallback UI.
- No progress-save spam. Do not call ctx.game.progress.save from animation frames, physics loops, collision loops, or every normal tap. Save checkpoints only.
- No blocking gameplay/replay on submit, checkpoint, rank, or leaderboard promises; no per-frame database writes, polling watchdog, or screenshot for each score tick. Checkpoint queue receipts are not accepted scores. Never derive global rank from the top-ten array or mix a new score with an old rank.
- No assuming ctx.input replaces advanced creator logic. Use it for ergonomic state and common gestures; custom physics, advanced geometry, shader controls, 3D raycasting, and library input systems are still allowed inside the sandbox.
