# Contributing to SceneView

Thanks for your interest in contributing! This guide covers everything you need to get started.

---

## Development environment setup

### Prerequisites

- **JDK 21** for the root Gradle build. `sceneview`, `arsceneview` and the Android demos
  it includes (`samples/android-demo`, `android-tv-demo`, `android-auto-demo`) compile to
  Java 21 (`JavaVersion.VERSION_21`, `JvmTarget.JVM_21`, e.g. `sceneview/build.gradle`) and
  declare no JVM toolchain, so the JDK that runs Gradle compiles them.
  `sceneview-compose` and `samples/desktop-demo` declare `jvmToolchain(21)`: Gradle uses an
  installed JDK 21, or downloads one through the foojay resolver in `settings.gradle`.
  The Flutter plugin and demo and the React Native module are separate Gradle builds that
  target Java 17 (`flutter/sceneview_flutter/android/build.gradle`,
  `react-native/react-native-sceneview/android/build.gradle.kts`); CI builds the Flutter
  job with JDK 17.
- **Android Studio** with an Android Gradle Plugin 9.5 release (the build uses AGP 9.5.0,
  `gradle/libs.versions.toml`)
- **Xcode 16+** (for SceneViewSwift / iOS work only — Swift 6 and the iOS 18 floor).
  CI builds with Xcode 26, falling back to the runner's default `Xcode.app`
  (`.github/workflows/ios.yml:145-149`), plus a non-blocking Xcode 27 canary job; no job
  tests Xcode 16.
