# Plethora Bit Agent 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.

Plethora Bits are tiny mobile-first interactive objects: games, puzzles, interactive art, fidget toys, music toys, educational activities, sensory experiences, and other small playful systems. Agents should be able to create them with no local starter repo as long as they follow this contract.

## Shortcut Interpretation

If the user says "upload to plethora studio", "Upload to Plethora", "Plethora par daaldo", "put this on Plethora", "make this a Plethora Bit", or mentions Plethora with an interactive/game/puzzle/art idea, treat it as a request to create a Plethora Bit and upload it as a draft. Do not ask the creator to copy another prompt or repeat the idea. Pair if needed, build from the current contract, upload a draft, and do not publish unless the creator explicitly asks from inside Plethora.

## Complete Reference (Optional)

Canonical agent origin: https://agent.plethora.studio

For a fresh conversation begin with `https://agent.plethora.studio/v1/agent/start.md` (`/v1/agent/start.md`). Follow [creation](https://agent.plethora.studio/v1/agent/creation.md), [fundamentals](https://agent.plethora.studio/v1/agent/fundamentals.md) and the [complete SDK](https://agent.plethora.studio/v1/agent/sdk.md); this assembled document remains for direct links and existing integrations. Offer pairing early but start building as soon as an idea is known, without waiting for approval.

## Current Flow

1. If the user says "upload to plethora studio", "Upload to Plethora", "Plethora par daaldo", "put this on Plethora", "make this a Plethora Bit", or mentions Plethora with an interactive idea, treat it as a request to create a Plethora Bit and upload it as a draft. Fetch https://agent.plethora.studio/v1/agent/start.md (/v1/agent/start.md) first. Offer pairing and retain the idea; building does not wait for approval.
2. Fetch https://agent.plethora.studio/v1/agent/context.md at the start of every new Bit and again before every upload, and build against its current contextVersion. Never rely on an SDK, context, schema or skill cached from an earlier chat; send that contextVersion as agentFeedback.contextVersion (an older one is refused with 409 context_outdated). Only full-screen Bits (manifest "display": "fullscreen") can be published.
3. Offer pairing immediately when the creator wants to create or upload. Reuse a valid saved agent token. Approval must never block reading docs, designing, coding, or testing.
4. If an idea or existing project is already supplied, retain it and start building while pairing approval is pending. Do not ask the creator to repeat the idea.
5. If no idea is supplied, briefly explain Bits, offer pairing, and ask what they want to make. Do not choose or build an unsolicited project.
6. Once the idea is known, follow creation.md: read fundamentals.md and the complete sdk.md before planning; use schema.json for exact declarations. Topic pages are focused lookups, not hidden capabilities. All build resources are public; credentials are required only for account operations and draft upload.
7. Before upload, reuse the saved token or check the pending pairing. If missing or expired, offer pairing again in place without discarding the completed source or asking the creator to restart the conversation.
8. Upload as a draft. Report saved, tested, and published as distinct states. Publishing remains the creator's manual decision in Plethora.
9. With an idea, follow https://agent.plethora.studio/v1/agent/creation.md. Read https://agent.plethora.studio/v1/agent/fundamentals.md, the complete https://agent.plethora.studio/v1/agent/sdk.md and https://agent.plethora.studio/v1/agent/schema.json before planning. Topic pages are focused lookups of the same SDK, not a capability-discovery gate.
10. Fetch https://agent.plethora.studio/v1/agent/libraries.json before choosing any dependency or font. Do not guess registry URLs, versions, globals, or filenames.
11. When adapting a working project, fetch https://agent.plethora.studio/v1/agent/existing-code.md before modifying it. Treat it as a conversion with its own readiness gate, not a normal from-scratch Bit.
12. Build a mobile-first bit using only the SDK and contract described by the agent resources. If any local starter, skill, or memory disagrees with these endpoints, these endpoints win.
13. Validate the manifest and source locally if the agent has a validator; otherwise keep to the schema endpoint exactly.
14. Include agentFeedback in every draft upload, even when outcome is clear, so Plethora can improve the SDK, docs, validator, and upload flow from real agent friction.
15. Keep the approved agent token for draft upload only. Do not publish; public publish is intentionally manual from the app or dashboard.

Creator web guide: https://create.plethora.studio

## Current Sensor Status

Camera, microphone/audio-reactive, and motion capabilities are available in native Plethora builds. Use them only for intentional mechanics, declare matching permissions, start from a user gesture, stop them on cleanup, and always provide denied-permission fallback UI.

## Existing-Code Conversion

Existing code is a conversion, not a normal Bit upload. Preserve its game or artwork logic where it is sound; adapt the runtime boundary deliberately, then prove actual mobile play before uploading.

Use it when: Use this workflow whenever a creator gives you an already-working game, sketch, prototype, or web project to bring into Plethora. This is workflow classification only; do not add an invented manifest field.

### Conversion Rules

- Inventory the project before rewriting it: entrypoint, dependencies, globals, DOM ownership, canvas/WebGL surfaces, input paths, timers/loops, audio, asset paths, resize behavior, and cleanup gaps.
- Do not construct or reference a delayed registry library at top level. Load the exact approved dependency inside async init, then create library-owned objects only after the await resolves.
- Choose one library loading model per dependency. For a module pin, keep the returned value such as const THREE = await ctx.importModule("three", "0.164.1"); do not assume a global THREE. For a documented script/global pin, await ctx.loadScript(...) before reading its documented global.
- Pass `ctx`, the created surface, and loaded library values explicitly into the imported game adapter. Do not make helpers depend on implicit globals such as ctx, THREE, canvas, renderer, or scene.
- Mount only through ctx.createRoot(), ctx.createCanvas2D(), or ctx.createCanvas(). Keep imported DOM queries scoped to the root you created; do not use document.body, document.head, global document queries, raw canvas creation, or injected script tags.
- Use `ctx.input` for touch controls and `ctx.input.activate` for DOM controls. Keep keyboard support optional only; every core action needs a visible, reachable mobile control. Declare `display: "fullscreen"`, let the scene fill the screen and keep the HUD and controls inside `ctx.contentSafeArea ?? ctx.safeArea`, clear of the camera cutout, the home indicator and Plethora's logo button.
- Use `ctx.listen(window, ...)` or `ctx.listen(document, ...)` for supported global events; never use direct global addEventListener calls. Bind class handlers or wrap them so this is never lost on the first touch.
- Use `ctx.game.loop` for Bit-owned simulation/rendering. A renderer-owned loop is allowed when the library owns it, but its stop/dispose path must be explicit and registered with `ctx.onDestroy`.
- Use `ctx.onDestroy` to dispose renderer loops, timers, audio, WebGL resources, library listeners, and late async work. Stop background-sensitive media and cancel/ignore loaders that resolve after disposal.
- Render a visible first state before `ctx.platform.ready()`. Call `ctx.platform.start()` only from a real user gesture that begins play or unlocks media.

### Adaptation Shape

```js
// Plethora Bit · docs and draft upload: https://agent.plethora.studio/v1/agent/start.md
window.plethoraBit = {
  async init(ctx) {
    const THREE = await ctx.importModule("three", "0.164.1");
    const canvas = ctx.createCanvas({ layer: "content" });
    const game = createImportedGame({ ctx, canvas, THREE });

    ctx.onDestroy(() => game.dispose());
    game.renderFirstFrame();
    ctx.platform.ready();
  }
};
```

### Three/WebGL Checks

- Do not label every startup exception as WebGL disabled. Distinguish dependency download, renderer/world initialization, and first-frame failures; report the original message and stage through ctx.platform.error. Offer a single-flight, user-triggered retry for failed dependency downloads, fence late results after ctx.onDestroy, and never automatically loop partial GPU initialization. A device model or generic catch block is not a WebGL capability test.
- Use ctx.createCanvas() for Three/WebGL and size the renderer from ctx.width and ctx.height. Bound pixel ratio deliberately, for example Math.min(ctx.dpr, 2), rather than assuming desktop DPR behavior.
- Initialize scene background/clear color, fog, lighting, renderer state, and any postprocessing before the first frame. Nonblank is not enough; preserve the imported piece’s intended visual language.
- When imported geometry carries vertex colors, create materials with vertexColors: true. Do not wrap vertex-colored geometry in a material that discards its color attributes.
- Translate minimaps and HUD markers from world coordinates into their local bounds. Do not assume an imported world origin is at screen/minimap origin.
- Exercise movement, collision edges, reset/recovery, and terrain starts. A controller that starts but gets stuck or misses large collider edges is not converted successfully.

### Required Mobile Proof

- Do not call a conversion ready because it renders one frame.
- On a phone-sized viewport, verify dependency load, init, first visible frame, and first real touch.
- Start/unlock audio from a real gesture when used, then verify it pauses/stops when the runtime backgrounds or disposes.
- Tap, drag, hold, or press every visible control at least once; verify the intended game state changes and keeps running for several seconds after input.
- Verify resize/orientation-safe layout where relevant, then pause/resume and unmount/remount without leftover timers, listeners, audio, or WebGL work.
- Verify visual semantics, not only absence of errors: expected background/fog/material color, nonempty HUD/minimap region, and supplied reference fidelity where a reference exists.
- Verify the primary gameplay scenario: movement, collision-critical behavior, reset/recovery, and the core goal or loop.

### Package And Review Identity

Never patch a published Bit row or package source directly. Upload a new draft/revision so package and review identity stay aligned. Let the creator publish manually.

## Required Resource Reads

`context.md` embeds the complete current SDK and creation guidance. You do not need to read identical material twice. All references are public without pairing; creation.md directs the complete SDK and fundamentals read. Fetch schema for manifest validation and registry before selecting dependencies:

- `https://agent.plethora.studio/v1/agent/sdk.md` (`/v1/agent/sdk.md`) - exact public `ctx` surface and runtime rules.
- `https://agent.plethora.studio/v1/agent/schema.json` (`/v1/agent/schema.json`) - machine-readable manifest/schema, permissions, memory contract, limits, and validation constants.
- `https://agent.plethora.studio/v1/agent/libraries.json` (`/v1/agent/libraries.json`) - approved pinned libraries, fonts, URLs, SHA-256 hashes, sizes, MIME types, and globals/kinds.
- `https://agent.plethora.studio/v1/agent/existing-code.md` (`/v1/agent/existing-code.md`) - mandatory conversion/readiness workflow whenever adapting an existing game, sketch, or web project.

If `context.md`, `sdk.md`, and `schema.json` have different `contextVersion` values, stop and report the mismatch instead of guessing.

## Available Endpoints

- GET /v1/agent/workflow.json (available, auth: none, idempotency: none) - Public structured workflow or focused creator reference.
- GET /v1/agent/core.md (available, auth: none, idempotency: none) - Public structured workflow or focused creator reference.
- GET /v1/agent/creation.md (available, auth: none, idempotency: none) - Public structured workflow or focused creator reference.
- GET /v1/agent/fundamentals.md (available, auth: none, idempotency: none) - Public structured workflow or focused creator reference.
- GET /v1/agent/common-mistakes.md (available, auth: none, idempotency: none) - Public structured workflow or focused creator reference.
- GET /v1/agent/sdk/index.md (available, auth: none, idempotency: none) - Public structured workflow or focused creator reference.
- GET /v1/agent/sdk/:topic.md (available, auth: none, idempotency: none) - Public structured workflow or focused creator reference.
- GET /v1/agent/examples/index.md (available, auth: none, idempotency: none) - Public structured workflow or focused creator reference.
- GET /v1/agent/examples/:name.md (available, auth: none, idempotency: none) - Public structured workflow or focused creator reference.
- GET /v1/agent/upload.md (available, auth: none, idempotency: none) - Public structured workflow or focused creator reference.
- GET /v1/agent/context-full.md (available, auth: none, idempotency: none) - Public structured workflow or focused creator reference.
- GET /v1/agent/start.md (available, auth: none, idempotency: none) - Fetch the pairing-first, idea-first bootstrap for a fresh creator conversation.
- GET /v1/agent (available, auth: none, idempotency: none) - Discover the creator-agent workflow and all agent resources.
- GET /v1/agent/context.md (available, auth: none, idempotency: none) - Fetch the complete standalone bit-making instructions.
- GET /v1/agent/schema.json (available, auth: none, idempotency: none) - Fetch the current public bit contract schema.
- GET /v1/agent/libraries.json (available, auth: none, idempotency: none) - Fetch approved library and font metadata.
- GET /v1/agent/existing-code.md (available, auth: none, idempotency: none) - Fetch the required existing-code conversion flow before adapting a working project.
- POST /v1/agent/pair/sessions (available, auth: none, idempotency: required) - Start creator approval immediately with a short-lived QR/link/manual pairing code, without exposing a Supabase token.
- POST /v1/agent/pair/claim (available, auth: user_session, idempotency: required) - Approve pairing from the mobile app or web dashboard.
- POST /v1/agent/pair/lookup (available, auth: user_session, idempotency: none) - Show the creator the pending agent identity and requested scopes before approval.
- POST /v1/agent/pair/sessions/:sessionId/exchange (available, auth: agent_pairing_secret, idempotency: required) - Poll/exchange an approved pairing session using the session secret. On approval, read data.accessToken exactly once and reuse it for future draft uploads until revoked or expired.
- POST /v1/agent/bits/drafts (available, auth: agent_access_token, idempotency: required) - Upload or update a draft bit for the paired user. Publish remains manual.
- GET /v1/agent/commands/:commandId (available, auth: agent_access_token, idempotency: none) - Reconcile a delayed draft-upload command with the same scoped agent token.
- POST /v1/agent/mcp (available, auth: none, idempotency: none) - Optional MCP server (Streamable HTTP, JSON responses; also at /mcp on the agent host): get_bit_guide, start_pairing, wait_for_pairing and upload_draft run these steps as tools, with the pairing secret and the upload key as tool arguments.
- GET /v1/agent/tokens (available, auth: user_session, idempotency: none) - List paired coding agents for the signed-in creator.
- DELETE /v1/agent/tokens/:tokenId (available, auth: user_session, idempotency: required) - Revoke a paired coding agent token. Publishing remains manual.

## Pairing And Upload Auth

Pairing is durable for the 4-hour agent session: the creator approves once, then the agent reuses `data.accessToken` for future draft uploads until the creator revokes it or it expires. The bootstrap pairing code/sessionSecret lasts 60 minutes. Fresh conversations use `https://agent.plethora.studio/v1/agent/start.md` (`/v1/agent/start.md`) to offer pairing early. Implementation and public resources do not require approval; upload does. Only the bootstrap exchange is one-time:

1. Call `POST /v1/agent/pair/sessions` with `Idempotency-Key: <stable-random-key-for-this-pairing-attempt>`. A create is never replayed: the same key again answers 409 `conflict` with `details.reason` `pairing_restart_required`, so after a lost or timed-out create answer, create a new session with a new key.
2. On a web-based coding agent, render the returned `pairingQrPayload` as a QR code, show `pairingUrl` as the phone deep link, show `approvalUrl` as the browser approval link, and show `pairingCode` as fallback. Scanning `pairingUrl` or `pairingQrPayload` on a phone opens Plethora -> Create -> Connect agent with the code pre-filled. A creator using web can open `approvalUrl` and enter the fallback code.
3. Do not ask for username, email, password, Supabase credentials, or OAuth login. The app approval binds the agent to the creator already signed in on their device.
4. Poll `POST /v1/agent/pair/sessions/:sessionId/exchange` with the private `sessionSecret` and an `Idempotency-Key`. Use a fresh key for each new polling attempt; reuse a key only when retrying the exact same exchange HTTP request after a lost or timed-out response, which returns the same answer, `data.accessToken` included, until the token expires.
5. When the response status is `approved`, save `data.accessToken` immediately.
6. Use `Authorization: Plethora-Agent <data.accessToken>` for draft upload now and future draft uploads.

If a completed draft upload returns `401` or `403`, inspect the error code. For a missing or expired token, retain the completed payload and idempotency key, resume pairing in place, and retry after approval. Do not request another starter prompt or rebuild. Respect explicit denial/revocation: stop account writes and ask before requesting access again. Not every 403 is expiry.

Do not look for `agentToken`. The token field is exactly `accessToken`, nested under `data` in the standard API envelope. The approved exchange consumes the session, so a new exchange call (a new key) will not return the token again; only a retry of the exact same request with the same key does. The saved access token is the durable pairing.

Approved exchange response shape:

```json
{
  "ok": true,
  "data": {
    "status": "approved",
    "sessionId": "11111111-1111-4111-8111-111111111111",
    "expiresAt": "2026-06-20T22:00:00.000Z",
    "accessToken": "plag_example_one_time_visible_token",
    "tokenId": "22222222-2222-4222-8222-222222222222",
    "tokenExpiresAt": "2026-06-21T01:00:00.000Z",
    "scopes": [
      "bits:draft:write"
    ]
  },
  "requestId": "request-id",
  "serverTime": "2026-06-20T21:00:00.000Z"
}
```

Pending exchange response shape:

```json
{
  "ok": true,
  "data": {
    "status": "pending",
    "sessionId": "11111111-1111-4111-8111-111111111111",
    "expiresAt": "2026-06-20T22:00:00.000Z",
    "scopes": [
      "bits:draft:write"
    ]
  },
  "requestId": "request-id",
  "serverTime": "2026-06-20T21:00:00.000Z"
}
```

## Draft Upload Request

Upload drafts with `POST /v1/agent/bits/drafts`.

- Header: `Authorization: Plethora-Agent <data.accessToken>`
- Content-Type: `application/json`
- Header: `X-Plethora-Command-Protocol: v1`
- Header: `Idempotency-Key: <new stable key per user action>`
- Retry rule: Reuse the exact same idempotency key only when retrying the same upload after a lost or timed-out response. A changed upload is a new user action and needs a new key.
- If the upload returns `202 Accepted`, poll `/v1/agent/commands/:commandId` with the same agent token until it returns the stored result.

Body shape:

- `title`: string fallback used only when manifest.title is missing; final title is required
- `description`: optional string fallback used only when manifest.description is missing
- `tags`: optional string[] fallback used only when manifest.tags is missing
- `source`: required JavaScript source string defining window.plethoraBit
- `manifest`: plethora.json object; strongly recommended for every upload; title, runtime, entry, permissions, dependencies, assets, memory, game.progress, tuning, onboarding, and display are validated and normalized; publishing requires display: "fullscreen"
- `generated`: optional boolean; true when coding agent generated the draft
- `agentFeedback`: optional but expected object reporting SDK/docs/validator/runtime/upload friction. Send it on every agent upload, even as { outcome: "clear", unclear: [], blockers: [], suggestions: [] } when nothing hurt.

Agent feedback shape:

- `agentFeedback.contextVersion`: string; use the contextVersion you fetched
- `agentFeedback.sdkVersion`: string; use the sdkVersion you built against
- `agentFeedback.outcome`: clear | minor_friction | blocked_then_fixed | blocked_unresolved
- `agentFeedback.confidence`: low | medium | high
- `agentFeedback.unclear`: string[] things that were not clear
- `agentFeedback.blockers`: string[] issues that stopped progress
- `agentFeedback.repeatedFixes`: string[] things fixed multiple times
- `agentFeedback.workarounds`: string[] hacks or detours needed
- `agentFeedback.suggestions`: string[] concrete SDK/docs/runtime/validator/upload improvements
- `agentFeedback.docsMissing`: string[] missing or misleading docs/context/schema items
- `agentFeedback.runtimeIssues`: string[] runtime behavior surprises
- `agentFeedback.validatorIssues`: string[] false positives, vague errors, or missing validation
- `agentFeedback.libraryIssues`: string[] registry/library/font issues
- `agentFeedback.uploadIssues`: string[] pairing/upload/idempotency issues
- `agentFeedback.pairingIssues`: string[] pairing/token/session friction
- `agentFeedback.timeSpentMinutes`: optional number
- `agentFeedback.iterationCount`: optional number
- `agentFeedback.notes`: optional short free-text summary; never include secrets, tokens, full source, auth headers, or private creator data

Request example:

```json
{
  "title": "Touch Sketch",
  "description": "A tiny touch-reactive Plethora Bit.",
  "tags": [
    "creative",
    "touch"
  ],
  "manifest": {
    "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."
    }
  },
  "generated": true,
  "agentFeedback": {
    "contextVersion": "plethora-agent-context-2026-10-22.1",
    "sdkVersion": "1.8.0",
    "outcome": "minor_friction",
    "confidence": "medium",
    "unclear": [
      "How to choose between ctx.onFrame and ctx.game.loop."
    ],
    "blockers": [],
    "repeatedFixes": [
      "Adjusted safe-area layout twice after mobile preview."
    ],
    "workarounds": [],
    "suggestions": [
      "Add one more tiny game-loop example with scoring and onboarding together."
    ],
    "docsMissing": [],
    "runtimeIssues": [],
    "validatorIssues": [],
    "libraryIssues": [],
    "uploadIssues": [],
    "pairingIssues": [],
    "timeSpentMinutes": 34,
    "iterationCount": 3,
    "notes": "Keep this honest and short. If everything was clear, send outcome \"clear\" and empty arrays."
  },
  "source": "// Plethora Bit · docs and draft upload: https://agent.plethora.studio/v1/agent/start.md\nwindow.plethoraBit = {\n  meta: {\n    title: \"Touch Sketch\",\n    runtime: \"plethora-bit@2\",\n    tags: [\"creative\", \"touch\"],\n    permissions: [\"haptics\"]\n  },\n\n  async init(ctx) {\n    const canvas = ctx.createCanvas2D({ coordinateSpace: \"css\", maxDpr: 2 });\n    const g = canvas.getContext(\"2d\");\n    const touches = [];\n\n    function draw() {\n      const area = ctx.contentSafeArea ?? ctx.safeArea; // clear of the island and the logo\n      g.fillStyle = \"#142a29\";\n      g.fillRect(0, 0, ctx.width, ctx.height);\n      g.fillStyle = \"#ffffff\";\n      g.font = \"20px sans-serif\";\n      g.textAlign = \"center\";\n      g.fillText(\"Touch to make a mark\", ctx.width / 2, area.top + 48);\n      g.fillStyle = \"#f2c94c\";\n      for (const touch of touches) {\n        g.beginPath();\n        g.arc(touch.x, touch.y, 12, 0, Math.PI * 2);\n        g.fill();\n      }\n    }\n\n    ctx.input.on(canvas, \"tap\", pointer => {\n      ctx.platform.start();\n      ctx.platform.haptic(\"light\");\n      touches.push({ x: pointer.x, y: pointer.y });\n      if (touches.length > 64) touches.shift();\n      draw();\n    });\n\n    ctx.onResize(draw, { immediate: true });\n    ctx.platform.ready();\n  }\n};"
}
```

Success response shape:

```json
{
  "ok": true,
  "data": {
    "action": "created | updated | draft_revision",
    "bit": "{ id, title, description, tags, source, manifest, runtime_version, ... }",
    "packageHash": "sha256:<64 hex chars>",
    "packageBytes": 12345,
    "notices": "[{ code, message }]: advice to pass on to the creator; the draft is saved either way (e.g. display_not_fullscreen: saved, but it cannot be published until the manifest declares display \"fullscreen\"); empty when there is none"
  },
  "requestId": "request-id",
  "serverTime": "2026-06-20T21:00:00.000Z"
}
```

Failure notes:

- 401 means missing Plethora-Agent token.
- 403 means invalid, expired, revoked, or wrong-scope agent token.
- If upload fails because the token is missing or expired, retain the completed payload and idempotency key, resume pairing in place, and retry after approval. Do not ask for another prompt or rebuild. On explicit denial/revocation stop account writes and ask before requesting access again; not every 403 is expiry.
- 409 is a conflict, not always a duplicate title: inspect the error code and details for an existing active title, idempotency-key payload mismatch, or another conflict. Do not silently rename, generate a fresh key, or create a duplicate to bypass it. The one 409 that asks for a new key is details.reason pairing_restart_required from creating a pairing session: start a new pairing session with a new Idempotency-Key.
- 409 context_outdated means agentFeedback.contextVersion is older than the served context: nothing was saved. Fetch the current context, re-check the Bit against it, send the new contextVersion and upload with a new idempotency key.
- 400 can mean malformed request JSON, invalid upload fields, or manifest/source contract validation. Read the precise error before changing code. Serialize a structured JSON object; correct the reported field/source issue and use a new idempotency key only for a genuinely changed request.

## Upload Verification and Recovery

## 0. Fetch the current context
Before this upload, fetch https://agent.plethora.studio/v1/agent/context.md again and compare its Version with the one you built against. If it changed, re-read what changed, re-check the Bit, and send the new version as agentFeedback.contextVersion. An upload declaring an older context is refused with 409 context_outdated and nothing is saved. Check the manifest declares "display": "fullscreen": Plethora only publishes full-screen Bits.

## 1. Verify without pairing
Read [best practices](https://agent.plethora.studio/v1/agent/best-practices.md) and the topic relevant to any failure. Parse plethora.json, validate against [schema.json](https://agent.plethora.studio/v1/agent/schema.json), check exact registry pins/loader kinds, and run the source. There is no public validation/preview endpoint yet. Do not invent one.

Check visible first frame BEFORE ready; first real touch; every control and replay; resize/orientation and the content safe area (no text under the island, nothing behind the logo, full screen and in the legacy safe frame older apps still use); lifecycle/audio cleanup; permission-denied fallbacks. Native-only motion/mic/camera needs phone testing. A browser stub or HTTP 200 is not that proof.

Use your environment's tools (PowerShell on Windows, shell on Unix). Serialize the upload with JSON.stringify or an equivalent structured serializer; do not splice source into quoted shell JSON. Do not rewrite the game merely to fix quoting.

## 2. Reconnect only if needed
Keep building/testing while approval is pending. At upload, reuse a valid saved token. Otherwise check the existing session or show new approval paths from [start.md](https://agent.plethora.studio/v1/agent/start.md) if absent/expired. Preserve source, manifest and pending upload identity. Do not ask for another starter prompt.
Respect denial/revocation: stop account writes, ask before requesting access again. Do not loop against an explicit refusal or treat every 403 as token expiry.

## 3. Save a draft
Endpoint: https://agent.plethora.studio/v1/agent/bits/drafts (POST).
- Authorization: Plethora-Agent <data.accessToken>
- Content-Type: application/json
- X-Plethora-Command-Protocol: v1
- Idempotency-Key: <new stable key per user action>

Reuse the exact same idempotency key only when retrying the same upload after a lost or timed-out response. A changed upload is a new user action and needs a new key.
Never generate a new key just because a response is slow: reconcile the existing operation first. For a genuinely corrected payload, use a new key. Retain keys and payload with local work; keep credentials out of source, logs, URLs and chat.

Body fields:
- title: string fallback used only when manifest.title is missing; final title is required
- description: optional string fallback used only when manifest.description is missing
- tags: optional string[] fallback used only when manifest.tags is missing
- source: required JavaScript source string defining window.plethoraBit
- manifest: plethora.json object; strongly recommended for every upload; title, runtime, entry, permissions, dependencies, assets, memory, game.progress, tuning, onboarding, and display are validated and normalized; publishing requires display: "fullscreen"
- generated: optional boolean; true when coding agent generated the draft
- agentFeedback: optional but expected object reporting SDK/docs/validator/runtime/upload friction. Send it on every agent upload, even as { outcome: "clear", unclear: [], blockers: [], suggestions: [] } when nothing hurt.

Keep the first line of the source as `// Plethora Bit · docs and draft upload: https://agent.plethora.studio/v1/agent/start.md`. The starter and every example begin with it; add it to a Bit without it before you test. It tells the next agent that opens the file how to upload or update the Bit.

Example (replace with your actual source and honest feedback):
```json
{
  "title": "Touch Sketch",
  "description": "A tiny touch-reactive Plethora Bit.",
  "tags": [
    "creative",
    "touch"
  ],
  "manifest": {
    "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."
    }
  },
  "generated": true,
  "agentFeedback": {
    "contextVersion": "plethora-agent-context-2026-10-22.1",
    "sdkVersion": "1.8.0",
    "outcome": "minor_friction",
    "confidence": "medium",
    "unclear": [
      "How to choose between ctx.onFrame and ctx.game.loop."
    ],
    "blockers": [],
    "repeatedFixes": [
      "Adjusted safe-area layout twice after mobile preview."
    ],
    "workarounds": [],
    "suggestions": [
      "Add one more tiny game-loop example with scoring and onboarding together."
    ],
    "docsMissing": [],
    "runtimeIssues": [],
    "validatorIssues": [],
    "libraryIssues": [],
    "uploadIssues": [],
    "pairingIssues": [],
    "timeSpentMinutes": 34,
    "iterationCount": 3,
    "notes": "Keep this honest and short. If everything was clear, send outcome \"clear\" and empty arrays."
  },
  "source": "// Plethora Bit · docs and draft upload: https://agent.plethora.studio/v1/agent/start.md\nwindow.plethoraBit = {\n  meta: {\n    title: \"Touch Sketch\",\n    runtime: \"plethora-bit@2\",\n    tags: [\"creative\", \"touch\"],\n    permissions: [\"haptics\"]\n  },\n\n  async init(ctx) {\n    const canvas = ctx.createCanvas2D({ coordinateSpace: \"css\", maxDpr: 2 });\n    const g = canvas.getContext(\"2d\");\n    const touches = [];\n\n    function draw() {\n      const area = ctx.contentSafeArea ?? ctx.safeArea; // clear of the island and the logo\n      g.fillStyle = \"#142a29\";\n      g.fillRect(0, 0, ctx.width, ctx.height);\n      g.fillStyle = \"#ffffff\";\n      g.font = \"20px sans-serif\";\n      g.textAlign = \"center\";\n      g.fillText(\"Touch to make a mark\", ctx.width / 2, area.top + 48);\n      g.fillStyle = \"#f2c94c\";\n      for (const touch of touches) {\n        g.beginPath();\n        g.arc(touch.x, touch.y, 12, 0, Math.PI * 2);\n        g.fill();\n      }\n    }\n\n    ctx.input.on(canvas, \"tap\", pointer => {\n      ctx.platform.start();\n      ctx.platform.haptic(\"light\");\n      touches.push({ x: pointer.x, y: pointer.y });\n      if (touches.length > 64) touches.shift();\n      draw();\n    });\n\n    ctx.onResize(draw, { immediate: true });\n    ctx.platform.ready();\n  }\n};"
}
```

## 4. Interpret responses, not wishes
- 200 with ok:true: saved draft/revision. Read data.action, data.bit.id, data.packageHash, data.packageBytes and data.notices. Not published, not a gameplay test. data.notices does not block saving: the draft is saved either way, but a notice can mean it cannot be published yet.
- 202: command still pending. Poll GET https://agent.plethora.studio/v1/agent/commands/:commandId using the SAME agent token. Follow returned command identity/status; do not launch another upload.
- 400: inspect the actual structured error. Fix source/manifest/JSON as indicated, then use a new key for the changed payload.
- 401/403: inspect error code. Missing/expired session may require pairing again; denial, revocation, wrong scopes or other permission errors need explanation, not blind retries.
- 409: inspect the error code. context_outdated: nothing was saved; fetch the current context, re-check the Bit, send the new contextVersion and upload with a new key. Otherwise it is a title or idempotency conflict: do not silently rename a creator's Bit or rotate keys against an unknown outcome. Re-pairing is the exception: a pairing create's 409 with details.reason pairing_restart_required asks for a new pairing session with a new key.
- 429: honor Retry-After/backoff. Network/5xx: bounded retry of the SAME request/key; reconcile before retrying a possibly accepted upload.

Command identity is data.command.id on a 202, also X-Plethora-Command-Id when supplied. Command status reads return data.command.status and data.result. A null result is still pending, not success. A terminal result has statusCode and envelope: inspect data.result.envelope.ok and its data/error. The outer status-read HTTP 200 only means you fetched a status successfully.

Command receipts are scoped to the original agent token. If that token expires after an upload with an unknown outcome, a newly paired token cannot read the old receipt. Preserve the command id, payload and key, report the uncertainty and have the creator check their draft before a new submission. Do not claim re-pairing alone proves the original upload failed.

Success envelope:
```json
{
  "ok": true,
  "data": {
    "action": "created | updated | draft_revision",
    "bit": "{ id, title, description, tags, source, manifest, runtime_version, ... }",
    "packageHash": "sha256:<64 hex chars>",
    "packageBytes": 12345,
    "notices": "[{ code, message }]: advice to pass on to the creator; the draft is saved either way (e.g. display_not_fullscreen: saved, but it cannot be published until the manifest declares display \"fullscreen\"); empty when there is none"
  },
  "requestId": "request-id",
  "serverTime": "2026-06-20T21:00:00.000Z"
}
```

## 5. Tell the creator what happened
Say "Saved draft", its title/id, actual tests run and any remaining phone checks. Open Plethora -> Create -> Drafts for review; do not invent Profile -> Uploads navigation. Do not say published or working just because upload succeeded. Publishing stays manual in Plethora.

Pass on every data.notices message in plain words. display_not_fullscreen means the draft was saved but cannot be published: Plethora only publishes full-screen Bits, and publishing answers 422 display_fullscreen_required. Add "display": "fullscreen" to the manifest, keep text and controls inside ctx.contentSafeArea ?? ctx.safeArea, test it, and upload again with a new Idempotency-Key before telling the creator it is ready to publish.

Include agentFeedback on every upload: outcome, unclear docs, blockers, repeated fixes and suggestions; empty lists and outcome clear are fine when truthful. Never include credentials or private creator data.
- Include agentFeedback in every paired-agent draft upload. Be honest about unclear docs, blockers, repeated fixes, runtime surprises, validator friction, upload/pairing friction, and SDK suggestions. Send outcome "clear" with empty arrays when the flow was smooth.


## 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 `plethora.json`:

```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."
  }
}
```

## SDK

## 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.
- Follow /v1/agent/creation.md. Read /v1/agent/fundamentals.md, the complete /v1/agent/sdk.md and /v1/agent/schema.json before planning. Topic pages are focused views, not hidden capabilities. Do not reread identical content by default. All fetched references should share the same contextVersion.
- 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.
- 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 manifest.tuning plus ctx.tune for meaningful draft-time knobs and curves: difficulty, feel, visual polish, audio intensity, and replay pacing. Expose a few creator-useful controls, not every internal constant.
- Include agentFeedback in every paired-agent draft upload. Be honest about unclear docs, blockers, repeated fixes, runtime surprises, validator friction, upload/pairing friction, and SDK suggestions. Send outcome "clear" with empty arrays when the flow was smooth.
- 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.
- 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.
- 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.
- 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.

## Hard Safety Rules

- 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.

## Best Practices

Implement applicable best practices by default; do not stop at considering them. Omit one only for a concrete reason tied to the creator's brief, the experience, accessibility, privacy or a documented capability limit, and record that reason briefly in your handoff. Convenience or forgetting the capability is not a reason. Respect explicit preservation instructions for existing work; this is not permission to redesign it or bolt on unrelated features. These are creator quality expectations, not new upload validation rules.

- Keep action buttons, important instructions, text, scores and controls inside ctx.contentSafeArea ?? ctx.safeArea: clear of the camera cutout or Dynamic Island, the home indicator and Plethora's logo button. Passive scenery and playfield may run to every edge; do not shrink the entire game into the top half.
- Choose manifest.onboarding deliberately for every new Bit. For puzzles needing explanation, prefer a short in-Bit interactive example with a meaningful touch, visible response, and Skip; use immersive to prevent a second runtime overlay. Use one_line for one clear action. Managed guided/briefing text cards are compatibility tools, not the default. Keep cues short and Bit World quick-reference tips separate.
- Provide tap-to-replay or a replay button for games and finite experiences.
- Check that buttons do not overlap each other on phone-sized screens.
- Music and sound: Add fitting background music and meaningful action sounds by default for almost every Bit. Choose musical style, instrumentation, timbres, rhythm and sound textures that belong to its world; vary them across Bits and within a session instead of defaulting to chiptune and identical frequency beeps. Give important actions distinct, restrained feedback. Omit a music bed or effects only for a concrete reason such as intentional silence, an existing listening/music-making mechanic, accessibility or the creator's request; do not add audio that masks the experience.
- Make the bit polished, tactile, and visually memorable.
- Update manifest permissions accurately whenever APIs change.
- When adapting an existing game, sketch, or web project, read /v1/agent/existing-code.md before changing code. It is a conversion with its own readiness proof, not a normal from-scratch Bit.
- Never turn a generic startup catch into a WebGL-disabled message. Library download, renderer initialization and first-frame failures need distinct diagnostics; preserve the original error via ctx.platform.error. Offer explicit bounded recovery without automatic renderer restart loops. See /v1/agent/existing-code.md.
- Treat camera, microphone/audio-reactive, and motion as intentional permission-gated mechanics; use them when requested or when they deliberately serve the creator's concept. Respect user consent, request permissions from a real gesture, and always include denied-permission fallback UI.
- Call ctx.platform.ready() after a meaningful first visible frame and ctx.platform.start() on the first real interaction of every attempt, including replay. Keep replay immediate; fence detached leaderboard callbacks by attempt and ctx.onDestroy.
- Call ctx.pulse.complete({ timeMs, text }) when a finished game or solved puzzle should become an implicit Pulsegraph post.
- Use ctx.game.loop() for custom motion/gameplay loops; use ctx.onFrame() once during init only for tiny one-callback animations or library interop.
- For continuous Canvas2D play, start with ctx.createCanvas2D() defaults. Use maxDpr:2 for crisper raw canvas.width/canvas.height drawing; add coordinateSpace:"css" or scaleToCssPixels:true only after all drawing uses ctx.width/ctx.height CSS pixels. Use ctx.onResize(layout, { immediate:true }) for responsive sizing. In CSS coordinate mode, avoid wiping the DPR transform; runtime repairs identity resets and warns once, but code should still draw in CSS pixels. Use alpha:false only when every pixel is painted; use willReadFrequently:true only for repeated local pixel readback.
- Leaderboards: Add a leaderboard wherever a repeatable outcome supports meaningful comparison or mastery: score, longest streak, accuracy, best time or completed level. Wire actual accepted results, not just a local high-score label. Choose useful record channels and modes/arena dimensions; add multiple boards when the measurements reward genuinely different achievements. Do not invent meaningless scores for art, tools or experiences with no comparable outcome. Use ctx.game.score for live numeric score state, then submit its declared ctx.memory record only at a result or checkpoint. Use raw ctx.memory records for custom non-live record flows.
- Use score.checkpoint(channel, options) for valid mid-run best_per_user scores: queued locally, not server acceptance. latest_per_user and all_entries require explicit submit. score.flush() is host synchronization only. Use explicit score.submit for acceptance and score.rank or leaderboard for authoritative standing; do not compute rank from visible rows. Never await leaderboard work before replay; retain cached rows with Updating status and ignore old-attempt results.
- Run-end scores: Submit the score at the end of every scored 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). Test it: win, keep playing, end the run, and check that the board shows the final score.
- Use ctx.game.progress for resumable games that should appear in Continue Playing. Save only at durable checkpoints, and call complete() or abandon() when that resume entry should disappear.
- Do not use ctx.game.progress or first-use onboarding completion as a stand-in for multiple people sharing one device. They are viewer-private platform conveniences; build pass-and-play identity/rules inside the Bit when the experience needs them.
- Use manifest.tuning and ctx.tune for important draft-time knobs: gameplay feel, difficulty curves, visual polish, audio intensity, and pacing. Keep them understandable and bounded.
- Global memory: Implement shared persistence when the experience benefits from everyone's contributions, collective results or cross-player comparisons, rather than keeping them in one viewer's local state. Use declared ctx.memory.tally channels for surveys/polls and aggregate choices, ctx.memory.record for rankings, and ctx.memory.world for bounded shared state. Show useful collective feedback and respect visibility, privacy and write limits. These existing channel families provide global memory; do not invent a ctx.memory.global API.
- Use ctx.fx for short meaningful visual feedback when it improves a touch-heavy Bit. It is visual-only and input-transparent; custom Canvas2D, WebGL, Three, DOM, and approved-library effects remain available for richer visual systems.
- Use ctx.visual.palette/kit, texture, material, and sprite when helpful for coherent colors, readable contrast, tactile procedural detail, and reusable local visual elements. For kit, combine categorical style axes with numeric axes so lazy defaults still diverge by Bit identity. Override freely; do not make every Bit look like the same preset.
- Fill agentFeedback honestly on every upload; it is how Plethora learns which SDK/docs/runtime/validator/pairing pieces hurt real agents.
- Never mount to document.body, create raw canvas elements for the main surface, or create script tags manually.
- Adaptive music: Make the soundtrack respond to the experience's meaningful states. Where they exist, give normal play, rising tension/danger, a new personal best/high score, and the post-score/result screen fitting variations or cues; do not keep one unchanged loop through all of them. A continuous calm experience can stay coherent without manufactured drama. Use the music handle's setIntensity, setTempo, setPreset, setPattern, fades, ducking or stings as appropriate; change on state transitions or bounded updates, not every frame or by repeatedly restarting the track. Balance music against action sounds, provide mute/level control, unlock on a real gesture and respect host-owned background suspension.
- Result-screen leaderboard: For scored Bits with a result/end-score screen, include a compact in-Bit top three (places 1, 2 and 3) and the viewer's rank when available. Use the record/score leaderboard read with the same channel, scope, period and dimensions as the submitted result; viewerRank is nullable, so read viewerRank.rank only when present. Render fewer rows for a small board, handle ties using returned ranks, and keep score/rank freshness together. Never invent competitors, infer the viewer's rank from three rows, or show stale placement as the new result. Show loading/updating/unavailable states honestly; do not block replay or navigation on network work. Keep the panel secondary to the result and replay, inside the content safe area (clear of the logo button), without covering gameplay or adding an end screen to an endless immersive Bit.
- Local memory: Implement viewer-private persistence whenever returning would benefit from remembered settings, unlocked levels, personal creations or unfinished work; this applies to art and tools as well as games. Use declared ctx.memory.local for private saved state and ctx.storage only for disposable local convenience. Use ctx.game.progress for a resumable game that should appear in Continue Playing; save durable checkpoints, validate/version restored state, and complete or abandon that entry appropriately. Do not reset useful state on every visit or save every animation frame.
- Cloud persistence: In authenticated published app playback, ctx.memory.local is cloud-backed per-account private state; ctx.storage is device-only convenience, never the sole best/progress store. Restore personal BEST from the existing all_time best_per_user record standing with the correct channel, dimensions and order. Use ctx.game.progress for Continue Playing and declared personal memory for other durable state. These guarantees exclude draft preview and shared-web play: shared-web memory uses page-local simulation even for published Bits, not account-cloud persistence. Preserve channel/epoch identity; hydrate/validate before saving and never turn a failed read into a default/reset write. Checkpoint valid improvements at bounded milestones and submit the final valid result, including continued play after a win. queued:true and ctx.platform.setScore are not accepted leaderboard receipts; show pending/failed honestly without blocking replay. Test reinstall after acknowledged saves, account switch, offline/partial delivery and stale success/failure. Never fabricate recovery of never-delivered bytes or import unattributed legacy device scores.
- Active-play timing: Use ctx.game.stopwatch for accumulated playing time, not Date.now()-savedStart, frame counts or clamped simulation dt. Start/pause at actual play/menu/colour/completion boundaries; let the host exclude time away. Keep calendar editions/countdowns on calendar time. Save elapsed snapshots with validated versioned cloud progress at bounded checkpoints; pending saves are not durable. Separate different colour/difficulty outcomes using declared record dimensions or channels, with matching submit/read identities. When timing semantics change, preserve old scores and progress; add a new channel instead of inventing active durations from legacy timestamps. Test background/return, reopen, slow frames, each colour, hints and delayed submissions across a UTC day boundary.
- Coordinated worlds: Implement a shared evolving world when visitors should affect the same creation, such as a communal pixel mural, collaborative sequencer, shared arrangement or garden. Use declared ctx.memory.world channels with get and bounded semantic mutate operations; preserve other visitors' contributions instead of replacing the whole world from a stale snapshot. Design for concurrent edits, rejected writes and rate limits, and refresh at a bounded cadence. This is persistent co-creation, not a continuous realtime multiplayer engine or an undocumented world subscription API. If the concept benefits from it, build the supported shared behavior rather than a local-only imitation.
- Clear the clutter: Remove duplicate labels, redundant buttons, explanatory paragraphs, competing HUD elements, decorative panels and effects that add no useful feedback or atmosphere. Recheck the real phone screen after adding audio controls, scores and the mini leaderboard; keep the main interaction, result and replay obvious and preserve readability. Do not confuse less clutter with a generic minimal style: retain meaningful richness, personality, scenery and the creator's visual intent.

## Rejection Risks

- 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.

## Creation Process

The process below guides your work, not eight questionnaires for the creator. Preserve the supplied idea and decisions. Scale planning to complexity; a small repair is not permission to redesign. Offer pairing early, continue while approval is pending, and ask for an idea only when none was supplied. Research-only questions do not authorize pairing.

## Reading Order
Read [fundamentals.md](https://agent.plethora.studio/v1/agent/fundamentals.md), the complete [sdk.md](https://agent.plethora.studio/v1/agent/sdk.md), and [schema.json](https://agent.plethora.studio/v1/agent/schema.json) before implementation choices. Fetch them together when tools allow. The SDK is one complete reference; focused topics are optional reminders, not a prerequisite search through genres. If a tool truncates a response, retrieve the missing sections before claiming the full read. Refresh references when their context versions disagree.

Creation owns the process. Fundamentals own the environment. The SDK owns callable behavior. Schema owns manifest declarations. Positive craft belongs in [best-practices.md](https://agent.plethora.studio/v1/agent/best-practices.md); failure patterns in [common-mistakes.md](https://agent.plethora.studio/v1/agent/common-mistakes.md); protocol in [upload.md](https://agent.plethora.studio/v1/agent/upload.md). For existing projects also read [existing-code.md](https://agent.plethora.studio/v1/agent/existing-code.md) before changing code.

- Follow /v1/agent/creation.md. Read /v1/agent/fundamentals.md, the complete /v1/agent/sdk.md and /v1/agent/schema.json before planning. Topic pages are focused views, not hidden capabilities. Do not reread identical content by default. All fetched references should share the same contextVersion.

## Step 1: Understand the Environment and Full Toolkit

Read [fundamentals.md](https://agent.plethora.studio/v1/agent/fundamentals.md) and the complete [sdk.md](https://agent.plethora.studio/v1/agent/sdk.md) before deciding the implementation.
Use [schema.json](https://agent.plethora.studio/v1/agent/schema.json) for the exact package/manifest declaration. These are public reads;
pairing approval is not a prerequisite. Confirm versions agree, refreshing mismatched
references rather than silently combining them.

Understand package structure, entry/init, surface ownership, lifecycle, input,
permissions, capability availability, libraries, state, performance and host layout.
Learn the entire SDK surface, including nested methods and returned handles; do not
stop at a list of namespace names. Notice what it can improve even if the creator did
not name the feature: motion, feedback, music, records, progress, shared state or knobs.

Keep distinctions clear: schema describes declarations; SDK describes callable
behavior; fundamentals describe the environment. A manifest passing JSON validation
does not prove source validity, dependency availability, rendering or gameplay.

For an imported project, inspect its working baseline before editing: dependencies,
globals, assets, renderer, entrypoint, input, audio, loops, layout, state and disposal.
Preserve its successful interaction and visual language. Identify the smallest adapter
needed; missing registry support is a constraint to explain, not a reason to invent a URL.

**Done when:** the agent knows the allowed package shape, all available capability families, important runtime guarantees/limits and which existing creator decisions must survive.

## Step 2: Plan the Experience

Make something worth spending time with. Treat the creator's idea as the brief, not
permission to add an unrelated game, scoring system, tutorial or decorative wrapper.

#### Concept

- Explore a few genuinely different interpretations when the brief leaves room,
  then choose a coherent direction. Do not ask the creator to decide every detail.
- Name the feeling: tension, delight, calm, discovery, mastery, expression, curiosity,
  or something specific to this Bit. Explain what interaction produces that feeling.
- Tighten the central action and its feedback. What changes because the user acts?
  Why is the second interaction worth doing? What makes this more than a static poster?
- For games: define the objective, controls, meaningful choices, failure/success,
  fairness, replay and difficulty progression. Make the core loop complete.
- For puzzles: define real rules and valid solution criteria, not a single saved
  answer. Plan interesting, solvable instances rather than accidental trivial cases.
- For education: identify the learning goal, the misconception, the manipulation
  the learner performs and the observable result that makes the concept clearer.
- For art, tools, toys and fidgets: identify discovery, usefulness or satisfaction
  without forcing a win state, score, tutorial or ending that weakens the experience.
- Consider duration, replay value, accessibility and meaningful progress persistence.
  Do not equate an endless session with a satisfying experience.

#### User Journey

- Design the first visible frame and first meaningful interaction. An opening should
  be attractive and useful; it does not automatically need a title screen or Start.
- Choose deliberate immediate immersion, a one-line cue or a skippable in-Bit worked
  example. Preserve intentional mystery where discovery is the actual experience.
- For non-obvious mechanics, show the action and its effect with short pointers,
  visual emphasis and participation. A sequence of paragraphs is not handholding.
- Plan play/exploration, feedback, failure, recovery, pause/resume, replay and completion
  where applicable. Seamlessly repeating art may need no post-play screen.
- Plan a result worth sharing: readable achievement or current composition, strong
  hierarchy, and enough context to understand it outside the session. Keep gameplay
  uncluttered; do not replace the scene with a generic celebratory card.
- Explain relevant Pulse/leaderboard actions accurately and sparingly. Use real host
  affordances; do not invent SDK buttons, gestures or automatic sharing behavior.
- Plan for the whole screen (display: "fullscreen"): keep actions/instructions inside
  ctx.contentSafeArea, clear of the island and the logo, but let passive scenery run to
  every edge. Do not shrink the whole composition into the top half.

#### Records, State and Tuning

- Plan a leaderboard wherever the outcome supports meaningful competition or mastery:
  streak, accuracy, best time, highest completed level or score. Choose order and
  separate mode/arena dimensions deliberately; multiple boards need a real purpose.
  For result screens, plan a compact top three and the viewer's available rank;
  keep replay immediate and do not force an ending onto an endless experience.
- Plan local memory for useful private preferences, levels, creations or unfinished
  work; global memory for useful aggregate contributions and records; coordinated
  worlds for useful shared evolving creations. Implement each when the concept
  benefits, not merely as a future suggestion. Non-games benefit from persistence too.
  Use the supported memory channels, not an invented realtime multiplayer API.
- Use Continue Playing only for state worth returning to; decide when a run is
  complete or abandoned. Do not save every transient animation value.
- Consider creator knobs and curves for the few parameters that most affect feel,
  difficulty, presentation or sound. They are not a substitute for calibrating defaults.
- For existing published Bits, preserve record keys, dimensions and other identity
  contracts. Never silently reset progress or leaderboards as part of visual cleanup.

#### Visual and Sonic Direction

- Before inventing the whole look, inspect multiple relevant references across the
  subject, visual history, illustration, typography, physical objects and interfaces.
  Research proportionately; do not turn a small Bit into an endless moodboard task.
- Record the useful principles: composition, shape, scale, color relationships,
  typography, material, lighting, rhythm and motion. Synthesize; do not clone a work.
- References inform art direction; they are not permission or technical support for
  bundling remote images, fonts or other assets. Verify rights and contract support.
- Choose a specific visual world. "Polished", "minimal", "neon" or a mood name alone
  is not sufficient. A mature design can be playful, rough, pixelated or very simple.
- Remove clutter that does not support the interaction or intended atmosphere. Avoid
  generic panel layouts, unnecessary borders and decorative effects added by habit.
- Ensure legibility, contrast, touch affordances, hierarchy and non-color-only cues.
  Keep deliberate variation; SDK presets are starting points, not the platform style.
- Include fitting background music and action sounds by default. Plan theme, timbre,
  pacing and variety rather than defaulting every Bit to chiptune and beeps. Map
  meaningful play/tension, personal-best and result states to musical variations;
  do not manufacture drama in a deliberately calm experience. Intentional silence,
  an existing listening mechanic or the creator's brief can justify an omission.
  Keep haptics purposeful, allow mute, and never require sensors merely to add features.

**Done when:** the agent has a concise brief covering feeling, core interaction, user journey, visual/sonic direction, relevant platform capabilities and what it will not add.

## Step 3: Plan the Implementation

Revisit exact SDK signatures/options for the selected design. Use the complete SDK
as the authority and focused sections for depth. Inspect the approved registry before
selecting libraries or fonts; check pin, kind, loading model and resource requirements.
Libraries should simplify real complexity, not be included just to tick a box.

- Choose DOM for appropriate text, semantic controls and ordinary UI; Canvas2D for
  appropriate drawing/game scenes; WebGL/Three/Pixi or another approved renderer when
  the work warrants it. Compose these. These are implementation choices, not Bit types.
- Plan surface layers, ordering, passthrough/input targets and coordinate spaces.
  Assign drawing, clearing, layout, hit testing and DPR to consistent units.
- Choose one owner for simulation/render scheduling per subsystem. Use SDK timing
  helpers where appropriate; preserve valid library-owned loops with explicit cleanup.
- Model real states and transitions for complex flows: ready, playing, paused,
  resolving, finished, replaying, or equivalents relevant to this experience.
  Use a state machine when useful; do not impose one on a simple toggle or fidget.
- Separate mechanics, rendering, input, audio and persistence where that reduces
  coupling. Use suitable abstractions, not an engine/framework for a tiny Bit.
- Choose proven approved libraries for complex physics, rendering, parsing or other
  specialist problems. SDK helpers do not cap custom logic, 3D interactions or shaders.
- Plan bounded allocation, pooling/caching where helpful, rendering budgets, readable
  quality fallbacks and stability at different refresh rates. Avoid per-frame I/O.
- Declare dependencies, permissions and state channels from actual usage. Decide
  permission-denied, unavailable-capability, library-failure and persistence-error UI.
- For scores/ranks, plan valid result/checkpoint writes and asynchronous presentation;
  replay must not wait for a leaderboard request. Fence late results to the right run.
- For progress, plan checkpoint boundaries, state versioning, restore validation and
  completion. For shared state, use the documented semantic operations and limits.
- Plan audio unlock, mute/levels, host-owned suspension, custom resource disposal and
  sensor calibration/fallback. Do not invent another competing host lifecycle manager.
- Pick useful bounded tuning values and progression curves. Be explicit about what
  changes live and what needs restart; test both defaults and extreme allowed values.
- Write a small verification matrix before code: core interaction, state transitions,
  correctness, layout, performance, media, persistence and important failure paths.

**Done when:** chosen APIs/libraries and their exact interfaces are known, state/resource owners are clear, and the agent can explain how the difficult parts will be tested.

## Step 4: Build the Bit

- Start with a vertical slice: meaningful first frame, actual input and core feedback.
  Exercise it in the relevant runtime before adding every system or polishing details.
- Preserve source/manifest as files and serialize structured payloads. Keep setup,
  simulation, rendering and cleanup ownership explicit. Do not guess API names.
- Build the complete interaction loop, then add the planned visual, audio, onboarding,
  state and tuning work. Test incrementally, especially library and native boundaries.
- Inspect actual rendered output while implementing. Fix faulty mechanics at their
  cause; do not cover blank screens, swallowed exceptions or broken input with a UI.
- Keep the creator's scope and existing project identity intact. Do not remove an
  intended mechanic because a first implementation attempt was inconvenient.

**Done when:** the intended experience is implemented and can be exercised, not merely compiled. Keep a short list of unverified device-only behaviors rather than claiming that browser mocks prove them.

## Step 5: Best Practices: Did You Do This?

Read [best-practices.md](https://agent.plethora.studio/v1/agent/best-practices.md) now, in full. Apply every relevant check to the built Bit;
the questions below supplement that document, not replace it. Fix identified gaps
and recheck the affected interactions before proceeding to Step 6. Keep brief evidence
for applicable checks and disclose remaining blockers or untested checks; do not
mark this step complete merely because the document was linked or fetched.

This is a required quality review, not a demand to add every feature or redesign
the creator's idea. Implement applicable defaults; do not stop at considering them.
For an omission, record a concrete reason tied to the brief, experience, privacy,
accessibility or capability limits. Preserve explicit existing-work constraints.

- Can a first-time user understand what to do, unless mystery is deliberate?
- Does the actual interaction produce the intended feeling? Does it respond promptly?
- Is the core experience complete, with clear feedback and useful recovery/replay?
- Does an educational interaction clarify the idea instead of merely decorating it?
- Are puzzle examples meaningful, rules coherent, and difficulty satisfying?
- Does the art direction survive the real phone viewport, not just a desktop screenshot?
- Are text and controls readable/reachable, inside the content safe area (not under the
  island or behind the logo) and not accidentally over content?
- Are the first frame and result/composition genuinely attractive and share-worthy?
- Confirm fitting, varied music and action sounds are implemented unless deliberately
  exempted. Where the experience has changing tension, a personal best or a result,
  verify the musical response rather than leaving one unchanged loop. Check mute/mix.
- Confirm a leaderboard is wired wherever outcomes support meaningful comparison.
  On result screens show a compact top three and the viewer's available rank with
  honest loading/failure states; replay must not wait for a network response.
- Verify local memory, global memory and coordinated worlds separately. Implement
  each that benefits the Bit; test returning/restoring and shared-state behavior.
  Use Continue Playing for resumable games, not arbitrary transient animations.
- Check useful Pulse and tuning opportunities without inventing host affordances.
- Clear the clutter after adding controls and result information. Remove redundant
  copy, buttons, HUD and decoration; preserve useful feedback, atmosphere and style.
- Are dependencies appropriate and options discoverable? Is custom code deliberate
  rather than a result of never learning the existing SDK capability?
- Does it preserve the requested/imported experience rather than a default template?

#### First-Time-User Walkthrough

Explicitly walk through the experience as someone encountering it for the first time.
When subagents with actual execution/interaction tools are available, delegate this
pass to an independent agent with fresh context where possible. Supply the playable
entry point and test environment, not the implementation plan, source explanation or
a coached sequence of correct actions. Let the Bit's own cues teach the experience.

Suggested reviewer prompt:

> Open and actually use this Bit as a first-time user with no prior knowledge of its
> mechanics. Use only the instructions and feedback available inside the experience;
> do not read its source or ask the builder how to play before this pass. Take plausible
> novice actions, including an obvious wrong guess or retry where appropriate. Report
> what you thought you should do, what you tried, what happened, where you hesitated or
> got stuck, and whether feedback helped you recover. Check entry, core interaction and
> replay/completion where applicable. Return concrete observations, reproduction steps
> and screenshots when available. Separate observations from guesses and list anything
> you could not test. Do not edit the Bit or publish it; use the supplied test/draft context.

The novice role means unfamiliar and willing to try, not deliberately incapable or
randomly destructive. Do not assume every discovery mechanic is a usability defect.
The building agent evaluates feedback against the creator's intent, fixes genuine
friction without imposing generic onboarding, and rechecks affected interactions.

This independent pass is optional when the agent cannot delegate or the reviewer
cannot actually launch/interact with the Bit. A source-only critique is not a performed
usability test. Use a self-walkthrough with available tools instead and disclose its
limits; do not invent independent feedback, block delivery on delegation, or require
the creator to change tools. An agent novice simulation is not a real human user test.

**Done when:** best-practices.md has been read and applied to the built Bit, relevant gaps are fixed and rechecked, and remaining blockers or untested checks are disclosed. Passing a self-rated checklist without looking at or interacting with the result is not evidence.

## Step 6: Check Known Failure Patterns

Read [common-mistakes.md](https://agent.plethora.studio/v1/agent/common-mistakes.md) and apply the relevant entries. Scan high-severity universal mistakes once; inspect subsystem/conversion entries when those paths are used. Check symptoms, causes, supported corrections and reproduction tests. Historical platform bugs are not creator prohibitions. Report a reproducing platform bug rather than introducing unsupported restrictions on variable names, helper functions or wrapper patterns.

**Done when:** each relevant known failure has been checked with evidence, with fixes fed back into the implementation and the regression checks for that Bit.

## Step 7: Audit and Test for Bugs

Re-read the actual implementation against the intended behavior, then exercise it.
Both are required: code review can expose faulty or incomplete logic that a happy-path
playthrough misses; running tests can expose failures that source inspection misses.
Step 6 checks previously known mistakes. This audit also looks for new defects specific
to this Bit, not just the same checklist again.

#### Audit the Implementation

- Trace each intended action through input, state changes, feedback and persistence.
  Find unfinished branches, placeholder behavior, unreachable states, missing handlers
  and features declared in the UI/manifest but not actually wired.
- Check mechanics and domain rules, boundary values, units, arithmetic and invariants:
  scoring, timers, collisions, win/loss conditions, puzzle constraints and alternate
  valid solutions where relevant. Do not assume the saved answer proves correctness.
- Follow state transitions and repeated runs. Check reset/restore completeness,
  cancellation, rapid/repeated input and actions during transitions or pending work.
- Inspect asynchronous success, failure and late completion: stale results, duplicate
  submissions, swallowed errors, missing fallbacks and resources surviving disposal.
- Compare coupled systems for inconsistent assumptions: input versus drawing coordinates,
  render versus simulation time, visible score versus submitted record, saved progress
  versus restored state, and permissions versus actual usage.
- Turn concrete findings into targeted fixes and regression cases. Stay within the
  creator's intended behavior; a bug audit is not permission for unrelated refactors,
  style changes or feature additions. A second reviewer can help but is not required.

#### Test the Behavior

Perform tests as well as the audit. Repeat affected checks after every correction.
Use the actual SDK/runtime or supported preview where possible; document where only
an approximation was available. Do not invent a hosted validation/preview endpoint.

- Package: parse manifest/source, validate declarations and limits, check exact
  dependency pins/kinds and file layout. Schema validation is not full source policy.
- Startup: dependency load, init, visible first frame, real first tap and continued play.
- Controls: every primary action, drag/hold/multitouch where used, cancel/release,
  blocked overlays and controls reached after state transitions.
- Mechanics: movement, collisions, success/failure, score/time arithmetic, reset and
  a second run. Test puzzle generation across seeds, solvability, meaningful complexity
  and alternate legal answers. Use a solver or domain library where justified.
- Layout/rendering: phone sizes, orientation where supported, high DPR, resize,
  typography, hit areas, surface composition, FX coverage and imported visual fidelity.
- Performance: actual motion and input under representative load, frame pacing and
  resource growth; avoid claiming a universal FPS from a desktop run.
- Lifecycle: replay, pause/resume, background/lock, dispose/reopen and late loader
  results. No leaked sounds, loops, listeners or duplicate saved state.
- Native features: Android/iOS device checks where required, denial/unavailable path,
  calibration and audio unlock. Unavailable phone access is a disclosed test gap.
- Persistence: accepted/failed/pending scores, rank consistency, checkpoint boundaries,
  progress restore/complete/abandon, repeated visits and declared shared operations.
- Tuning: defaults, edge values, curves over time, live changes and restart changes.
- Delivery preparation: retain exact tested source/manifest and honest feedback. Do
  not change the payload after testing without rerunning the affected proof.

**Done when:** the code audit is complete, findings are fixed and rechecked or explicitly reported as unresolved, actual tested cases are recorded, and remaining device or environment limitations are explicit. Source review does not replace execution; passing tests do not replace visual inspection. None proves the absence of all bugs.

## Step 8: Deliver and Verify the Draft

Use [upload.md](https://agent.plethora.studio/v1/agent/upload.md) for the account/upload protocol; do not maintain a second copy here.
Reuse a valid paired token; recover missing/expired pairing in place while preserving
work. Respect denial/revocation. Preserve idempotency and reconcile unknown outcomes
instead of blindly issuing fresh writes.

- Upload the tested source and manifest to the intended creator's drafts. Confirm the
  response identifies the expected draft and revision/package; use available receipt
  or readback evidence to establish that it corresponds to the tested payload.
- Where access permits, open the saved draft in Plethora and verify the visible first
  frame, first interaction and critical host integration. A standalone preview cannot
  establish that the uploaded package behaves correctly inside the host.
- If the host/device cannot be exercised, report that gap explicitly. Do not claim a
  successful upload proves playability, or demand unrelated tooling just to finish.
- If delivery exposes a defect, repair it within scope, repeat the affected audit/tests,
  and verify the updated draft identity. Do not leave a knowingly broken draft labelled ready.
- Include honest agentFeedback about SDK, documentation and workflow friction. Report
  the saved draft title/identity, actual tests and remaining phone checks, then direct
  the creator to Create -> Drafts. Creator review and publication remain their decision.

**Done when:** the intended draft is confirmed saved, host verification is completed or clearly marked unverified, and the creator receives an accurate handoff. Never patch published records directly or equate saved, tested and published.

Use these checks to produce the requested experience, not to force every SDK feature into it. Do not turn toolkit coverage into feature stuffing, a mandatory renderer, or one Plethora visual style.


## Fundamentals

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.


## Known Failure Patterns

Check universal failures, then the subsystems you actually use. These are evidence-backed checks, not a fixed renderer or visual style. Historical platform bugs are not creator prohibitions: variables, tables, helpers, destructuring and supported wrapper patterns must not be banned because an old analyzer failed. Keep a minimal repro and report a current platform failure; do not force unnecessary source rewrites. See [existing-code.md](https://agent.plethora.studio/v1/agent/existing-code.md) for the complete conversion-specific rules.

## active-play-time
- **Symptom:** A puzzle timer includes hours away, or slower devices receive shorter completion times.
- **Cause:** Using Date.now()-savedStart or summing clamped simulation dt as competitive play time.
- **Correction:** Use ctx.game.stopwatch for active elapsed time, start/pause on actual gameplay boundaries, and persist elapsed snapshots. Keep calendar dates/countdowns separate. Old timestamps cannot reconstruct active durations: preserve old progress without awarding invented timed records.
- **Proof:** Pause for hours, reopen an acknowledged save, switch colour/menu, use slow frames and finish. Time away adds zero; foreground thinking counts.
- **Owner:** [sdk/game.md](https://agent.plethora.studio/v1/agent/sdk/game.md)

## mixed-challenge-boards
- **Symptom:** Different colours, difficulties or timing rules compete on one board.
- **Cause:** A shared record channel lacks distinguishing dimensions, or reads omit the submitted dimension.
- **Correction:** Declare dimensions or separate channels and use the same identity for submit/rank/leaderboard. For changed measurement semantics add a new channel and preserve old keys/epochs/scores. Metadata alone does not select a board or enforce a calendar edition.
- **Proof:** Complete each colour independently, inspect its matching board, preserve legacy rows and reject local stale-edition submits.
- **Owner:** [sdk/memory.md](https://agent.plethora.studio/v1/agent/sdk/memory.md)

## blank-ready
- **Symptom:** Blank first frame or a ready event with no useful content.
- **Cause:** Signaling readiness after setup rather than actual drawing.
- **Correction:** Paint meaningful content first; preserve errors and wire the first real input.
- **Proof:** Inspect rendered pixels and trigger actual input before claiming playability.
- **Owner:** [sdk/runtime.md](https://agent.plethora.studio/v1/agent/sdk/runtime.md)

## canvas-return
- **Symptom:** Drawing methods are missing or nothing is drawn.
- **Cause:** Treating ctx or the SDK canvas as the 2D painter.
- **Correction:** Use canvas = ctx.createCanvas2D(), then canvas.getContext("2d").
- **Proof:** Run init and verify visible drawing, not a mock return shape.
- **Owner:** [sdk/surfaces.md](https://agent.plethora.studio/v1/agent/sdk/surfaces.md)

## invented-api
- **Symptom:** Undefined method, invalid manifest or a nonexistent endpoint.
- **Cause:** Guessing familiar names instead of reading current interfaces.
- **Correction:** Read the complete SDK and schema; distinguish supported, legacy and unavailable features.
- **Proof:** Trace every authored call/field to its documented owner; exercise each path.
- **Owner:** [sdk.md](https://agent.plethora.studio/v1/agent/sdk.md)

## dependency-load
- **Symptom:** A library constructor/global is undefined.
- **Cause:** Use before await, wrong registry kind/export, guessed version or leaked global.
- **Correction:** Inspect exact registry pins/resources; await the right loader inside init and pass dependencies explicitly.
- **Proof:** Cold load and retry a real failure; verify the first frame and actual handler bindings.
- **Owner:** [sdk/libraries.md](https://agent.plethora.studio/v1/agent/sdk/libraries.md)

## dom-network
- **Symptom:** SecurityError or host content altered.
- **Cause:** Global DOM mounting, arbitrary networking, CDN fallback or script insertion.
- **Correction:** Use scoped DOM/surfaces and approved managed registry loads. Do not weaken the sandbox.
- **Proof:** Run the original authored source in the target runtime and preserve the actual diagnostic.
- **Owner:** [fundamentals.md](https://agent.plethora.studio/v1/agent/fundamentals.md)

## touch-trap
- **Symptom:** Scene looks alive but taps never reach it.
- **Cause:** Full-screen root/HUD/overlay intercepts input or all child controls are disabled.
- **Correction:** Set intentional surface input policy, preserve interactive children and close/skip controls.
- **Proof:** Use real hit-tested pointer events at visible coordinates, including the first tap and overlay dismissal.
- **Owner:** [sdk/surfaces.md](https://agent.plethora.studio/v1/agent/sdk/surfaces.md)

## dpr
- **Symptom:** Quarter-screen rendering/flash, zoomed corner, or displaced hit targets.
- **Cause:** CSS size and backing-store DPR/transform disagree.
- **Correction:** Choose one coordinate model consistently across draw, clear, FX and input; respect CSS-mode transforms.
- **Proof:** Check DPR 1/2/3, resize and full transition coverage using backing pixels and screenshots.
- **Owner:** [sdk/surfaces.md](https://agent.plethora.studio/v1/agent/sdk/surfaces.md)

## canvas-flags
- **Symptom:** A transparent layer disappears or composition differs on Android.
- **Cause:** Blanket alpha:false/desynchronized flags or inappropriate readback optimization.
- **Correction:** Use defaults first; alpha:false requires full painting, desynchronized is opt-in, willReadFrequently only for repeated local reads.
- **Proof:** Check layered canvas/WebGL on a real Android host as well as desktop.
- **Owner:** [sdk/surfaces.md](https://agent.plethora.studio/v1/agent/sdk/surfaces.md)

## control-boundary
- **Symptom:** Text sits under the camera cutout or island, buttons hide behind the logo or keyboard, or half the scene is unnecessarily empty.
- **Cause:** Fixed offsets instead of ctx.contentSafeArea ?? ctx.safeArea, a 0px bottom CSS fallback, or treating every lower pixel as prohibited.
- **Correction:** Lay out text and controls from ctx.contentSafeArea ?? ctx.safeArea (CSS: var(--plethora-content-safe-bottom, 120px)); move only obscured actionables/important cues; retain passive scenery edge to edge and compose layers deliberately.
- **Proof:** Check full screen on a notch, Dynamic Island and Android 3-button phone and in the safe frame (no contentSafeArea, safeArea.bottom 120), with the logo and keyboard visible; check button/content overlap.
- **Owner:** [fundamentals.md](https://agent.plethora.studio/v1/agent/fundamentals.md)

## time-loops
- **Symptom:** Speed changes by device/refresh rate or tapping; resume jumps.
- **Cause:** Per-frame movement, inconsistent ms/seconds, duplicate scheduling or unbounded resume dt.
- **Correction:** Use coherent time-based simulation and one deliberate scheduling owner per subsystem.
- **Proof:** Compare low/high cadence, input bursts, pause/resume and a second run.
- **Owner:** [sdk/game.md](https://agent.plethora.studio/v1/agent/sdk/game.md)

## async-lifetime
- **Symptom:** Old results alter a new run or disposed resources reappear.
- **Cause:** Late callbacks have no attempt/lifetime owner.
- **Correction:** Fence results by attempt and disposal; dispose late resources and avoid duplicate replay listeners.
- **Proof:** Delay success/failure across replay, close and reopen.
- **Owner:** [sdk/runtime.md](https://agent.plethora.studio/v1/agent/sdk/runtime.md)

## audio
- **Symptom:** Silent audio, swallowed playback failure or leaked sound.
- **Cause:** Missing gesture unlock/permission or unowned custom resources.
- **Correction:** Use actual readiness/error signals, deliberate gesture startup and cleanup. Host owns background suspension; report its failures rather than replacing it.
- **Proof:** Real Android/iOS tap, replay, mute, lock, background, foreground and disposal checks.
- **Owner:** [sdk/audio.md](https://agent.plethora.studio/v1/agent/sdk/audio.md)

## sensors
- **Symptom:** Motion/mic/camera fails or permission denial strands the player.
- **Cause:** Missing permission, unavailable native capability, bad units/calibration or no fallback.
- **Correction:** Declare/check permissions, use a real gesture, distinguish raw measurements from normalized controls and offer recovery.
- **Proof:** Phone test accepted/denied/unavailable paths; real physical movement/audio, not rising counters alone.
- **Owner:** [sdk/sensors.md](https://agent.plethora.studio/v1/agent/sdk/sensors.md)

## score-writes
- **Symptom:** Lag, request spam or replay waits for the server.
- **Cause:** Writing every frame/tap instead of meaningful results/checkpoints.
- **Correction:** Keep numeric score local; bounded checkpoints and detached, attempt-fenced result presentation.
- **Proof:** Count writes in a full run and rapidly replay while a request is delayed.
- **Owner:** [sdk/game.md](https://agent.plethora.studio/v1/agent/sdk/game.md)

## score-standing
- **Symptom:** queued is shown as accepted, stale rank, or guessed position.
- **Cause:** Confusing local state, host synchronization and committed leaderboard snapshots.
- **Correction:** Use explicit submit for acceptance and authoritative rank/board results. Handle null, pending, failure and cached Updating honestly.
- **Proof:** Test improvement/non-improvement, pending/failed writes, empty board and replay during completion.
- **Owner:** [sdk/memory.md](https://agent.plethora.studio/v1/agent/sdk/memory.md)

## device-only-persistence
- **Symptom:** BEST, unlocks or progress disappear after reinstall, or leak across account switch.
- **Cause:** Using ctx.storage as durable account state or assuming a record declaration restores an authored BEST display.
- **Correction:** In authenticated published app playback, read the existing all_time record standing for the exact channel/dimensions/order; use ctx.memory.local for cloud private state or ctx.game.progress for Continue Playing. This excludes draft preview and shared-web play: shared-web memory uses page-local simulation even for published Bits, not account-cloud persistence. A failed read must not cause a default/reset write. Never import unattributed legacy device values into competitive records.
- **Proof:** Clear device storage after acknowledged cloud saves, reopen on the same account, switch accounts and delay/fail hydration. Distinguish a missing accepted score from never-delivered local bytes; simulated success cannot prove an account save.
- **Owner:** [sdk/memory.md](https://agent.plethora.studio/v1/agent/sdk/memory.md)

## lost-score-delivery
- **Symptom:** A higher score never reaches the board, especially during continued play after a win.
- **Cause:** Only submitting the first win, swallowing rejection, or treating ctx.platform.setScore/queued:true as acceptance.
- **Correction:** Checkpoint already-valid best_per_user improvements at bounded milestones and submit the final valid result even after an earlier win. Keep pending/failed separate from accepted, fence async UI callbacks, and never use silent .catch(() => {}) as a save strategy.
- **Proof:** Test post-win improvement then game-over, offline/partial delivery, checkpoint failure, replay during pending work and reinstall before versus after acknowledgement. Count requests to rule out per-frame writes.
- **Owner:** [sdk/game.md](https://agent.plethora.studio/v1/agent/sdk/game.md)

## progress-identity
- **Symptom:** Lost resume/records or pass-and-play users share the wrong state.
- **Cause:** Confusing viewer progress/preferences with party identity, or changing published keys.
- **Correction:** Preserve record dimensions/keys and progress identity; version restore data and complete/abandon appropriately. Model local players explicitly.
- **Proof:** Reopen old saved state, test completion/abandon and keep existing records through the update.
- **Owner:** [sdk/game.md](https://agent.plethora.studio/v1/agent/sdk/game.md)

## shared-world
- **Symptom:** One creator overwrites others or writes are throttled.
- **Cause:** Whole-world replacement or unbounded per-frame mutations.
- **Correction:** Use documented semantic operations, channels, budgets and errors.
- **Proof:** Exercise concurrent updates, limits and failed writes without losing local feedback.
- **Owner:** [sdk/memory.md](https://agent.plethora.studio/v1/agent/sdk/memory.md)

## onboarding
- **Symptom:** Every Bit opens the same paragraphs or users still cannot play.
- **Cause:** Text cards substituted for teaching; no deliberate first-use decision.
- **Correction:** Use immersion, one cue or an interactive skippable example as appropriate. Bit-owned teaching uses immersive to avoid a second overlay.
- **Proof:** Watch an uncoached first use and Skip/replay; preserve intentional discovery.
- **Owner:** [sdk/onboarding.md](https://agent.plethora.studio/v1/agent/sdk/onboarding.md)

## puzzle-correctness
- **Symptom:** Only the stored solution is accepted, invalid boards win, or generators output trivial puzzles.
- **Cause:** Comparing arrays instead of validating rules, or not testing the generator distribution.
- **Correction:** Validate actual rules and alternate legal solutions; test solvability and meaningful complexity across seeds.
- **Proof:** Use valid alternate answers, invalid near-misses and representative generated boards; use an appropriate solver when justified.
- **Owner:** [creation.md](https://agent.plethora.studio/v1/agent/creation.md)

## generic-webgl-error
- **Symptom:** A generic failure says the device cannot do 3D.
- **Cause:** One catch relabels dependency, renderer and first-frame errors.
- **Correction:** Keep original error/stage via ctx.platform.error; recover explicitly and with bounds.
- **Proof:** Inject each failure separately; verify diagnostics and no automatic restart loop.
- **Owner:** [existing-code.md](https://agent.plethora.studio/v1/agent/existing-code.md)

## conversion-fidelity
- **Symptom:** Imported game loses controls, fog/materials, HUD alignment or visual identity.
- **Cause:** Rebuilding instead of adapting ownership; CSS/backing coordinates or imported globals changed.
- **Correction:** Preserve the original design and renderer, explicit dependencies/this binding, and compare key scenarios.
- **Proof:** Match original reference screenshots and first real input, resize, replay and cleanup.
- **Owner:** [existing-code.md](https://agent.plethora.studio/v1/agent/existing-code.md)

## json-upload
- **Symptom:** Broken JSON, wrong response key, duplicate drafts or unknown outcomes.
- **Cause:** Shell-escaped source, assumed envelopes or changing retry identity prematurely.
- **Correction:** Serialize files structurally; inspect exact envelopes; preserve request identity and reconcile before retrying.
- **Proof:** Parse payload locally, test a lost response, a 202 and corrected-payload retry following upload.md.
- **Owner:** [upload.md](https://agent.plethora.studio/v1/agent/upload.md)

## claiming-success
- **Symptom:** A 200/compile pass is called working or published.
- **Cause:** Transport acceptance is mistaken for behavior or creator consent.
- **Correction:** Distinguish saved, tested and published. Report real tests and gaps; creator opens Create -> Drafts.
- **Proof:** Verify correct saved draft identity and host interaction where access permits; label unavailable evidence.
- **Owner:** [upload.md](https://agent.plethora.studio/v1/agent/upload.md)

These checks complement, not replace, Step 7's source audit for new faulty/incomplete logic and actual execution. Fix within the creator's scope and repeat the affected checks.


## Approved Library Pins

- three@0.164.1
- three-global@0.134.0
- three-global@0.128.0
- playcanvas@1.74.0
- mediapipe-hands@0.4.1675469240
- html2canvas@1.4.1
- ammo.js@0.0.10
- d3@7.9.0
- tone@15.1.22
- howler@2.2.4
- matter-js@0.20.0
- planck@1.5.0
- gsap@3.15.0
- roughjs@4.6.6
- canvas-confetti@1.9.4
- vfx-js-core@0.11.1+esbuild.0.28.1
- animejs@3.2.1
- p5@2.2.3
- pixi.js@8.18.1
- paper@0.12.18
- regl@2.1.1
- ogl@1.0.11+esbuild.0.28.1
- two.js@0.8.23
- pts@0.12.9
- twgl.js@7.0.0
- zdog@1.1.3
- oimo@1.0.9
- phaser@4.1.0
- fabric@7.4.0
- makerjs@0.19.2
- sketch-js@1.1.3
- picogl@0.17.9
- babylonjs@9.7.0
- css-doodle@0.51.0
- hydra-synth@1.4.0
- @jscad/modeling@2.13.0+esbuild.0.28.1
- @luma.gl/core@9.3.3+esbuild.0.28.1
- @theatre/core@0.7.2+esbuild.0.28.1
- canvas-sketch@0.7.7+esbuild.0.28.1
- @thi.ng/geom@8.3.30+esbuild.0.28.1
- shader-park-core@0.2.8+esbuild.0.28.1

## Approved Resource Sidecars

These are loaded through dedicated helpers or `ctx.registry.resources()`; do not add them as separate manifest dependencies unless the SDK explicitly asks for it.

- mediapipe-hands-runtime@0.4.1675469240

Fetch `https://agent.plethora.studio/v1/agent/libraries.json` for exact URLs, SHA-256 hashes, sizes, MIME types, and font metadata.

## Minimal Single-File Bit

```js
// Plethora Bit · docs and draft upload: https://agent.plethora.studio/v1/agent/start.md
window.plethoraBit = {
  meta: {
    title: "Touch Sketch",
    runtime: "plethora-bit@2",
    tags: ["creative", "touch"],
    permissions: ["haptics"]
  },

  async init(ctx) {
    const canvas = ctx.createCanvas2D({ coordinateSpace: "css", maxDpr: 2 });
    const g = canvas.getContext("2d");
    const touches = [];

    function draw() {
      const area = ctx.contentSafeArea ?? ctx.safeArea; // clear of the island and the logo
      g.fillStyle = "#142a29";
      g.fillRect(0, 0, ctx.width, ctx.height);
      g.fillStyle = "#ffffff";
      g.font = "20px sans-serif";
      g.textAlign = "center";
      g.fillText("Touch to make a mark", ctx.width / 2, area.top + 48);
      g.fillStyle = "#f2c94c";
      for (const touch of touches) {
        g.beginPath();
        g.arc(touch.x, touch.y, 12, 0, Math.PI * 2);
        g.fill();
      }
    }

    ctx.input.on(canvas, "tap", pointer => {
      ctx.platform.start();
      ctx.platform.haptic("light");
      touches.push({ x: pointer.x, y: pointer.y });
      if (touches.length > 64) touches.shift();
      draw();
    });

    ctx.onResize(draw, { immediate: true });
    ctx.platform.ready();
  }
};
```

## Diverse Example Bits

### Score Chase

Short arcade score bit with a standard Plethora leaderboard.

`plethora.json`:

```json
{
  "schemaVersion": 1,
  "runtime": "plethora-bit@2",
  "entry": "main.js",
  "title": "Score Chase",
  "description": "Tap targets, build a score, submit a high score.",
  "tags": [
    "arcade",
    "score"
  ],
  "permissions": [
    "haptics"
  ],
  "dependencies": [],
  "display": "fullscreen",
  "onboarding": {
    "kind": "one_line",
    "version": 1,
    "message": "Tap each target before it fades."
  },
  "memory": {
    "records": {
      "score": {
        "label": "High Score",
        "valueType": "number",
        "order": "desc",
        "format": "integer",
        "periods": [
          "daily",
          "weekly",
          "all_time"
        ],
        "scopes": [
          "following",
          "global"
        ],
        "dedupe": "best_per_user",
        "dimensions": {
          "mode": [
            "classic"
          ]
        }
      }
    }
  }
}
```

`main.js`:

```js
// Plethora Bit · docs and draft upload: https://agent.plethora.studio/v1/agent/start.md
window.plethoraBit = {
  async init(ctx) {
    // Keep the UI clear of the island and the logo; the fallbacks are the safe frame's.
    const root = ctx.createRoot({ style: "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)" });
    const score = ctx.game.score({ initial: 0, min: 0 });
    let taps = 0;
    let run = 0;
    let playing = false;
    let disposed = false;
    let cachedBoard = null;
    root.innerHTML = '<button class="target">tap</button><strong class="score">0</strong><button class="replay">replay</button><p class="board"></p><p class="status"></p>';
    const scoreNode = root.querySelector(".score");
    const boardNode = root.querySelector(".board");
    const statusNode = root.querySelector(".status");
    const boardOptions = { scope: "global", period: "all_time", dimensions: { mode: "classic" } };
    function beginRun() {
      run += 1;
      taps = 0;
      playing = true;
      ctx.platform.start();
      score.reset();
      scoreNode.textContent = "0";
      statusNode.textContent = "";
    }
    async function refreshBoard(attempt) {
      // Keep cached rows visible while the matching submission settles.
      statusNode.textContent = "Updating";
      try {
        const board = await score.leaderboard("score", boardOptions);
        if (disposed || attempt !== run) return;
        cachedBoard = board;
        boardNode.textContent = cachedBoard.rows.map(row => "#" + row.rank + " " + row.value).join(" | ");
        statusNode.textContent = board.checkpointStatus && board.checkpointStatus.failed
          ? "Some checkpoints were not saved. Showing accepted scores."
          : (board.viewerRank ? "Your rank: " + board.viewerRank.rank : "Not ranked yet");
      } catch (error) {
        if (disposed || attempt !== run) return;
        statusNode.textContent = "Result could not be refreshed. You can still replay.";
      }
    }
    ctx.input.activate(root.querySelector(".replay"), beginRun);
    ctx.input.activate(root.querySelector(".target"), () => {
      if (!playing) beginRun();
      score.add(10);
      taps += 1;
      scoreNode.textContent = String(score.value);
      ctx.platform.haptic("light");
      ctx.platform.interact({ type: "score" });
      if (taps === 3) {
        const attempt = run;
        // This completed checkpoint is a valid score, not an unfinished timer.
        // The receipt means queued locally, not server acceptance.
        score.checkpoint("score", { label: score.value + " pts", dimensions: { mode: "classic" } })
          .catch(() => { if (!disposed && attempt === run) statusNode.textContent = "Checkpoint not queued"; });
      }
      if (taps < 5) return;
      playing = false;
      score.submit("score", {
        label: score.value + " pts",
        dimensions: { mode: "classic" }
      }).catch(() => {}); // refreshBoard also observes this submission failure.
      ctx.platform.complete({ score: score.value });
      void refreshBoard(run); // Replay never waits for this promise.
    });
    ctx.onDestroy(() => { disposed = true; run += 1; });
    ctx.platform.ready();
  }
};
```

### Tunable Difficulty Dash

A small arcade bit showing draft-time knobs, a difficulty curve, and live ctx.tune updates.

`plethora.json`:

```json
{
  "schemaVersion": 1,
  "runtime": "plethora-bit@2",
  "entry": "main.js",
  "title": "Tunable Difficulty Dash",
  "description": "Tune speed, color, music intensity, and the difficulty ramp from Draft Tools.",
  "tags": [
    "arcade",
    "tuning"
  ],
  "permissions": [
    "haptics",
    "backgroundMusic"
  ],
  "dependencies": [],
  "display": "fullscreen",
  "onboarding": {
    "kind": "one_line",
    "version": 1,
    "message": "Tap targets; drag to follow."
  },
  "tuning": {
    "schemaVersion": 1,
    "groups": {
      "gameplay": {
        "label": "Gameplay"
      },
      "difficulty": {
        "label": "Difficulty"
      },
      "visual": {
        "label": "Visual Feel"
      },
      "audio": {
        "label": "Audio"
      }
    },
    "knobs": {
      "player_speed": {
        "label": "Player speed",
        "type": "number",
        "default": 220,
        "min": 120,
        "max": 420,
        "step": 10,
        "group": "gameplay",
        "intent": "feel",
        "apply": "live"
      },
      "accent_color": {
        "label": "Accent color",
        "type": "color",
        "default": "#5fc9a4",
        "group": "visual",
        "intent": "visual",
        "apply": "live"
      },
      "music_intensity": {
        "label": "Music intensity",
        "type": "percent",
        "default": 0.45,
        "min": 0,
        "max": 1,
        "step": 0.05,
        "group": "audio",
        "intent": "audio",
        "apply": "live"
      },
      "arena_style": {
        "label": "Arena style",
        "type": "choice",
        "default": "neon",
        "options": [
          "neon",
          "paper",
          "night"
        ],
        "group": "visual",
        "intent": "visual",
        "apply": "restart"
      }
    },
    "curves": {
      "difficulty_ramp": {
        "label": "Difficulty ramp",
        "domain": "elapsed_seconds",
        "range": [
          0.8,
          2.6
        ],
        "default": [
          {
            "x": 0,
            "y": 0.8
          },
          {
            "x": 45,
            "y": 1.25
          },
          {
            "x": 120,
            "y": 2.2
          }
        ],
        "easing": "smooth",
        "group": "difficulty",
        "apply": "live"
      }
    },
    "presets": {
      "gentle": {
        "label": "Gentle",
        "values": {
          "player_speed": 180,
          "music_intensity": 0.25,
          "difficulty_ramp": [
            {
              "x": 0,
              "y": 0.7
            },
            {
              "x": 90,
              "y": 1.1
            },
            {
              "x": 180,
              "y": 1.5
            }
          ]
        }
      },
      "spicy": {
        "label": "Spicy",
        "values": {
          "player_speed": 300,
          "music_intensity": 0.75,
          "accent_color": "#f2c94c"
        }
      }
    }
  }
}
```

`main.js`:

```js
// Plethora Bit · docs and draft upload: https://agent.plethora.studio/v1/agent/start.md
window.plethoraBit = {
  async init(ctx) {
    const canvas = ctx.createCanvas2D({ alpha: false });
    const g = canvas.getContext("2d");
    const input = ctx.input.track(canvas);
    const score = ctx.game.score({ initial: 0, min: 0 });
    let elapsed = 0;
    let player = { x: ctx.width * 0.5, y: ctx.height * 0.72 };
    let target = { x: ctx.width * 0.5, y: ctx.height * 0.28 };
    let accent = ctx.tune.color("accent_color");
    let music = null;

    ctx.tune.onChange(["accent_color", "music_intensity"], () => {
      accent = ctx.tune.color("accent_color");
      if (music) music.setIntensity(ctx.tune.percent("music_intensity"));
    });

    function draw() {
      const area = ctx.contentSafeArea ?? ctx.safeArea; // clear of the island and the logo
      const ramp = ctx.tune.curve("difficulty_ramp").at(elapsed);
      g.fillStyle = ctx.tune.choice("arena_style") === "paper" ? "#f7f3ea" : "#090609";
      g.fillRect(0, 0, ctx.width, ctx.height);
      g.fillStyle = accent;
      g.beginPath();
      g.arc(target.x, target.y, 22 * ramp, 0, Math.PI * 2);
      g.fill();
      g.fillStyle = "#ffffff";
      g.beginPath();
      g.arc(player.x, player.y, 18, 0, Math.PI * 2);
      g.fill();
      g.font = "700 24px system-ui";
      g.fillText(score.value + " pts", area.left + 24, area.top + 44);
    }

    ctx.input.on(canvas, "tap", async pointer => {
      ctx.platform.start();
      if (!music) {
        await ctx.music.unlock();
        music = ctx.music.play({ preset: "arcade", volume: 0.35, intensity: ctx.tune.percent("music_intensity") });
      }
      const speed = ctx.tune.number("player_speed");
      const dx = target.x - pointer.x;
      const dy = target.y - pointer.y;
      if (Math.hypot(dx, dy) < Math.max(34, speed * 0.14)) {
        score.add(10);
        const area = ctx.contentSafeArea ?? ctx.safeArea;
        target = {
          x: area.left + 32 + Math.random() * (ctx.width - area.left - area.right - 64),
          y: area.top + 72 + Math.random() * (ctx.height - area.top - area.bottom - 144)
        };
        ctx.fx.impact({ x: pointer.x, y: pointer.y, color: accent });
        ctx.fx.floatText({ text: "+10", x: pointer.x, y: pointer.y, color: accent });
        ctx.platform.haptic("light");
      }
      ctx.platform.interact({ type: "tap", score: score.value });
    });

    draw();
    ctx.game.loop({
      input,
      update(dt) {
        const dtSeconds = dt / 1000;
        elapsed += dtSeconds;
        const speed = ctx.tune.number("player_speed");
        if (input.down) {
          player.x = ctx.math.lerp(player.x, input.x, Math.min(1, dtSeconds * speed / 120));
          player.y = ctx.math.lerp(player.y, input.y, Math.min(1, dtSeconds * speed / 120));
        }
      },
      render: draw
    });
    ctx.platform.ready();
  }
};
```

### Pocket Quest Resume

Small level game that appears in Continue Playing after a checkpoint save.

`plethora.json`:

```json
{
  "schemaVersion": 1,
  "runtime": "plethora-bit@2",
  "entry": "main.js",
  "title": "Pocket Quest Resume",
  "description": "Resume a tiny quest from your last saved level.",
  "tags": [
    "game",
    "story"
  ],
  "permissions": [
    "haptics"
  ],
  "dependencies": [],
  "display": "fullscreen",
  "game": {
    "progress": {
      "main": {
        "label": "Quest progress",
        "stateSchemaVersion": 1,
        "ttlDays": 90
      }
    }
  },
  "onboarding": {
    "kind": "guided",
    "version": 1,
    "steps": [
      {
        "id": "collect",
        "title": "Collect",
        "body": "Tap collect gem to move through the quest.",
        "advance": "interaction"
      },
      {
        "id": "checkpoint",
        "title": "Continue later",
        "body": "Every three gems saves a checkpoint for Continue Playing.",
        "advance": "continue"
      }
    ]
  }
}
```

`main.js`:

```js
// Plethora Bit · docs and draft upload: https://agent.plethora.studio/v1/agent/start.md
window.plethoraBit = {
  async init(ctx) {
    const root = ctx.createRoot({ style: "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)" });
    const saved = await ctx.game.progress.load("main");
    const savedState = saved && saved.resumeEligible === true ? saved.state : {};
    let level = Number(savedState.level) || 1;
    let gems = Number(savedState.gems) || 0;
    root.innerHTML = '<section><h1></h1><p></p><button class="play">collect gem</button><button class="restart">restart</button></section>';
    const title = root.querySelector("h1");
    const info = root.querySelector("p");
    function render() {
      title.textContent = "Level " + level;
      info.textContent = gems + " gems collected. Every 3 gems saves a checkpoint.";
    }
    async function saveCheckpoint() {
      return ctx.game.progress.save("main", {
        state: { level, gems, seed: "quest-v1" },
        label: "Level " + level,
        percent: Math.min(95, level * 18),
        dimensions: { mode: "story" }
      });
    }
    ctx.input.activate(root.querySelector(".play"), async () => {
      ctx.platform.start();
      gems += 1;
      ctx.platform.interact({ type: "collect", level, gems });
      if (gems % 3 === 0) {
        level += 1;
        await saveCheckpoint();
        ctx.platform.haptic("success");
      }
      if (level >= 6) {
        await ctx.game.progress.complete("main", {
          state: { level, gems, seed: "quest-v1", finished: true },
          label: "Finished",
          percent: 100,
          dimensions: { mode: "story" }
        });
        ctx.platform.complete({ level, gems });
      }
      render();
    });
    ctx.input.activate(root.querySelector(".restart"), async () => {
      ctx.platform.start();
      level = 1;
      gems = 0;
      await ctx.game.progress.abandon("main");
      ctx.platform.interact({ type: "restart" });
      render();
    });
    render();
    ctx.platform.ready();
  }
};
```

### One-Tap Poll

Survey bit with a global tally visible after voting.

`plethora.json`:

```json
{
  "schemaVersion": 1,
  "runtime": "plethora-bit@2",
  "entry": "main.js",
  "title": "One-Tap Poll",
  "description": "Vote once, then see how everyone answered.",
  "tags": [
    "survey",
    "choice"
  ],
  "permissions": [],
  "dependencies": [],
  "display": "fullscreen",
  "memory": {
    "tallies": {
      "mood": {
        "label": "Pick a mood",
        "type": "single_choice",
        "options": [
          "bright",
          "soft",
          "strange"
        ],
        "visibility": "after_vote",
        "rules": [
          {
            "type": "replace_previous",
            "by": "user"
          }
        ]
      }
    }
  },
  "onboarding": {
    "kind": "briefing",
    "version": 1,
    "pages": [
      {
        "title": "One vote",
        "body": "Choose the mood that fits right now."
      },
      {
        "title": "Then see the room",
        "body": "After voting, Plethora shows the current global tally."
      }
    ]
  }
}
```

`main.js`:

```js
// Plethora Bit · docs and draft upload: https://agent.plethora.studio/v1/agent/start.md
window.plethoraBit = {
  async init(ctx) {
    const root = ctx.createRoot({ style: "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)" });
    root.innerHTML = '<button data-v="bright">bright</button><button data-v="soft">soft</button><button data-v="strange">strange</button><pre></pre>';
    const out = root.querySelector("pre");
    for (const button of root.querySelectorAll("button")) {
      ctx.input.activate(button, async () => {
        ctx.platform.start();
        await ctx.memory.tally("mood").choose(button.dataset.v);
        const results = await ctx.memory.tally("mood").results();
        out.textContent = JSON.stringify(results, null, 2);
        ctx.platform.interact({ type: "vote" });
        ctx.platform.complete({ choice: button.dataset.v });
      });
    }
    ctx.platform.ready();
  }
};
```

### Shared Pixel Mural

Co-creation bit where each visitor mutates a bounded shared world.

`plethora.json`:

```json
{
  "schemaVersion": 1,
  "runtime": "plethora-bit@2",
  "entry": "main.js",
  "title": "Shared Pixel Mural",
  "description": "Tap one pixel into a small shared canvas.",
  "tags": [
    "art",
    "shared"
  ],
  "permissions": [
    "haptics"
  ],
  "dependencies": [],
  "display": "fullscreen",
  "memory": {
    "worlds": {
      "mural": {
        "label": "Shared mural",
        "type": "pixel_grid",
        "width": 64,
        "height": 64,
        "rules": [
          {
            "type": "rate_limit",
            "max": 1,
            "per": "day",
            "by": "user"
          }
        ],
        "attribution": true
      }
    }
  },
  "onboarding": {
    "kind": "immersive",
    "version": 1
  }
}
```

`main.js`:

```js
// Plethora Bit · docs and draft upload: https://agent.plethora.studio/v1/agent/start.md
window.plethoraBit = {
  async init(ctx) {
    const canvas = ctx.createCanvas2D();
    const g = canvas.getContext("2d");
    const world = ctx.memory.world("mural");
    // One grid for drawing and tapping: 64 square cells inside the content-safe area.
    function grid() {
      const area = ctx.contentSafeArea ?? ctx.safeArea;
      const room = Math.min(ctx.width - area.left - area.right, ctx.height - area.top - area.bottom);
      return { area, cell: Math.max(1, Math.floor(room / 64)) };
    }
    async function draw() {
      const snapshot = await world.get();
      const { area, cell } = grid();
      g.clearRect(0, 0, ctx.width, ctx.height);
      for (const pixel of snapshot?.pixels || []) {
        g.fillStyle = pixel.color;
        g.fillRect(area.left + pixel.x * cell, area.top + pixel.y * cell, cell, cell);
      }
    }
    ctx.input.on(canvas, "tap", async (pointer) => {
      const { area, cell } = grid();
      const x = Math.floor((pointer.x - area.left) / cell);
      const y = Math.floor((pointer.y - area.top) / cell);
      if (x < 0 || y < 0 || x >= 64 || y >= 64) return;
      ctx.platform.start();
      await world.mutate({ x, y, color: "#00ff99" });
      ctx.platform.haptic("success");
      ctx.platform.interact({ type: "world_mutation" });
      await draw();
    });
    ctx.onResize(() => { draw(); });
    await draw();
    ctx.platform.ready();
  }
};
```

### Layered Canvas HUD

Canvas gameplay with a DOM HUD that stays visible without stealing play input.

`plethora.json`:

```json
{
  "schemaVersion": 1,
  "runtime": "plethora-bit@2",
  "entry": "main.js",
  "title": "Layered Canvas HUD",
  "description": "A compact surface-layer composition example.",
  "tags": [
    "canvas",
    "hud"
  ],
  "onboarding": {
    "kind": "one_line",
    "version": 1,
    "message": "Tap the canvas; use Pause to toggle input."
  },
  "permissions": [],
  "dependencies": [],
  "display": "fullscreen"
}
```

`main.js`:

```js
// Plethora Bit · docs and draft upload: https://agent.plethora.studio/v1/agent/start.md
window.plethoraBit = {
  async init(ctx) {
    const canvas = ctx.createCanvas2D({ layer: "content" });
    const g = canvas.getContext("2d");
    const hud = ctx.createRoot({
      layer: "overlay",
      input: "passthrough",
      style: "padding:24px;padding-top:calc(var(--plethora-content-safe-top, 0px) + 24px);display:flex;align-items:flex-start;justify-content:space-between"
    });
    hud.innerHTML = '<strong>Layered HUD</strong><button>pause</button>';
    let paused = false;
    ctx.input.activate(hud.querySelector("button"), () => {
      paused = !paused;
      ctx.platform.interact({ type: "pause", paused });
    });
    ctx.input.on(canvas, "tap", pointer => {
      if (!paused) ctx.platform.interact({ type: "canvas_tap", x: pointer.x, y: pointer.y });
    });
    g.fillStyle = "#10121a";
    g.fillRect(0, 0, ctx.width, ctx.height);
    ctx.platform.ready();
  }
};
```

### Feedback Sprint

A small Canvas2D game that uses managed visual feedback while keeping game state and rendering in the Bit.

`plethora.json`:

```json
{
  "schemaVersion": 1,
  "runtime": "plethora-bit@2",
  "entry": "main.js",
  "title": "Feedback Sprint",
  "description": "Tap five targets, then replay through a visual transition.",
  "tags": [
    "arcade",
    "feedback"
  ],
  "onboarding": {
    "kind": "one_line",
    "version": 1,
    "message": "Tap five times, then tap to replay."
  },
  "permissions": [],
  "dependencies": [],
  "display": "fullscreen"
}
```

`main.js`:

```js
// Plethora Bit · docs and draft upload: https://agent.plethora.studio/v1/agent/start.md
window.plethoraBit = {
  async init(ctx) {
    const canvas = ctx.createCanvas2D({ layer: "content", alpha: false });
    const g = canvas.getContext("2d");
    const input = ctx.input.track(canvas);
    let score = 0;
    let scene = "play";

    function draw() {
      const area = ctx.contentSafeArea ?? ctx.safeArea;
      g.fillStyle = scene === "play" ? "#101820" : "#1b1335";
      g.fillRect(0, 0, ctx.width, ctx.height);
      g.fillStyle = "#f8f6ed";
      g.font = "700 26px system-ui";
      g.fillText(scene === "play" ? "Tap the field: " + score + "/5" : "Finished. Tap to replay.", area.left + 24, area.top + 64);
    }

    ctx.input.on(canvas, "tap", async pointer => {
      ctx.platform.start();
      if (scene === "results") {
        const transition = ctx.fx.transition({ kind: "iris", color: "#090b10" });
        await transition.cover();
        score = 0;
        scene = "play";
        draw();
        await transition.reveal();
        return;
      }

      score += 1;
      ctx.fx.impact({ x: pointer.x, y: pointer.y, color: "#95f9d6", strength: 0.7 });
      ctx.fx.floatText({ text: "+1", x: pointer.x, y: pointer.y, color: "#ffffff" });
      ctx.platform.interact({ type: "target", score });
      if (score < 5) return draw();

      const transition = ctx.fx.transition({ kind: "wipe", color: "#090b10" });
      await transition.cover();
      scene = "results";
      draw();
      await transition.reveal();
      ctx.platform.complete({ score });
    });

    draw();
    ctx.game.loop({ input, render: draw });
    ctx.platform.ready();
  }
};
```

### Visual Kit Toy

Palette, texture, material, and procedural sprite example that keeps the renderer simple while giving the bit a coherent visual language.

`plethora.json`:

```json
{
  "schemaVersion": 1,
  "runtime": "plethora-bit@2",
  "entry": "main.js",
  "title": "Visual Kit Toy",
  "description": "Tap to remix a tactile visual kit.",
  "tags": [
    "design",
    "fidget"
  ],
  "onboarding": {
    "kind": "one_line",
    "version": 1,
    "message": "Tap to remix; hold to move the orb."
  },
  "permissions": [
    "haptics"
  ],
  "dependencies": [],
  "display": "fullscreen"
}
```

`main.js`:

```js
// Plethora Bit · docs and draft upload: https://agent.plethora.studio/v1/agent/start.md
window.plethoraBit = {
  async init(ctx) {
    const canvas = ctx.createCanvas2D({ alpha: false });
    const g = canvas.getContext("2d");
    const input = ctx.input.track(canvas);
    let seed = 0;
    let kit = ctx.visual.kit({
      mood: "crystalline",
      style: {
        medium: "screen",
        material: "glass",
        era: "futuristic",
        geometry: "organic",
        composition: "centered",
        lighting: "luminous",
        texture: "paper-fiber",
        motion: "floaty",
        finish: "polished"
      },
      axes: { energy: 0.48, glow: 0.7, polish: 0.82 },
      harmony: "split",
      seed: "kit-" + seed
    });
    let texture = ctx.visual.texture.paper({ kit, seed: "paper-" + seed, opacity: 0.18 });
    let material = ctx.visual.material.glass({ kit, color: kit.colors.accent, texture });
    let orb = ctx.visual.sprite.compose({
      seed: "orb-" + seed,
      width: 96,
      height: 96,
      shapes: [
        { kind: "circle", x: 48, y: 48, r: 34, material, glow: { color: kit.colors.accent, blur: 14 } },
        { kind: "circle", x: 36, y: 32, r: 9, fill: "rgba(255,255,255,0.44)" }
      ]
    });

    function draw() {
      const area = ctx.contentSafeArea ?? ctx.safeArea;
      g.fillStyle = kit.colors.bg;
      g.fillRect(0, 0, ctx.width, ctx.height);
      texture.draw(g, { x: 0, y: 0, width: ctx.width, height: ctx.height });
      g.fillStyle = material.canvas.fill;
      g.shadowColor = material.canvas.shadow.color;
      g.shadowBlur = material.canvas.shadow.blur;
      g.beginPath();
      g.roundRect(28, area.top + 44, ctx.width - 56, ctx.height - area.top - 88, kit.surface.panel.radius);
      g.fill();
      g.shadowBlur = 0;
      g.strokeStyle = kit.colors.line;
      g.lineWidth = 2;
      g.stroke();
      orb.draw(g, input.down ? input.x : ctx.width * 0.5, input.down ? input.y : ctx.height * 0.52, {
        scale: input.down ? 1.08 : 1
      });
      g.fillStyle = kit.colors.ink;
      g.font = kit.type.title.weight + " " + kit.type.title.size + "px " + kit.type.title.family;
      g.fillText("Tap to remix", area.left + 44, area.top + 92);
    }

    ctx.input.on(canvas, "tap", pointer => {
      ctx.platform.start();
      seed += 1;
      kit = ctx.visual.kit("crystalline", {
        style: {
          medium: "screen",
          material: seed % 2 ? "neon" : "glass",
          era: seed % 3 ? "futuristic" : "art-deco",
          geometry: seed % 2 ? "rounded" : "isometric",
          composition: seed % 2 ? "radial" : "layered",
          lighting: seed % 2 ? "neon-bloom" : "luminous",
          texture: seed % 2 ? "scanline" : "paper-fiber",
          motion: seed % 2 ? "bouncy" : "floaty",
          finish: seed % 2 ? "toy-like" : "polished"
        },
        axes: { energy: seed % 2 ? 0.76 : 0.44, glow: seed % 2 ? 0.88 : 0.62 },
        harmony: seed % 3 ? "split" : "triadic",
        seed: "kit-" + seed
      });
      texture = ctx.visual.texture.paper({ kit, seed: "paper-" + seed, opacity: 0.18 });
      material = ctx.visual.material(seed % 2 ? "neon" : "glass", { kit, color: kit.colors.accent, texture });
      orb = ctx.visual.sprite.compose({
        seed: "orb-" + seed,
        width: 96,
        height: 96,
        shapes: [
          { kind: "circle", x: 48, y: 48, r: 34, material, glow: { color: kit.colors.accent, blur: 14 } },
          { kind: "circle", x: 36, y: 32, r: 9, fill: "rgba(255,255,255,0.44)" }
        ]
      });
      ctx.fx.ripple({ x: pointer.x, y: pointer.y, color: kit.colors.accent2 });
      ctx.platform.haptic("light");
      ctx.platform.interact({ type: "visual_remix" });
    });

    draw();
    ctx.game.loop({ input, render: draw });
    ctx.platform.ready();
  }
};
```
