# Plethora: Fundamentals

Context version: plethora-agent-context-2026-10-22.1
SDK version: 1.8.0
Workflow version: 2026-10-30.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.

Public guidance. No pairing or token needed to read or build.

No pairing or account token is needed to read these docs, plan, build or test. Account writes need an approved agent token; publication remains the creator's decision. Current server documents replace deprecated local starters/skills.

## Which Document Answers What?
- [creation.md](https://agent.plethora.studio/v1/agent/creation.md): the eight-step process and evidence required before delivery.
- [sdk.md](https://agent.plethora.studio/v1/agent/sdk.md): the complete public API, including nested methods and returned handles. Focused topic pages project that reference.
- [schema.json](https://agent.plethora.studio/v1/agent/schema.json): exact manifest fields, types, enums and bounds. Parse the standard response envelope's data field; data.jsonSchema is the manifest schema.
- [libraries.json](https://agent.plethora.studio/v1/agent/libraries.json): exact approved dependency, font and auxiliary-resource pins and loading metadata.
- [existing-code.md](https://agent.plethora.studio/v1/agent/existing-code.md): preserving a working project while adapting its ownership and lifecycle.

The schema is not the SDK and cannot teach all capabilities. Valid JSON or a valid manifest does not prove valid source, a resolved dependency, visible rendering, correct mechanics, or native behavior. Read versions together; never silently combine stale local examples with the live contract.

## Package and Declarations
Keep exact authored JavaScript and plethora.json in files. The package entry defines window.plethoraBit = { meta?, async init(ctx) {} }. The manifest owns title, description, tags, runtime, entry, permissions, dependencies and declared state; meta contains documented runtime hints, not a competing manifest. Do not guess fields or duplicate contradictory metadata.

## Manifest Contract

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`)


Minimal matching manifest:
```json
{
  "schemaVersion": 1,
  "runtime": "plethora-bit@2",
  "entry": "main.js",
  "title": "Touch Sketch",
  "description": "A tiny touch-reactive Plethora Bit.",
  "tags": [
    "creative",
    "touch"
  ],
  "permissions": [
    "haptics"
  ],
  "dependencies": [],
  "display": "fullscreen",
  "onboarding": {
    "kind": "one_line",
    "version": 1,
    "message": "Touch the canvas to make a mark."
  }
}
```

Declare only what the Bit uses. Manifest memory declares record/tally/world channels; game.progress declares resumable viewer state; tuning declares creator-editable values/curves; onboarding declares the deliberate first-use mode; display: "fullscreen" is required in every Bit: it gets the whole screen, and publishing refuses a Bit without it (a draft without it is still saved, so add it before asking the creator to publish). Refer to schema for every nested type and limit and SDK for the corresponding operations. These optional capabilities do not impose a game structure on art, tools, DOM experiences or toys.

Preserve published channel keys, dimensions, ordering and progress identity when revising an existing Bit. Version and validate saved state before restoring it; a style update is not consent to reset someone's records or progress. Use structured serializers for manifest and upload JSON, not shell string interpolation. Source bytes tested must be source bytes submitted.

## Runtime, Surfaces and Ownership
init receives ctx, the runtime SDK, not a 2D painter. ctx.createCanvas2D() returns an HTMLCanvasElement; canvas.getContext("2d") returns its painter. ctx.createCanvas() supports a library/WebGL canvas. ctx.createRoot() supports DOM. The SDK documents ctx.root, scoped DOM utilities and surface handles; do not invent browser globals or mount into the host document.

DOM, Canvas2D, WebGL and approved renderers can compose. Use explicit background/content/overlay/modal layers and order, not factory call order. A full-screen HUD can be input-transparent while child controls remain interactive. Test actual browser hit testing; forcing a handler in a unit test cannot prove a user can reach it. Libraries retain their renderer, materials and controls; helpers are conveniences, not capability ceilings.

The host owns the sandbox, activity state, native bridges and surface lifetime. The Bit owns its mechanics, visual composition, authored state and disposal of library/custom resources. Use cleanup-owned SDK listeners/timers/frames and ctx.onDestroy for resources created outside them. Async work can finish after disposal: ignore stale results and dispose late arrivals. Avoid duplicate input/audio/render loops after replay or restore.

For accumulated active-play timing use ctx.game.stopwatch, not saved wall-clock timestamps or clamped simulation dt. Start on the real play view; pause on menus, colour changes and completion. The host excludes background/offscreen time. Keep calendar editions and reset countdowns on calendar time. Save elapsed snapshots with versioned cloud state at bounded checkpoints; only acknowledged writes are durable. Separate colour/difficulty boards with declared dimensions or new channels; preserve old record identity and never invent missing active durations from old timestamps.

## Lifecycle and Readiness
- Await registry dependencies before constructing library objects, inside async init. Pass dependencies explicitly to imported modules and bind handlers that use this.
- Paint a meaningful first visible frame before ctx.platform.ready(). ctx.markVisualReady(reason) is an explicit readiness signal, not a way to hide blank output. Never announce readiness merely because a loader or init returned.
- Call ctx.platform.start() from the first real user gesture of each attempt, including replay. Wire a real first interaction, not only a title/loading screen.
- Use ctx.game.loop for custom continuous simulation and coherent time units. A library-owned ticker is valid with deliberate ownership and cleanup; do not run a competing loop. Tiny animations/library interop can use one ctx.onFrame registration during init.
- Respect host pause/resume/background/dispose. Test lock, app switch, repeated play and late async completions. Do not build a competing host visibility manager to compensate for an SDK bug.
- Separate ctx.platform.complete lifecycle analytics from ctx.pulse.complete when an implicit completion post is appropriate. A score write, completion event and social post are different outcomes.
- Preserve the original error with ctx.platform.error. Distinguish dependency load, renderer initialization and first-frame failure; a generic catch is not evidence that WebGL is unavailable. Recovery must be explicit and bounded, never an automatic restart loop.

## Coordinates, Layout and Input
ctx.width/height are CSS pixels. Canvas backing-store size can differ by DPR. Choose coordinateSpace:"css" explicitly for CSS-space drawing; maxDpr bounds cost. Legacy backing-store drawing remains supported. Keep drawing, clearing, FX and hit tests in the same coordinate space. Identity transform repair is a runtime safeguard, not a reason to mix units. desynchronized is opt-in; alpha:false is only suitable when every pixel is painted; willReadFrequently is a local Canvas2D performance hint, not a backend or upload channel.

Use ctx.onResize(layout, { immediate:true }) and reflow phone layouts. Every Bit is full screen and owns the whole screen: paint the background edge to edge and lay out from const area = ctx.contentSafeArea ?? ctx.safeArea, which is clear of the camera cutout or Dynamic Island, the home indicator and Plethora's logo button (ctx.logoArea); in CSS use var(--plethora-content-safe-top, 0px) and var(--plethora-content-safe-bottom, 120px). On older apps the same Bit plays in the safe frame, where ctx.safeArea and those fallbacks still keep it clear. Keep actionables, important feedback and instruction cues inside that area; scenery may extend underneath. Do not shrink the whole game to the upper half or treat all lower playfield pixels as forbidden. Avoid drag zones along the bottom inset and the side edges, where the phone takes system swipes, and buttons covering active content. DOM text inputs use host keyboard avoidance on iOS; only a Bit that owns its entire keyboard layout should opt out via meta.keyboardBehavior = "none".

ctx.input provides normalized tracking/gestures while ctx.listen remains the raw event escape hatch. Respect documented local, normalized, NDC and native units; do not assume everything is 0..1. Use native DOM activation for controls, deliberate capture/touch-action settings and cancellation. Complex raycasting, physics, spatial queries and library-specific controls remain available.

## Permissions, Dependencies and Safety
- Public bits run in a fixed WebView sandbox owned by Plethora.
- Bits cannot load arbitrary public CDNs or arbitrary remote code.
- External libraries must be approved, version-pinned registry dependencies served from libs.plethora.studio.
- Packaged bit assets are currently disabled: maxAssets is 0.
- Camera, microphone/audio-reactive, and motion bits are supported in native Plethora builds. Use them when they serve the creator intent; require manifest permission, OS/user grant, user-gesture startup, cleanup, and a non-sensor fallback.
- Publish stays manual so the creator can review AI feedback and platform moderation before release.

Every permission-gated call needs its matching declaration, available capability and intentional user consent. Camera/microphone/motion are native capabilities, not universally available in every browser/preview. Check ctx.capabilities, start protected media from a real gesture and offer useful denial/unavailable fallbacks. Raw motion units are not normalized steering or accurate world-position tracking; use the documented derived controls/calibration where appropriate.

Read registry kind, version, URL, exports/global name and auxiliary resources before choosing a loader. Use ctx.importModule for module pins, ctx.loadScript for approved script pins and ctx.loadFont for approved font pins. Await the returned value; do not assume a global appeared. Variables, tables, helpers and destructuring are valid authoring patterns; the resolved resource must still be approved. Do not fall back to arbitrary fetch, CDN scripts or manual script tags. Missing registry support is a constraint to explain, not permission to invent a URL. Current asset limits apply even if a reference image would be convenient.

Resource sidecars are loaded through dedicated helpers or ctx.registry.resources(); do not add them as separate manifest dependencies unless the SDK explicitly asks for it. Self-contained procedural drawing and inline SVG are distinct from remote/packaged assets; they do not grant network access.

### Contract Reminders
- Use ctx helpers for DOM/canvas, events, frame loops, media, storage, registry libraries, platform events, audio, and memory. Avoid raw document/body/script patterns unless explicitly allowed below.
- Every new Bit must consciously choose manifest.onboarding. For mechanics that need handholding, prefer a brief, interactive example drawn inside the Bit with a clear Skip and safe control placement; declare immersive when the Bit owns that first-use scene so the runtime adds no second overlay. Use one_line for one obvious action. The managed guided and briefing modes remain available for compatibility, not as the default puzzle tutorial. Use short pointers, not paragraphs. First-use entry is separate from optional post-play Bit World quick-reference tips.
- For multi-surface composition, use layer: "background" | "content" | "overlay" | "modal" plus optional order. This works for Canvas2D, raw WebGL/Three canvases, DOM roots, and managed camera preview without imposing a factory call order. A full-screen HUD should usually use input:"passthrough" or pointerEvents:"none". ctx.listen and ctx.input.delegate preserve hit testing; enable interactive children with CSS pointer-events:auto, ctx.surface.enableInput(child), or ctx.input.track/on/activate. Prefer CSS text for createRoot style; do not use React Native style arrays or implicit numeric units.
- Camera, microphone/audio-reactive, and motion features are permission-gated native capabilities. Do not make them the default solution without creator intent; always provide a fallback.
- Every permission-gated API must have the matching manifest permission. Check ctx.capabilities before optional features and show a graceful fallback.
- DOM text inputs default to host keyboard avoidance on iOS. If a bit fully manages its own keyboard layout, set window.plethoraBit.meta.keyboardBehavior = "none"; otherwise leave it unset.
- Call ctx.platform.ready() only after first visible render or after calling ctx.markVisualReady(reason). Call ctx.platform.start() from the first real user gesture.
- Explicit sexual content, hateful content, harassment, or graphic violence.
- No-interaction content that looks like a blank screen, wallpaper, or static poster.
- Misleading metadata, an incoherent onboarding choice, or missing first-use guidance for non-obvious interaction.
- Any raw public CDN, arbitrary fetch, socket, worker, or remote script outside the Plethora registry.
- Undeclared camera, microphone, or motion input, permission-gated bits without fallback UI, or packaged assets under the current public contract.

## State and Platform Outcomes
Keep transient simulation in memory. Local preferences, viewer-private Continue Playing progress, competitive records, shared tallies/worlds and first-use completion are distinct. None automatically implements pass-and-play identity. Use documented semantic shared-state mutations, bounded checkpoint writes and explicit failure handling, never per-frame network I/O.

In authenticated published app playback, ctx.memory.local is cloud-backed per-account private state; ctx.storage is synchronous device-only convenience with no durable acknowledgement. Use ctx.game.progress for resumable Continue Playing state and declared personal memory for other durable unlocks/work. Restore BEST from the existing best_per_user record's all_time standing with the exact dimensions/order, not a competing device cache. Preserve channel/epoch identity. A failed read is not empty state and must not trigger a default/reset write. Reinstall cannot restore never-delivered bytes; never import unattributed legacy device values as account records. Verify reinstall after acknowledged saves, account switch, offline/partial delivery, stale callbacks and continued play after a win. These cloud guarantees exclude draft preview and shared-web play: shared-web memory uses page-local simulation even for published Bits, not account-cloud persistence. A simulated success or separate web score claim does not prove a cloud memory/progress save.

Scores update locally during play. Queued checkpoints are not server acceptance. Use explicit submit and authoritative rank/leaderboard results where needed; do not infer rank from visible top rows. Replay must stay immediate while pending/failed requests are displayed honestly; fence callbacks to the current attempt. Complete or abandon resumable progress when appropriate. Pulse sharing and leaderboards are opportunities, not compulsory features for every Bit.

## First Use and Verification
Every new Bit chooses manifest.onboarding deliberately. Immersive fits obvious or intentional discovery; one_line fits a single cue. For complex mechanics, prefer a short, skippable, interactive example inside the Bit, with immersive preventing a second host overlay. Managed guided/briefing modes remain compatibility tools. Keep optional Bit World quick-reference tips separate from first-use teaching.

Follow [creation.md](https://agent.plethora.studio/v1/agent/creation.md) for craft, novice walkthrough, known mistakes, code audit and execution. A saved draft is not proof of a functioning Bit. Browser evidence is not native Android/iOS proof. Report what actually ran and what remains unverified; use [upload.md](https://agent.plethora.studio/v1/agent/upload.md) for the real command/auth/retry protocol.

Reading path: [Creation](https://agent.plethora.studio/v1/agent/creation.md) | [Fundamentals](https://agent.plethora.studio/v1/agent/fundamentals.md) | [Complete SDK](https://agent.plethora.studio/v1/agent/sdk.md) | [Verify and upload](https://agent.plethora.studio/v1/agent/upload.md).