- **bash, python3 and curl** on the `PATH` for `tools/fetch-assets.sh`, which the Android,
  TV and Auto demo builds and the iOS demo build run (see [Assets](#assets)). On macOS
  they come with the Command Line Tools (`xcode-select --install`); on Windows, build
  from WSL.
- Optional but recommended: Google's [`android` CLI](https://developer.android.com/tools/agents/android-cli)
  for agent-driven QA.

#### Toolchain by task

Only install what the part you work on needs.

| You work on | You need | Source |
|---|---|---|
| Any Android module | Android SDK platform `platforms;android-37.0` (`compileSdk 37`) | `sceneview/build.gradle`, `arsceneview/build.gradle`, `samples/android-demo/build.gradle` |
| Android demo **release** build | NDK `28.2.13676358` (strips native symbols) | `samples/android-demo/build.gradle` (`ndkVersion`) |
| `:sceneview-core:allTests`, `sceneview-web` tests | Chrome or Chromium (Karma runs `useChromeHeadless()`) | `sceneview-core/build.gradle.kts:33`, `sceneview-web/build.gradle.kts:33` |
| Flutter plugin and demo | Flutter 3.10.0 or newer; CI tests 3.41.6 | `flutter/sceneview_flutter/pubspec.yaml` (`environment`), `.github/workflows/ci.yml` (`flutter-demo` job) |
| MCP server, web demo (`npx http-server`), React Native | Node.js 18 or newer; CI runs Node 20 | `mcp/package.json` (`engines`), `.github/workflows/ci.yml` (`web-desktop` job) |

The demo app's Firebase setup is optional: the Google Services plugin is only applied
when a `google-services.json` is present, so a fork builds without one
(`samples/android-demo/build.gradle`).

### Clone and open

```bash
git clone --filter=blob:none https://github.com/sceneview/sceneview.git
cd sceneview
```

`--filter=blob:none` downloads the full commit history but fetches file contents only
for the commit you check out (older blobs arrive on demand, e.g. on `git log -p`). The
repository's history carries large binaries, so this is much faster than a full clone.
A plain `git clone` also works.

Open the project in Android Studio. Gradle sync will pull all dependencies automatically.

### Assets

The demo apps' models and HDR environments and the website's platform models are not in
git. They live in the `assets-v1` GitHub Release, listed with their sha256 in
[`assets/manifest.json`](assets/manifest.json). After cloning, run once:

```bash
bash tools/fetch-assets.sh --scope android
```

`--scope android` fetches what the Android demo uses, about 55 MiB. `--scope ios` and
`--scope tv` also pull the `android` scope (`needs` in the manifest): about 285 MiB and
85 MiB. The Auto demo adds the `web` scope, about 465 MiB, so a root
`./gradlew assembleDebug`, which builds every demo, downloads about 550 MiB. Without
`--scope`, the script fetches every platform's assets, about 780 MiB (iOS and web models
included).

Some builds run the script themselves, so a plain build of them also works:

- **Gradle**: the `fetchAssets` task runs before `preBuild` and before unit tests in
  `samples/android-demo` (`--scope android`), `samples/android-tv-demo`
  (`--scope tv --scope android`) and `samples/android-auto-demo`
  (`--scope android --scope web`).
- **Xcode**: the iOS demo's *Fetch assets* build phase runs `--scope ios` before Copy
  Bundle Resources (`samples/ios-demo/SceneViewDemo.xcodeproj`).
- **CI**: workflows call it through `.github/actions/fetch-assets`, the website deploy
  (`docs.yml`) included, with `--scope web`.

The Auto demo's build is the only local run that fetches `--scope web`
(`website-static/models/platforms`, where its Car Concept lives). Nothing runs it locally
for the website itself or for the web demo's splat test page (`--scope web-test`): run it
by hand before serving them. The Flutter and React Native demos use no file from the manifest.

Files are downloaded once into `~/.cache/sceneview-assets/` (shared by every clone and
worktree, override with `SCENEVIEW_ASSETS_CACHE`), verified, then cloned (APFS / reflink)
or copied into place. `--scope android|ios|tv|web|web-test` limits the fetch, `--check`
verifies what is in place. A sparse checkout must include `assets/` and `tools/`.

To add or replace an asset, put the file at its path and run
`bash tools/fetch-assets.sh --register <path>`: it updates the manifest and prints the
`gh release upload` command for any blob the release does not have yet — a maintainer
runs it before the PR merges. The file itself stays out of git (see `.gitignore`). Until
it is registered, the fetch — and therefore the demo build — fails on it: a file only
your machine has would be missing from every other build.

### Build

```bash
# Android libraries
./gradlew assembleDebug

# Android demo app
./gradlew :samples:android-demo:assembleDebug
```

For iOS (SceneViewSwift), open `SceneViewSwift/Package.swift` in Xcode and build from there.

### Store secrets and the release-build guard

The demo apps read two optional secrets — `SKETCHFAB_API_KEY` (Sketchfab
carousels in the Explore tab) and `ARCORE_API_KEY` (AR Streetscape / Geospatial
/ Cloud Anchor demos). They're resolved from an environment variable or, on
developer machines, from the repo-root `local.properties`
(`sketchfab.api.key` and `ARCORE_API_KEY` respectively).

**Debug builds are permissive** — a missing key just disables those features at
runtime, so you can build and contribute without either secret.

**Release builds fail loud (#1915).** A release `assembleRelease` /
`bundleRelease` (Android) or `Release` archive (iOS) *refuses to build* when a
secret is empty or unsubstituted, instead of silently shipping a store APK with
invisible Sketchfab carousels (the regression class behind #1909). This guard
only fires on the release path — it never affects `assembleDebug` or PR-check
builds.

Forks have no access to the org GitHub Secrets, so to produce a release build
without the keys, opt out of the guard:

```bash
# Android
./gradlew :samples:android-demo:bundleRelease -PSV_ALLOW_MISSING_SECRETS=1
# or export SV_ALLOW_MISSING_SECRETS=1

# iOS
xcodebuild archive ... SV_ALLOW_MISSING_SECRETS=1
```

### Run tests

```bash
# All tests
./gradlew test

# KMP core tests only
./gradlew :sceneview-core:allTests
```

### Reading a leak-churn failure

`LeakChurnTest` (`sceneview/src/androidTest/.../leak/`, issue #2762) builds and
tears down node trees 40 times per test and asserts engine state returns to
baseline. It runs headless — no SwapChain, no `readPixels` — so unlike the
`render` package it really executes on the CI emulator instead of skipping.
It lands in `render-tests.yml`'s `android-library-render` job. On a pull request
that job reports its own verdict (a red job on the PR), but it is not a required
check; on `main` and nightly it is `continue-on-error`, so a red run there is an
advisory signal in the Actions tab, not a merge block.

```bash
ANDROID_SERIAL=<your-emulator> ./gradlew :sceneview:connectedDebugAndroidTest \
  -Pandroid.testInstrumentationRunnerArguments.class=io.github.sceneview.leak.LeakChurnTest
```

What a red run means, by probe:

| Failing assert | What leaked | Where to look |
|---|---|---|
| `LightManager component count did not return to baseline` | one light component per cycle | a `destroy()` override that returns early or never reaches `super.destroy()` (`Node.kt`'s `isDestroyed` guard, or a subclass that forgets the super call). Note `Engine.destroyEntity()` already drops *every* Filament-known component, so `LightNode.destroy()`'s explicit `lightManager.destroy(entity)` is defensive, not the load-bearing release |
| `still has a TransformManager component` | the node's transform was never released | `Node.destroy()` path — a `return` before `safeDestroyTransformable`, or an exception swallowed by `runCatching` |
| `still has a RenderableManager component` | geometry/renderable never released | the renderable owner's `destroy()`; check an early-return added to a subclass |
| `the queue still holds resources after N drained frames` | textures/streams enqueued but never released (#1630 shape) | `DeferredDestroyQueue.drain()` frame accounting, or a `GRACE_FRAMES` change that outlives the drain loop |
| `enqueued textures must be held for the grace period` | `DeferredDestroyQueue.enqueue` stopped deferring — the #874 `SIGABRT` shape | the deferral branch in `EngineDestroyQueue.kt`. **Uncovered gap:** this probe enqueues directly, so it cannot catch a *caller* (`ImageNode`, `ViewNode`, `SplatNode`) switching to an eager `engine.destroyTexture` — those need an asset/bitmap, which would make the probe non-deterministic |
| `canary_injectedLeakIsDetected` fails | **the instrument is broken**, not your code | a Filament upgrade changed `hasComponent`/`getComponentCount` semantics — fix the probe before trusting any other result in the class |
| `entityIdRecycling_isTheKnownPreExistingGap` fails | someone **fixed** entity-id recycling (#2859) | invert that test and tighten `assertComponentsReleased` to also require `EntityManager.isAlive(entity) == false` |

To bisect: the failure message names the exact entity id and the cycle index
that created it, so re-run with a smaller `CYCLES` and log around that cycle.
Never widen an assertion to silence a red you cannot explain.

### Set up an emulator

Google's `android` CLI creates and boots emulators with one command — no
sdkmanager / avdmanager dance:

```bash
android emulator create medium_phone        # positional <profile>; device auto-named from it
android emulator start medium_phone         # boots, waits for ready
```

`android emulator create` takes a single positional argument — the **profile**
— and the resulting device is auto-named from the profile (so `medium_phone`
above creates a device called `medium_phone`). v0.7 does not support a
separate `--name` flag. List profiles with `android emulator create --list-profiles`,
list existing devices with `android emulator list`, remove with
`android emulator remove <name>`.

The `medium_phone` profile matches the Pixel-7-class form factor most of the
screenshot scripts assume.

For SDK packages, prefer `android sdk install` / `android sdk list` over the
legacy `sdkmanager` from `cmdline-tools`.

---

## AI-assisted workflow

Contribute with whichever assistant you already use. No tool is recommended over another.

### Rules files

A checkout carries the repository conventions under each of the filenames these tools
look for, so yours picks them up with no setup (alphabetical):

| Read by | File |
|---|---|
| Claude Code | `CLAUDE.md` |
| Codex, and any agent following the AGENTS.md convention | `AGENTS.md` |
| Cursor | `.cursorrules` — legacy single file, still read; Cursor's current mechanism is `.cursor/rules/*.mdc` plus `AGENTS.md` |
| Devin Desktop / Windsurf | `.windsurfrules` — legacy single file, still read; the current mechanism is `.devin/rules/` (or `.windsurf/rules/`) plus `AGENTS.md` |
| GitHub Copilot | `.github/copilot-instructions.md` |

Point your assistant at [AGENTS.md](AGENTS.md) and ask for the workflow you want.
[CLAUDE.md](CLAUDE.md) carries the module map, architecture overview and threading rules
in the most detail.

### MCP server

The SceneView MCP server gives any MCP client the full API context:

```json
{
  "mcpServers": {
    "sceneview": { "command": "npx", "args": ["-y", "sceneview-mcp"] }
  }
}
```

Where that JSON lives, and what its keys are called, differs per client — per-tool setup
is in [docs/docs/ai-development.md](docs/docs/ai-development.md).

### Slash commands

Slash commands are a Claude Code feature, so this section is specific to it. Working in
the repo with another assistant? `AGENTS.md` describes the same workflows in prose — ask
for them by name.

| Command | What it does |
|---|---|
| `/contribute` | Full guided workflow from understanding to PR |
| `/review` | Checks threading rules, Compose API, Kotlin style, module boundaries |
| `/document` | Generates/updates KDoc and `llms.txt` for changed APIs |
| `/review --coverage` | Audits coverage and generates missing tests |

### Codex plugin and skills

The repository is also a Codex plugin. The three skills under [`agents/`](agents/) are
mirrored at `.agents/skills/`, which Codex scans from the working directory up to the
repository root, and `.agents/plugins/marketplace.json` declares the local marketplace
(`.codex-plugin/plugin.json` is kept as the compatibility fallback). To install it from
your checkout:

```bash
codex plugin marketplace add .
```

[AGENTS.md](AGENTS.md) carries the rules a delegated Codex session must respect — it
implements, investigates and critiques, but does not own version control. Maintainers
delegate through `.claude/scripts/codex-delegate.sh` (`ask` · `review` ·
`implement --new-worktree`) rather than a raw `codex` invocation, so a delegation always
lands in its own worktree with the repository conventions attached. Commits, merges and
releases stay with the lead session.

---

## Pull request guidelines

1. **One feature per PR.** Keep changes focused and reviewable.
2. **Tests required.** Add or update tests for any behavior change.
3. **Follow existing code style.** Match the patterns in the module you are editing.
4. **Describe the why.** PR descriptions should explain the motivation, not just list changed files.
5. **Keep commits clean.** Squash fixups before requesting review.

Contributions to any part of the project are welcome — Android (`sceneview/`, `arsceneview/`), iOS (`SceneViewSwift/`), shared KMP core (`sceneview-core/`), samples, documentation, or the MCP server.

### Changing the Apple platform floor

`SceneViewSwift/Package.swift` is the only *enforced* statement of the iOS / macOS /
visionOS minimum; the three podspecs, the root `Package.swift`, the README badges, the
docs site, `llms.txt`, the MCP guides and the demo's About screen all repeat it as prose.
When you move the floor, run
[`.claude/scripts/check-ios-floor.sh`](.claude/scripts/check-ios-floor.sh) — it reads
the manifest and lists every podspec and doc line that still names the old version
(exit 1 on drift). It runs offline in under a second; nothing in CI runs it for you
(#3046).

### Adding a demo to `samples/android-demo`

The Android demo app uses an **append-only fragment registry** so that two
parallel PRs adding two different demos never conflict on a shared file
(issue #1797). To add a demo:

1. Add the demo composable under
   `samples/android-demo/src/main/java/io/github/sceneview/demo/demos/`.
2. Drop a new fragment file at
   `samples/android-demo/src/main/java/io/github/sceneview/demo/fragments/<MyDemo>Fragment.kt`
   declaring `object <MyDemo>Fragment : DemoFragment` with the demo's id,
   title/subtitle string resources, category, icon, and a one-line `Screen`
   wrapper calling your composable. See [the package
   README](samples/android-demo/src/main/java/io/github/sceneview/demo/fragments/README.md)
   for the full template.
3. Drop the demo's strings into their own resource fragment at
   `samples/android-demo/src/main/res/values/strings_demo_<my_demo>.xml`
   (`-` → `_` in the id). Each demo owns its strings file so parallel PRs
   never share a string-resource anchor (#1870). Android's resource merger
   fans every `res/values/*.xml` file in at build time, so `R.string.demo_*`
   references resolve identically.
4. Run the collator to regenerate `GeneratedDemos.kt`:
   `bash samples/android-demo/scripts/collate-demos.sh`. The quality gate runs
   the collator in `--check` mode and blocks the push if the file is stale.

You should **never** edit `DemoRegistry.kt`, `MainActivity.kt`, or
`GeneratedDemos.kt` by hand — the fragments are the single source of truth.

### Device-QA flows when adding a demo

The demo apps are exercised on real emulators/simulators by the **autonomous
device-QA harness** (`bash .claude/scripts/device-qa.sh`). When you **add or
change a demo**, update its device-QA coverage in the same PR — an untested
demo is invisible to the release-checkpoint gate:

- **Android** — add the demo to its category flow under `.maestro/android/`
  (`3d-basics.yaml`, `lighting.yaml`, `content.yaml`, `interaction.yaml`,
  `advanced.yaml`, or `ar.yaml`) and to the master `catalog.yaml`. Each entry
  reuses `flows/demo.yaml` with the demo's `DEMO_ID` / `DEMO_NAME`.
- **iOS** — add the matching entry under `.maestro/ios/` (same category files
  + `catalog.yaml`). A deep-linkable demo must also be registered in
  `DemoDeepLinkRegistry.allowedIds` so the `sceneview://demo/<id>` ingress can
  reach it; otherwise add a `placeholders.yaml` entry.
- **Web** — extend the Playwright `catalog.spec.ts` coverage in
  `samples/web-demo/tests/` so the new demo/tab is walked and asserted.

See [`.maestro/README.md`](.maestro/README.md) for the flow layout and the
known no-pinch / deep-link-zoom limitation. Run `device-qa.sh` for the affected
platform before requesting review.

### Changelog entries

**Do not edit `CHANGELOG.md` directly.** Changelog entries go in `changelog.d/`
as a small fragment file — one per PR. Add a file named
`changelog.d/<issue-or-pr-number>-<short-slug>.md` containing your release-note
bullet(s), prefixed with a category tag:

```markdown
<!-- category: Fixed -->
- **Short headline ([#1234](https://github.com/sceneview/sceneview/issues/1234)).** What changed and why.
```

Recognised categories: `Added`, `Changed`, `Fixed`, `Security`, `Performance`, `Removed`, `Tests`, `Docs`.
Distinct filenames mean parallel PRs never conflict on the changelog. At release
time `.claude/scripts/collate-changelog.sh` collates all fragments into a new
`## vX.Y.Z` section. See [`changelog.d/README.md`](changelog.d/README.md) for
the full convention.

**Fragments are copied verbatim, not reformatted.** Write the bullet(s) exactly
as they should read in the release notes — every non-blank line must be a
top-level `- ` bullet or an indented continuation of one, never a bare
paragraph. `ci.yml`'s `changelog-lint` job runs
`.claude/scripts/check-changelog-fragments.sh` on the fragments a PR adds or
modifies (diffed against the merge base) and fails on a malformed one; a paragraph fragment that
slips past this check would collate cleanly but produce zero highlights in the
demo's "What's new" card, since it only recognises lines starting with `- `.

Two rules worth knowing before you write one:

- **HTML comments are stripped**, so anything inside `<!-- … -->` is a
  maintainer-only note and never reaches the published release notes. Close
  them — an unterminated `<!--` would swallow the bullets after it, so the
  collator refuses instead.
- **Mark a breaking change** with a `<!-- breaking -->` comment, on its own line
  or trailing the bullet it describes. Major `4` is frozen and breaking changes
  ship as a **minor** bump; a marked (or plainly worded) fragment makes the
  release tooling refuse a patch-level tag, because `release.yml` derives the
  npm version straight from the git tag.

After your changes are merged, the Discord bot will award you the **Contributor** role.

### Public API changes

SceneView is an **AI-first SDK**: `llms.txt` and the KDoc promise *exact* public
signatures so an AI can generate correct code on the first try. To stop a public
signature from changing silently, the published library modules — `sceneview`,
`arsceneview` and `sceneview-core` — have their public ABI tracked by Kotlin's
[`binary-compatibility-validator`](https://github.com/Kotlin/binary-compatibility-validator).
Each module's public surface is dumped to a committed text file under
`<module>/api/<module>.api`, and CI runs a **blocking** `apiCheck` (the
`API compatibility` job in `ci.yml`, same tier as the unit tests).

**If your change touches a public signature** (adds/removes/renames a public
class, function, property, or changes a public type), `apiCheck` will fail with
a diff naming the offending symbol, e.g.:

```
> API check failed for project sceneview-core.
  +	public static final fun temporaryGateProbe (J)D
  You can run :sceneview-core:apiDump task to overwrite API declarations
```

When the change is **intentional**, regenerate the dumps and commit the diff:

```bash
./gradlew apiDump          # rewrites <module>/api/*.api for every module
git add '**/api/*.api'
```

The updated `.api` diff then rides along in your PR, so the reviewer sees the
exact public-API delta — a new symbol, a removed one, or a changed signature —
as a first-class part of the review. Treat a *removed* or *retyped* public symbol
as a breaking change: it needs a deprecation cycle and a matching update to
`llms.txt`, the KDoc, and the cross-platform surfaces (see
[CLAUDE.md](CLAUDE.md) "Documentation drift").

> **Scope.** Only the JVM public surface is validated. `sceneview-core`'s
> `jvm("android")` dump already captures the shared `commonMain` API. Native
> (iOS) and JS klib ABI validation stays disabled for now — it is experimental
> and not buildable on the ubuntu CI runner. `sceneview-web` (a JS-only KMP
> module published to npm, not Maven) has no JVM surface and is excluded; its
> public API is documented via the hand-written `sceneview-web.d.ts` — there is
> no automated JS ABI gate yet (a `.d.ts` drift gate is shortlist #2642 item 12).

### Dependency resolution failures on CI

On GitHub-hosted runners, failed Gradle dependency resolution adds a
`dependency-resolution diagnostics` group to the failing Gradle step's log.
It records live HEAD responses (and a one-byte ranged GET after HTTP 200)
from the reported Central / Google Maven URLs, module-cache filenames with
sizes and modification times, JVM network properties, and the offline / refresh flags.
A live 200 for an artifact Gradle reported missing means the file was there
when the build gave up, so suspect Gradle's cached lookup state or a transient
CDN answer; live 404 / 5xx responses or timeouts point to the network or CDN.
Metadata lines only name cache files that mention the exact artifact-version;
they are not decoded hit or miss records. Probes are capped at 8 modules,
16 URLs and 45 seconds. These checks only run after failure and do not change
dependency resolution or caching.

### CI on docs-only PRs

**Docs-only PRs** — changes confined to `*.md`, `docs/**`, `website-static/**`,
`marketing/**`, `branding/**`, `llms*.txt`, or `LICENSE` — skip the Android +
MCP build and verification jobs by design. The diff cannot affect runtime
behaviour, so spending 10-20 min of emulator time to re-build and re-render
is pure noise. You will see fewer green checks than on a code PR; this is
correct. Specifically:

- **`ci.yml`** — the single consolidated PR workflow (`build`, `lint`,
  `unit-test`, `api-check`, `web-desktop`, `flutter-demo`, `compile-kmp`,
  `kmp-native-test`, `changelog-lint`). Its `paths-ignore` filter sits under the `push:`
  trigger only — on a pull request the skipping is done by the `changes`
  job, which detects the touched paths and gates every other job, so a
  docs-only PR runs none of them. (Before #1370 this was three separate
  workflows — `ci.yml`, `pr-check.yml`, `quality-gate.yml` — each with its
  own `changes` job; they are now one workflow with one path-detection job.)
- **`render-tests.yml`** has its own `pull_request` path filter, and its own
  `changes` job that gates each leg on its half of that filter. A PR touching
  `sceneview/**`, `sceneview-core/**`, `arsceneview/**` or the Gradle build
  files runs the `android-library-render` job
  (`:sceneview:connectedDebugAndroidTest` on the emulator, #3216); a PR
  touching `samples/web-demo/**` or `sceneview-web/**` runs the
  `web-render` Playwright job. The iOS leg is push-to-main + nightly +
  `workflow_dispatch` only, and on a push each leg runs only when its
  platform's paths changed. A docs-only PR matches none of
  the paths, so the workflow does not run at all.
- The **`Path filter completed`** job (`changes-verdict` in `ci.yml`) runs
  on every PR whatever it touches, and it is the required check: it resolves
  green once path detection has run. That is how a docs-only PR stays
  mergeable without any job being "skipped → green for life".

If your docs PR needs to force a full CI run (for example, you suspect a
markdown change has accidentally invalidated an example referenced from
runtime code), trigger the gates manually from the Actions tab —
`Run workflow` on `ci.yml` / `render-tests.yml` accepts your PR's branch as
input.

### Heavy suites on `main`: every merge reaches a verdict

`render-tests.yml` and `device-qa.yml` run on every (path-matched) push to
`main`, and since #2917 / #3216 a later merge no longer cancels the run of
the one before it: each run has its own concurrency group, so runs queue
instead of being killed. Before that change roughly half of the runs on a
busy `main` ended `cancelled` — neither pass nor fail — and the commit they
were testing was never covered. The one place cancellation is still allowed
is a pull request on `render-tests.yml`, where a new push to the same PR
supersedes the previous SHA. The cost is GitHub-hosted minutes proportional
to the merge rate; if the queue becomes a problem, the lever is the `paths:`
filter on each workflow (and the per-job `changes` gate that both
`render-tests.yml` and `device-qa.yml` carry), not `cancel-in-progress`. The
web Playwright suite runs on `main` through `device-qa.yml`'s blocking web leg
only, and only when the push touched `samples/web-demo/**` (or the harness);
the Android legs likewise need `samples/android-demo/**`, `.maestro/**` or
their scripts. `render-tests.yml`'s `web-render` job reports test failures and no
longer repeats the web suite on push or at night. On `workflow_dispatch` and
in the nightly every leg of both workflows still runs.

### Other workflow triggers worth knowing

- **Superseded PR runs are cancelled.** `ci.yml`, `snippets-check.yml`,
  `mcp-ts-check.yml` and `rn-ts-check.yml` key their PR concurrency group on
  the PR number, so pushing a new commit cancels the previous run of the same
  PR. Pushes to `main` in `ci.yml` are never cancelled.
- **`ios.yml`** runs for `SceneViewSwift/**`, `samples/ios-demo/**` and its
  own file — not for `sceneview-core/**`, which no Swift target links. The
  core's iOS Kotlin/Native compile is `ci.yml`'s `compile-kmp`.
- **`build-apks.yml`** runs on a release tag or by hand only; `ci.yml`'s
  `build` job already assembles the same demo APKs on every push to `main`.
- **`docs.yml`** deploys on a push to `main` that touches the site's actual
  inputs (`docs/**`, `website-static/**`, `llms.txt`, `CHANGELOG.md`,
  `CONTRIBUTING.md`, `marketing/codelabs/**`, `samples/web-demo/site/**`, its
  requirements files), not on every `*.md` — a `changelog.d/` fragment alone no
  longer redeploys the site; the generated `CHANGELOG.md` does.

### Build and screenshot on CI instead of locally

`preview.yml` builds the demos and captures them, light and dark, on free
GitHub-hosted runners: an emulator on `ubuntu-latest` with KVM for Android, a
Simulator on `macos-15` for iOS. Use it before compiling the demo or booting an
emulator on your own machine, agents included. It is opt-in and never a
required check.

```bash
# Any branch pushed to sceneview/sceneview (the file must be on main):
gh workflow run preview.yml -R sceneview/sceneview --ref <branch> \
  -f platforms=android -f demos=home,model-viewer    # platforms: android | ios | both
# Or on a pull request: add the `preview` label (Android) and/or `preview-ios`.
gh pr edit <pr> -R sceneview/sceneview --add-label preview

gh run list -R sceneview/sceneview -w preview.yml -b <branch> -L 1   # get the run id
gh run watch <run-id> -R sceneview/sceneview --exit-status
gh run download <run-id> -R sceneview/sceneview -n preview-android-screenshots -D /tmp/preview
```

| Artifact | Contents |
|---|---|
| `android-demo-debug-apk` | Debug APK, install with `adb install -r` |
| `preview-android-screenshots` | `light/<id>.png`, `dark/<id>.png` at 1080x2400, 420 dpi, plus `summary.md` (an app that was gone at capture time, crash lines) and `logcat/<theme>-<id>.txt` |
| `preview-ios` | `SceneView-simulator.app.zip` (`xcrun simctl install booted`), `screenshots/<theme>/<id>.png`, `summary.md`, `crashes/` if the app crashed |

`demos` takes ids from `DemoRegistry` / `DemoDeepLinkRegistry`, plus `home` for
the launch screen. The builds are keyless: artifacts of a public repository can
be downloaded by any signed-in user, so no store key is baked in, and the
Sketchfab- and Geospatial-backed screens show their keyless fallback. The
captures come from SwiftShader and the Simulator, not a phone GPU, so use them to
check layout, theming and "does it launch", and never copy one into a render
golden. Artifacts are kept 7 days.

### Code style

- **Kotlin**: follow the official [Kotlin style guide](https://developer.android.com/kotlin/style-guide) and existing Compose API conventions (composable functions, `remember*` helpers, named parameters). The code style is stored in the repository and auto-configured by Android Studio.
- **Swift**: follow the existing SceneViewSwift patterns (builder-style modifiers, RealityKit conventions).
- No wildcard imports. No unused imports.
- Keep changes minimal — you can fix obvious mistakes in formatting or documentation along the way.
- **Swift `#if os(...)` guards**: do not nest a platform `#if` whose condition is
  a permutation of the file's outer guard — it is always true and only adds
  noise (issue #2044). Every `SceneViewSwift` file is wrapped in
  `#if os(iOS) || os(macOS) || os(visionOS)`; an inner
  `#if os(iOS) || os(visionOS) || os(macOS)` is the same three platforms and
  therefore dead. Use a `#if` only for a genuinely narrower set
  (`#if os(visionOS)`, `#if !os(visionOS)`, `#if os(macOS)`), and prefer a
  runtime `#available` check when the gate is an OS-version requirement.

### Changes in Filament materials

Recompile Filament materials using the [current Filament version](https://github.com/google/filament/releases) if you modify them. Enable the [Filament plugin](https://github.com/sceneview/sceneview/blob/main/gradle.properties) and build.

#### Filament runtime ↔ `.filamat` ABI invariant

> **Every committed `.filamat` blob MUST be produced by a `matc` toolchain whose version matches the Filament runtime *that loads that blob*.**

There are **three runtimes**, so three pins in [`gradle/libs.versions.toml`](gradle/libs.versions.toml), and a blob is only correct against its own:

| Blob group | Pin | Runtime | MATERIAL_VERSION |
|---|---|---|---|
| `sceneview/`, `arsceneview/` assets | `filament` | Filament AAR (Android) | 72 |
| `website-static/materials/` | `filamentWebsite` | Filament.js vendored at `website-static/js/filament/` | 72 |
| `sceneview-web/materials/` | `filamentWeb` | npm `filament` (Kotlin/JS bundle) | 52 |

Wiring a group to the wrong pin is the same defect as forgetting to recompile: #2783 found the 3 `website-static` blobs at v72 (they rode the Android pin) against a v70 runtime — latent only because nothing on the site calls `createMaterial()` yet.

Filament refuses any material whose binary version field does not match the runtime, with `Filament panic — material version N ≠ runtime M` on first frame. There is no compile-time check; the mismatch only manifests at runtime, demo by demo. v4.1.0 shipped with the runtime at 1.70.2 and blobs at 1.71 (two parallel branches each fixed half of the pair) — 10 demos crashed; v4.1.1 hot-fixed by realigning both sides to 1.71.

**The 26 committed blobs that must stay in sync with their `.mat` sources**, spread across three modules:

```
sceneview/src/main/assets/materials/     (14) — image_texture, occlusion, opaque/transparent
                                                colored/textured/unlit, semantics_overlay, splat,
                                                video_texture(_chroma_key), view_texture_lit/_unlit
arsceneview/src/main/assets/materials/    (9) — camera_stream_flat/_depth/_person_occlusion,
                                                face_mesh(_occluder), plane_renderer(_shadow)(_v2),
                                                shadow_receiver
website-static/materials/                 (3) — lit_colored, transparent_colored, unlit_colored
```

**The `tools/GenerateFilamat.sh` workflow.** [`tools/GenerateFilamat.sh`](tools/GenerateFilamat.sh) is the single entry point for every Filament material in the repo. It auto-downloads the `matc` toolchain pinned to the Filament version in [`gradle/libs.versions.toml`](gradle/libs.versions.toml) and compiles each `.mat` to its `.filamat` blob — no manual `matc` install needed.

```
bash tools/GenerateFilamat.sh                 # regenerate all 26 .filamat blobs in place
bash tools/GenerateFilamat.sh --check         # diff against committed blobs; exit 1 on drift
bash tools/GenerateFilamat.sh --mat <name>    # regenerate one (e.g. --mat opaque_colored)
bash tools/GenerateFilamat.sh --ci-tolerant   # treat a matc download failure as WARN, not FAIL
```

The `matc` binary is cached at `~/.cache/sceneview/matc-<version>/` (overridable via `$XDG_CACHE_HOME`); the first run downloads it, subsequent runs reuse it. `--ci-tolerant` exists for sandboxed CI runners with no network — it lets the check pass with a WARN instead of failing the build when `matc` cannot be fetched.

**The drift check.** `bash tools/GenerateFilamat.sh --check` reports every `.filamat` blob that no longer matches its `.mat` source. Nothing runs it for you — run it yourself in the same sitting as any `.mat` edit. Shipping a `.mat` change without recompiling its blob is the v4.1.0-class mistake, and this is the check that catches it.

**The runtime check (#2783).** `--check` proves a blob matches its `.mat` *source*; it compiles with the pinned `matc`, so a blob wired to the wrong pin still passes. [`.claude/scripts/check-web-filamat-abi.sh`](.claude/scripts/check-web-filamat-abi.sh) closes that gap for the two web tracks: it reads each blob's `MATERIAL_VERSION` header and compares it to its own runtime pin, and sha256-pins the vendored `filament.js`/`.wasm` (via `website-static/js/filament/RUNTIME.json`) so the runtime cannot be swapped without moving the pin. It needs no `matc` and no network, so it runs anywhere in a second — pair it with the drift check above.

**The five matc flag profiles.** The committed blobs were compiled with five distinct profiles (recorded in each blob's MRPC chunk). `GenerateFilamat.sh` reproduces each one — including flag *order*, since matc embeds the verbatim flag string:

| Profile | Flags | Module |
|---|---|---|
| **A** — heavy Android | `-p all -a all` | `sceneview/` lit/textured/video/view materials |
| **B** — lean Android | `-a opengl -p mobile` | `sceneview/` unlit colored materials (2) |
| **C** — ARCore | `--optimize-size -p mobile -a opengl -a vulkan` | `arsceneview/` (9) + `sceneview/` semantics_overlay (1) |
| **D** — website / WebGL | `-p mobile -a opengl` | `website-static/materials/` (3) |
| **E** — Android occluder | `-a vulkan -a opengl -p mobile` | `sceneview/` occlusion material (1) |

When adding a new material, pick a profile by deployment target and add an entry to the `MATS` inventory in `GenerateFilamat.sh`. Each `.mat` source carries a short header block (purpose, used-by, parameters, profile) — read those headers to learn what an individual material does and where it is consumed.

**How to recompile after a Filament version bump:**

1. Bump `filament = "X.Y.Z"` in [`gradle/libs.versions.toml`](gradle/libs.versions.toml).
2. Run `bash tools/GenerateFilamat.sh` — it downloads the matching `matc` and recompiles every `.filamat` from its `.mat` source.
3. Commit **the runtime bump AND the recompiled `.filamat` files in the SAME PR**. Never split them across commits — that's the failure mode that broke v4.1.0.

`GenerateFilamat.sh --check` and `check-web-filamat-abi.sh` catch a runtime/blob mismatch — but only if you run them. If you skip them, the first signal is a runtime crash on whichever demo loads the affected material first.

#### Visual QA for material / shader changes (Mac-friendly)

A material change can compile, pass unit tests, and still render wrong (the v4.16.x plane-renderer "white blob", #2224, is the canonical example — three "fixes" shipped before the real cause was found). Compile + unit tests are **not** a visual gate. This is the validated flow, refined while fixing #2224.

**1 — Diagnose & iterate on the shader on a plain Mac, with no ARCore.** ARCore cannot run in an Android emulator on Apple Silicon (x86 needs TCG → ARCore watchdog-timeouts; arm64 has no ARCore camera bridge — see `feedback_arcore_emulator_mac_dead_end` / issue #1645, definitively closed). **But pure Filament rendering works perfectly on the standard arm64 emulator.** So isolate the shader: render the exact committed `.filamat` on a static, hand-built mesh in a **non-AR** `SceneView`, with no ARCore session — the pattern in [`PlaneGridPreviewDemo`](samples/android-demo/src/debug/java/io/github/sceneview/demo/demos/PlaneGridPreviewDemo.kt) (debug-only, `adb shell am start -n io.github.sceneview.demo.qa/io.github.sceneview.demo.DemoHostActivity --es demo_id plane-grid-preview`). Mirror the AR render pipeline: pass `renderQuality = RenderQuality.Performance` (bloom/SSAO **off**, like `ARSceneView`) — the default `SceneView` keeps bloom on, which washes a translucent material into a uniform blob and hides the real output.

**2 — Pixel-measure, don't eyeball.** Capture `adb exec-out screencap -p`, convert to BMP (`sips -s format bmp`), parse pixels (no ImageMagick on most Macs). Over a known background you can read the actual composite. #2224's root cause was found this way: an unlit `blending: transparent` material that writes a straight (non-premultiplied) `baseColor.rgb` composites as `color + (1-α)·bg` (colour at full strength) instead of `lerp(bg, color, α)`, so capping `α` never reduces the colour. Fix: premultiply in the fragment — `material.baseColor.rgb = <color> * material.baseColor.a;`. A distinguishing test (render with two different `color` values and check the slope) tells premultiplied from straight-add unambiguously.

**3 — Confirm on a real device (the only true AR gate).** USB, not wireless — `adb`-over-Wi-Fi drops mid-transfer on a 200+ MB demo APK. The debug APK installs as its own app, `io.github.sceneview.demo.qa`, next to the Play Store one — no need to uninstall the store build. Launch an AR demo via `io.github.sceneview.demo.qa/io.github.sceneview.demo.DemoHostActivity` (`--es demo_id ar-placement`), grant `android.permission.CAMERA`, and screen-record while sweeping over varied surfaces — **especially a bright/outdoor one**, the condition that made the #2224 blob worst.

**4 — Analyse the screen recording.** Pull it, then: contact-sheet the frames with ffmpeg's `tile` filter (`-vf "fps=1/3,scale=200:-1,tile=5x4"` — no ImageMagick needed) for a fast overview, then extract full-res frames at the interesting timestamps for the actual judgement. If the recording has narration, transcribe with Whisper **large-v3** (smaller models are not reliable for this). ⚠️ A transcript that is only `Sous-titrage ST'…` / `Merci` / `Amara.org` repeated is Whisper's **silence hallucination** — it means there was no speech, not a real transcript.

**Two hard rules (born from the #2224 saga):** (a) **look at an actual rendered frame — and pixel-measure it — before claiming a visual fix works**; never infer "it looks better" from code. (b) **Verify any flag an LLM suggests against the real binary before trusting it** — e.g. the proposed ARCore replay property `debug.com.google.ar.core.camera_playback_autostart` was a confident hallucination (0 hits in 1 M strings extracted from the ARCore APK).

---

## Issues and discussions

- **Bug reports**: use the issue templates on [GitHub Issues](https://github.com/sceneview/sceneview/issues). Include platform, SceneView version, minimal reproduction steps, and relevant logs.
- **Questions**: open a [Discussion](https://github.com/sceneview/sceneview/discussions) instead of an issue.
- **Feature requests**: welcomed as issues or discussions.
- **Chat**: join the [Discord](https://discord.gg/UbNDDBTNqb) to talk with the community and maintainers.

---

## License of contributions

SceneView is licensed under the [Apache License 2.0](LICENSE); the `mcp/` directory (the `sceneview-mcp` npm package) is licensed under the [MIT License](mcp/LICENSE). By submitting a pull request you agree that your contribution is licensed under the same license as the files it changes (Apache License 2.0, Section 5: inbound = outbound), and that you have the right to submit it. Code copied or ported from another project must keep that project's copyright and license notice in the file header and be listed in [`NOTICE`](NOTICE).
