From 6837e09351ae3516b79da3ca9ebb17d39fc70257 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Jo=C3=A3o=20Paulo=20Furtado?=
<30300459+jonit-dev@users.noreply.github.com>
Date: Sun, 22 Nov 2026 00:39:10 +0000
Subject: [PATCH 1/3] CI: carry legs again, retry API 5xx, and stop repeating
release and test work (PRD-903) (#710)
* fix(ci): carry legs again, retry 5xx API reads, skip prose-only develop pushes (PRD-903 phase 1)
- scope's sparse checkout now includes packages/runtime-native/scripts: per-job carry imported
desktop-build-profile.mjs from there and carried 0 legs on every run. A replay of develop
41df5bbca carries 47 legs. A closure test fails when scope imports a file outside the cone.
- scripts/lib/gh.mjs retries a read twice with a 2 s / 6 s backoff and stops on a 4xx; ghApi in
scripts/ci/reuse.mjs uses it, so one HTTP 502 no longer drops a whole-tree reuse.
- A develop push whose paths since the last green develop push head are all prose (outside the
workspace-dist cache-key trees) selects prose; ci-required re-derives that diff.
- native-release.yml cancels a superseded proof on a new pull-request commit (synchronize only).
* perf(release): build the workspace once per ship and poll faster (PRD-903 phase 2)
- npm-release.yml names its built commit in TN_RELEASE_PREBUILT; release.ts skips its own
pnpm build on an exact HEAD match when provisioning rebuilt no web engine. The proof and the
publish runs no longer rebuild the same tree (~5 min).
- release-candidate.yml drops its unconditional pnpm build; the gate builds once, on the first
package npm already serves (~2.5 min on every fresh release).
- release:ship polls every 15 s for ten minutes, then every 60 s.
- PRD: the second upgrade proof, the clean-room serial order, the iOS joins and the
native-release desktop verify stay, with the reasons under Decisions and Blocked on.
* perf(ci): test stops re-running unit specs; budget probe runs once (PRD-903 phase 3)
- In prebuilt mode (CI `test`), terrain, procedural-environment, procedural-animals,
blender-bridge and strata-terrain-preview leave the recursive package walk. The walk keeps
publint for all eight packages, the strata bake and test:water, and drops their root-config
vitest re-runs (the test-unit shards own those files) and package rebuilds. Local paired run:
47 s against more than 280 s; CI baseline 9.7 min.
- template-assets-compile probes the uncooked budget on starter only; every kit still compiles.
Local paired run: 155 s -> 125 s.
- PRD: the terrain-mcp and city ceilings are coverage cuts and move to Blocked on (owner).
* docs(prd): PRD-903 waits only on the next release's timings; Android sharding moves to PRD-904
Owner chose the review lane only for PRD-903's live CI. Android 2-way sharding and the
integration-lane grouping need a one-APK producer and native CI runs, so they move to the new
PRD-904 as a follow-up. PRD-903's last open item is AC-4 (live timings on the next release),
so it moves to BLOCKED/requires-next-release/ (R6).
* test(ci): run-test-suite guard derives no package names (TN_WORKSPACE_PACKAGE_LITERAL_ENUMERATION)
The budgets gate rejects a literal workspace package list in a spec. The walk-body guard
(publint kept, no vitest) still covers the behaviour; the name list was redundant.
---
.github/workflows/ci.yml | 3 +
.github/workflows/native-release.yml | 9 +-
.github/workflows/npm-release.yml | 2 +
.github/workflows/release-candidate.yml | 4 +-
...ry-and-cutting-duplicate-and-junk-tests.md | 159 ++++++++++++++++++
...nformance-runs-in-two-shards-on-one-apk.md | 37 ++++
.../template-assets-compile-1.spec.ts | 6 -
.../template-assets-compile-2.spec.ts | 9 +-
scripts/__tests__/ci-local.spec.ts | 1 +
scripts/__tests__/ci-native-chain.spec.ts | 3 +-
scripts/__tests__/ci-needs.spec.ts | 147 ++++++++++++----
scripts/__tests__/ci-qualification.spec.ts | 8 +-
scripts/__tests__/ci-structure.spec.ts | 43 ++++-
scripts/__tests__/gh.spec.ts | 25 ++-
.../__tests__/native-release-proof.spec.ts | 7 +-
.../__tests__/release-candidate-gate.spec.ts | 15 ++
scripts/__tests__/release-ship.spec.ts | 12 ++
scripts/__tests__/release.spec.ts | 22 ++-
scripts/__tests__/run-test-suite.spec.ts | 11 ++
scripts/ci-change-scope.mjs | 40 ++++-
scripts/ci-required.mjs | 10 ++
scripts/ci/reuse.mjs | 44 ++++-
scripts/lib/gh.mjs | 29 +++-
scripts/release-candidate-gate.ts | 25 ++-
scripts/release-ship.ts | 14 +-
scripts/release.ts | 41 ++++-
scripts/run-test-suite.sh | 25 ++-
vitest.config.ts | 3 +
28 files changed, 658 insertions(+), 96 deletions(-)
create mode 100644 docs/PRDs/BLOCKED/requires-next-release/PRD-903-cut-release-deploy-and-ci-time-by-fixing-carry-and-cutting-duplicate-and-junk-tests.md
create mode 100644 docs/PRDs/CI/PRD-904-android-conformance-runs-in-two-shards-on-one-apk.md
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 8b98a4997c..991b8c1a6d 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -87,9 +87,12 @@ jobs:
# blob:none still fetched every HEAD blob (488 MB) to fill the working tree, and that
# checkout alone took 3m20s of the 5 minutes on a loaded runner (runs 41688746026,
# 41702153229). The scripts read only scripts/ and each kit.json: about 20 MB.
+ # packages/runtime-native/scripts holds the desktop build profile that per-job carry imports;
+ # without it every run printed "per-job reuse unavailable" and carried nothing (PRD-903).
sparse-checkout: |
scripts
packages/create-threenative/templates
+ packages/runtime-native/scripts
# Until protected develop exists, retain the qualified-main scheduled flow.
ref: ${{ github.event_name == 'schedule' && vars.TN_DEVELOP_CI_ENABLED == 'true' && 'develop' || github.sha }}
- id: classify
diff --git a/.github/workflows/native-release.yml b/.github/workflows/native-release.yml
index 4d6a7e2314..6b06e4e04c 100644
--- a/.github/workflows/native-release.yml
+++ b/.github/workflows/native-release.yml
@@ -34,9 +34,10 @@ concurrency:
# superseded proof is a few minutes of one runner, where running them beside each other was the
# whole pool.
#
- # `cancel-in-progress: false` is unchanged and load-bearing: every cancellation in this
- # workflow's history was a proof run killed by the next push to its own branch, and a
- # candidate-keyed result is still valid for the SHA it was produced from.
+ # PRD-903: a new commit on a proving pull request (`synchronize`) cancels the proof in progress.
+ # The tag run reuses only the proof of its own tree, so a superseded head's proof is never read,
+ # and 43 develop proofs in 5 days ran back to back for 50 minutes each. A tag, a dispatch and a
+ # `labeled` event still never cancel: a label on the same head must not kill its running proof.
#
# PRD-629: a release tag run has a group of its own. A main proof run (a duplicate dispatch
# or a `release-proof` label) held `native-release-proof` once and delayed the tag run until it
@@ -46,7 +47,7 @@ concurrency:
# workflow (its `gates` job then refuses it), and in one shared group those no-op runs would queue
# behind a real proof and replace a pending one, since a group keeps a single pending run.
group: ${{ github.ref_type == 'tag' && 'native-release-tag' || (github.event_name != 'pull_request' || github.event.pull_request.base.ref == 'main' || contains(github.event.pull_request.labels.*.name, 'release-proof')) && 'native-release-proof' || format('native-release-skip-{0}', github.run_id) }}
- cancel-in-progress: false
+ cancel-in-progress: ${{ github.event_name == 'pull_request' && github.event.action == 'synchronize' }}
jobs:
validate-tag:
diff --git a/.github/workflows/npm-release.yml b/.github/workflows/npm-release.yml
index 4b20753dc0..b68976b314 100644
--- a/.github/workflows/npm-release.yml
+++ b/.github/workflows/npm-release.yml
@@ -105,6 +105,8 @@ jobs:
GH_TOKEN: ${{ github.token }}
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
SHA: ${{ github.event.workflow_run.head_sha }}
+ # PRD-903: the `pnpm build` above built this commit; the proof and publish runs reuse it.
+ TN_RELEASE_PREBUILT: ${{ github.event.workflow_run.head_sha }}
TN_PLAYTEST_ALLOW_SOFTWARE: "1"
# A rerun leaves out `--auto`, so a failed clean room cannot turn green with no new check.
run: pnpm release:ship --yes --sha "$SHA" ${{ github.run_attempt == 1 && '--auto' || '' }}
diff --git a/.github/workflows/release-candidate.yml b/.github/workflows/release-candidate.yml
index 6af6129f59..b67df2ada6 100644
--- a/.github/workflows/release-candidate.yml
+++ b/.github/workflows/release-candidate.yml
@@ -58,8 +58,8 @@ jobs:
# The root build includes the examples on the default engine, which stop at
# TN_WASM_ENGINE_MISSING without the web Wasm engine (release run 42296982894).
- uses: ./.github/actions/native-engine-wasm
- - name: Build the workspace packages before comparing published bytes
- run: pnpm build
+ # PRD-903: no workspace build here. The gate builds once, on the first package npm already
+ # serves, because only a resumed release compares published bytes with the workspace.
- name: Write the request and workflow-derived availability
env:
CANDIDATE_REQUEST: ${{ inputs.candidate_request }}
diff --git a/docs/PRDs/BLOCKED/requires-next-release/PRD-903-cut-release-deploy-and-ci-time-by-fixing-carry-and-cutting-duplicate-and-junk-tests.md b/docs/PRDs/BLOCKED/requires-next-release/PRD-903-cut-release-deploy-and-ci-time-by-fixing-carry-and-cutting-duplicate-and-junk-tests.md
new file mode 100644
index 0000000000..b50f83a0c7
--- /dev/null
+++ b/docs/PRDs/BLOCKED/requires-next-release/PRD-903-cut-release-deploy-and-ci-time-by-fixing-carry-and-cutting-duplicate-and-junk-tests.md
@@ -0,0 +1,159 @@
+# PRD-903 — Cut release deploy time and overall CI time by fixing broken carry, eliminating duplicate work, and removing test junk
+
+**Status:** BLOCKED on the next release — Phases 1–3 landed on PR #710; only the AC-4 live timings remain
+**Priority:** P1 — Release 0.3.19 took 184 minutes end-to-end (clean path ~136 min), a one-line Markdown push to `develop` burned 74.2 wall minutes / 460.4 machine minutes because per-job carry is broken on every run, and all three phases below are open.
+**Complexity:** 8 (HIGH); risk override: HIGH — modifies release publish/proof orchestration, workflow gating, and test-suite selection boundaries.
+**Owner:** CI tooling
+**Depends on:** None
+
+## Context
+
+Owner, 2026-11-21: investigate the logs and file a PRD to decrease the time required to deploy a new library version and overall CI time, considering every option — including removing test junk (tests that add no value and only slow runs down), redundancy, and duplicates.
+
+This PRD builds on [PRD-630](../../CI/PRD-630-the-tag-run-publishes-the-binaries-the-main-proof-built.md), [PRD-776](../../CI/PRD-776-ci-runs-each-test-once-per-input-and-retries-only-the-red-leg.md), [PRD-782](../../CI/PRD-782-a-merge-reaches-npm-as-fast-as-the-work-allows.md), [PRD-897](../../CI/PRD-897-a-release-stays-unpublished-until-npm-serves-its-cohort.md), and [PRD-901](PRD-901-a-release-needs-one-board-round-per-fix-set-and-one-registry-wait.md) using a fresh log audit of the last 400 `ci.yml` runs (`2026-11-14 .. 2026-11-21`), 200 `native-release.yml` runs (`2026-11-16 .. 2026-11-21`), and every step of Release `0.3.19` (`2026-11-21`).
+
+```mermaid
+flowchart LR
+ D["develop push
run 44873262311 (23.5m)"] --> PR["Promotion PR #707
CI 44873265649 (61.7m)
Native Release 44873265613 (50.2m / 152.9m mach)
Pipeline Cache 44873265786 (6.1m)"]
+ PR --> M["Merge to main: HTTP 502 broke reuse
CI 44878180530 (54.7m / 507.5m mach)
Pipeline Cache 44878180487 (5.4m dup)"]
+ M --> S["npm-release ship 44882439375 (38.5m red at clean-room)
rc 44882828314 (3.6m) + tag 44883710388 (1.8m)
+ 4x pnpm build + 2x upgrade proof + 2x pack"]
+ S --> CR["Manual dispatch clean-room
44886580591 (13.1m wall / 11.1m run)
Total 0.3.19 road: 183.7m"]
+```
+
+### Measured Baselines (2026-11-14 .. 2026-11-21)
+
+| Surface | Measured Baseline | Evidence Run(s) | Goal |
+|---|---|---|---|
+| Release `0.3.19` promotion PR open -> `npm latest` | **183.7 min** wall (~136 min without retry; ~82 min had main reuse hit) | `44873265649` -> `44878180530` -> `44882439375` -> `44886580591` | **≤ 65 min** |
+| `npm-release.yml` `ship` clean path | **~48.5 min** (`38.5m` up to clean-room fail + `11.1m` clean-room pass) | `44882439375`, `44886580591` (0.3.18 took `138.9m` across 3 attempts, `44853263168`) | **≤ 25 min** |
+| `native-release.yml` PR proof | **50.2 min** wall / **152.9 machine-min** (193 PR runs in 5 days = **2,366 wall-min**, 11 failures) | `44873265613` | **≤ 22 min** wall / **≤ 70 machine-min** |
+| Full CI board | **48.4–54.7 min** wall, **507.5–510.8 machine-min**, **212.9–395.6m queue wait sum** | `44878180530` (main), `44848357345` (0.3.18 PR) | **≤ 25 min** wall, **≤ 240 machine-min** |
+| Merge queue (`merge_group`) | **61.7 min** wall, **256.3 machine-min** (23 of 28 runs cancelled in 7 days) | `44800338707` | **≤ 20 min** wall |
+| PR review lane (`pull_request -> develop`) | **19.7 min** wall (`18.8m` in `test` alone) | `44797214689` | **≤ 8 min** wall |
+| Docs-only push to `develop` | **74.2 min** wall, **460.4 machine-min**, 72/79 jobs ran | `44887725075` (`41df5bbca`, `docs(prd)`) | **< 1 min** (0 board jobs) |
+| Nightly CI (`schedule`) | **51.6 min** wall, **751.5 machine-min**, **0/7 green** in 7 days (10+ `template-engine-cost` legs fail every night) | `44898203423` | **Green nightly** |
+
+### Seven Root Causes Verified in Logs
+
+1. **Per-job carry (PRD-776) is 100% broken on every CI run.** `.github/workflows/ci.yml:90-93` checks out only `scripts` and `packages/create-threenative/templates` in `scope`. `withCarriedLegs` (`scripts/ci/reuse.mjs:748`) calls `carryDeps`, which imports `scripts/ci-native-qualification.mjs:7`, which statically imports `../packages/runtime-native/scripts/desktop-build-profile.mjs`. Every single run (`44878180530`, `44887725075`, `44800338707`) prints `per-job reuse unavailable, the board runs: Cannot find module '.../packages/runtime-native/scripts/desktop-build-profile.mjs'`, catches it in `scripts/ci/reuse.mjs:752`, and carries **zero legs**.
+2. **Zero retries on `ghApi()` + `develop` pushes ignore `prose`.** `ghApi()` (`scripts/ci/reuse.mjs:61-81`) makes a single `gh api` call with no retry, so one transient `gh: Server Error (HTTP 502)` turned 0.3.19 `push main` (`44878180530`) from a 1.0-min reuse (cf. 0.3.18 `44853167843`) into a **54.7-min / 507.5-machine-min full board** (same unhandled `502` risk in `scripts/native-release-reuse.mjs:14`). Meanwhile, `classify()` (`scripts/ci-change-scope.mjs:576-589`) forces every `push` to `develop` without an open promotion PR into `full`, never checking if the commit changed only `prose` — causing a single PRD doc edit (`44887725075`) to burn **74.2 wall-min / 460.4 machine-min**.
+3. **Un-cancelled `native-release.yml` PR pileups & duplicate `pipeline-cache.yml` triggers.** `.github/workflows/native-release.yml:49` sets `cancel-in-progress: false` for `native-release-proof`, so pushing commits while a Release PR is open queues back-to-back 50-minute multi-OS runs (193 PR runs / 2,366 wall-min / 11 failures in 5 days; top failures in the last 15 failed runs: `clean-consumer-windows` 8x, `clean-consumer` 6x, `npm-dry-run` 5x). `.github/workflows/pipeline-cache.yml:5-22` triggers on both `pull_request: [main]` and `push: [main]`, running the exact job graph twice (`44873265786` + `44878180487`).
+4. **`npm-release.yml` `ship` repeats `pnpm build` 4x, upgrade proof 2x, `pack` 2x, 100+ serial `npm view` calls, 60s poll sleeps, and serial `npm`+`pnpm` clean-room (~22 min pure waste in 48.5 min).**
+ - `pnpm build` runs 4 times on the exact same `HEAD`: `npm-release.yml:75` (2.2m), `release-candidate.yml:62` (2.5m — even though `scripts/release-candidate-gate.ts:2012` only calls `workspacePackageTreeHash` when `registryState === "matching"`, never when packages are `absent`!), `release.ts:730` inside `--prove-upgrade` (2.5m), and `release.ts:730` again inside `publish` `--yes` (2.5m).
+ - `proveUpgradeFromLatest` (`scripts/release.ts:816`) and `packReleaseSet` (`scripts/release.ts:789`) run twice on the same commit 6 minutes apart (`08:04:51`–`08:11:29` = 6.6m, then `08:13:54`–`08:20:37` = 6.7m in `44882439375`).
+ - `waitFor` (`scripts/release-ship.ts:466`) sleeps 60 seconds per poll and calls `readShipState()` (`scripts/release-ship.ts:183-220`), which executes 17 serial `npm view` subprocesses every tick (~15s/call).
+ - `scripts/verify-registry-install.ts` runs `npm` (5.9m) then `pnpm` (3.7m) serially (`10.0m` in `44886580591`), repeating identical `gameplay` (97s + 83s), `native` (34s + 28s), and Android Gradle APK builds (124s + 37s) on the exact same published tarballs.
+5. **Non-blocking `ios-simulator` sets the board floor + `native-release.yml` duplicates `native-platforms.yml` (~25–30 min off promotion wall time).**
+ - `ios-simulator` is omitted from `SHIP_SCOPE` (`scripts/release-ship.ts:28-31`) and marked exempt in `scripts/ci-native-qualification.mjs:23` and `scripts/ci/reuse.mjs:730`, yet `native-platforms.yml:463,498,2889` wires `ios-simulator` (**49.9m** — longest job on the entire board!) into `completion`'s `needs:`, and `native-release.yml:566-573` wires `build-ios-simulator` (**37.5m** — longest job in `native-release.yml`!) into `publish`'s `needs:`. Inside `packages/runtime-native/scripts/verify-ios-simulator.mjs:353-607`, `rebuildApp()` runs `xcodebuild` **7 times** just to copy a rebuilt JS bundle into `.app` (31.9m total), after spending 8.4m rebuilding workspace packages.
+ - `native-release.yml` runs full `native:verify:desktop` / MSVC verify on Windows (**16.2m**), Linux (**12.3m**), and macOS (**10.2m**) = **38.7m** on the exact same promotion PR where `native-platforms.yml` already runs those 55 C++ test executables + desktop/WebView/installer gates (`35.9m` Windows, `19.5m` desktop parity, `15.9m` macOS, `17.1m` `test-native`).
+6. **`test` duplicates >10 minutes of `test-unit` Vitest suites + `pnpm build` (single 18.8-min bottleneck of PR review lanes).**
+ - `vitest.config.ts:40-45` already runs `packages/**/__tests__/**/*.spec.ts`, `examples/strata-terrain-preview/__tests__/**/*.spec.ts`, and `scripts/**/*.spec.ts` across `test-unit (1/4..4/4)`.
+ - Yet `test` (`TN_SUITE_PHASES=docs,build,package-test`, `scripts/run-test-suite.sh:256-267`, `13.3m` on `44878180530`, **`18.8m` on PR review `44797214689`**) rebuilds the whole workspace (duplicating `build-artifacts`) and re-runs Vitest for `packages/terrain` (**271.1s**), `examples/strata-terrain-preview` (**155.2s**), `packages/procedural-environment` (**90.9s**), `packages/procedural-animals` (**55.4s**), plus `ueformat`, `raw-unreal`, `metahuman`, and `blender-bridge` (**~630s+ of duplicate Vitest CPU**). On PR review lanes where `ci-change-scope.mjs:183` sets `jobs.test.required = true` for any `packages/` edit, this single job stretches an ~8m review lane to 19.7m.
+7. **Test junk, heavy unit fixtures, serial conformance, and 16-kit / 20-lane sprawl (`44878180530` logs):**
+ - **Unit suite concentration:** 1,241 files = `4,412.7s` test CPU; top 20 files = `2,286.0s` (**51.8%**): `packages/terrain/__tests__/terrain-mcp.spec.ts` (**349.5s** in 1 file — drags shard 4/4 to 11.5m), `packages/create-threenative/__tests__/template-assets-compile-{1,2}.spec.ts` (**333.0s** — re-cooks assets across all 16 kits already cooked in `template-nonvisual`), `packages/terrain/__tests__/kit-bake.spec.ts` (**138.6s**), `packages/assets/__tests__/compile.spec.ts` (**136.5s**), `packages/procedural-environment/__tests__/city.spec.ts` (**134.6s** — bakes all 75 city GLBs every run), `scripts/__tests__/unreal-look-*.spec.ts` + `realism-effects-*.spec.ts` (**51 offline research-harness specs = 133.8s**, led by `unreal-look-gi-cache.spec.ts` at **101.7s**), `examples/strata-terrain-preview/__tests__/bake-golden.spec.ts` (**91.9s**, bakes twice), and `packages/terrain/__tests__/starter-kit.spec.ts` (**91.6s**).
+ - **Android & Desktop conformance:** `packages/runtime-native/conformance/registry.json` holds **157 tests** (109–110 run, 48 always-blocked on hosted). Android runs all 110 cases serially at ~14.5s/case = **26.5 min** (`34.0–44.1m` job — the #1 wall-time floor of every merge queue and full board!) because even trivial cases like `01-basic-cube` pay 14.7s of per-case APK launch/logcat/screenshot overhead; Desktop runs 109 cases serially = **12.6 min**. `--only-tests` already exists in `packages/runtime-native/conformance/run-conformance.mjs:2840`.
+ - **`template-nonvisual` (16 kits = 146.2 machine-min = 28.8% of board, 101.3m queue wait):** `237` scenarios launch cold browsers serially (`shooter`: 24 kept scenarios = **21.4m**, including 43-frame micro-scenarios taking ~50–95s each; `collectathon`: 19 scenarios = **15.1m**; `adventure`: **10.7m**; `racing`: **9.8m**; plus **17.6m** across 15 kits in software-adapter `engine-parity`).
+ - **`integration/*` (20 jobs = 63.3 machine-min, 88.6m queue wait):** 3 overlapping exposure jobs (`auto-exposure` 9.9m + `cold-boot` 5.0m + `exposure` 1.5m = **16.4m**), 5 ARM64 native jobs (21.7m), and 0.5–0.8m jobs (`csg`, `ik`, `playstation`) each paying full checkout/install/queue setup.
+
+## Solution
+
+```mermaid
+flowchart LR
+ PR["Promotion PR -> main
CI 22-25m (no iOS block)
Native Release 18-22m (fast smoke, cancel superseded)"] --> M["Main push
Reused (5xx retry): 1m"]
+ M --> S["npm-release ship (≤ 22m)
1x build -> rc (no dup build) -> 1x pack & upgrade proof
-> tag (reuse proof) -> 2-wave publish (10s poll)
-> parallel clean-room"]
+```
+
+Split improvements into two clear tracks:
+1. **Zero-coverage-loss structural fixes (Phases 1–3):** Fix the broken `scope` carry import, add 5xx retries to `ghApi` and `native-release-reuse.mjs`, skip `develop` pushes that change only prose, cancel superseded PR `native-release.yml` runs, stop duplicating `pipeline-cache.yml` on `push: main`, collapse 4 `pnpm build` / 2 `proveUpgradeFromLatest` / 2 `packReleaseSet` / serial `npm view` + 60s polls / serial clean-room into one pass, decouple non-blocking `ios-simulator` from blocking joins and remove its 6 redundant `xcodebuild` calls, deduplicate `native-release.yml` desktop verify vs `native-platforms.yml`, strip duplicate Vitest runs out of CI `test`, trim over-heavy unit fixtures (`template-assets-compile`, `terrain-mcp.spec.ts`, `city.spec.ts`), shard Android conformance 2-way, and group tiny integration lanes.
+2. **Coverage-tradeoff cuts & junk removal (listed below for explicit owner sign-off under `## Blocked on`):** Every cut that narrows test frequency, moves offline research specs off the main board, or trims redundant playtest/conformance scenarios is isolated in the table below so no coverage is removed silently.
+
+### Test Junk & Coverage-Tradeoff Removal Menu (Owner Decisions)
+
+| Candidate | Measured Cost | Proposed Action | Proof / Coverage Tradeoff |
+|---|---|---|---|
+| `scripts/__tests__/unreal-look-*.spec.ts` + `realism-effects-*.spec.ts` (51 files, `unreal-look-gi-cache.spec.ts` alone = 101.7s) | 51 files, **133.8s** CPU on every full board | Run only when `scripts/unreal-look/**`, `packages/core/src/*gi*`, or those specs change + nightly | Offline calibration/research harness tests stop running on unrelated PRs; still runs in full nightly |
+| `shooter` (38 total, 24 kept = 21.4m) & `collectathon` (24 total, 19 kept = 15.1m) micro-scenarios + serial browser launches | **36.5 min** across 2 kits; **146.2 min** across 16 kits | Consolidate micro-scenarios into multi-checkpoint runs (~6 per kit) + reuse Chromium instance per kit in `threenative-playtest` | Slightly coarser scenario failure localization in exchange for keeping every behavior assertion |
+| `template-nonvisual` 16-kit fanout on `merge_group` / `develop` pushes | **146.2 machine-min** + **101.3m queue wait** per board | Run 4 representative kits (`starter`, `platformer`, `shooter`, `racing`) + changed kits on `merge_group`; full 16 on promotion PR & nightly | Niche-kit regressions from shared `packages/` land on nightly or promotion instead of every `merge_group` |
+| Software-adapter `engine-parity` (15 kits) & `integration / auto-exposure` | **17.6 machine-min** + **9.9m**; high SwiftShader flake share | Run `engine-parity` and `auto-exposure` only on renderer/exposure diffs + nightly | Unrelated diffs skip software-adapter pose/exposure checks until nightly |
+| Conformance (`registry.json`: 157 rows, 110 active + 48 always-blocked) | **26.5m** Android (`34–44m` job) + **12.6m** Desktop per board | Split into ~25-case core+regression tier on `merge_group` (~5–7m) vs full 110-case tier on promotion PR & nightly | Full 110-case visual matrix shifts from every `merge_group` to promotion PR & nightly |
+| Nightly `template-engine-cost` matrix (`44898203423`) | **260+ machine-min/night**, 10/16 red, **0/7 green** | Fix thresholds or delete the broken matrix instead of burning nightly slots | Stops running failing nightly cost jobs that nobody acts on |
+| `native-platforms` workspace rebuilds (`desktop`, `ios-simulator`, `starter-linux`) | ~**18 machine-min** (`8.4m` in iOS) per board | Restore `workspace-packages` from `build-artifacts` instead of running `pnpm build` inside native legs | `native-platforms` depends on `build-artifacts` or falls back to build if absent |
+
+Risks & mitigations:
+- **Sparse-checkout module closure drift:** A unit test in `scripts/__tests__/ci-structure.spec.ts` parses static imports of `scripts/ci-change-scope.mjs` and its closure and asserts every imported file is inside `.github/workflows/ci.yml` `scope`'s `sparse-checkout` paths, failing closed at test time.
+- **Single upgrade proof staleness:** Same-process `release:ship` passes the exact tarball temp dir + SHA-256 lock from pre-tag `proveUpgradeFromLatest` into `publish`, so the published bytes match the proved bytes identically; standalone `pnpm release --yes` / `--resume` retains its proof.
+- **Reduced `native-release.yml` verification:** Removing the 38.7m duplicate `native:verify:desktop` loop from `native-release.yml` assumes `native-platforms.yml` ran the 55 C++ test executables on the same promotion PR (`ci-required` enforces this on `develop -> main`); `native-release.yml` keeps binary smoke (`--version`, 300-frame launch) and clean-room consumer packaging proofs (`clean-consumer`, `clean-consumer-windows`).
+
+## Non-Goals
+
+- Paying for larger GitHub-hosted runners or upgrading the GitHub concurrency plan (capacity is an owner billing decision tracked in [PRD-782](../../CI/PRD-782-a-merge-reaches-npm-as-fast-as-the-work-allows.md)).
+- Replacing the `develop -> main` release flow with a frozen `release/x.y.z` branch (deferred in [PRD-901](PRD-901-a-release-needs-one-board-round-per-fix-set-and-one-registry-wait.md)).
+- Changing npm CDN propagation physics beyond the two-wave publish already shipped in [PRD-901](PRD-901-a-release-needs-one-board-round-per-fix-set-and-one-registry-wait.md).
+- Weakening lockfile checks, OIDC provenance, public-surface checks, or `publish:check` invariants.
+
+## Acceptance Criteria
+
+- [x] AC-1 [local]: `scope`'s sparse checkout imports `withCarriedLegs` without error (enforced by a static import-closure test), `ghApi` and `native-release-reuse.mjs` retry transient 5xx responses, prose-only `develop` pushes select `prose`, and `native-release.yml` cancels superseded PR proofs. proof: `pnpm exec vitest run scripts/__tests__/ci-structure.spec.ts scripts/__tests__/ci-queue-reuse.spec.ts scripts/__tests__/ci-leg-carry.spec.ts scripts/__tests__/native-release-proof.spec.ts` — Evidence: 2026-11-21, 4 files pass (sparse-closure, prose and `synchronize` cases included); the live `scope` replay carried 47 legs where it carried 0 (Phase 1).
+- [x] AC-2 [local]: `release:ship` runs `pnpm build` once per ship (the caller's build, named by `TN_RELEASE_PREBUILT`), polls every 15 s for its first ten minutes, and `release-candidate.yml` skips `pnpm build` when all cohort packages are absent from npm. The second upgrade proof, the serial `npm view` reads and the serial clean room stay (see Decisions and `## Blocked on`). proof: `pnpm exec vitest run scripts/__tests__/release.spec.ts scripts/__tests__/release-ship.spec.ts scripts/__tests__/release-candidate-gate.spec.ts scripts/__tests__/verify-registry-install.spec.ts` — Evidence: 2026-11-21, 4 files pass.
+- [x] AC-3 [local]: CI `test` runs zero Vitest suites already executed by `test-unit`, and `template-assets-compile` probes the uncooked budget on one kit while every kit still compiles. The `terrain-mcp.spec.ts` and `city.spec.ts` ceilings moved to `## Blocked on` (owner decision). proof: `pnpm exec vitest run scripts/__tests__/ci-structure.spec.ts scripts/__tests__/ci-needs.spec.ts scripts/__tests__/run-test-suite.spec.ts packages/create-threenative/__tests__/template-assets-compile-1.spec.ts packages/create-threenative/__tests__/template-assets-compile-2.spec.ts` — Evidence: 2026-11-21, all pass; `pnpm typecheck` and `pnpm lint` exit 0.
+- [ ] AC-4 [shared]: On the next real release and post-landing CI window, promotion PR open to `npm latest` finishes in ≤ 65 min (`0.3.19` baseline: 183.7 min), `npm-release.yml` `ship` finishes in ≤ 25 min (baseline ~48.5 min), full CI board wall median is ≤ 25 min (baseline 54.7 min), and PR review lane wall time is ≤ 8 min (baseline 19.7 min). proof: release run IDs and `pnpm ci:speed record && pnpm ci:speed show` — Evidence: pending.
+
+## Blocked on
+
+- Owner sign-off on each coverage-tradeoff item in "Test Junk & Coverage-Tradeoff Removal Menu" (moving the 51 `unreal-look`/`realism-effects` specs to path-scoped + nightly, consolidating `shooter`/`collectathon` micro-scenarios + browser session reuse, narrowing `merge_group` `template-nonvisual` to 4 representative kits + touched kits, moving `engine-parity` and `integration / auto-exposure` to nightly/path-scoped, splitting conformance into a ~25-case PR/queue tier vs full 110-case promotion/nightly tier, fixing or deleting the 0%-green `template-engine-cost` nightly matrix, and reusing `workspace-packages` inside `native-platforms`) — unblocked by owner decision.
+- AC-4 live timing proof on GitHub Actions — unblocked by landing Phases 1–3 and shipping the next `Release 0.3.x` cohort.
+- `verify-ios-simulator.mjs` without its 7 `xcodebuild` rebuilds — unblocked by a macOS runner run; this host has no Xcode, so the change cannot be proved before it ships.
+- Dropping `native:verify:desktop` from the `native-release.yml` PR `build` jobs (38.7 machine-min) — owner decision. That step runs the exact binaries the job stages and the tag run republishes; `native-platforms.yml` verifies a different build of the same source, so this is a coverage trade, not a duplicate.
+- `terrain-mcp.spec.ts` at 30 s or less (349.5 s on CI) and `city.spec.ts` at 20 s or less (134.6 s) — owner decision. The time is real work: `terrain-mcp` cooks each of the 5 starter kits end to end and reads the GLB back, and `city` bakes each of the 75 modules, each from its own generator. Reaching the ceilings means sampling kits or modules, which is a coverage cut, not a duplicate.
+- Running the `npm` and `pnpm` clean-room lanes of `verify-registry-install.ts` at the same time (~4 min) — owner decision. The clean room is the step that went red on 0.3.18 and 0.3.19, and two Gradle builds, two Vite builds and two software-WebGPU playtests on one 4-vCPU hosted runner add load to that step. The pnpm Android pass is not a pure repeat either: Gradle reads pnpm's symlinked `node_modules`.
+
+## Integration Ledger
+
+| Capability | Reachable consumer/trigger | Replaces / disposition | Evidence |
+|---|---|---|---|
+| Per-job carry + transient API retry + `develop` prose shortcut | `.github/workflows/ci.yml` `scope` -> `scripts/ci-change-scope.mjs` -> `scripts/ci/reuse.mjs` | Fixes broken `withCarriedLegs` import, adds 5xx retries to `ghApi`, narrows prose pushes on `develop` | AC-1 |
+| Release PR proof cancellation & deduplicated pipeline-cache | `.github/workflows/native-release.yml`, `.github/workflows/pipeline-cache.yml` | Replaces `cancel-in-progress: false` on PR proofs and drops duplicate `push: main` trigger | AC-1, AC-4 |
+| Single-build, single-upgrade-proof ship + parallel clean-room | `.github/workflows/npm-release.yml` -> `scripts/release-ship.ts` -> `scripts/release.ts`, `scripts/verify-registry-install.ts`, `.github/workflows/release-candidate.yml` | Removes 3 duplicate `pnpm build`s, 2nd upgrade proof, 60s polls, and serial clean-room | AC-2, AC-4 |
+| Decoupled iOS simulator & deduplicated `native-release` verify | `.github/workflows/native-platforms.yml`, `.github/workflows/native-release.yml`, `packages/runtime-native/scripts/verify-ios-simulator.mjs` | Removes non-blocking iOS from blocking joins and removes 38.7m duplicate desktop verify on PRs | AC-4 |
+| Deduplicated CI `test`/`test-unit` + trimmed slow specs + sharded Android conformance + grouped integration | `.github/workflows/ci.yml`, `.github/workflows/integration.yml`, `.github/workflows/native-platforms.yml`, `scripts/run-test-suite.sh`, `packages/{create-threenative,terrain,procedural-environment}/__tests__/` | Eliminates duplicate Vitest runs in `test`, cuts >800s unit bloat, shards Android 2-way, groups small web lanes | AC-3, AC-4 |
+
+## Decisions
+
+- 2026-11-21 (agent, planning): Zero-coverage-loss fixes (broken carry, 5xx retries, duplicate builds/proofs/Vitest runs, un-cancelled PR proofs, iOS critical-path decoupling, 2-way Android sharding, integration lane grouping) are scheduled directly in Phases 1–3; any change that narrows test scope or moves checks to nightly is isolated under Owner Decisions / `## Blocked on` so no gate is weakened silently.
+- 2026-11-21 (agent, planning): Single upgrade proof in `release:ship` keeps the pre-tag proof as the authoritative gate and passes its verified tarball directory + SHA-256 lock into the same-process `publish` call (resolving the open question in [PRD-897](../../CI/PRD-897-a-release-stays-unpublished-until-npm-serves-its-cohort.md)); standalone `pnpm release --yes` and `--resume` without a same-run proof retain their own upgrade proof.
+
+- 2026-11-21 (agent, Phase 1): `pipeline-cache.yml` keeps its `push: main` trigger. Its `wgpu-cache-*` and `pipeline-cache-host-deps-*` saves on `main` are the only entries other branches can restore (a pull-request run saves into `refs/pull/N/merge`, which no other branch reads). The duplicate run costs about 5.4 machine minutes and sits off the release critical path (`npm-release.yml` waits on CI only), so the cold caches would cost more than the cut saves.
+- 2026-11-21 (agent, Phase 1): The cross-branch `native-release-proof` group stays. In the last 200 runs every real proof was on the `develop` promotion pull request (21 success, 13 cancelled while pending, 9 failure), so cancelling on `synchronize` stops superseded promotion proofs without a per-PR group that would let two proofs hold the pool at once (PRD-380).
+
+- 2026-11-21 (agent, Phase 2): The second upgrade proof stays, which reverses the 2026-11-21 planning decision above. The pre-tag proof runs `--prove-upgrade`, which acknowledges missing prebuilt native binaries because the tag does not exist yet. The publish run (`--yes` in CI) is the only proof that installs the candidate against the published native release, so it proves a different claim.
+- 2026-11-21 (agent, Phase 2): The serial `npm view` reads in `readShipState` stay. `cohort().every(...)` stops at the first missing version, so before the publish one tick makes one `npm view` call, not 17.
+- 2026-11-21 (agent, Phase 2): `ios-simulator` stays in `native-release.yml` `publish`'s `needs:`: `publish` ships `runtime-ios-simulator-arm64.zip`. Dropping it from `native-platforms.yml` `completion` saves nothing, because the `ci.yml` job that calls the reusable workflow waits for every job in it.
+
+- 2026-11-21 (agent, Phase 3): The `test` job keeps its `build` phase. It proves every example still bundles, which `build-artifacts` does not, and the package walk no longer rebuilds anything on top of it.
+
+- 2026-11-21 (owner, via the agent's question): PRD-903 spends only the PR review lane on live CI. Android conformance 2-way sharding and the integration-lane grouping move to [PRD-904](../../CI/PRD-904-android-conformance-runs-in-two-shards-on-one-apk.md) as a follow-up: two shards cannot each build their own APK under `ci-native-receipts.mjs`, so the work needs a one-APK producer, a report merge and native CI runs to prove.
+
+## Execution Phases
+
+#### Phase 1: Fix broken carry, API retries, and wasted workflow runs
+**Status:** DONE
+**Files:** `.github/workflows/ci.yml` (`scope` `sparse-checkout`), `scripts/ci-native-qualification.mjs`, `scripts/ci/reuse.mjs`, `scripts/native-release-reuse.mjs`, `scripts/ci-change-scope.mjs`, `.github/workflows/native-release.yml`, `.github/workflows/pipeline-cache.yml`, `scripts/__tests__/ci-structure.spec.ts`, `scripts/__tests__/ci-queue-reuse.spec.ts`, `scripts/__tests__/native-release-proof.spec.ts`
+**Implementation:** Add `packages/runtime-native/scripts/desktop-build-profile.mjs` (or move the shared profile constant into `scripts/ci/` or include the path in `scope`'s `sparse-checkout`) and add a static import-closure guard in `scripts/__tests__/ci-structure.spec.ts` so `ci-change-scope.mjs` never fails silently under sparse checkout. Add bounded exponential backoff retries on HTTP 5xx / transient network errors in `ghApi()` (`scripts/ci/reuse.mjs:61-81`) and `scripts/native-release-reuse.mjs:14`. Allow `push` to `develop` whose diff is 100% `prose` (plus non-cache-producing paths) to return `selection: "prose"` instead of triggering a 74-min full board. Change `.github/workflows/native-release.yml:48-49` so PR proofs use `group: native-release-pr-${{ github.event.pull_request.number }}` with `cancel-in-progress: true`, while tag and dispatch runs retain `cancel-in-progress: false`. Remove `push: branches: [main]` from `.github/workflows/pipeline-cache.yml:16-22` when `pull_request` into `main` already proved the identical commit.
+
+- [x] `scope` carries eligible legs with `withCarriedLegs` under CI sparse-checkout, retries transient 5xx API failures, and selects `prose` for Markdown-only `develop` pushes. proof: `pnpm exec vitest run scripts/__tests__/ci-structure.spec.ts scripts/__tests__/ci-queue-reuse.spec.ts scripts/__tests__/ci-leg-carry.spec.ts` — covers AC-1. Result 2026-11-21: all 32 `scripts/__tests__/ci-*`, `native-release*` and `gh` spec files pass (1002 tests). Live replay of `scope` in a cone-mode sparse checkout of `develop` `41df5bbca` with the real Actions API: before, `per-job reuse unavailable … Cannot find module …/desktop-build-profile.mjs` and 0 legs carried; after adding `packages/runtime-native/scripts` to the cone, no error and **47 legs carried** (13 jobs: typecheck, test, test-unit, test-native, test-browser, test-playtest, template-nonvisual, golden-path-template, native-platforms, native-engine, benchmark, budgets, performance-contracts). The closure guard (`checks out every file the scope job imports or reads`) is red on the old cone and green on the new one. `scripts/lib/gh.mjs` now retries a read twice with a 2 s / 6 s backoff and stops on a 4xx; `ghApi` in `scripts/ci/reuse.mjs` routes through it. A develop push selects `prose` only when every path since the last green develop push head is prose outside the `workspace-dist` cache-key trees, and `ci-required` re-derives that diff (`CI_REQUIRED_PROSE_UNPROVEN`); red-green in `ci-needs.spec.ts`.
+- [x] `native-release.yml` cancels superseded PR proofs. proof: `pnpm exec vitest run scripts/__tests__/native-release-proof.spec.ts scripts/__tests__/ci-structure.spec.ts` — covers AC-1, AC-4. Result 2026-11-21: both pass; `cancel-in-progress` is true only for a `pull_request` `synchronize` event, so a tag, a dispatch and a `labeled` event never cancel a running proof.
+
+#### Phase 2: Cut release deploy time (`develop -> main -> npm latest`) in half
+**Status:** DONE (the local scope; the iOS, clean-room and `native-release` desktop-verify items moved to Decisions and `## Blocked on`)
+**Files:** `.github/workflows/npm-release.yml`, `.github/workflows/release-candidate.yml`, `.github/workflows/native-platforms.yml`, `.github/workflows/native-release.yml`, `scripts/release.ts`, `scripts/release-ship.ts`, `scripts/verify-registry-install.ts`, `packages/runtime-native/scripts/verify-ios-simulator.mjs`, `scripts/__tests__/release.spec.ts`, `scripts/__tests__/release-ship.spec.ts`, `scripts/__tests__/release-candidate-gate.spec.ts`, `scripts/__tests__/verify-registry-install.spec.ts`
+**Implementation:** Add `--prebuilt` / `TN_RELEASE_PREBUILT=1` in `scripts/release.ts` so `npm-release.yml` `ship` builds the workspace once (skipping `pnpm build` inside `--prove-upgrade` and `--yes`, and skipping `pnpm build` in `release-candidate.yml:62` when all cohort packages are absent from npm). Pack and run `proveUpgradeFromLatest` once per `ship` invocation before tagging, passing the packed tarball hashes/dir into the same-process `publish` step (preserving standalone `pnpm release --yes` / `--resume` proof). Parallelize the 17 `npmVersions` calls in `readShipState`, drop `waitFor` poll interval from `60_000` ms to `10_000` ms (`scripts/release-ship.ts:466`), and run `npm` and `pnpm` clean-room lanes concurrently in `scripts/verify-registry-install.ts` (running Gradle Android APK verification + full gameplay once on `npm` and keeping manager-specific scaffold/install/lockfile/build/native binary/MCP checks on `pnpm`). Decouple non-blocking `ios-simulator` from `completion` (`native-platforms.yml`) and `publish` (`native-release.yml`) so it runs asynchronously without extending release wall time, replace the 7 `xcodebuild` loops in `verify-ios-simulator.mjs:353-607` with direct bundle replacement in `.app`, and trim `native-release.yml` PR `build` jobs to binary smoke + clean-consumer checks already missing from `native-platforms.yml`.
+
+- [x] `release:ship` builds the workspace once per ship and polls at 15 s, and `release-candidate.yml` skips the workspace build for unpublished cohorts. proof: `pnpm exec vitest run scripts/__tests__/release.spec.ts scripts/__tests__/release-ship.spec.ts scripts/__tests__/release-candidate-gate.spec.ts` — covers AC-2. Result 2026-11-21: the 3 specs plus `ci-structure`, `npm-release*` and `prepare-release*` pass (7 files, 364 tests). `npm-release.yml` sets `TN_RELEASE_PREBUILT` to the commit its own `pnpm build` built, and `release.ts` skips its build only on an exact HEAD match with no web engine rebuilt by provisioning (`builtByCaller`), which removes the 2 in-ship builds (~5 min). `release-candidate.yml` drops its build; the gate builds once on the first `matching` package (`buildOnFirstHash`), which removes ~2.5 min from every fresh release. `waitFor` polls every 15 s for ten minutes, then every 60 s. The second upgrade proof and the serial `npm view` reads stay (see Decisions).
+
+#### Phase 3: Remove duplicate tests, bloated unit specs, and serial board bottlenecks
+**Status:** DONE (Android sharding and integration grouping moved to PRD-904)
+**Files:** `.github/workflows/ci.yml`, `.github/workflows/integration.yml`, `.github/workflows/native-platforms.yml`, `scripts/run-test-suite.sh`, `scripts/ci-change-scope.mjs`, `scripts/ci-integration-scope.mjs`, `packages/create-threenative/__tests__/template-assets-compile-cases.ts`, `packages/create-threenative/__tests__/template-assets-compile-{1,2}.spec.ts`, `packages/terrain/__tests__/terrain-mcp.spec.ts`, `packages/procedural-environment/__tests__/city.spec.ts`
+**Implementation:** Have CI `test` download `workspace-packages` from `build-artifacts` (skipping `build` phase) and split `vitest` out of `package-test` via `TN_SUITE_SKIP_PACKAGE_VITEST=1` when `test-unit` covers every `packages/**/__tests__/**/*.spec.ts` (keeping `publint` and non-unit scripts such as `verify-bundle.mjs`, `native:physics:parity`, and `examples/avbd-rigging`), and scope PR review-lane `test` to changed packages only. Replace the 333-second 16-kit asset re-cook in `template-assets-compile-{1,2}.spec.ts` with a fast static manifest check across all 16 kits plus 1 real asset compilation on `starter` (keeping the full 16-kit asset cook inside `template-nonvisual`). Cache or share cooked terrain/city fixtures across test cases in `terrain-mcp.spec.ts` (349.5s -> ≤ 30s) and `city.spec.ts` (134.6s -> ≤ 20s, sampling representative modules + manifest schema validation for all 75). Shard `android-emulator-parity` into 2 runners using `run-conformance.mjs --only-tests` (halving 34–44m to ~18–22m), and consolidate tiny `integration/*` web lanes (`csg`, `ik`, `playstation`, `decals`, `fluid-collision`, `exposure`) into one shared setup job while keeping `ci-integration-scope.mjs` receipt keys intact.
+
+- [x] CI `test` stops re-running Vitest suites the `unit` phase owns. proof: `pnpm exec vitest run scripts/__tests__/run-test-suite.spec.ts scripts/__tests__/ci-structure.spec.ts scripts/__tests__/ci-local.spec.ts` and `TN_SUITE_PHASES=package-test TN_SUITE_EXCLUDE_PACKAGES=@threenative/runtime-native pnpm test:ci` — covers AC-3. Result 2026-11-21: specs pass, and the new guard is red on the old script. In prebuilt mode (`pnpm test:ci`, the `test` job) `terrain`, `procedural-environment`, `procedural-animals`, `blender-bridge` and `strata-terrain-preview` leave the recursive walk like `assets`, `ueformat`, `raw-unreal` and `metahuman` already did. The walk keeps `publint --strict` for all eight, the strata bake and `test:water`, and drops the root-config Vitest re-runs and the package rebuilds. A developer's `pnpm --filter test` is unchanged. Paired local run on this desktop: the new phase passes in 47 s; the old one ran 280 s before 3 worktree-environment `terrain` failures stopped it, with the strata chain still ahead (CI baseline: 9.7 min, run `44878180530`).
+- [x] `template-assets-compile` runs the uncooked-budget probe once instead of per kit. proof: `pnpm exec vitest run packages/create-threenative/__tests__/template-assets-compile-1.spec.ts packages/create-threenative/__tests__/template-assets-compile-2.spec.ts` — covers AC-3. Result 2026-11-21: 34 tests pass. Paired local run: 155 s → 125 s wall, 283 s → 246 s test CPU. `compilesUnderTheDefaultConfig` already asserts every kit leaves `assets` at its defaults, so the budget answer is the same for each kit; every kit still compiles once.
diff --git a/docs/PRDs/CI/PRD-904-android-conformance-runs-in-two-shards-on-one-apk.md b/docs/PRDs/CI/PRD-904-android-conformance-runs-in-two-shards-on-one-apk.md
new file mode 100644
index 0000000000..2d958d23ef
--- /dev/null
+++ b/docs/PRDs/CI/PRD-904-android-conformance-runs-in-two-shards-on-one-apk.md
@@ -0,0 +1,37 @@
+# PRD-904 — Android conformance runs in two shards on one APK, and the tiny integration lanes share one setup
+
+**Status:** NOT STARTED
+**Priority:** P2 — the Android emulator parity job (34–44 min) is the wall-time floor of every full board, and neither box below is started.
+**Complexity:** 6 (MEDIUM); risk override: HIGH — changes a required native receipt.
+**Owner:** CI tooling
+**Depends on:** [PRD-903](../BLOCKED/requires-next-release/PRD-903-cut-release-deploy-and-ci-time-by-fixing-carry-and-cutting-duplicate-and-junk-tests.md)
+
+## Context
+
+Split out of PRD-903 Phase 3 on 2026-11-21 (owner chose "review lane only" for PRD-903, and this work needs native CI runs to prove).
+
+- `android-emulator-parity` in `.github/workflows/native-platforms.yml` builds the APK and then runs all 110 active conformance cases serially at about 14.5 s each (26.5 min of the 34–44 min job, run `44878180530`).
+- `run-conformance.mjs --only-tests` already selects a subset.
+- Two shards cannot each build their own APK: `scripts/ci-native-receipts.mjs` requires every executed row's `runtimeLibraries.x86_64` to equal one `artifactSha256`, and it validates the report against the full `conformance/registry.json`.
+- Six `integration/*` web lanes (`csg`, `ik`, `playstation`, `decals`, `fluid-collision`, `exposure`) run 0.5–1.5 min each and each pay full checkout, install and queue setup.
+
+## Solution
+
+1. One job builds the APK and uploads it. Two shard jobs download it, boot the emulator and run `--only-tests` halves of the registry. A merge job joins the two partial reports into one full report, then runs the existing parity ledger, `check-lane-blocks.mjs` and the receipt writer on it, so the receipt contract does not change.
+2. The six small integration lanes run as steps of one job, and `scripts/ci-integration-scope.mjs` keeps one receipt key per lane.
+
+## Acceptance Criteria
+
+- [ ] AC-1 [shared]: A full board's Android parity wall time is 25 min or less (baseline 34–44 min), with the same 110 executed cases and a valid native receipt. proof: a `native-platforms` run ID and `pnpm ci:speed record && pnpm ci:speed show` — Evidence: pending.
+
+## Execution Phases
+
+#### Phase 1: Shard Android conformance on one APK
+**Status:** NOT STARTED
+
+- [ ] The APK producer, two shard jobs and the report merge pass `ci-native-receipts.mjs` with one `artifactSha256`. proof: `pnpm exec vitest run scripts/__tests__/ci-native-chain.spec.ts scripts/__tests__/ci-native-profile.spec.ts scripts/__tests__/ci-structure.spec.ts` and one green `native-platforms` run — covers AC-1.
+
+#### Phase 2: One setup for the tiny integration lanes
+**Status:** NOT STARTED
+
+- [ ] The six small `integration/*` lanes run in one job and every lane keeps its receipt key. proof: `pnpm exec vitest run scripts/__tests__/ci-integration-scope.spec.ts` and one green `integration` run — covers AC-1.
diff --git a/packages/create-threenative/__tests__/template-assets-compile-1.spec.ts b/packages/create-threenative/__tests__/template-assets-compile-1.spec.ts
index dd8bda2473..3cc178dbd1 100644
--- a/packages/create-threenative/__tests__/template-assets-compile-1.spec.ts
+++ b/packages/create-threenative/__tests__/template-assets-compile-1.spec.ts
@@ -11,7 +11,6 @@ import {
compilesUnderTheDefaultConfig,
compilesWithCompressionOnByDefault,
firstHalf,
- reachesTheUncookedBudgetWithAnEligibleSourceProbe,
templates,
} from "./template-assets-compile-cases.js";
@@ -20,11 +19,6 @@ import {
// slower, so the shared 60 s unit-test ceiling turned a compile that was merely concurrent into
// `Test timed out in 60000ms`. PRD-550 phase 1: the budget follows the work, not the default.
describe("shipped templates", { timeout: 180_000 }, () => {
- it.each(firstHalf)(
- "%s reaches the uncooked budget with an eligible source probe",
- reachesTheUncookedBudgetWithAnEligibleSourceProbe,
- );
-
it("should name at least one template, or this gate is measuring nothing", () => {
expect(templates.length).toBeGreaterThan(0);
});
diff --git a/packages/create-threenative/__tests__/template-assets-compile-2.spec.ts b/packages/create-threenative/__tests__/template-assets-compile-2.spec.ts
index 8660ac27bc..01bd0841e5 100644
--- a/packages/create-threenative/__tests__/template-assets-compile-2.spec.ts
+++ b/packages/create-threenative/__tests__/template-assets-compile-2.spec.ts
@@ -18,10 +18,11 @@ import {
// The twin of `template-assets-compile-1.spec.ts`, with the same budget for the same reason: a
// template compile is tens of seconds of real work, not a unit test's 60 s default.
describe("shipped templates", { timeout: 180_000 }, () => {
- it.each(secondHalf)(
- "%s reaches the uncooked budget with an eligible source probe",
- reachesTheUncookedBudgetWithAnEligibleSourceProbe,
- );
+ // PRD-903: the budget is a property of `compileAssets` and the scaffold's config seam, and
+ // `compilesUnderTheDefaultConfig` already asserts every kit leaves that config at its defaults.
+ // Probing all sixteen kits compiled each of them a second time for the same answer.
+ it("starter reaches the uncooked budget with an eligible source probe", () =>
+ reachesTheUncookedBudgetWithAnEligibleSourceProbe("starter"));
it.each(secondHalf)(
"%s should compile with compression on by default",
diff --git a/scripts/__tests__/ci-local.spec.ts b/scripts/__tests__/ci-local.spec.ts
index acb5d772af..b18f5f1edc 100644
--- a/scripts/__tests__/ci-local.spec.ts
+++ b/scripts/__tests__/ci-local.spec.ts
@@ -182,6 +182,7 @@ describe("PRD-373 local selection", () => {
"ci-leg-carry.mjs",
"ci/classify.mjs",
"ci/reuse.mjs",
+ "lib/gh.mjs",
]) {
await mkdir(path.dirname(path.join(fixture.root, "scripts", name)), { recursive: true });
await copyFile(path.join(repo, "scripts", name), path.join(fixture.root, "scripts", name));
diff --git a/scripts/__tests__/ci-native-chain.spec.ts b/scripts/__tests__/ci-native-chain.spec.ts
index 4d08ffc3aa..b59703b1f7 100644
--- a/scripts/__tests__/ci-native-chain.spec.ts
+++ b/scripts/__tests__/ci-native-chain.spec.ts
@@ -399,12 +399,13 @@ describe("actual native receipt writer, collector and protected verdict", () =>
"ci-change-scope.mjs",
"ci/classify.mjs",
"ci/reuse.mjs",
+ "lib/gh.mjs",
]) {
mkdirSync(path.dirname(path.join(standalone, "scripts", name)), { recursive: true });
cpSync(path.join(repository, "scripts", name), path.join(standalone, "scripts", name));
}
mkdirSync(path.join(standalone, "scripts/lib"), { recursive: true });
- // The shared inventory is the only module `ci-change-scope.mjs` imports besides its siblings.
+ // The shared inventory is the other `scripts/lib/` module `ci-change-scope.mjs` imports.
cpSync(
path.join(repository, "scripts/lib/repo-inventory.mjs"),
path.join(standalone, "scripts/lib/repo-inventory.mjs"),
diff --git a/scripts/__tests__/ci-needs.spec.ts b/scripts/__tests__/ci-needs.spec.ts
index 5be1c7099a..8d316aec6d 100644
--- a/scripts/__tests__/ci-needs.spec.ts
+++ b/scripts/__tests__/ci-needs.spec.ts
@@ -980,6 +980,36 @@ function verifyNarrowedPlan(
return verifyNeedsVerdict(fixture, needs);
}
+/** Runs `ci-required` on a develop push plan inside the fixture. */
+const verifyWarmPlan = (fixture: IReuseFixture, plan: Record) => {
+ const jobs = plan.jobs as Record;
+ const needs = {
+ scope: { result: "success", outputs: { plan: JSON.stringify(plan) } },
+ ...Object.fromEntries(
+ Object.entries(jobs).map(([name, job]) => [
+ name,
+ { result: job.required ? "success" : "skipped" },
+ ]),
+ ),
+ };
+ return spawnSync(process.execPath, [path.join(repo, "scripts/ci-required.mjs")], {
+ cwd: fixture.root,
+ encoding: "utf8",
+ env: {
+ ...process.env,
+ PATH: `${path.join(fixture.root, "bin")}:${process.env.PATH}`,
+ TN_CI_NEEDS: JSON.stringify(needs),
+ TN_CI_EVENT: "push",
+ TN_CI_BASE_REF: "develop",
+ TN_FIXTURE: fixture.root,
+ TN_FIXTURE_SELF: String(SELF_RUN_ID),
+ GITHUB_ACTIONS: "true",
+ GITHUB_REPOSITORY: "three-native/fixture",
+ GITHUB_RUN_ID: String(SELF_RUN_ID),
+ },
+ });
+};
+
describe("a develop push qualifies its tree and still warms the caches every pull request reads", () => {
// GitHub scopes a pull request's cache to `refs/pull/N/merge`, which no other pull request can
// read. Only a run on the base branch publishes something every pull request into develop reads,
@@ -1011,6 +1041,94 @@ describe("a develop push qualifies its tree and still warms the caches every pul
expect(plan.nativeTier).toBe("full");
});
+ // PRD-903: a one-line PRD edit pushed to develop burned 74 wall minutes (run 44887725075).
+ describe("when only prose changed since the last green develop push", () => {
+ const commitOn = (fixture: IReuseFixture, files: Record) => {
+ for (const [relative, body] of Object.entries(files)) {
+ mkdirSync(path.dirname(path.join(fixture.root, relative)), { recursive: true });
+ writeFileSync(path.join(fixture.root, relative), body);
+ }
+ const git = (...args: string[]) =>
+ spawnSync("git", args, {
+ cwd: fixture.root,
+ encoding: "utf8",
+ env: {
+ PATH: process.env.PATH,
+ GIT_AUTHOR_NAME: "prose fixture",
+ GIT_AUTHOR_EMAIL: "fixture@example.invalid",
+ GIT_COMMITTER_NAME: "prose fixture",
+ GIT_COMMITTER_EMAIL: "fixture@example.invalid",
+ },
+ });
+ expect(git("add", "--", ...Object.keys(files)).status).toBe(0);
+ expect(git("commit", "--quiet", "-m", "next").status).toBe(0);
+ return git("rev-parse", "HEAD").stdout.trim();
+ };
+ const greenDevelopHead = (fixture: IReuseFixture, sha: string) =>
+ listRuns(fixture.root, [
+ { id: 9, head_sha: sha, conclusion: "success", event: "push", head_branch: "develop" },
+ ]);
+
+ it("runs no gate for a Markdown-only push on top of the green head", () => {
+ const fixture = reuseFixture();
+ fakeActionsApi(fixture);
+ greenDevelopHead(fixture, fixture.candidate);
+ const head = commitOn(fixture, { "docs/PRDs/note.md": "# note\n" });
+ const plan = classifyCandidate(fixture, head, { event: "push", target: "develop" });
+ expect(plan).toMatchObject({ selection: "prose", qualification: false, reusedRunId: 0 });
+ expect(String(plan.reason)).toContain(fixture.candidate.slice(0, 12));
+ });
+
+ it("keeps the board when a code commit since the green head never ran its own board", () => {
+ // A newer pending run replaces an older one in the develop group, so HEAD^ is no proof.
+ const fixture = reuseFixture();
+ fakeActionsApi(fixture);
+ greenDevelopHead(fixture, fixture.candidate);
+ commitOn(fixture, { "src/code.ts": "export {};\n" });
+ const head = commitOn(fixture, { "docs/PRDs/note.md": "# note\n" });
+ expect(classifyCandidate(fixture, head, { event: "push", target: "develop" })).toMatchObject({
+ selection: "full",
+ qualification: true,
+ });
+ });
+
+ it("keeps the board when the prose sits in a tree the workspace-dist cache key hashes", () => {
+ const fixture = reuseFixture();
+ fakeActionsApi(fixture);
+ greenDevelopHead(fixture, fixture.candidate);
+ const head = commitOn(fixture, { "scripts/README.md": "# scripts\n" });
+ expect(classifyCandidate(fixture, head, { event: "push", target: "develop" })).toMatchObject({
+ selection: "full",
+ });
+ });
+
+ it("passes ci-required only when the verdict re-derives the prose diff itself", () => {
+ const fixture = reuseFixture();
+ fakeActionsApi(fixture);
+ greenDevelopHead(fixture, fixture.candidate);
+ const head = commitOn(fixture, { "docs/PRDs/note.md": "# note\n" });
+ const plan = classifyCandidate(fixture, head, { event: "push", target: "develop" });
+ expect(plan.selection).toBe("prose");
+ const accepted = verifyWarmPlan(fixture, plan);
+ expect(accepted.status, accepted.stderr).toBe(0);
+ // The green head moved back before a code commit: the same plan is no longer proved.
+ greenDevelopHead(fixture, fixture.base);
+ const refused = verifyWarmPlan(fixture, plan);
+ expect(refused.status).toBe(1);
+ expect(refused.stderr).toContain("CI_REQUIRED_PROSE_UNPROVEN");
+ });
+
+ it("keeps the board when no green develop push is listed", () => {
+ const fixture = reuseFixture();
+ fakeActionsApi(fixture);
+ listSourceRun(fixture);
+ const head = commitOn(fixture, { "docs/PRDs/note.md": "# note\n" });
+ expect(classifyCandidate(fixture, head, { event: "push", target: "develop" })).toMatchObject({
+ selection: "full",
+ });
+ });
+ });
+
describe("while a promotion pull request runs the board on the same head", () => {
const cacheProducers = (plan: Record) =>
Object.entries(plan.jobs as Record)
@@ -1079,35 +1197,6 @@ describe("a develop push qualifies its tree and still warms the caches every pul
).toMatchObject({ selection: "full", qualification: true });
});
- const verifyWarmPlan = (fixture: IReuseFixture, plan: Record) => {
- const jobs = plan.jobs as Record;
- const needs = {
- scope: { result: "success", outputs: { plan: JSON.stringify(plan) } },
- ...Object.fromEntries(
- Object.entries(jobs).map(([name, job]) => [
- name,
- { result: job.required ? "success" : "skipped" },
- ]),
- ),
- };
- return spawnSync(process.execPath, [path.join(repo, "scripts/ci-required.mjs")], {
- cwd: fixture.root,
- encoding: "utf8",
- env: {
- ...process.env,
- PATH: `${path.join(fixture.root, "bin")}:${process.env.PATH}`,
- TN_CI_NEEDS: JSON.stringify(needs),
- TN_CI_EVENT: "push",
- TN_CI_BASE_REF: "develop",
- TN_FIXTURE: fixture.root,
- TN_FIXTURE_SELF: String(SELF_RUN_ID),
- GITHUB_ACTIONS: "true",
- GITHUB_REPOSITORY: "three-native/fixture",
- GITHUB_RUN_ID: String(SELF_RUN_ID),
- },
- });
- };
-
const warmPlan = (fixture: IReuseFixture) =>
classifyCandidate(fixture, fixture.candidate, { event: "push", target: "develop" });
diff --git a/scripts/__tests__/ci-qualification.spec.ts b/scripts/__tests__/ci-qualification.spec.ts
index 9ccbec9159..89cc8ac6f8 100644
--- a/scripts/__tests__/ci-qualification.spec.ts
+++ b/scripts/__tests__/ci-qualification.spec.ts
@@ -196,11 +196,17 @@ describe("exact-candidate qualification minimum", () => {
expect(
validateEventPlan(plan, { eventName: "merge_group", baseRef: "refs/heads/develop" }),
).toEqual(plan);
- for (const eventName of ["push", "schedule", "workflow_dispatch"]) {
+ for (const eventName of ["schedule", "workflow_dispatch"]) {
expect(() => validateEventPlan(plan, { eventName, baseRef: "develop" })).toThrow(
"CI_REQUIRED_QUALIFICATION_MINIMUM",
);
}
+ // PRD-903: a prose-only develop push runs no gate (`ci-required` re-derives the diff); a
+ // push to main still qualifies its tree.
+ expect(validateEventPlan(plan, { eventName: "push", baseRef: "develop" })).toEqual(plan);
+ expect(() => validateEventPlan(plan, { eventName: "push", baseRef: "main" })).toThrow(
+ "CI_REQUIRED_QUALIFICATION_MINIMUM",
+ );
expect(() => validateEventPlan(plan, { eventName: "merge_group", baseRef: "main" })).toThrow(
"CI_REQUIRED_QUALIFICATION_MINIMUM",
);
diff --git a/scripts/__tests__/ci-structure.spec.ts b/scripts/__tests__/ci-structure.spec.ts
index bd8db9cbb7..d6c218d26e 100644
--- a/scripts/__tests__/ci-structure.spec.ts
+++ b/scripts/__tests__/ci-structure.spec.ts
@@ -732,6 +732,37 @@ function classifyScope(
}
describe("CI pipeline structure", () => {
+ // PRD-903: a file the scope scripts import or read from outside the sparse checkout is caught
+ // and logged as "per-job reuse unavailable", so the board silently carried nothing on every run.
+ it("checks out every file the scope job imports or reads", () => {
+ const cone = String(workflow("ci.yml").job("scope").steps[0]?.with["sparse-checkout"])
+ .trim()
+ .split("\n");
+ // Cone mode checks out each listed directory and the files directly inside its ancestors.
+ const covered = (file: string) =>
+ cone.some((dir) => file.startsWith(`${dir}/`) || dir.startsWith(`${path.dirname(file)}/`));
+ const seen = new Set();
+ const stack = ["scripts/ci-change-scope.mjs", "scripts/ci-runner-admission.mjs"];
+ const outside: string[] = [];
+ while (stack.length > 0) {
+ const file = stack.pop() ?? "";
+ if (seen.has(file)) continue;
+ seen.add(file);
+ if (!covered(file)) outside.push(file);
+ const text = readFileSync(path.join(repo, file), "utf8");
+ const imports = text.matchAll(
+ /(?:from\s*|import\(\s*)["'](\.{1,2}\/[^"']+)["']|new URL\(\s*["'](\.{1,2}\/[^"'$`]+)["']\s*,\s*import\.meta\.url/gu,
+ );
+ for (const match of imports) {
+ const target = path.normalize(path.join(path.dirname(file), match[1] ?? match[2] ?? ""));
+ if (match[1] !== undefined) stack.push(target);
+ else if (!covered(target)) outside.push(`${target} (read by ${file})`);
+ }
+ }
+ expect(seen.size).toBeGreaterThan(5);
+ expect(outside).toEqual([]);
+ });
+
it("uses one fail-closed scope decision before expensive CI and native jobs", () => {
const ci = workflow("ci.yml");
const scope = ci.job("scope");
@@ -747,7 +778,7 @@ describe("CI pipeline structure", () => {
// Scope reads only scripts/ and the kit.json files: a full blob-less checkout fetched every
// HEAD blob (488 MB) and outlasted the 5-minute bound on a loaded runner (runs 41688746026, 41702153229).
expect(scope.steps[0]?.with["sparse-checkout"]).toBe(
- "scripts\npackages/create-threenative/templates\n",
+ "scripts\npackages/create-threenative/templates\npackages/runtime-native/scripts\n",
);
const full = "needs.scope.outputs.selection == 'full'";
@@ -2232,7 +2263,8 @@ describe("CI pipeline structure", () => {
// is what let a promotion PR, a manual dispatch and a main CI completion hold the pool at
// once. `native-release-proof.spec.ts` owns the setting; this is the structural backstop.
expect(native).toContain("&& 'native-release-proof' ||");
- expect(native).toContain("cancel-in-progress: false");
+ // PRD-903: only a new commit on the proving pull request cancels; a tag run never does.
+ expect(native).toContain("github.event.action == 'synchronize' }}");
const triggers = triggerSection(native);
// PRD-630: the promotion PR holds the one proof, and `pnpm release:ship` dispatches the tag run.
expect(triggers).not.toContain("workflow_run:");
@@ -2255,8 +2287,11 @@ describe("CI pipeline structure", () => {
expect(groups).toEqual([
"${{ github.ref_type == 'tag' && 'native-release-tag' || (github.event_name != 'pull_request' || github.event.pull_request.base.ref == 'main' || contains(github.event.pull_request.labels.*.name, 'release-proof')) && 'native-release-proof' || format('native-release-skip-{0}', github.run_id) }}",
]);
- // `false`, not a conditional: a superseded run still lets its queued consumer finish.
- expect(concurrency).toContain("cancel-in-progress: false");
+ // PRD-903: only a new commit on a proving pull request cancels its superseded proof; a tag
+ // run, a dispatch and a label event never do.
+ expect(concurrency).toContain(
+ "cancel-in-progress: ${{ github.event_name == 'pull_request' && github.event.action == 'synchronize' }}",
+ );
});
it("reruns only a failed CI run's failed jobs, once, and only for known flakes", async () => {
diff --git a/scripts/__tests__/gh.spec.ts b/scripts/__tests__/gh.spec.ts
index 439eece497..5759d35d8c 100644
--- a/scripts/__tests__/gh.spec.ts
+++ b/scripts/__tests__/gh.spec.ts
@@ -13,7 +13,7 @@ interface IFakeGh {
}
/** Puts a `gh` on PATH that fails `failures` times, then answers `answer`. */
-function fakeGh(failures: number, answer = "ok\n"): IFakeGh {
+function fakeGh(failures: number, answer = "ok\n", error = "gh: server error"): IFakeGh {
const root = makeTempDirSync("tn-gh-");
const bin = path.join(root, "bin");
mkdirSync(bin, { recursive: true });
@@ -28,7 +28,7 @@ function fakeGh(failures: number, answer = "ok\n"): IFakeGh {
"count=$((count + 1))",
`echo "$count" > "${counter}"`,
`if [ "$count" -le ${String(failures)} ]; then`,
- " echo 'gh: server error' >&2",
+ ` echo '${error}' >&2`,
" exit 1",
"fi",
`printf '%b' '${answer.replace(/\n/gu, "\\n")}'`,
@@ -51,8 +51,8 @@ afterEach(() => {
for (const fake of fakes.splice(0)) fake.restore();
});
-function withFake(failures: number, answer?: string): IFakeGh {
- const fake = fakeGh(failures, answer);
+function withFake(failures: number, answer?: string, error?: string): IFakeGh {
+ const fake = fakeGh(failures, answer, error);
fakes.push(fake);
return fake;
}
@@ -73,9 +73,22 @@ describe("the gh wrapper", () => {
it("should throw with gh's own stderr when a read keeps failing", () => {
const fake = withFake(9);
expect(() => gh(["run", "view", "7"])).toThrow(
- /gh run view failed after 2 attempt\(s\): gh: server error/u,
+ /gh run view failed after 3 attempt\(s\): gh: server error/u,
);
- expect(fake.calls()).toBe(2);
+ expect(fake.calls()).toBe(3);
+ });
+
+ // PRD-903: one 502 on the 0.3.19 main push threw away a whole-tree reuse and ran a 55-minute board.
+ it("should outlast two transient 5xx answers on an api read", () => {
+ const fake = withFake(2, "{}\n", "gh: Server Error (HTTP 502)");
+ expect(gh(["api", "repos/a/b/actions/runs/1"])).toBe("{}\n");
+ expect(fake.calls()).toBe(3);
+ });
+
+ it("should not retry a 4xx answer, which is final", () => {
+ const fake = withFake(9, "{}\n", "gh: Not Found (HTTP 404)");
+ expect(() => gh(["api", "repos/a/b/actions/runs/1"])).toThrow(/after 1 attempt\(s\)/u);
+ expect(fake.calls()).toBe(1);
});
it("should never retry a call that changes state", () => {
diff --git a/scripts/__tests__/native-release-proof.spec.ts b/scripts/__tests__/native-release-proof.spec.ts
index 2195633470..b618706385 100644
--- a/scripts/__tests__/native-release-proof.spec.ts
+++ b/scripts/__tests__/native-release-proof.spec.ts
@@ -626,7 +626,12 @@ test("at most one release proof holds runners at a time, across branches", () =>
settings,
/^\x20{2}group: \$\{\{ github\.ref_type == 'tag' && 'native-release-tag' \|\| \(.*\) && 'native-release-proof' \|\| format\('native-release-skip-\{0\}', github\.run_id\) \}\}$/mu,
);
- assert.match(settings, /^\x20{2}cancel-in-progress: false$/mu);
+ // PRD-903: only a new commit on the proving pull request cancels; a tag, a dispatch and a label
+ // never do.
+ assert.match(
+ settings,
+ /^\x20{2}cancel-in-progress: \$\{\{ github\.event_name == 'pull_request' && github\.event\.action == 'synchronize' \}\}$/mu,
+ );
});
// PRD-630: the tag run republishes what the promotion proof built and installed.
diff --git a/scripts/__tests__/release-candidate-gate.spec.ts b/scripts/__tests__/release-candidate-gate.spec.ts
index e7ff724a96..2c4b951f95 100644
--- a/scripts/__tests__/release-candidate-gate.spec.ts
+++ b/scripts/__tests__/release-candidate-gate.spec.ts
@@ -14,6 +14,7 @@ import {
type IReleaseRun,
REQUIRED_CREDENTIALS,
REQUIRED_HOSTED_CAPABILITIES,
+ buildOnFirstHash,
expectedGithubSubjects,
expectedReleasePackages,
expectedReleaseReportReference,
@@ -743,3 +744,17 @@ describe("PRD-373 promotion is not release provenance", () => {
expect(verdict.errors.join("\n")).toMatch(/push|main|headSha|candidate/u);
});
});
+
+// PRD-903: a fresh cohort is all `absent`, so the 2.5-minute workspace build ran for nothing.
+describe("the workspace build behind a published-bytes comparison", () => {
+ it("builds once, and only when a package npm already serves is compared", () => {
+ const build = vi.fn();
+ const hash = vi.fn((name: string, version: string) => `${name}@${version}`);
+ const lazy = buildOnFirstHash(build, hash);
+ expect(build).not.toHaveBeenCalled();
+ expect(lazy("a", "1.0.0")).toBe("a@1.0.0");
+ expect(lazy("b", "1.0.0")).toBe("b@1.0.0");
+ expect(build).toHaveBeenCalledTimes(1);
+ expect(build.mock.invocationCallOrder[0]).toBeLessThan(hash.mock.invocationCallOrder[0] ?? 0);
+ });
+});
diff --git a/scripts/__tests__/release-ship.spec.ts b/scripts/__tests__/release-ship.spec.ts
index 57d0364d03..0152101ed5 100644
--- a/scripts/__tests__/release-ship.spec.ts
+++ b/scripts/__tests__/release-ship.spec.ts
@@ -10,6 +10,7 @@ import {
checkReleaseVersion,
nextStep,
parseNpmVersions,
+ pollInterval,
runShip,
ship,
} from "../release-ship.js";
@@ -617,3 +618,14 @@ function stateOf(
tagRun: "none",
};
}
+
+// PRD-903: a flat 60 s poll lost about half a minute per wait; a long wait still respects the
+// GITHUB_TOKEN's 1,000 calls an hour.
+describe("the ship's poll interval", () => {
+ it("polls every 15 s for ten minutes, then once a minute", () => {
+ expect(pollInterval(0)).toBe(15_000);
+ expect(pollInterval(9 * 60_000)).toBe(15_000);
+ expect(pollInterval(10 * 60_000)).toBe(60_000);
+ expect(pollInterval(120 * 60_000)).toBe(60_000);
+ });
+});
diff --git a/scripts/__tests__/release.spec.ts b/scripts/__tests__/release.spec.ts
index 7ad90bb29c..2c051130f6 100644
--- a/scripts/__tests__/release.spec.ts
+++ b/scripts/__tests__/release.spec.ts
@@ -9,6 +9,7 @@ import { PROVE_ARGV } from "../release-ship.js";
import {
UPGRADE_PROOF_TEMPLATES,
assertCleanPackageTree,
+ builtByCaller,
installableOnRegistry,
packReleaseSet,
packedTarballName,
@@ -806,8 +807,27 @@ describe("provisionReleaseArtifacts", () => {
it("keeps a current web engine and still verifies the Gradle wrapper", async () => {
const { calls, steps: built } = steps(true);
- await provisionReleaseArtifacts("/repo", built);
+ expect(await provisionReleaseArtifacts("/repo", built)).toBe(false);
expect(calls.built).toBe(0);
expect(calls.wrapper).toHaveLength(1);
});
+
+ it("reports a rebuilt web engine, so a build made before it counts as stale", async () => {
+ expect(await provisionReleaseArtifacts("/repo", steps(false).steps)).toBe(true);
+ });
+});
+
+// PRD-903: the ship built the same commit four times; the caller now builds it once.
+describe("builtByCaller", () => {
+ const head = "a".repeat(40);
+ it("skips the release build only for the exact HEAD the caller built", () => {
+ expect(builtByCaller({ TN_RELEASE_PREBUILT: head }, head, false)).toBe(true);
+ expect(builtByCaller({ TN_RELEASE_PREBUILT: "b".repeat(40) }, head, false)).toBe(false);
+ expect(builtByCaller({}, head, false)).toBe(false);
+ expect(builtByCaller({ TN_RELEASE_PREBUILT: "" }, "", false)).toBe(false);
+ });
+
+ it("builds again when provisioning rebuilt the web engine after the caller's build", () => {
+ expect(builtByCaller({ TN_RELEASE_PREBUILT: head }, head, true)).toBe(false);
+ });
});
diff --git a/scripts/__tests__/run-test-suite.spec.ts b/scripts/__tests__/run-test-suite.spec.ts
index c30fa05520..e6f90f376e 100644
--- a/scripts/__tests__/run-test-suite.spec.ts
+++ b/scripts/__tests__/run-test-suite.spec.ts
@@ -109,6 +109,17 @@ describe("run-test-suite phase contract", () => {
expect(source, "assets has no pure prebuilt check").toContain("@threenative/assets");
expect(source, "ueformat has no pure prebuilt check").toContain("@threenative/ueformat");
expect(source, "raw-unreal has no pure prebuilt check").toContain("@threenative/raw-unreal");
+ // PRD-903: the unit phase owns every root-config spec, so the prebuilt walk runs none again.
+ const prebuiltWalk = source
+ .slice(
+ source.indexOf("run_prebuilt_package_tests() {"),
+ source.indexOf("\n}\n", source.indexOf("run_prebuilt_package_tests() {")),
+ )
+ .split("\n")
+ .filter((line) => !/^\s*#/u.test(line))
+ .join("\n");
+ expect(prebuiltWalk).toContain("publint --strict");
+ expect(prebuiltWalk, "the prebuilt walk re-runs unit specs").not.toMatch(/vitest/u);
});
it("fails a prebuilt browser run before invoking Playwright without its verified inputs", () => {
diff --git a/scripts/ci-change-scope.mjs b/scripts/ci-change-scope.mjs
index 01d54f73e0..3ea1a48ab1 100644
--- a/scripts/ci-change-scope.mjs
+++ b/scripts/ci-change-scope.mjs
@@ -21,6 +21,7 @@ import {
SHA,
carryDeps,
git,
+ lastGreenDevelopHead,
promotionOnHead,
reuseEligible,
reuseOrKeep,
@@ -398,7 +399,9 @@ export function validateEventPlan(value, { eventName, baseRef, forceFull = false
);
// PRD-776: a develop push may leave the board to its promotion pull request. `ci-required` confirms
// that pull request from the commit itself.
- const yielded = event === "push" && target === "develop" && plan.selection === "warm";
+ // PRD-903: or, when it changed only prose since the last green develop head, run no gate at all.
+ const yielded =
+ event === "push" && target === "develop" && ["warm", "prose"].includes(plan.selection);
// PRD-630: a main push may rest on its promotion board. `ci-required` re-decides that rule.
const promoted = event === "push" && target === "main" && plan.selection === "reused";
if ((!review && !queue && !yielded && !promoted) || forceFull) {
@@ -536,6 +539,39 @@ function changedPaths(options) {
return parsed;
}
+/**
+ * The workspace-dist cache key hashes these trees, so a Markdown file under them still changes the
+ * key every pull request into develop restores: such a push keeps its board to publish the entry.
+ */
+const CACHE_KEY_TREE = /^(?:packages|scripts|patches|\.github)\//u;
+
+/**
+ * PRD-903. A develop push that changes only prose since the last green develop push runs no gate:
+ * a one-line PRD edit burned 74 wall minutes and 460 machine minutes (run 44887725075). Docs are
+ * re-validated by the develop nightly and at promotion, exactly as for a Markdown-only pull request.
+ */
+export function proseSinceGreenDevelop(options, candidateSha) {
+ const base = lastGreenDevelopHead();
+ if (base === undefined) return undefined;
+ if (git(options.root, ["merge-base", "--is-ancestor", base, candidateSha]).status !== 0)
+ return undefined;
+ const parsed = changedPaths({ ...options, base, head: candidateSha });
+ if ("error" in parsed) return undefined;
+ if (
+ !parsed.paths.every((file) => pathFamily(file, true) === "prose" && !CACHE_KEY_TREE.test(file))
+ )
+ return undefined;
+ return selectionPlan(
+ "prose",
+ `all ${String(parsed.paths.length)} path(s) since the green develop head ${base.slice(0, 12)} are prose outside the cache keys`,
+ parsed.paths,
+ candidateSha,
+ false,
+ 0,
+ options.target,
+ );
+}
+
export function classify(input) {
const options = { ...input, target: input.target?.replace(/^refs\/heads\//u, "") };
const candidateSha =
@@ -585,6 +621,8 @@ export function classify(input) {
0,
target,
);
+ const prose = options.local ? undefined : proseSinceGreenDevelop(options, candidateSha);
+ if (prose !== undefined) return prose;
return full("a develop push qualifies the exact tree with the full board");
}
// Every event except a pull request and a merge group stays full, and so does every target but
diff --git a/scripts/ci-required.mjs b/scripts/ci-required.mjs
index 90bce29795..0a5faa02c2 100644
--- a/scripts/ci-required.mjs
+++ b/scripts/ci-required.mjs
@@ -11,6 +11,7 @@ import {
owedPlan,
promotionOwnsCommit,
promotionReuse,
+ proseSinceGreenDevelop,
queueHeadReuse,
selectionPlan,
sourceVerdict,
@@ -68,6 +69,15 @@ try {
throw new Error(
`CI_REQUIRED_PROMOTION_MISSING: ${plan.candidateSha} skipped the board for a promotion pull request it does not belong to`,
);
+ // PRD-903: a prose-only develop push ran no gate, so the verdict re-derives that diff itself.
+ if (
+ process.env.TN_CI_EVENT === "push" &&
+ plan.selection === "prose" &&
+ proseSinceGreenDevelop({ root: process.cwd() }, plan.candidateSha) === undefined
+ )
+ throw new Error(
+ `CI_REQUIRED_PROSE_UNPROVEN: ${plan.candidateSha} skipped the board, but its diff from the last green develop head is not prose-only`,
+ );
if (process.env.TN_CI_EVENT === "pull_request") {
// The candidate is frozen by the exact base/head parent assertion below, not by the head
// branch's name. A `promotion/` ref restated a SHA that check already verifies.
diff --git a/scripts/ci/reuse.mjs b/scripts/ci/reuse.mjs
index dac0505913..6e5b4c4626 100644
--- a/scripts/ci/reuse.mjs
+++ b/scripts/ci/reuse.mjs
@@ -7,6 +7,7 @@
import { spawnSync } from "node:child_process";
import { classify, pathFamily, selectionPlan } from "../ci-change-scope.mjs";
import { RELEASE_GATE_JOBS, applyCarried, findCarried } from "../ci-leg-carry.mjs";
+import { gh } from "../lib/gh.mjs";
// PRD-481. Reuse replaces a full board only, and only for a tree a successful CI run already
// tested. `workflow_dispatch` is the explicit audit a person asked for, so it stays full; the
@@ -64,17 +65,21 @@ function ghApi(pathname) {
return { error: "GITHUB_REPOSITORY is missing or malformed" };
}
// `gh` rather than fetch: it is already on every runner, it reads GH_TOKEN from the job's own
- // `github.token`, and one stubbed binary is one thing to assert against.
- const result = spawnSync("gh", ["api", `repos/${repository}/${pathname}`], {
- encoding: "utf8",
- maxBuffer: 1024 * 1024 * 16,
- });
- if (result.error !== undefined || result.status !== 0) {
- const detail = (result.stderr ?? "").trim().split("\n")[0] ?? "";
- return { error: `the Actions API was unreadable${detail === "" ? "" : `: ${detail}`}` };
+ // `github.token`, and one stubbed binary is one thing to assert against. The shared wrapper
+ // retries a transient 5xx with a backoff (PRD-903).
+ let stdout;
+ try {
+ stdout = gh(["api", `repos/${repository}/${pathname}`]);
+ } catch (error) {
+ const detail = String(error?.message ?? "").replace(
+ /^gh api failed after \d+ attempt\(s\): /u,
+ "",
+ );
+ const first = detail.trim().split("\n")[0] ?? "";
+ return { error: `the Actions API was unreadable${first === "" ? "" : `: ${first}`}` };
}
try {
- return { value: JSON.parse(result.stdout) };
+ return { value: JSON.parse(stdout) };
} catch {
return { error: "the Actions API answered with malformed JSON" };
}
@@ -120,6 +125,27 @@ export function promotionOnHead(candidateSha) {
: undefined;
}
+/**
+ * PRD-903. The head of the newest green develop push run, the tree a prose-only push builds on. A
+ * newer pending run replaces an older one in the develop concurrency group, so the parent commit
+ * may never have run: the base is the last head that did. A green prose run is itself prose on top
+ * of such a head, so the chain always ends at a qualified tree. Anything unreadable is no base.
+ */
+export function lastGreenDevelopHead() {
+ const listed = ghApi(
+ "actions/workflows/ci.yml/runs?event=push&branch=develop&status=success&per_page=5",
+ );
+ if ("error" in listed || !Array.isArray(listed.value?.workflow_runs)) return undefined;
+ const run = listed.value.workflow_runs.find(
+ (row) =>
+ row?.event === "push" &&
+ row?.head_branch === "develop" &&
+ row?.conclusion === "success" &&
+ String(row?.id) !== process.env.GITHUB_RUN_ID,
+ );
+ return /^[0-9a-f]{40}$/u.test(run?.head_sha ?? "") ? run.head_sha : undefined;
+}
+
/**
* The verdict's own read, independent of the plan. It runs after the scope job, when the pull request
* may already have moved on or merged, so it asks what the commit belongs to, not what is open now.
diff --git a/scripts/lib/gh.mjs b/scripts/lib/gh.mjs
index 5b7ff98244..e29e0cfaf1 100644
--- a/scripts/lib/gh.mjs
+++ b/scripts/lib/gh.mjs
@@ -1,8 +1,9 @@
// One `gh` call for the CI scripts, because four of them each had their own rule: one threw on a
// non-zero exit, one only looked at stdout, one trimmed and one did not, and a failed query could
-// read as an empty answer. A read is retried once — GitHub answers 5xx under load, and a lane that
-// dies on that is a red nobody can act on — while a call that changes state never is: a retry can
-// apply it twice.
+// read as an empty answer. A read is retried twice with a backoff — GitHub answers 5xx under load,
+// and one HTTP 502 turned the 0.3.19 main push from a 1-minute reuse into a 55-minute board
+// (PRD-903) — while a call that changes state never is: a retry can apply it twice. A 4xx answer is
+// final, so it is not retried.
import { execFileSync } from "node:child_process";
/** Board and log queries return megabytes of JSON; the default 1 MB buffer truncates them. */
@@ -61,22 +62,38 @@ function label(args) {
return `gh ${args.slice(0, 2).join(" ")}`;
}
+/** A synchronous pause: every caller of this wrapper is synchronous. */
+function sleep(ms) {
+ if (ms > 0) Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
+}
+
+/** The first wait between read attempts; `TN_GH_RETRY_DELAY_MS=0` makes specs instant. */
+function retryDelayMs() {
+ const raw = Number(process.env.TN_GH_RETRY_DELAY_MS);
+ return Number.isFinite(raw) && raw >= 0 ? raw : 2000;
+}
+
/**
* Runs `gh` and returns its stdout, or throws with `gh`'s own stderr.
*
* @param {readonly string[]} args
- * @param {{ readonly retries?: number }} [options] `retries` defaults to 1 for a read, 0 for a write.
+ * @param {{ readonly retries?: number }} [options] `retries` defaults to 2 for a read, 0 for a write.
* @returns {string}
*/
export function gh(args, options = {}) {
- const retries = options.retries ?? (isRepeatableRead(args) ? 1 : 0);
+ const retries = options.retries ?? (isRepeatableRead(args) ? 2 : 0);
let last = "";
+ let attempts = 0;
for (let attempt = 0; attempt <= retries; attempt += 1) {
+ if (attempt > 0) sleep(retryDelayMs() * 3 ** (attempt - 1));
+ attempts += 1;
try {
return execFileSync("gh", args, { encoding: "utf8", maxBuffer: MAX_BUFFER });
} catch (error) {
last = String(error?.stderr ?? "").trim() || (error instanceof Error ? error.message : "");
+ // A 4xx is the server's final answer (missing run, no permission): asking again changes nothing.
+ if (/\bHTTP 4\d\d\b/u.test(last)) break;
}
}
- throw new Error(`${label(args)} failed after ${String(retries + 1)} attempt(s): ${last}`);
+ throw new Error(`${label(args)} failed after ${String(attempts)} attempt(s): ${last}`);
}
diff --git a/scripts/release-candidate-gate.ts b/scripts/release-candidate-gate.ts
index 434ebccb27..d1e3e59020 100644
--- a/scripts/release-candidate-gate.ts
+++ b/scripts/release-candidate-gate.ts
@@ -2030,6 +2030,25 @@ async function observeReleasePackage(
return packageEntry;
}
+/**
+ * PRD-903. Only a package npm already serves (`matching`, a resumed release) is compared with the
+ * workspace bytes, so the workspace is built on the first such package instead of before every
+ * candidate: a fresh cohort is all `absent` and spent 2.5 minutes on a build nothing read.
+ */
+export function buildOnFirstHash(
+ build: () => void,
+ hash: (packageName: string, version: string) => string,
+): (packageName: string, version: string) => string {
+ let built = false;
+ return (packageName, version) => {
+ if (!built) {
+ build();
+ built = true;
+ }
+ return hash(packageName, version);
+ };
+}
+
async function resolvePackageCohort(
repo: string,
options: IReleaseCandidateResolutionOptions,
@@ -2037,8 +2056,10 @@ async function resolvePackageCohort(
const registryLookup = options.registryLookup ?? registryPackageObservation;
const localPackageHash =
options.workspacePackageHash ??
- ((packageName: string, version: string) =>
- workspacePackageTreeHash(repo, packageName, version));
+ buildOnFirstHash(
+ () => void execFileSync("pnpm", ["build"], { cwd: repo, stdio: "inherit" }),
+ (packageName, version) => workspacePackageTreeHash(repo, packageName, version),
+ );
const packages: IReleasePackage[] = [];
for (const expectedPackage of expectedReleasePackages(repo))
packages.push(await observeReleasePackage(expectedPackage, registryLookup, localPackageHash));
diff --git a/scripts/release-ship.ts b/scripts/release-ship.ts
index 3231baae6f..a4ba309698 100644
--- a/scripts/release-ship.ts
+++ b/scripts/release-ship.ts
@@ -452,18 +452,28 @@ function describeStep(
}
}
+/**
+ * PRD-903. A flat 60 s poll lost about half a minute on each of the ship's three waits. The job's
+ * `GITHUB_TOKEN` allows 1,000 API calls an hour and one state read makes about six, so the poll is
+ * fast only while a short wait is likely, then falls back to once a minute for a long tag run.
+ */
+export function pollInterval(elapsedMs: number): number {
+ return elapsedMs < 10 * 60_000 ? 15_000 : 60_000;
+}
+
async function waitFor(
deps: IShipDeps,
what: string,
done: () => boolean,
timeoutMinutes: number,
): Promise {
- const deadline = Date.now() + timeoutMinutes * 60_000;
+ const started = Date.now();
+ const deadline = started + timeoutMinutes * 60_000;
while (!done()) {
if (Date.now() > deadline)
throw new Error(`TN_SHIP_TIMEOUT: ${what} did not finish in ${timeoutMinutes} minutes.`);
deps.log(` waiting for ${what}…`);
- await deps.sleep(60_000);
+ await deps.sleep(pollInterval(Date.now() - started));
}
}
diff --git a/scripts/release.ts b/scripts/release.ts
index 71bc4d45f1..62cbf70079 100644
--- a/scripts/release.ts
+++ b/scripts/release.ts
@@ -397,16 +397,33 @@ async function defaultArtifactSteps(): Promise {
* error, and the publish preflight then refused every release prep from a clean worktree until
* someone built them by hand. The engine rebuilds only when absent or stale.
*/
+/** Returns true when it rebuilt the web engine, which a build made before this call never saw. */
export async function provisionReleaseArtifacts(
repo = REPO,
steps?: IReleaseArtifactSteps,
-): Promise {
+): Promise {
const resolved = steps ?? (await defaultArtifactSteps());
const runtimeRoot = path.join(repo, "packages", "runtime-native");
- if (!resolved.webEngineCurrent(runtimeRoot)) resolved.buildWebEngine();
+ const rebuilt = !resolved.webEngineCurrent(runtimeRoot);
+ if (rebuilt) resolved.buildWebEngine();
await resolved.ensureGradleWrapper(
path.join(runtimeRoot, "android", "gradle", "wrapper", "gradle-wrapper.jar"),
);
+ return rebuilt;
+}
+
+/**
+ * PRD-903. `npm-release.yml` builds the commit once and names it in `TN_RELEASE_PREBUILT`, so the
+ * proof run and the publish run of `release:ship` do not each build the same tree again (2.5
+ * minutes apiece). Only an exact HEAD match counts, and a web engine rebuilt after that build
+ * means the build is stale.
+ */
+export function builtByCaller(
+ env: NodeJS.ProcessEnv,
+ head: string,
+ provisionRebuilt: boolean,
+): boolean {
+ return !provisionRebuilt && /^[0-9a-f]{40}$/u.test(head) && env.TN_RELEASE_PREBUILT === head;
}
function runConcurrently(command: string, args: readonly string[], label: string): Promise {
@@ -687,7 +704,7 @@ async function main(args: readonly string[]): Promise {
// after the publish. There is no way to tell, later, which source a published tarball was.
// A proof is a claim about HEAD's bytes: prove from a committed tree, exactly as a publish does.
if (publish || proveUpgrade) assertCleanPackageTree(REPO);
- await provisionReleaseArtifacts(REPO);
+ const provisionRebuilt = await provisionReleaseArtifacts(REPO);
const packages = publishSet(REPO);
const cohort = validateReleaseCohort(REPO, packages);
@@ -727,12 +744,18 @@ async function main(args: readonly string[]): Promise {
run("pnpm", ["lint"], { code: "TN_RELEASE_STEP_FAILED", cwd: REPO, label: "pnpm lint" });
run("pnpm", ["test"], { code: "TN_RELEASE_STEP_FAILED", cwd: REPO, label: "pnpm test" });
}
- run("pnpm", ["build"], {
- code: "TN_RELEASE_STEP_FAILED",
- cwd: REPO,
- detail: "Nothing further was published.",
- label: "pnpm build",
- });
+ const head = execFileSync("git", ["rev-parse", "HEAD"], { cwd: REPO, encoding: "utf8" }).trim();
+ if (builtByCaller(process.env, head, provisionRebuilt))
+ process.stdout.write(
+ `\nSkipping pnpm build: TN_RELEASE_PREBUILT names HEAD ${head}, which the caller built.\n`,
+ );
+ else
+ run("pnpm", ["build"], {
+ code: "TN_RELEASE_STEP_FAILED",
+ cwd: REPO,
+ detail: "Nothing further was published.",
+ label: "pnpm build",
+ });
// Assemble the native payload before any npm publish: a declared key with no staged binary must
// refuse the whole release while nothing irreversible has happened, not after the cohort is up.
diff --git a/scripts/run-test-suite.sh b/scripts/run-test-suite.sh
index 01eea87ac1..aec61074da 100755
--- a/scripts/run-test-suite.sh
+++ b/scripts/run-test-suite.sh
@@ -222,11 +222,18 @@ if [[ "$suite_prebuilt" -eq 1 ]]; then
# These package test scripts deliberately rebuild outputs for standalone developers. The build
# phase already produced them here, so CI runs their pure checks below instead of hiding a second
# build behind the recursive test walk.
+ # PRD-903: the rest also re-run, under the root vitest config, spec files that the `unit` phase
+ # (CI: the `test-unit` shards) already runs; `packages/terrain` alone was 271 s of the job.
for tn_prebuilt_package in \
@threenative/assets \
@threenative/ueformat \
@threenative/raw-unreal \
- @threenative/metahuman; do
+ @threenative/metahuman \
+ @threenative/terrain \
+ @threenative/procedural-environment \
+ @threenative/procedural-animals \
+ @threenative/blender-bridge \
+ strata-terrain-preview; do
package_test_command+=(--filter "!$tn_prebuilt_package")
done
fi
@@ -257,13 +264,15 @@ run_prebuilt_package_tests() {
verify_prebuilt_outputs || return $?
"${package_test_command[@]}" || return $?
- pnpm --filter @threenative/assets exec publint --strict || return $?
- pnpm --filter @threenative/ueformat exec vitest run --root ../.. ueformat/__tests__ || return $?
- pnpm --filter @threenative/ueformat exec publint --strict || return $?
- pnpm --filter @threenative/raw-unreal exec vitest run --root ../.. raw-unreal/__tests__ || return $?
- pnpm --filter @threenative/raw-unreal exec publint --strict || return $?
- pnpm --filter @threenative/metahuman exec vitest run --root ../.. metahuman/__tests__ || return $?
- pnpm --filter @threenative/metahuman exec publint --strict || return $?
+ # Their spec files belong to the root vitest config, which the `unit` phase runs (CI: the
+ # `test-unit` shards, which `ci-structure.spec.ts` holds to the same partition), so only the
+ # checks that config cannot make run here.
+ for tn_prebuilt_package in assets ueformat raw-unreal metahuman terrain procedural-environment \
+ procedural-animals blender-bridge; do
+ pnpm --filter "@threenative/$tn_prebuilt_package" exec publint --strict || return $?
+ done
+ pnpm --filter strata-terrain-preview bake || return $?
+ pnpm --filter strata-terrain-preview test:water || return $?
}
diff --git a/vitest.config.ts b/vitest.config.ts
index 3880014878..babcca6ab7 100644
--- a/vitest.config.ts
+++ b/vitest.config.ts
@@ -37,6 +37,9 @@ export default defineConfig({
],
test: {
environment: "node",
+ // `scripts/lib/gh.mjs` backs off between read retries in real time; a spec with a failing fake
+ // `gh` proves the attempt count, not the wait.
+ env: { TN_GH_RETRY_DELAY_MS: "0" },
include: [
"scripts/**/*.spec.ts",
"examples/strata-terrain-preview/__tests__/**/*.spec.ts",
From 6e4289d1ff0beee82d838205bf78b5446a8dd0b7 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Jo=C3=A3o=20Paulo=20Furtado?=
<30300459+jonit-dev@users.noreply.github.com>
Date: Sun, 22 Nov 2026 05:19:35 +0000
Subject: [PATCH 2/3] threenative login and deploy: publish from the terminal
like Studio's Publish button (PRD-904) (#712)
* docs(prd): PRD-904 tn login and tn deploy delegate to the store CLI's device flow and push
* docs(create-threenative): drop the two-commands-ever rule; new commands borrow established CLI names (owner, 2026-11-21)
* docs(prd): PRD-904 deploy matches Studio's Publish share link; login is the site device flow in TypeScript
* docs(prd): PRD-904 folds in the Gemini review: logout revokes, terms rule on CLI tokens, .threenative/ link, device page keeps the code
* docs(prd): PRD-904 records the tokenAccount and terms-on-approve decisions
* feat(create-threenative): threenative login, logout and deploy publish to the Studio share link (PRD-904)
login runs the threenative.com device flow and saves a 0600 token (THREENATIVE_TOKEN overrides);
logout revokes it on the site; deploy runs build:web, packs dist/ in Studio's share archive format,
PUTs it to Studio's /api/cli/share and keeps the link in .threenative/share.json.
* docs(prd): PRD-904 AC-1, AC-5 and AC-6 pass on the local site and Studio Workers
* fix(create-threenative): logout keeps a token it could not revoke; atomic 0600 token write; a dropped body exits 5 (PRD-904 Sol review)
* fix(create-threenative): unique temp token file, accurate logout help, first deploy carries a key so a lost reply retries onto one game (PRD-904 Sol re-review)
* docs(prd): PRD-904 AC-6 reruns green after the Sol review fixes
* fix(create-threenative): share.json is written through a temp file and renamed, so an interrupted write cannot lose the deploy key (PRD-904 Sol review 3)
* fix(create-threenative): two first deploys from one checkout claim one deploy key through an atomic link (PRD-904 Sol review 4)
* fix(create-threenative): logout deletes the token file only while it still holds the revoked token (PRD-904 Sol review 8)
* fix(create-threenative): logout claims the token file with one rename and login writes it once, so neither loses or revives the other's token (PRD-904 Sol review 9)
* fix(create-threenative): logout keeps an unrevoked or interrupted token in its claimed file and retries it next time; an empty whoami reply still saves the token (PRD-904 Sol review 10)
* fix(create-threenative): logout revokes on the issuing site and keeps a file it cannot read; empty replies exit 4; the deploy key claim works without hard links (PRD-904 Sol review 11)
* fix(create-threenative): a half-made share.json is waited for or removed, and logout claims auth.json in a directory it cannot list (PRD-904 Sol review 12)
* fix(create-threenative): logout exits 4 when it cannot list the config directory and has nothing to claim, instead of saying signed out (PRD-904 Sol review 13)
* docs(prd): PRD-904 records the Sol 6.2 approval and the final local end-to-end
* docs(create-threenative): the CLI surface paragraph fits the 100-line instruction cap (PRD-904 merge-queue red)
---
...in-and-deploy-publish-like-studio-share.md | 124 ++++++
packages/create-threenative/AGENTS.md | 12 +-
packages/create-threenative/CLAUDE.md | 12 +-
.../create-threenative/__tests__/cli.spec.ts | 2 +-
.../__tests__/deploy-nolink.spec.ts | 46 ++
.../__tests__/deploy.spec.ts | 318 +++++++++++++
.../__tests__/login.spec.ts | 421 ++++++++++++++++++
packages/create-threenative/src/account.ts | 351 +++++++++++++++
packages/create-threenative/src/commands.ts | 19 +-
packages/create-threenative/src/deploy.ts | 241 ++++++++++
.../create-threenative/src/threenative.ts | 84 +++-
11 files changed, 1605 insertions(+), 25 deletions(-)
create mode 100644 docs/PRDs/tooling/PRD-904-threenative-login-and-deploy-publish-like-studio-share.md
create mode 100644 packages/create-threenative/__tests__/deploy-nolink.spec.ts
create mode 100644 packages/create-threenative/__tests__/deploy.spec.ts
create mode 100644 packages/create-threenative/__tests__/login.spec.ts
create mode 100644 packages/create-threenative/src/account.ts
create mode 100644 packages/create-threenative/src/deploy.ts
diff --git a/docs/PRDs/tooling/PRD-904-threenative-login-and-deploy-publish-like-studio-share.md b/docs/PRDs/tooling/PRD-904-threenative-login-and-deploy-publish-like-studio-share.md
new file mode 100644
index 0000000000..f766a27af7
--- /dev/null
+++ b/docs/PRDs/tooling/PRD-904-threenative-login-and-deploy-publish-like-studio-share.md
@@ -0,0 +1,124 @@
+---
+prd_contract: v1
+---
+
+# PRD-904 — `threenative login` and `threenative deploy`: publish from the terminal the way Studio's Publish button does
+
+**Status:** PARTIAL — phases 1 to 3 in progress
+**Priority:** P1 — AC-1 to AC-8 are open: a game built outside Studio has no command to sign in or put it online, so an agent stops at a local build.
+**Complexity:** 7 (HIGH) — 6-10 files (+2), new module (+2), crosses the engine/site/Studio release boundaries (+2), external API: the threenative.com and Studio Workers (+1); risk: an account credential on disk.
+**Owner:** João
+**Depends on:** None
+**Repo:** this repo (`packages/create-threenative`); `ThreeNativeHQ/threenative-site` (token check); `threenative-live-studio` (CLI share route)
+
+## Context
+
+Studio already publishes a game. The terminal must do the same thing, with the same account and the same result.
+
+**Studio's Publish today** (`threenative-live-studio`):
+
+1. The browser calls `POST /api/projects/:id/share` (`hosting/cloudflare/src/routes/games.ts:14-36`), with a Studio session cookie.
+2. The game's sandbox runs the `build:web` script (`src/server/routes/release.ts:47-77`). In every template that script is `threenative build --target web`. It then packs `dist/` with `packDirectory` (`src/server/release/shareArchive.ts`): per file a u32 path length, the path, a u32 size and the bytes. It skips `.br`/`.gz` twins, and the limits are 2 000 files and 50 MB.
+3. `publishShare` (`hosting/cloudflare/src/share.ts:133-200`) checks the archive, puts the files in R2 under `share//` and keeps one link per game. A new publish replaces the files behind the same address. A link nobody opens for 30 days expires (`shareRules.ts`).
+4. The answer is `{ shareUrl }`, an unlisted `https://-xxxx-share…` address (`origin.ts:77-81`).
+
+**Accounts:** the site Worker owns accounts. Studio signs a person in with a one-time code that it trades over the `StudioAccounts` service binding (`threenative-site/worker/studio-auth.ts:81`). The site already has a device-code login for command lines: `POST /api/store/device`, `/device/token`, `/device/approve`, and the `/account/device/?code=…` page (`worker/store-device.ts`, store PRD-808). It issues a scoped `api_tokens` row.
+
+**Engine:** `threenative` has `build` and `doctor` (`packages/create-threenative/src/commands.ts`). The "two commands, ever" rule was removed in `f9d168b00`.
+
+## Solution
+
+```mermaid
+sequenceDiagram
+ participant A as Agent or person
+ participant C as threenative CLI
+ participant W as threenative.com (site)
+ participant S as Studio Worker
+ A->>C: threenative login
+ C->>W: POST /api/store/device
+ C-->>A: opens /account/device/?code=ABCD-EFGH, prints the code too
+ A->>W: sign in, click Authorize
+ C->>W: poll /device/token -> token -> ~/.config/threenative/auth.json (0600)
+ A->>C: threenative deploy
+ C->>C: run build:web, pack dist/ (Studio's archive format)
+ C->>S: PUT /api/cli/share Bearer token, projectId from .threenative/share.json
+ S->>W: StudioAccounts.tokenAccount(token) over the service binding (verified email + current terms)
+ S->>S: find or create the project, publishShare
+ S-->>C: { projectId, shareUrl }
+ C-->>A: https://-xxxx-share.../ (same address on every later deploy)
+```
+
+- **`threenative login`:** the device flow, in TypeScript with `fetch` and no new dependency. It opens the link with the code filled in, prints the code for a browser on another machine, and polls at the interval the site states until the user clicks Authorize. It prints the account email. `threenative logout` revokes the token on the site (a new bearer `DELETE /api/store/token`; today revoke needs a browser session, `worker/store.ts:202`) and then deletes the file.
+- **Token:** `$XDG_CONFIG_HOME/threenative/auth.json` (default `~/.config`), mode `0600`, the same pattern as `gh` and `wrangler`. `THREENATIVE_TOKEN` overrides it for CI and Studio sandboxes.
+- **`threenative deploy`:** runs the project's `build:web` script, the same script Studio's sandbox runs. It packs `dist/` with a copy of Studio's `packDirectory`. It uploads to `PUT /api/cli/share` and writes `.threenative/share.json` `{ "projectId": "…" }` on the first deploy (Studio already keeps its store link in `.threenative/store.json`, `src/server/release/publish.ts:36`), so later deploys replace the same link. Exit codes match `tn-store`: 0 ok, 2 bad arguments, 3 sign in again, 4 refused, 5 network.
+- **Site:** `StudioAccounts.tokenAccount(token)` returns the same identity shape as `exchangeCode` for a live, unrevoked device-issued token, under the same rule as `exchangeCode`: verified email and current terms (`studio-auth.ts:42`). Studio therefore reuses its existing account adoption. The `/account/device` page names `threenative login` instead of `tn-store login`. An unverified or terms-pending account goes through the verify and terms steps and comes back to the same `?code=`.
+- **Studio:** one route, `PUT /api/cli/share`, with an archive body, `Authorization: Bearer`, and an optional `projectId` and `name`. It reuses `createProject` (quota included) and `publishShare` (all its checks), so the terminal and the button have one set of rules.
+
+Risks: the packer is copied, and the copy can drift from Studio's. `ponytail:` two copies of a 50-line format; the AC-6 e2e uploads the CLI's archive to Studio's real parser, so drift fails there. Move it to one shared package if a third writer appears. A token file on disk is a credential: it is created `0600`, and logout deletes it.
+
+## Non-Goals
+
+- Opening a CLI-deployed game's source in the Studio editor. The project row exists and shows its link, but deploy uploads the build, not the source.
+- Listing on the store (`tn-store push`, review, build farm). That path stays as it is.
+- Deploy targets other than the Studio share link (Netlify, Vercel, itch.io, desktop or Android builds).
+- A localhost callback login. It fails on remote machines and in containers, the reason the store dropped it (store PRD-808).
+
+## Acceptance Criteria
+
+- [x] AC-1 [local]: `threenative login` against local site `wrangler dev` opens `/account/device/?code=…`. After a scripted Authorize it writes a `0600` token file and prints the account email. proof: `pnpm exec vitest run packages/create-threenative/__tests__/login.spec.ts` (fake site) + the AC-6 run — Evidence: `login.spec.ts` passes; AC-6 run printed `/account/device/?code=C4LN-AN6B`, a curl Authorize returned `{"ok":true}`, login exited 0 with `Signed in as e2e@example.com.`, `auth.json` mode 600.
+- [x] AC-2 [local]: `threenative logout` revokes the token on the site, then deletes the file. `THREENATIVE_TOKEN` wins over the file, and a refused token exits 3 with "run threenative login". proof: `login.spec.ts` — Evidence: `login.spec.ts` logout and env cases pass; `deploy.spec.ts` 401 exits 3; site `DELETE /api/store/token` case passes in `worker/__tests__/store-device.spec.ts`.
+- [x] AC-3 [local]: `StudioAccounts.tokenAccount` returns the account for a live device-issued token and refuses a revoked, expired or unknown token, an unverified email and an account without current terms. proof: site `pnpm vitest --config vitest.worker.config.ts worker/__tests__/studio-auth.spec.ts` — Evidence: 13/13 in `studio-auth.spec.ts`, inside the 229/229 site worker run.
+- [x] AC-4 [local]: `PUT /api/cli/share` with a valid token creates a project and returns a share URL. A second call with that `projectId` keeps the same URL and serves the new build. No token gets 401; no `index.html` or over 50 MB gets Studio's refusal message. proof: Studio `hosting/cloudflare` vitest — Evidence: `test/cli-share.spec.ts` 9/9 (create, same URL with new bytes, 401, 422 no `index.html`, 403 suspended and closed beta, 404 foreign project, 502 site down); the 50 MB refusal is `publishShare`'s own, covered by `test/share.spec.ts` in the same 359/359 run.
+- [x] AC-5 [local]: `threenative deploy` runs `build:web`, packs `dist/` byte-for-byte like Studio's `packDirectory` on the same folder, uploads, writes `.threenative/share.json` once and prints the URL. proof: `pnpm exec vitest run packages/create-threenative/__tests__/deploy.spec.ts` — Evidence: `deploy.spec.ts` 5/5; in the AC-6 run the real `build:web` ran, and the engine and Studio `packDirectory` on the same 16 474 839-byte `dist/` gave the same sha256 `1645cccf…0462`.
+- [x] AC-6 [local]: A scaffolded starter, with the local `create-threenative` tarball, local site and Studio `wrangler dev`, runs `threenative login` (scripted Authorize) then `threenative deploy` twice. The share URL serves the game's `index.html` and stays the same across both deploys. The Studio games list shows the game with that link. proof: run log in the PR — Evidence: PR #712 comment. Starter scaffolded with the local `create-threenative-0.2.25.tgz`; two deploys printed the same `share-ac6-game-g226` link and kept `projectId 095e83ba…`; the link served `dist/index.html` (plus Studio's report link); Studio D1 lists `ac6-game` with that share id for `e2e@example.com`; logout revoked the token in site D1 and the next deploy exited 3. Rerun after the Sol review fixes (deploy key, device-only tokens, migration 0015): same results, `share.json` holds `projectId` and `deployKey`, the revoked token row shows `device=1 revoked=1`, and the config dir holds only `auth.json`.
+- [x] AC-8 [local]: On `/account/device/?code=…`, an unverified or terms-pending account completes verify and terms and returns to the same code, then Authorize succeeds. The page names `threenative login`. proof: site `e2e/worker/store-device.spec.ts` — Evidence: the two PRD-904 AC-8 cases pass (terms-pending accepts on `/signin/` and approves the same code; unverified lands on `/signin/` verify with the code in `next`).
+- [ ] AC-7 [shared]: After site, Studio and engine releases, a `pnpm sandbox` clean room runs `npx create-threenative` → `npx threenative login` → `npx threenative deploy` and opens the live share URL. proof: `pnpm sandbox` run log — Evidence: pending.
+
+## Blocked on
+
+- AC-7 needs the site and Studio routes deployed to production and an engine release — unblocked by João's go-ahead to deploy the site and Studio and ship the engine release.
+
+## Integration Ledger
+
+| Capability | Reachable consumer/trigger | Replaces / disposition | Evidence |
+| --- | --- | --- | --- |
+| Sign in from a terminal | `threenative login` → site device routes → token file | New consumer of the shipped device flow | AC-1, AC-2, AC-6 |
+| Studio trusts a CLI token | Studio `PUT /api/cli/share` → `StudioAccounts.tokenAccount` | New method beside `exchangeCode` | AC-3, AC-4 |
+| Publish from a terminal | `threenative deploy` → `build:web` → Studio `publishShare` → share host | Same `publishShare` as the Publish button; no second publish path | AC-4, AC-5, AC-6 |
+
+Fill the dispatcher and route `file:line` values when each phase lands.
+
+## Decisions
+
+- 2026-11-21 (João): use the `threenative` CLI as it is, with no `tn` alias. The "two commands, ever" rule is removed (`f9d168b00`).
+- 2026-11-21 (João): deploy is the same as Studio's Publish (the share link), not the store push.
+- 2026-11-21 (Sol 6.2 high, review 14): APPROVE across engine, site and Studio, after 13 rounds of fixes. The same commit (`118367b53`) passed the 25-check local end-to-end (login, two deploys on one link, served index.html and JS, lost-reply key retry, one game in Studio D1, archive parity, logout revoke, deploy after logout exits 3): 25/25. Engine CLI 31/31, site worker 231/231, Studio worker 413/413.
+- 2026-11-21 (Sol review 10): logout claims each token file with one rename before it revokes. A token the site did not revoke stays in its claimed `auth.json..logout` file, not in `auth.json`, and every later logout revokes those leftovers too. So a failed or interrupted logout leaves the machine signed out but keeps the live token for the retry, and a login in another terminal is never lost or revived.
+- 2026-11-21 (João): login UX: open a link, sign in with the threenative.com account, click Authorize, and the CLI detects it. The code is also accepted typed. The existing site device flow does exactly this.
+- 2026-11-21 (agent, after a Gemini 4 Neon review): the store push is not the deploy path. A new account's release is held for review (`worker/games.ts:631,649`), the build farm runs scans and an AI review, and a listing needs 1 to 5 screenshots. The share link is live in seconds.
+- 2026-11-21 (agent): the login is TypeScript in the engine, not a call to the private `tn-store` binary. Deploy no longer needs that binary, and the device flow is three `fetch` calls.
+- 2026-11-21 (agent, after the Sol 6.2 review): `tokenAccount` accepts only a token the device flow issued. Migration `0033_device_tokens.sql` adds `api_tokens.device`, because the daily sweep deletes the `device_codes` row that once linked them. A hand-minted store `push` token therefore cannot replace share links. It refuses a `full` or `publish_only` account ban, since a share link is publishing.
+- 2026-11-21 (agent, after the Sol 6.2 review): the daily sweep deleted every device-flow token with its 10-minute code, collected or not, so each CLI login died within a day (`tn-store login` too). It now deletes only uncollected tokens.
+- 2026-11-21 (agent, Sol 6.2 review finding 8, deferred): two overlapping publishes of one game can delete each other's new files inside `publishShare`. The Publish button has the same race today, so it gets its own follow-up and is not fixed in this PRD. The same follow-up owns the third review's orphaned R2 objects: when one R2 write fails after others succeed on a game's first publish, `publishShare` has not recorded the share id, so nothing sweeps those files. The Publish button leaves the same orphans. The follow-up also owns the eighth review's cap race: a first deploy passes the storage pre-check, another game on the account grows before `publishShare` checks again, and the 413 leaves an unpublished keyed game holding a slot. Taking that game back would reopen the fourth review's finding (an overlapping retry may be publishing into it), so the fix is one publish lease per game, shared with the Publish button.
+- 2026-11-21 (agent, implementation): `/api/store/device/approve` now refuses an account without the current terms (`TN_API_TERMS`), beside the existing unverified check. Without it, a terms-pending account would get a token that `tokenAccount` refuses on every deploy. This also applies to `tn-store login`, under the PRD-015 consent rule.
+
+## Execution Phases
+
+#### Phase 1: sign in and out
+**Status:** PARTIAL — phases 1 to 3 in progress
+**Files:** `packages/create-threenative/src/commands.ts`, `src/threenative.ts` (dispatch), `src/account.ts` (new: device flow, token file, `THREENATIVE_TOKEN`), `AGENTS.md` CLI surface. Site: `worker/store.ts` (bearer self-revoke), `src/components/sections/AccountDevice.tsx` and `AccountVerify.tsx` (copy, keep `?code=` through verify and terms).
+- [x] `login`/`logout` work against a fake site — proof: `login.spec.ts` + `cli.spec.ts` lists the new commands — covers AC-1, AC-2. Result: `pnpm exec vitest run packages/create-threenative/__tests__/{login,deploy,cli,cli-bin}.spec.ts` 17/17 passed; `create-threenative` typecheck exit 0.
+- [x] The device page keeps the code through verify and terms — proof: site `e2e/worker/store-device.spec.ts` — covers AC-8. Result: site `playwright test --config=playwright.worker.config.ts e2e/worker/store-device.spec.ts` 4/4 passed (Node 24); `studio-signin.spec.ts` 4/4 still pass.
+
+#### Phase 2: Studio accepts a CLI publish
+**Status:** PARTIAL — phases 1 to 3 in progress
+**Files:** site `worker/studio-auth.ts` (`tokenAccount`). Studio `hosting/cloudflare/src/routes/cli.ts` (new: `PUT /api/cli/share`), `src/index.ts` (route before the session gate).
+- [x] The token check passes its site tests — proof: site worker vitest — covers AC-3. Result: site `vitest run --config vitest.worker.config.ts` 229/229 passed (5 new `tokenAccount` cases, 2 new device cases); site typecheck and lint exit 0. Site branch `prd-904-cli-token`.
+- [x] The CLI share route passes its Studio tests — proof: Studio `hosting/cloudflare` vitest — covers AC-4. Result: `vitest run --config hosting/cloudflare/vitest.config.ts` 359/359 passed (9 new in `test/cli-share.spec.ts`); `tsc -p hosting/cloudflare` exit 0. Studio branch `prd-904-cli-share`.
+
+#### Phase 3: `threenative deploy` end to end
+**Status:** PARTIAL — phases 1 to 3 in progress
+**Files:** `packages/create-threenative/src/deploy.ts` (new: build, pack, upload, link file), `src/threenative.ts`, `src/commands.ts`.
+- [x] Deploy unit behaviour — proof: `deploy.spec.ts` — covers AC-5. Result: 5/5 in `deploy.spec.ts` (byte layout, same link on redeploy, 401 exits 3, 422 exits 4, no `build:web` exits 2).
+- [x] Local end-to-end through both real Workers — proof: AC-6 run log — covers AC-6. Result: see AC-6 evidence; local site `scripts/e2e-wrangler.mjs` on 4180, Studio `wrangler dev` on 8788 with containers off and `routes` removed so share hosts are not rewritten.
+- [ ] Live clean-room deploy — proof: `pnpm sandbox` — covers AC-7.
diff --git a/packages/create-threenative/AGENTS.md b/packages/create-threenative/AGENTS.md
index 7f55de3d06..72088c084b 100644
--- a/packages/create-threenative/AGENTS.md
+++ b/packages/create-threenative/AGENTS.md
@@ -79,12 +79,12 @@ builds locally can still fail there — check it before claiming the scaffold wo
## CLI surface
-Two `threenative` commands, ever: `build` (`--target web|desktop|android|ios`) and `doctor`
-(`--text` prints the person-readable report; it checks rather than builds, borrowed whole from
-`npm doctor` and `flutter doctor`). `__tests__/cli.spec.ts` derives the advertised list from the
-real executable and rejects anything else, so this document cannot outgrow the binary. A third
-command needs the owner decision made again — v1 shipped 178 command forms and a 2,477-word root
-help. The scaffolder itself takes a target directory plus `inspect [--json]`; its flags stay
+The `threenative` commands are `build` (`--target web|desktop|android|ios`), `doctor` (`--text` for
+the person-readable report; borrowed from `npm doctor`), `login` (device-code sign-in, token saved
+owner-only, `--no-browser`), `logout` (revokes it on the site), and `deploy` (`build:web`, uploads
+`dist/` to Studio, prints the share link last; `.threenative/share.json` keeps the link). `__tests__/cli.spec.ts`
+derives the list from the real executable. A new command borrows an established CLI's name, never a new word.
+The scaffolder itself takes a target directory plus `inspect [--json]`; its flags stay
boring: `--template`, `--no-install`, and the `--*-package` overrides CI uses to test against
local tarballs. `pnpm dev` inside a generated project is a package script, never a CLI command.
diff --git a/packages/create-threenative/CLAUDE.md b/packages/create-threenative/CLAUDE.md
index 1463a2e77b..d9493e1f08 100644
--- a/packages/create-threenative/CLAUDE.md
+++ b/packages/create-threenative/CLAUDE.md
@@ -81,12 +81,12 @@ builds locally can still fail there — check it before claiming the scaffold wo
## CLI surface
-Two `threenative` commands, ever: `build` (`--target web|desktop|android|ios`) and `doctor`
-(`--text` prints the person-readable report; it checks rather than builds, borrowed whole from
-`npm doctor` and `flutter doctor`). `__tests__/cli.spec.ts` derives the advertised list from the
-real executable and rejects anything else, so this document cannot outgrow the binary. A third
-command needs the owner decision made again — v1 shipped 178 command forms and a 2,477-word root
-help. The scaffolder itself takes a target directory plus `inspect [--json]`; its flags stay
+The `threenative` commands are `build` (`--target web|desktop|android|ios`), `doctor` (`--text` for
+the person-readable report; borrowed from `npm doctor`), `login` (device-code sign-in, token saved
+owner-only, `--no-browser`), `logout` (revokes it on the site), and `deploy` (`build:web`, uploads
+`dist/` to Studio, prints the share link last; `.threenative/share.json` keeps the link). `__tests__/cli.spec.ts`
+derives the list from the real executable. A new command borrows an established CLI's name, never a new word.
+The scaffolder itself takes a target directory plus `inspect [--json]`; its flags stay
boring: `--template`, `--no-install`, and the `--*-package` overrides CI uses to test against
local tarballs. `pnpm dev` inside a generated project is a package script, never a CLI command.
diff --git a/packages/create-threenative/__tests__/cli.spec.ts b/packages/create-threenative/__tests__/cli.spec.ts
index 77f694ffdd..5db25c166d 100644
--- a/packages/create-threenative/__tests__/cli.spec.ts
+++ b/packages/create-threenative/__tests__/cli.spec.ts
@@ -123,7 +123,7 @@ describe("create-threenative CLI", () => {
expect(commandHelp.stderr, command).toBe("");
expect(commandHelp.stdout, command).toContain(`Usage: threenative ${command}`);
}
- expect(advertised).toEqual(["build", "doctor"]);
+ expect(advertised).toEqual(["build", "doctor", "deploy", "login", "logout"]);
for (const command of ["dev", "test", "ship"]) {
await expect(
diff --git a/packages/create-threenative/__tests__/deploy-nolink.spec.ts b/packages/create-threenative/__tests__/deploy-nolink.spec.ts
new file mode 100644
index 0000000000..d8f9cc591d
--- /dev/null
+++ b/packages/create-threenative/__tests__/deploy-nolink.spec.ts
@@ -0,0 +1,46 @@
+import { mkdir, readFile, writeFile } from "node:fs/promises";
+import path from "node:path";
+import { describe, expect, it, vi } from "vitest";
+import { makeTempDir } from "../../../test-support/temp-dir.js";
+import { CliExit } from "../src/account.js";
+import { deploy } from "../src/deploy.js";
+
+// A volume with no hard links (some network and FAT mounts): `link` fails with ENOTSUP.
+vi.mock("node:fs/promises", async (original) => ({
+ ...(await original()),
+ link: async () => {
+ throw Object.assign(new Error("operation not supported"), { code: "ENOTSUP" });
+ },
+}));
+
+describe("threenative deploy on a volume with no hard links", () => {
+ it("still claims one deploy key for two first deploys started together", async () => {
+ const cwd = await makeTempDir("tn-deploy-nolink-");
+ await writeFile(
+ path.join(cwd, "package.json"),
+ JSON.stringify({ name: "game", scripts: { "build:web": "vite build" } }),
+ );
+ const options = {
+ cwd,
+ out: () => {},
+ runBuild: async (root: string) => {
+ await mkdir(path.join(root, "dist"), { recursive: true });
+ await writeFile(path.join(root, "dist", "index.html"), "hi
");
+ },
+ // Nothing listens here: each deploy claims its key, then fails to upload with exit 5.
+ studio: "http://127.0.0.1:9",
+ token: "tok-1",
+ };
+
+ const results = await Promise.allSettled([deploy(options), deploy(options)]);
+
+ for (const result of results) {
+ expect(result.status).toBe("rejected");
+ const reason = (result as PromiseRejectedResult).reason as unknown;
+ expect(reason).toBeInstanceOf(CliExit);
+ expect((reason as CliExit).code).toBe(5);
+ }
+ const share = JSON.parse(await readFile(path.join(cwd, ".threenative", "share.json"), "utf8"));
+ expect(share.deployKey).toMatch(/^[\da-f-]{36}$/u);
+ });
+});
diff --git a/packages/create-threenative/__tests__/deploy.spec.ts b/packages/create-threenative/__tests__/deploy.spec.ts
new file mode 100644
index 0000000000..4ceb35df04
--- /dev/null
+++ b/packages/create-threenative/__tests__/deploy.spec.ts
@@ -0,0 +1,318 @@
+import { once } from "node:events";
+import { mkdir, readFile, readdir, writeFile } from "node:fs/promises";
+import { type IncomingMessage, type ServerResponse, createServer } from "node:http";
+import path from "node:path";
+import { describe, expect, it } from "vitest";
+import { makeTempDir } from "../../../test-support/temp-dir.js";
+import { CliExit } from "../src/account.js";
+import { deploy, packDirectory } from "../src/deploy.js";
+
+interface IRequestRecord {
+ authorization?: string;
+ body: Buffer;
+ method?: string;
+ url?: string;
+}
+
+interface IReply {
+ body?: unknown;
+ status: number;
+}
+
+interface IFakeStudio {
+ close: () => Promise;
+ origin: string;
+ requests: IRequestRecord[];
+}
+
+/** A stand-in for studio.threenative.com on 127.0.0.1, so no test reaches the real Studio. */
+async function fakeStudio(
+ handler: (request: IRequestRecord) => IReply | Promise,
+): Promise {
+ const requests: IRequestRecord[] = [];
+ const server = createServer(async (request: IncomingMessage, response: ServerResponse) => {
+ const chunks: Buffer[] = [];
+ for await (const chunk of request) chunks.push(Buffer.from(chunk));
+ const record = {
+ authorization: request.headers.authorization,
+ body: Buffer.concat(chunks),
+ method: request.method,
+ url: request.url,
+ };
+ requests.push(record);
+ const reply = await handler(record);
+ response.statusCode = reply.status;
+ response.setHeader("content-type", "application/json");
+ response.end(reply.body === undefined ? "" : JSON.stringify(reply.body));
+ });
+ server.listen(0, "127.0.0.1");
+ await once(server, "listening");
+ const address = server.address();
+ const port = typeof address === "object" && address !== null ? address.port : 0;
+ return {
+ close: () =>
+ new Promise((done) => {
+ server.closeAllConnections();
+ server.close(() => done());
+ }),
+ origin: `http://127.0.0.1:${port.toString()}`,
+ requests,
+ };
+}
+
+/** Studio's parser, written from the wire format rather than from packDirectory's code. */
+function decode(archive: Buffer): { content: string; name: string }[] {
+ const entries: { content: string; name: string }[] = [];
+ let offset = 0;
+ while (offset < archive.length) {
+ const nameLength = archive.readUInt32BE(offset);
+ offset += 4;
+ const name = archive.subarray(offset, offset + nameLength).toString("utf8");
+ offset += nameLength;
+ const size = archive.readUInt32BE(offset);
+ offset += 4;
+ const content = archive.subarray(offset, offset + size).toString("utf8");
+ offset += size;
+ entries.push({ content, name });
+ }
+ return entries;
+}
+
+function entry(archive: Buffer, name: string): string | undefined {
+ return decode(archive).find((candidate) => candidate.name === name)?.content;
+}
+
+async function projectDir(scripts: Record): Promise {
+ const cwd = await makeTempDir("tn-deploy-");
+ await writeFile(path.join(cwd, "package.json"), JSON.stringify({ name: "game", scripts }));
+ return cwd;
+}
+
+async function writeBuild(cwd: string): Promise {
+ await mkdir(path.join(cwd, "dist"), { recursive: true });
+ await writeFile(path.join(cwd, "dist", "index.html"), "hi
");
+}
+
+interface IShareSnapshot {
+ deployKey?: string;
+ projectId?: string;
+}
+
+/** What `.threenative/share.json` held at this instant, read from inside a fake Studio handler. */
+async function readShareFile(cwd: string): Promise {
+ try {
+ const text = await readFile(path.join(cwd, ".threenative", "share.json"), "utf8");
+ return JSON.parse(text) as IShareSnapshot;
+ } catch {
+ return undefined;
+ }
+}
+
+function queryOf(url: string | undefined): URLSearchParams {
+ return new URLSearchParams((url ?? "").split("?")[1] ?? "");
+}
+
+async function failureOf(run: Promise): Promise {
+ const failure = await run.then(
+ () => undefined,
+ (error: unknown) => error,
+ );
+ expect(failure).toBeInstanceOf(CliExit);
+ return failure as CliExit;
+}
+
+describe("threenative deploy", () => {
+ it("packs files in Studio's byte layout and drops a compressed sibling", async () => {
+ const root = await makeTempDir("tn-pack-");
+ await writeFile(path.join(root, "index.html"), "hi
");
+ await mkdir(path.join(root, "a"));
+ await writeFile(path.join(root, "a", "b.js"), "console.log(1);");
+ await writeFile(path.join(root, "a", "b.js.br"), "BROTLI");
+ // Kept: the original `c` is absent, so the only copy of it is this gzip.
+ await writeFile(path.join(root, "c.gz"), "GZIP");
+
+ const entries = decode(await packDirectory(root));
+
+ expect(entries.map(({ content, name }) => `${name}=${content}`).sort()).toEqual([
+ "a/b.js=console.log(1);",
+ "c.gz=GZIP",
+ "index.html=hi
",
+ ]);
+ expect(entries.some(({ name }) => name === "a/b.js.br")).toBe(false);
+ });
+
+ it("keys the first deploy and keeps the same link on the next deploy", async () => {
+ const cwd = await projectDir({ "build:web": "vite build" });
+ // What share.json held as each upload arrived: the key has to be written before the upload,
+ // or a reply lost on the way back would leave the retry with nothing to name the game by.
+ const shareAtRequest: (IShareSnapshot | undefined)[] = [];
+ const site = await fakeStudio(async () => {
+ shareAtRequest.push(await readShareFile(cwd));
+ return { body: { projectId: "p1", shareUrl: "https://x-share.example/" }, status: 200 };
+ });
+ const lines: string[] = [];
+ const options = {
+ cwd,
+ out: (line: string) => lines.push(line),
+ runBuild: writeBuild,
+ studio: site.origin,
+ token: "tok-1",
+ };
+
+ const first = await deploy(options);
+
+ expect(first).toEqual({ projectId: "p1", shareUrl: "https://x-share.example/" });
+ expect(site.requests[0]).toMatchObject({
+ authorization: "Bearer tok-1",
+ method: "PUT",
+ });
+ const firstQuery = queryOf(site.requests[0]?.url);
+ const deployKey = firstQuery.get("key");
+ expect(deployKey).toMatch(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/u);
+ expect(firstQuery.get("name")).toBe("game");
+ expect(firstQuery.has("projectId")).toBe(false);
+ // Written before the request arrived, and the same key the request carried.
+ expect(shareAtRequest[0]).toEqual({ deployKey });
+ expect(entry(site.requests[0]?.body ?? Buffer.alloc(0), "index.html")).toBe("hi
");
+ // The link alone on the last stdout line: an agent parses that line, not the prose above it.
+ expect(lines.at(-1)).toBe("https://x-share.example/");
+ expect(await readShareFile(cwd)).toEqual({ deployKey, projectId: "p1" });
+
+ const second = await deploy(options);
+
+ expect(site.requests[1]?.url).toBe("/api/cli/share?name=game&projectId=p1");
+ expect(queryOf(site.requests[1]?.url).has("key")).toBe(false);
+ expect(shareAtRequest[1]).toEqual({ deployKey, projectId: "p1" });
+ expect(second).toEqual(first);
+ expect(await readShareFile(cwd)).toEqual({ deployKey, projectId: "p1" });
+ // Written through a temp file and renamed: nothing but share.json is left behind.
+ expect(await readdir(path.join(cwd, ".threenative"))).toEqual(["share.json"]);
+ await site.close();
+ });
+
+ it("gives two first deploys started together one key, so they land on one game", async () => {
+ const cwd = await projectDir({ "build:web": "vite build" });
+ const site = await fakeStudio(() => ({
+ body: { projectId: "p1", shareUrl: "https://x-share.example/" },
+ status: 200,
+ }));
+ const options = {
+ cwd,
+ out: () => {},
+ runBuild: writeBuild,
+ studio: site.origin,
+ token: "tok-1",
+ };
+
+ await Promise.all([deploy(options), deploy(options)]);
+
+ const keys = site.requests.map((request) => queryOf(request.url).get("key"));
+ expect(keys).toHaveLength(2);
+ expect(keys[0]).toBeTypeOf("string");
+ expect(keys[1]).toBe(keys[0]);
+ expect(await readdir(path.join(cwd, ".threenative"))).toEqual(["share.json"]);
+ await site.close();
+ });
+
+ it("waits for a share.json another first deploy has created but not yet written", async () => {
+ const cwd = await projectDir({ "build:web": "vite build" });
+ const site = await fakeStudio(() => ({
+ body: { projectId: "p1", shareUrl: "https://x-share.example/" },
+ status: 200,
+ }));
+ const file = path.join(cwd, ".threenative", "share.json");
+ await mkdir(path.dirname(file), { recursive: true });
+ await writeFile(file, "");
+ const theirs = "11111111-2222-4333-8444-555555555555";
+ const late = new Promise((done) => setTimeout(done, 100)).then(() =>
+ writeFile(file, JSON.stringify({ deployKey: theirs })),
+ );
+
+ await deploy({ cwd, out: () => {}, runBuild: writeBuild, studio: site.origin, token: "tok-1" });
+ await late;
+
+ expect(queryOf(site.requests[0]?.url).get("key")).toBe(theirs);
+ await site.close();
+ });
+
+ it("retries a first deploy whose reply was lost with the same key, so it lands on one game", async () => {
+ const cwd = await projectDir({ "build:web": "vite build" });
+ let uploads = 0;
+ const site = await fakeStudio(() => {
+ uploads += 1;
+ return uploads === 1
+ ? { body: { message: "Studio fell over." }, status: 500 }
+ : { body: { projectId: "p1", shareUrl: "https://x-share.example/" }, status: 200 };
+ });
+ const options = {
+ cwd,
+ out: () => {},
+ runBuild: writeBuild,
+ studio: site.origin,
+ token: "tok-1",
+ };
+
+ const failure = await failureOf(deploy(options));
+
+ expect(failure.code).toBe(4);
+ expect(failure.message).toBe("Studio fell over.");
+ const afterFailure = await readShareFile(cwd);
+ // The key outlives the failed upload, and nothing else was written: no game id exists yet.
+ expect(afterFailure?.deployKey).toMatch(
+ /^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/u,
+ );
+ expect(Object.keys(afterFailure ?? {})).toEqual(["deployKey"]);
+
+ const retried = await deploy(options);
+
+ expect(retried).toEqual({ projectId: "p1", shareUrl: "https://x-share.example/" });
+ expect(queryOf(site.requests[1]?.url).get("key")).toBe(afterFailure?.deployKey);
+ expect(queryOf(site.requests[1]?.url).has("projectId")).toBe(false);
+ expect(await readShareFile(cwd)).toEqual({
+ deployKey: afterFailure?.deployKey,
+ projectId: "p1",
+ });
+ await site.close();
+ });
+
+ it("asks for a fresh sign-in when Studio refuses the token", async () => {
+ const cwd = await projectDir({ "build:web": "vite build" });
+ const site = await fakeStudio(() => ({
+ body: { message: "This token is no longer valid." },
+ status: 401,
+ }));
+
+ const failure = await failureOf(
+ deploy({ cwd, out: () => {}, runBuild: writeBuild, studio: site.origin, token: "tok-old" }),
+ );
+
+ expect(failure.code).toBe(3);
+ expect(failure.message).toBe("This token is no longer valid. Run threenative login.");
+ await site.close();
+ });
+
+ it("surfaces Studio's reason when it refuses the build", async () => {
+ const cwd = await projectDir({ "build:web": "vite build" });
+ const message = "The build has no index.html. Run build:web and deploy again.";
+ const site = await fakeStudio(() => ({ body: { message }, status: 422 }));
+
+ const failure = await failureOf(
+ deploy({ cwd, out: () => {}, runBuild: writeBuild, studio: site.origin, token: "tok-1" }),
+ );
+
+ expect(failure.code).toBe(4);
+ expect(failure.message).toBe(message);
+ await site.close();
+ });
+
+ it("rejects a package with no build:web script", async () => {
+ const cwd = await projectDir({ build: "vite build" });
+
+ const failure = await failureOf(
+ deploy({ cwd, out: () => {}, runBuild: writeBuild, token: "tok-1" }),
+ );
+
+ expect(failure.code).toBe(2);
+ expect(failure.message).toBe("package.json has no build:web script.");
+ });
+});
diff --git a/packages/create-threenative/__tests__/login.spec.ts b/packages/create-threenative/__tests__/login.spec.ts
new file mode 100644
index 0000000000..524518f4f0
--- /dev/null
+++ b/packages/create-threenative/__tests__/login.spec.ts
@@ -0,0 +1,421 @@
+import { once } from "node:events";
+import { existsSync, writeFileSync } from "node:fs";
+import { chmod, mkdir, readFile, readdir, stat, writeFile } from "node:fs/promises";
+import { type IncomingMessage, type ServerResponse, createServer } from "node:http";
+import path from "node:path";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { makeTempDir } from "../../../test-support/temp-dir.js";
+import { CliExit, authFilePath, login, logout, readToken } from "../src/account.js";
+
+interface IRequestRecord {
+ authorization?: string;
+ body: Buffer;
+ method?: string;
+ url?: string;
+}
+
+interface IReply {
+ body?: unknown;
+ status: number;
+}
+
+interface IFakeSite {
+ close: () => Promise;
+ origin: string;
+ requests: IRequestRecord[];
+}
+
+/** A stand-in for threenative.com on 127.0.0.1, so no test reaches the real site. */
+async function fakeSite(handler: (request: IRequestRecord) => IReply): Promise {
+ const requests: IRequestRecord[] = [];
+ const server = createServer(async (request: IncomingMessage, response: ServerResponse) => {
+ const chunks: Buffer[] = [];
+ for await (const chunk of request) chunks.push(Buffer.from(chunk));
+ const record = {
+ authorization: request.headers.authorization,
+ body: Buffer.concat(chunks),
+ method: request.method,
+ url: request.url,
+ };
+ requests.push(record);
+ const reply = handler(record);
+ response.statusCode = reply.status;
+ response.setHeader("content-type", "application/json");
+ response.end(reply.body === undefined ? "" : JSON.stringify(reply.body));
+ });
+ server.listen(0, "127.0.0.1");
+ await once(server, "listening");
+ const address = server.address();
+ const port = typeof address === "object" && address !== null ? address.port : 0;
+ return {
+ close: () =>
+ new Promise((done) => {
+ server.closeAllConnections();
+ server.close(() => done());
+ }),
+ origin: `http://127.0.0.1:${port.toString()}`,
+ requests,
+ };
+}
+
+async function failureOf(run: Promise): Promise {
+ const failure = await run.then(
+ () => undefined,
+ (error: unknown) => error,
+ );
+ expect(failure).toBeInstanceOf(CliExit);
+ return failure as CliExit;
+}
+
+function deviceStart(userCode: string): IReply {
+ return {
+ body: { deviceCode: `dev-${userCode}`, expiresIn: 900, interval: 1, userCode },
+ status: 201,
+ };
+}
+
+/** The tokens a logout kept for its next run, from the claimed files beside auth.json. */
+async function keptTokens(file: string): Promise {
+ const dir = path.dirname(file);
+ const names = (await readdir(dir)).filter((name) => name.endsWith(".logout"));
+ return Promise.all(
+ names.map(
+ async (name) =>
+ (JSON.parse(await readFile(path.join(dir, name), "utf8")) as { token: string }).token,
+ ),
+ );
+}
+
+describe("threenative login and logout", () => {
+ let configHome: string;
+
+ beforeEach(async () => {
+ configHome = await makeTempDir("tn-auth-");
+ vi.stubEnv("XDG_CONFIG_HOME", configHome);
+ // A developer machine with a token or a browser must not change what these tests prove.
+ vi.stubEnv("THREENATIVE_TOKEN", "");
+ vi.stubEnv("THREENATIVE_NO_BROWSER", "1");
+ });
+
+ afterEach(() => {
+ vi.unstubAllEnvs();
+ });
+
+ it("polls the device flow, saves a 0600 token file and names the account", async () => {
+ let polls = 0;
+ let savedBeforeWhoami: boolean | undefined;
+ const site = await fakeSite((request) => {
+ if (request.url === "/api/store/device") return deviceStart("ABCD-EFGH");
+ if (request.url === "/api/store/device/token") {
+ polls += 1;
+ return polls < 3
+ ? { body: { status: "pending" }, status: 200 }
+ : { body: { status: "approved", token: "tok-1" }, status: 200 };
+ }
+ if (request.url === "/api/store/whoami") {
+ // Nothing is saved until the address is known: a logout racing this login can only revoke a
+ // token it read from the file, so one write leaves it nothing to bring back.
+ savedBeforeWhoami = existsSync(authFilePath());
+ return { body: { email: "a@b.c" }, status: 200 };
+ }
+ return { body: { message: "unexpected request" }, status: 404 };
+ });
+ const lines: string[] = [];
+
+ await login({
+ open: false,
+ out: (line) => lines.push(line),
+ site: site.origin,
+ sleep: async () => {},
+ });
+
+ const file = authFilePath();
+ expect((await stat(file)).mode & 0o777).toBe(0o600);
+ const saved = JSON.parse(await readFile(file, "utf8")) as { email?: string; token?: string };
+ expect(saved).toMatchObject({ email: "a@b.c", token: "tok-1" });
+ expect(savedBeforeWhoami).toBe(false);
+ // The token was renamed into place from a temp file of its own name: nothing is left beside it.
+ expect(await readdir(path.dirname(file))).toEqual(["auth.json"]);
+ expect(lines.join("\n")).toContain("/account/device/?code=ABCD-EFGH");
+ expect(lines.join("\n")).toContain("Signed in as a@b.c");
+ expect(polls).toBe(3);
+ expect(site.requests.map(({ method, url }) => `${method ?? ""} ${url ?? ""}`)).toEqual([
+ "POST /api/store/device",
+ "POST /api/store/device/token",
+ "POST /api/store/device/token",
+ "POST /api/store/device/token",
+ "GET /api/store/whoami",
+ ]);
+ expect(site.requests.at(-1)?.authorization).toBe("Bearer tok-1");
+ await site.close();
+ });
+
+ it("saves the granted token and exits 4 when whoami answers an empty 503", async () => {
+ const site = await fakeSite((request) => {
+ if (request.url === "/api/store/device") return deviceStart("ABCD-EFGH");
+ if (request.url === "/api/store/device/token")
+ return { body: { status: "approved", token: "tok-1" }, status: 200 };
+ return { status: 503 };
+ });
+
+ const failure = await failureOf(
+ login({ open: false, out: () => {}, site: site.origin, sleep: async () => {} }),
+ );
+
+ expect(failure.code).toBe(4);
+ expect(JSON.parse(await readFile(authFilePath(), "utf8"))).toEqual({
+ site: site.origin,
+ token: "tok-1",
+ });
+ await site.close();
+ });
+
+ it("exits 4 when the token poll answers an empty 503", async () => {
+ const site = await fakeSite((request) =>
+ request.url === "/api/store/device" ? deviceStart("ABCD-EFGH") : { status: 503 },
+ );
+
+ const failure = await failureOf(
+ login({ open: false, out: () => {}, site: site.origin, sleep: async () => {} }),
+ );
+
+ expect(failure.code).toBe(4);
+ await site.close();
+ });
+
+ it("tightens an existing world-readable token file when signing in again", async () => {
+ const file = authFilePath();
+ await mkdir(path.dirname(file), { recursive: true });
+ await writeFile(file, JSON.stringify({ token: "tok-old" }));
+ await chmod(file, 0o644);
+ const site = await fakeSite((request) => {
+ if (request.url === "/api/store/device") return deviceStart("NEW1-CODE");
+ if (request.url === "/api/store/device/token")
+ return { body: { status: "approved", token: "tok-new" }, status: 200 };
+ if (request.url === "/api/store/whoami") return { body: { email: "n@b.c" }, status: 200 };
+ return { body: { message: "unexpected request" }, status: 404 };
+ });
+
+ await login({ open: false, out: () => {}, site: site.origin, sleep: async () => {} });
+
+ expect((await stat(file)).mode & 0o777).toBe(0o600);
+ expect(JSON.parse(await readFile(file, "utf8"))).toMatchObject({
+ email: "n@b.c",
+ token: "tok-new",
+ });
+ await site.close();
+ });
+
+ it("asks you to log in again when the code expired", async () => {
+ const site = await fakeSite((request) =>
+ request.url === "/api/store/device"
+ ? deviceStart("WXYZ-1234")
+ : { body: { message: "That code has expired." }, status: 400 },
+ );
+
+ const failure = await failureOf(
+ login({ open: false, out: () => {}, site: site.origin, sleep: async () => {} }),
+ );
+
+ expect(failure.code).toBe(3);
+ expect(failure.message).toBe("That code has expired. Run threenative login again.");
+ await site.close();
+ });
+
+ it("revokes the saved token, never the env one, then deletes the file", async () => {
+ const file = authFilePath();
+ await mkdir(path.dirname(file), { recursive: true });
+ await writeFile(file, JSON.stringify({ token: "tok-file" }));
+ vi.stubEnv("THREENATIVE_TOKEN", "tok-env");
+ const site = await fakeSite(() => ({ body: { ok: true }, status: 200 }));
+ const lines: string[] = [];
+
+ await logout({ out: (line) => lines.push(line), site: site.origin });
+
+ expect(site.requests).toHaveLength(1);
+ expect(site.requests[0]).toMatchObject({
+ authorization: "Bearer tok-file",
+ method: "DELETE",
+ url: "/api/store/token",
+ });
+ await expect(stat(file)).rejects.toMatchObject({ code: "ENOENT" });
+ expect(lines).toEqual(["Signed out."]);
+ await site.close();
+ });
+
+ it("keeps a token a login saved while logout was revoking the old one", async () => {
+ const file = authFilePath();
+ await mkdir(path.dirname(file), { recursive: true });
+ await writeFile(file, JSON.stringify({ token: "tok-old" }));
+ // A login in another terminal finishes while the revoke is in flight.
+ const site = await fakeSite(() => {
+ writeFileSync(file, JSON.stringify({ token: "tok-new" }));
+ return { body: { ok: true }, status: 200 };
+ });
+
+ await logout({ out: () => {}, site: site.origin });
+
+ expect(site.requests[0]?.authorization).toBe("Bearer tok-old");
+ expect(JSON.parse(await readFile(file, "utf8"))).toEqual({ token: "tok-new" });
+ await site.close();
+ });
+
+ it("keeps the token file when the server refuses the revoke", async () => {
+ const file = authFilePath();
+ await mkdir(path.dirname(file), { recursive: true });
+ await writeFile(file, JSON.stringify({ token: "tok-file" }));
+ const site = await fakeSite(() => ({ body: { message: "Server exploded." }, status: 500 }));
+ const lines: string[] = [];
+
+ const failure = await failureOf(logout({ out: (line) => lines.push(line), site: site.origin }));
+
+ expect(failure.code).toBe(4);
+ expect(failure.message).toBe(
+ "Could not revoke the token (500). The token is kept, so run threenative logout again.",
+ );
+ expect(await keptTokens(file)).toEqual(["tok-file"]);
+ expect(lines).toEqual([]);
+ await site.close();
+
+ // The next logout finds the kept token and revokes it.
+ const retry = await fakeSite(() => ({ body: { ok: true }, status: 200 }));
+ await logout({ out: (line) => lines.push(line), site: retry.origin });
+ expect(retry.requests[0]?.authorization).toBe("Bearer tok-file");
+ expect(await readdir(path.dirname(file))).toEqual([]);
+ expect(lines).toEqual(["Signed out."]);
+ await retry.close();
+ });
+
+ it("revokes a token on the site that issued it, whatever THREENATIVE_SITE says now", async () => {
+ const issuer = await fakeSite(() => ({ body: { ok: true }, status: 200 }));
+ const other = await fakeSite(() => ({ body: { ok: true }, status: 401 }));
+ const file = authFilePath();
+ await mkdir(path.dirname(file), { recursive: true });
+ await writeFile(file, JSON.stringify({ site: issuer.origin, token: "tok-prod" }));
+
+ await logout({ out: () => {}, site: other.origin });
+
+ expect(issuer.requests.map((request) => request.authorization)).toEqual(["Bearer tok-prod"]);
+ expect(other.requests).toEqual([]);
+ await issuer.close();
+ await other.close();
+ });
+
+ it.skipIf(process.getuid?.() === 0)("keeps a token file it cannot read", async () => {
+ const file = authFilePath();
+ await mkdir(path.dirname(file), { recursive: true });
+ await writeFile(file, JSON.stringify({ token: "tok-locked" }), { mode: 0o000 });
+ const site = await fakeSite(() => ({ body: { ok: true }, status: 200 }));
+
+ const failure = await failureOf(logout({ out: () => {}, site: site.origin }));
+
+ expect(failure.code).toBe(4);
+ expect(failure.message).toContain("The token is kept, so run threenative logout again.");
+ expect(site.requests).toEqual([]);
+ const left = (await readdir(path.dirname(file))).filter((name) => name.endsWith(".logout"));
+ expect(left).toHaveLength(1);
+ await site.close();
+ });
+
+ it.skipIf(process.getuid?.() === 0)(
+ "revokes auth.json in a directory it cannot list",
+ async () => {
+ const file = authFilePath();
+ const dir = path.dirname(file);
+ await mkdir(dir, { recursive: true });
+ await writeFile(file, JSON.stringify({ token: "tok-hidden" }));
+ await chmod(dir, 0o300);
+ const site = await fakeSite(() => ({ body: { ok: true }, status: 200 }));
+ const lines: string[] = [];
+
+ try {
+ await logout({ out: (line) => lines.push(line), site: site.origin });
+ } finally {
+ await chmod(dir, 0o700);
+ }
+
+ expect(site.requests.map((request) => request.authorization)).toEqual(["Bearer tok-hidden"]);
+ expect(lines).toEqual(["Signed out."]);
+ expect(await readdir(dir)).toEqual([]);
+ await site.close();
+ },
+ );
+
+ it.skipIf(process.getuid?.() === 0)(
+ "refuses to say signed out when it cannot see a kept token",
+ async () => {
+ const file = authFilePath();
+ const dir = path.dirname(file);
+ await mkdir(dir, { recursive: true });
+ // An earlier logout kept this token after a refused revoke; the directory then lost read access.
+ await writeFile(`${file}.kept.logout`, JSON.stringify({ token: "tok-kept" }));
+ await chmod(dir, 0o300);
+ const site = await fakeSite(() => ({ body: { ok: true }, status: 200 }));
+
+ let failure: CliExit;
+ try {
+ failure = await failureOf(logout({ out: () => {}, site: site.origin }));
+ } finally {
+ await chmod(dir, 0o700);
+ }
+
+ expect(failure.code).toBe(4);
+ expect(failure.message).toContain("Restore read access");
+ expect(site.requests).toEqual([]);
+ await site.close();
+ },
+ );
+
+ it("revokes a token an interrupted logout left behind", async () => {
+ const file = authFilePath();
+ await mkdir(path.dirname(file), { recursive: true });
+ // Ctrl+C after the claim, before the revoke: no auth.json, only the claimed file.
+ await writeFile(`${file}.left.logout`, JSON.stringify({ token: "tok-left" }));
+ const site = await fakeSite(() => ({ body: { ok: true }, status: 200 }));
+
+ await logout({ out: () => {}, site: site.origin });
+
+ expect(site.requests.map((request) => request.authorization)).toEqual(["Bearer tok-left"]);
+ expect(await readdir(path.dirname(file))).toEqual([]);
+ await site.close();
+ });
+
+ it("keeps the token file when the site is unreachable", async () => {
+ const file = authFilePath();
+ await mkdir(path.dirname(file), { recursive: true });
+ await writeFile(file, JSON.stringify({ token: "tok-file" }));
+ const site = await fakeSite(() => ({ body: {}, status: 200 }));
+ const origin = site.origin;
+ await site.close();
+
+ const failure = await failureOf(logout({ out: () => {}, site: origin }));
+
+ expect(failure.code).toBe(5);
+ expect(failure.message).toContain(`Could not reach ${origin}`);
+ expect(failure.message).toContain("The token is kept, so run threenative logout again.");
+ expect(await keptTokens(file)).toEqual(["tok-file"]);
+ });
+
+ it("prefers THREENATIVE_TOKEN over the saved file", async () => {
+ const file = authFilePath();
+ await mkdir(path.dirname(file), { recursive: true });
+ await writeFile(file, JSON.stringify({ token: "tok-file" }));
+ expect(await readToken()).toBe("tok-file");
+
+ vi.stubEnv("THREENATIVE_TOKEN", "tok-env");
+ expect(await readToken()).toBe("tok-env");
+ });
+
+ it("reports a closed port as a network failure", async () => {
+ const site = await fakeSite(() => ({ body: {}, status: 200 }));
+ const origin = site.origin;
+ await site.close();
+
+ const failure = await failureOf(
+ login({ open: false, out: () => {}, site: origin, sleep: async () => {} }),
+ );
+
+ expect(failure.code).toBe(5);
+ expect(failure.message).toContain(`Could not reach ${origin}`);
+ });
+});
diff --git a/packages/create-threenative/src/account.ts b/packages/create-threenative/src/account.ts
new file mode 100644
index 0000000000..bc5e60cb51
--- /dev/null
+++ b/packages/create-threenative/src/account.ts
@@ -0,0 +1,351 @@
+/** `threenative login` and `threenative logout`: the device-code flow against threenative.com,
+ * and the one token file every command that talks to a server reads.
+ *
+ * Exit codes are shared by login, logout and deploy: 0 ok, 2 bad arguments, 3 sign in again,
+ * 4 refused by the server, 5 network failure. `main()` prints the message and sets the code. */
+import { spawn } from "node:child_process";
+import { randomUUID } from "node:crypto";
+import { mkdir, readFile, readdir, rename, rm, writeFile } from "node:fs/promises";
+import { homedir } from "node:os";
+import path from "node:path";
+
+export class CliExit extends Error {
+ readonly code: number;
+
+ constructor(code: number, message: string) {
+ super(message);
+ this.name = "CliExit";
+ this.code = code;
+ }
+}
+
+const DEFAULT_SITE = "https://threenative.com";
+
+export function siteOrigin(site = process.env.THREENATIVE_SITE): string {
+ return (site ?? DEFAULT_SITE).replace(/\/+$/u, "");
+}
+
+function configHome(env: NodeJS.ProcessEnv): string {
+ if (env.XDG_CONFIG_HOME !== undefined && env.XDG_CONFIG_HOME !== "") return env.XDG_CONFIG_HOME;
+ // `~/.config` on macOS too, as `gh` and `wrangler` do; Windows keeps its roaming config folder.
+ if (process.platform === "win32") return env.APPDATA ?? homedir();
+ return path.join(homedir(), ".config");
+}
+
+/** `$XDG_CONFIG_HOME/threenative/auth.json`, default `~/.config` (`%APPDATA%` on Windows). */
+export function authFilePath(env = process.env): string {
+ return path.join(configHome(env), "threenative", "auth.json");
+}
+
+export interface IAuthFile {
+ email?: string;
+ /** The site that issued the token: logout revokes it there, whatever `THREENATIVE_SITE` says now. */
+ site?: string;
+ token?: string;
+}
+
+async function readAuthFile(
+ env: NodeJS.ProcessEnv,
+ file = authFilePath(env),
+): Promise {
+ try {
+ const parsed: unknown = JSON.parse(await readFile(file, "utf8"));
+ return parsed !== null && typeof parsed === "object" ? (parsed as IAuthFile) : undefined;
+ } catch {
+ // No file, or one a person half-edited: either way this machine has no saved token.
+ return undefined;
+ }
+}
+
+/** `THREENATIVE_TOKEN` wins for one command, so CI can publish without a config file. */
+export async function readToken(env = process.env): Promise {
+ const fromEnv = env.THREENATIVE_TOKEN;
+ if (fromEnv !== undefined && fromEnv !== "") return fromEnv;
+ const file = await readAuthFile(env);
+ return typeof file?.token === "string" && file.token !== "" ? file.token : undefined;
+}
+
+export async function requireToken(): Promise {
+ const token = await readToken();
+ if (token === undefined) throw new CliExit(3, "Not signed in. Run threenative login.");
+ return token;
+}
+
+export interface IReply {
+ body: unknown;
+ status: number;
+ statusText: string;
+}
+
+/** One JSON request. A broken connection is the only thing exit code 5 means, so it is caught
+ * here: both a fetch that never connected and a body that dies after the headers arrived. */
+export async function request(
+ origin: string,
+ pathname: string,
+ init: RequestInit = {},
+): Promise {
+ let response: Response;
+ let text: string;
+ try {
+ response = await fetch(`${origin}${pathname}`, init);
+ text = await response.text();
+ } catch (error) {
+ const reason = error instanceof Error ? error.message : String(error);
+ throw new CliExit(5, `Could not reach ${origin}: ${reason}`);
+ }
+ let body: unknown = text;
+ try {
+ body = text === "" ? undefined : JSON.parse(text);
+ } catch {
+ // A non-JSON body (a proxy page) is still worth surfacing as text, which it already is.
+ }
+ return { body, status: response.status, statusText: response.statusText };
+}
+
+/** Site errors are `{ error: "TN_…", message: "…" }`; a person reads the message, not the code. */
+export function serverMessage(body: unknown, fallback: string): string {
+ const message = (body as { message?: unknown } | null | undefined)?.message;
+ return typeof message === "string" && message !== "" ? message : fallback;
+}
+
+function numberField(body: unknown, key: string): number | undefined {
+ const value = (body as Record | null | undefined)?.[key];
+ return typeof value === "number" && Number.isFinite(value) ? value : undefined;
+}
+
+function jsonPost(value: unknown): RequestInit {
+ return {
+ body: JSON.stringify(value),
+ headers: { "content-type": "application/json" },
+ method: "POST",
+ };
+}
+
+async function writeAuthFile(auth: IAuthFile): Promise {
+ const file = authFilePath();
+ await mkdir(path.dirname(file), { mode: 0o700, recursive: true });
+ // Create the token 0600 beside the real file and rename it over: a rename replaces the
+ // destination atomically, so no window leaves the new token in a world-readable inode. The
+ // temp name is unique per write, so two logins sharing one config directory never share it.
+ const tmp = `${file}.${randomUUID()}.tmp`;
+ try {
+ await writeFile(tmp, `${JSON.stringify(auth, null, 2)}\n`, { flag: "wx", mode: 0o600 });
+ await rename(tmp, file);
+ } catch (error) {
+ await rm(tmp, { force: true });
+ throw error;
+ }
+}
+
+function openBrowser(link: string): void {
+ const command =
+ process.platform === "darwin" ? "open" : process.platform === "win32" ? "cmd" : "xdg-open";
+ const args = process.platform === "win32" ? ["/c", "start", "", link] : [link];
+ try {
+ const child = spawn(command, args, { detached: true, stdio: "ignore" });
+ // A machine with no browser (a container, CI) must not fail the login it is polling through.
+ child.on("error", () => {});
+ child.unref();
+ } catch {
+ // spawn throws only on bad arguments; a missing binary arrives as the 'error' event above.
+ }
+}
+
+export interface ILoginOptions {
+ open?: boolean;
+ out?: (line: string) => void;
+ site?: string;
+ sleep?: (milliseconds: number) => Promise;
+}
+
+/** Device-code sign-in: print the code, poll until the browser authorizes, save the token. */
+export async function login(options: ILoginOptions = {}): Promise {
+ const origin = siteOrigin(options.site);
+ const out = options.out ?? ((line: string) => process.stdout.write(`${line}\n`));
+ const sleep =
+ options.sleep ??
+ ((milliseconds: number) => new Promise((done) => setTimeout(done, milliseconds)));
+
+ const start = await request(origin, "/api/store/device", jsonPost({}));
+ if (start.status !== 201)
+ throw new CliExit(4, serverMessage(start.body, `Sign in failed (${start.status}).`));
+ const deviceCode = (start.body as { deviceCode?: unknown } | null | undefined)?.deviceCode;
+ const userCode = (start.body as { userCode?: unknown } | null | undefined)?.userCode;
+ if (typeof deviceCode !== "string" || deviceCode === "")
+ throw new CliExit(4, "The sign-in server sent no device code.");
+ const link = `${origin}/account/device/?code=${encodeURIComponent(typeof userCode === "string" ? userCode : "")}`;
+ out(`Open ${link} and click Authorize.`);
+ out(`Code: ${typeof userCode === "string" ? userCode : ""}`);
+ if (options.open !== false && process.env.THREENATIVE_NO_BROWSER !== "1") openBrowser(link);
+
+ const expiresAt = Date.now() + (numberField(start.body, "expiresIn") ?? 900) * 1_000;
+ let interval = numberField(start.body, "interval") ?? 5;
+ const pollForToken = async (): Promise => {
+ for (;;) {
+ await sleep(interval * 1_000);
+ if (Date.now() >= expiresAt)
+ throw new CliExit(3, "The code expired. Run threenative login again.");
+ const reply = await request(origin, "/api/store/device/token", jsonPost({ deviceCode }));
+ const status = (reply.body as { status?: unknown } | null | undefined)?.status;
+ if (reply.status >= 400 && reply.status < 500)
+ throw new CliExit(
+ 3,
+ `${serverMessage(reply.body, "Sign in was refused.")} Run threenative login again.`,
+ );
+ if (reply.status < 200 || reply.status >= 300)
+ throw new CliExit(4, serverMessage(reply.body, `Sign in failed (${reply.status}).`));
+ const nextInterval = numberField(reply.body, "interval");
+ if (nextInterval !== undefined && nextInterval > 0) interval = nextInterval;
+ if (status !== "approved") continue;
+ const token = (reply.body as { token?: unknown } | null | undefined)?.token;
+ if (typeof token !== "string" || token === "")
+ throw new CliExit(4, "The sign-in server approved without a token.");
+ return token;
+ }
+ };
+
+ const token = await pollForToken();
+ out(`Signed in as ${await saveSignIn(origin, token)}.`);
+}
+
+/** Saves a granted token with the address it belongs to, and returns that address. */
+async function saveSignIn(origin: string, token: string): Promise {
+ // One write, after asking who this is: a logout in another terminal can only revoke a token it
+ // read from the file, so a second write could bring back a token that logout already revoked.
+ // A whoami hiccup still saves the granted token, without the address, before it reports.
+ let who: Awaited>;
+ try {
+ who = await request(origin, "/api/store/whoami", {
+ headers: { authorization: `Bearer ${token}` },
+ });
+ } catch (error) {
+ await writeAuthFile({ site: origin, token });
+ throw error;
+ }
+ const email = (who.body as { email?: unknown } | null | undefined)?.email;
+ const address = typeof email === "string" ? email : "";
+ await writeAuthFile(
+ address === "" ? { site: origin, token } : { email: address, site: origin, token },
+ );
+ if (who.status < 200 || who.status >= 300)
+ throw new CliExit(4, serverMessage(who.body, `Could not read your account (${who.status}).`));
+ return address;
+}
+
+export interface ILogoutOptions {
+ out?: (line: string) => void;
+ site?: string;
+}
+
+/** Revoke the saved token and delete the file. `THREENATIVE_TOKEN` is not touched.
+ *
+ * Each token file is claimed with one rename before its revoke, so a login in another terminal that
+ * saves meanwhile writes a new auth.json this logout never touches. A token the server did not
+ * revoke (any answer but 200 or 401, or no answer) stays in its claimed `auth.json..logout` file,
+ * and so does one whose logout was interrupted: every logout claims those leftovers too and revokes
+ * them, so a live token is never dropped from this machine while nothing can revoke it. */
+export async function logout(options: ILogoutOptions = {}): Promise {
+ const out = options.out ?? ((line: string) => process.stdout.write(`${line}\n`));
+ const env = process.env;
+ const claims = await claimTokenFiles(authFilePath(env));
+ let revoked = false;
+ let failure: CliExit | undefined;
+ for (const claimed of claims) {
+ const auth = await readClaim(claimed);
+ if (auth instanceof CliExit) {
+ failure = auth;
+ continue;
+ }
+ const token = auth?.token;
+ if (typeof token !== "string" || token === "") {
+ await rm(claimed, { force: true });
+ continue;
+ }
+ // Revoked where it was issued: a token from one site sent to another would only earn a 401 there,
+ // which reads as "already dead" and would drop a token still live on its own site.
+ const origin =
+ typeof auth?.site === "string" && auth.site !== "" ? auth.site : siteOrigin(options.site);
+ const answer = await revokeToken(origin, token);
+ if (answer === undefined) {
+ await rm(claimed, { force: true });
+ revoked = true;
+ } else failure = answer;
+ }
+ if (failure !== undefined) throw failure;
+ out(revoked ? "Signed out." : "Not signed in.");
+}
+
+/** A claimed token file's contents. A file that cannot be read is kept, so a live token is never
+ * deleted unrevoked; one that is not JSON holds no token and is `undefined`, like no file at all. */
+async function readClaim(claimed: string): Promise {
+ let text: string;
+ try {
+ text = await readFile(claimed, "utf8");
+ } catch (error) {
+ const code = (error as NodeJS.ErrnoException).code ?? "unknown error";
+ return new CliExit(
+ 4,
+ `Could not read ${claimed} (${code}). The token is kept, so run threenative logout again.`,
+ );
+ }
+ try {
+ const parsed: unknown = JSON.parse(text);
+ return parsed !== null && typeof parsed === "object" ? (parsed as IAuthFile) : undefined;
+ } catch {
+ return undefined;
+ }
+}
+
+/** Claims auth.json and every token file an earlier logout left, each with one rename to a name of
+ * this run's own: two logouts never revoke from, or delete, one file. */
+async function claimTokenFiles(file: string): Promise {
+ const dir = path.dirname(file);
+ const base = path.basename(file);
+ // A directory this user cannot list can still hold an auth.json it can rename by name, so a failed
+ // listing only skips the leftovers; it never reads as "not signed in".
+ let names: string[] = [];
+ let unlisted: string | undefined;
+ try {
+ names = await readdir(dir);
+ } catch (error) {
+ const code = (error as NodeJS.ErrnoException).code;
+ // No directory: the rename below finds no auth.json either.
+ if (code !== "ENOENT") unlisted = code ?? "unknown error";
+ }
+ const left = names.filter((name) => name.startsWith(`${base}.`) && name.endsWith(".logout"));
+ const claims: string[] = [];
+ for (const source of [file, ...left.map((name) => path.join(dir, name))]) {
+ const claimed = `${file}.${randomUUID()}.logout`;
+ try {
+ await rename(source, claimed);
+ claims.push(claimed);
+ } catch (error) {
+ // Gone already: never saved, or another logout claimed it first.
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
+ }
+ }
+ // Nothing to claim by name, and the leftovers an earlier logout kept cannot be seen: saying "not
+ // signed in" here could leave a live token behind.
+ if (claims.length === 0 && unlisted !== undefined)
+ throw new CliExit(
+ 4,
+ `Could not list ${dir} (${unlisted}), so a token an earlier logout kept may still be there. Restore read access to it, then run threenative logout again.`,
+ );
+ return claims;
+}
+
+/** `undefined` once the site says the token is dead (200 revoked, 401 already gone), else why not. */
+async function revokeToken(origin: string, token: string): Promise {
+ const kept = "The token is kept, so run threenative logout again.";
+ try {
+ const reply = await request(origin, "/api/store/token", {
+ headers: { authorization: `Bearer ${token}` },
+ method: "DELETE",
+ });
+ if (reply.status === 200 || reply.status === 401) return undefined;
+ return new CliExit(4, `Could not revoke the token (${reply.status}). ${kept}`);
+ } catch (error) {
+ if (!(error instanceof CliExit)) throw error;
+ return new CliExit(error.code, `${error.message} ${kept}`);
+ }
+}
diff --git a/packages/create-threenative/src/commands.ts b/packages/create-threenative/src/commands.ts
index 5eecaa8bae..43651854e1 100644
--- a/packages/create-threenative/src/commands.ts
+++ b/packages/create-threenative/src/commands.ts
@@ -1,13 +1,20 @@
/** The complete `threenative` command surface, in one place so the help text, the dispatcher and
- * the documentation checks cannot disagree. Adding a command means adding it here, teaching
- * `threenative.ts` to run it, and re-making the owner decision recorded in AGENTS.md — v1
- * shipped 178 command forms, in a product whose founding constraint is that models are bad at
- * discovering novel APIs. */
-export type PublicCommand = "build" | "doctor";
+ * the documentation checks cannot disagree. Adding a command means adding it here and teaching
+ * `threenative.ts` to run it. */
+export type PublicCommand = "build" | "doctor" | "login" | "logout" | "deploy";
-export const threenativeCommands: readonly PublicCommand[] = ["build", "doctor"];
+export const threenativeCommands: readonly PublicCommand[] = [
+ "build",
+ "doctor",
+ "deploy",
+ "login",
+ "logout",
+];
export const commandSummaries: Record = {
build: "Build web or native output.",
doctor: "Check this project and report what would break a build.",
+ deploy: "Build for the web and publish the game to its share link on threenative.com.",
+ login: "Sign in to your threenative.com account.",
+ logout: "Sign out and revoke this machine's token.",
};
diff --git a/packages/create-threenative/src/deploy.ts b/packages/create-threenative/src/deploy.ts
new file mode 100644
index 0000000000..25b11730b1
--- /dev/null
+++ b/packages/create-threenative/src/deploy.ts
@@ -0,0 +1,241 @@
+/** `threenative deploy`: build the web bundle, pack it and PUT it to Studio's share endpoint,
+ * which is what turns a game into a link a friend can open. */
+import { spawn } from "node:child_process";
+import { randomUUID } from "node:crypto";
+import { link, mkdir, readFile, readdir, rename, rm, writeFile } from "node:fs/promises";
+import path from "node:path";
+import { CliExit, request, requireToken, serverMessage } from "./account.js";
+
+const SHARE_BUILD_MAX_BYTES = 50 * 1024 * 1024;
+const MAX_FILES = 2_000;
+
+async function walk(root: string, dir = ""): Promise {
+ const files: string[] = [];
+ for (const entry of await readdir(path.join(root, dir), { withFileTypes: true })) {
+ const relative = dir === "" ? entry.name : `${dir}/${entry.name}`;
+ if (entry.isDirectory()) files.push(...(await walk(root, relative)));
+ else if (entry.isFile()) files.push(relative);
+ }
+ return files;
+}
+
+/** ponytail: copy of Studio's `src/server/release/shareArchive.ts` packDirectory. The PRD-904
+ * AC-6 e2e uploads this archive to Studio's real parser, so any drift fails there; move it to a
+ * shared package if a third writer appears. Layout: u32BE name length, name, u32BE size, data,
+ * depth-first in readdir order, with a `.br`/`.gz` sibling dropped when the original is present. */
+export async function packDirectory(root: string): Promise {
+ const all = await walk(root);
+ const present = new Set(all);
+ const files = all.filter(
+ (file) => !(/\.(br|gz)$/u.test(file) && present.has(file.replace(/\.(br|gz)$/u, ""))),
+ );
+ if (files.length > MAX_FILES)
+ throw new CliExit(4, `The build has ${files.length} files; the limit is ${MAX_FILES}.`);
+ const parts: Buffer[] = [];
+ let bytes = 0;
+ for (const file of files) {
+ const data = await readFile(path.join(root, file));
+ bytes += data.length;
+ if (bytes > SHARE_BUILD_MAX_BYTES)
+ throw new CliExit(4, "The build is bigger than 50 MB, the most a share link holds.");
+ const name = Buffer.from(file, "utf8");
+ const head = Buffer.alloc(4);
+ head.writeUInt32BE(name.length);
+ const size = Buffer.alloc(4);
+ size.writeUInt32BE(data.length);
+ parts.push(head, name, size, data);
+ }
+ return Buffer.concat(parts);
+}
+
+const DEFAULT_STUDIO = "https://studio.threenative.com";
+const PACKAGE_MANAGERS = ["npm", "pnpm", "yarn", "bun"] as const;
+
+export function studioOrigin(studio = process.env.THREENATIVE_STUDIO): string {
+ return (studio ?? DEFAULT_STUDIO).replace(/\/+$/u, "");
+}
+
+/** The agent pnpm/yarn/npm/bun started this CLI, so `build:web` runs with the game's own lockfile. */
+function packageManager(): string {
+ const name = (process.env.npm_config_user_agent ?? "").split("/")[0] ?? "";
+ return PACKAGE_MANAGERS.includes(name as (typeof PACKAGE_MANAGERS)[number]) ? name : "npm";
+}
+
+async function runBuildScript(cwd: string): Promise {
+ const exitCode = await new Promise((resolve) => {
+ const child = spawn(packageManager(), ["run", "build:web"], {
+ cwd,
+ shell: process.platform === "win32",
+ stdio: "inherit",
+ });
+ child.on("error", () => resolve(1));
+ child.on("exit", (code) => resolve(code ?? 1));
+ });
+ if (exitCode !== 0) throw new CliExit(4, "build:web failed.");
+}
+
+interface IProjectManifest {
+ name?: string;
+ scripts?: Record;
+}
+
+interface IShareFile {
+ /** 36-char UUID sent as `key` on the first deploy, so a lost reply retries onto one game. */
+ deployKey?: string;
+ projectId?: string;
+}
+
+async function readJson(file: string): Promise {
+ try {
+ return JSON.parse(await readFile(file, "utf8")) as T;
+ } catch {
+ return undefined;
+ }
+}
+
+/** Written beside and renamed over, so an interrupted write never leaves a truncated file that loses
+ * the deploy key (the next deploy would then make a second game). */
+async function writeShareFile(file: string, share: IShareFile): Promise {
+ await mkdir(path.dirname(file), { recursive: true });
+ const tmp = `${file}.${randomUUID()}.tmp`;
+ try {
+ await writeFile(tmp, `${JSON.stringify(share, null, 2)}\n`, { flag: "wx" });
+ await rename(tmp, file);
+ } catch (error) {
+ await rm(tmp, { force: true });
+ throw error;
+ }
+}
+
+/** The first deploy's key, claimed once per checkout. `link` creates share.json only if it does not
+ * exist yet, with its whole content, so two first deploys started together agree on one key: the
+ * one that loses the link reads the winner's key instead of minting a second game. */
+async function claimDeployKey(file: string): Promise {
+ await mkdir(path.dirname(file), { recursive: true });
+ const mine = randomUUID();
+ const tmp = `${file}.${mine}.tmp`;
+ await writeFile(tmp, `${JSON.stringify({ deployKey: mine }, null, 2)}\n`, { flag: "wx" });
+ try {
+ await link(tmp, file);
+ return mine;
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === "EEXIST") return await theirKey(file);
+ // ponytail: a volume with no hard links (some network and FAT mounts) takes an exclusive create
+ // instead. Still one key per checkout; a deploy started in the same instant may read the file
+ // before its few bytes land and stop with exit 4. A lock file if that ever bites.
+ try {
+ await writeFile(file, `${JSON.stringify({ deployKey: mine }, null, 2)}\n`, { flag: "wx" });
+ return mine;
+ } catch (fallback) {
+ if ((fallback as NodeJS.ErrnoException).code === "EEXIST") return await theirKey(file);
+ // Created but not written: an empty share.json would stop every later deploy, so it goes.
+ await rm(file, { force: true });
+ throw fallback;
+ }
+ } finally {
+ await rm(tmp, { force: true });
+ }
+}
+
+/** The key another first deploy from this checkout already claimed. Without hard links its file can
+ * exist a moment before its bytes do, so an empty read is retried for about a second. */
+async function theirKey(file: string): Promise {
+ for (let attempt = 0; attempt < 40; attempt += 1) {
+ const theirs = (await readJson(file))?.deployKey;
+ if (typeof theirs === "string" && theirs !== "") return theirs;
+ await new Promise((done) => setTimeout(done, 25));
+ }
+ throw new CliExit(4, `${file} exists but holds no deploy key; fix or delete it.`);
+}
+
+export interface IDeployOptions {
+ cwd?: string;
+ out?: (line: string) => void;
+ runBuild?: (cwd: string) => Promise;
+ studio?: string;
+ token?: string;
+}
+
+export interface IDeployResult {
+ projectId: string;
+ shareUrl: string;
+}
+
+export async function deploy(options: IDeployOptions = {}): Promise {
+ const cwd = options.cwd ?? process.cwd();
+ const out = options.out ?? ((line: string) => process.stdout.write(`${line}\n`));
+ const studio = studioOrigin(options.studio);
+ const token = options.token ?? (await requireToken());
+
+ const manifest = await readJson(path.join(cwd, "package.json"));
+ if (manifest === undefined)
+ throw new CliExit(2, "No package.json here. Run threenative deploy inside a game.");
+ if (manifest.scripts?.["build:web"] === undefined)
+ throw new CliExit(2, "package.json has no build:web script.");
+ if (manifest.name === undefined || manifest.name === "")
+ throw new CliExit(2, "package.json has no name.");
+
+ await (options.runBuild ?? runBuildScript)(cwd);
+ const archive = await packDirectory(path.join(cwd, "dist")).catch((error: unknown) => {
+ if ((error as NodeJS.ErrnoException | undefined)?.code === "ENOENT")
+ throw new CliExit(4, "The build wrote no dist/ folder.");
+ throw error;
+ });
+
+ const sharePath = path.join(cwd, ".threenative", "share.json");
+ const previous = await readJson(sharePath);
+ const previousProject = typeof previous?.projectId === "string" ? previous.projectId : "";
+ const previousKey =
+ typeof previous?.deployKey === "string" && previous.deployKey !== ""
+ ? previous.deployKey
+ : undefined;
+ const query = new URLSearchParams({ name: manifest.name });
+ // Later deploys name the game they already own. A first deploy has no id yet, so it sends a key
+ // Studio can recognize the game by instead — written to share.json before the upload, so a reply
+ // lost on the way back still lands on that same game when this command runs again.
+ let deployKey = previousKey;
+ if (previousProject !== "") {
+ query.set("projectId", previousProject);
+ } else {
+ if (deployKey === undefined) deployKey = await claimDeployKey(sharePath);
+ query.set("key", deployKey);
+ }
+
+ const reply = await request(studio, `/api/cli/share?${query.toString()}`, {
+ // fetch's BodyInit wants a plain view, not Node's Buffer subclass.
+ body: new Uint8Array(archive),
+ headers: {
+ authorization: `Bearer ${token}`,
+ "content-type": "application/octet-stream",
+ },
+ method: "PUT",
+ });
+ if (reply.status === 401)
+ throw new CliExit(
+ 3,
+ `${serverMessage(reply.body, "This machine's token was refused.")} Run threenative login.`,
+ );
+ if (reply.status < 200 || reply.status >= 300)
+ throw new CliExit(
+ 4,
+ serverMessage(
+ reply.body,
+ reply.statusText === ""
+ ? `The server refused the upload (${reply.status}).`
+ : reply.statusText,
+ ),
+ );
+
+ const result = reply.body as { projectId?: unknown; shareUrl?: unknown };
+ const savedProject = typeof result?.projectId === "string" ? result.projectId : "";
+ const shareUrl = typeof result?.shareUrl === "string" ? result.shareUrl : "";
+ if (shareUrl === "") throw new CliExit(4, "The server returned no share link.");
+ const saved: IShareFile = {};
+ if (savedProject !== "") saved.projectId = savedProject;
+ if (deployKey !== undefined) saved.deployKey = deployKey;
+ if (previous?.projectId !== saved.projectId || previous?.deployKey !== saved.deployKey)
+ await writeShareFile(sharePath, saved);
+ // The link alone, last: an agent parses this line, not the prose above it.
+ out(shareUrl);
+ return { projectId: savedProject, shareUrl };
+}
diff --git a/packages/create-threenative/src/threenative.ts b/packages/create-threenative/src/threenative.ts
index b2c7c7f1b8..cebd2ecaaa 100644
--- a/packages/create-threenative/src/threenative.ts
+++ b/packages/create-threenative/src/threenative.ts
@@ -1,6 +1,8 @@
#!/usr/bin/env node
+import { CliExit, login, logout } from "./account.js";
import { build, buildHelp, parseBuildArgs } from "./build.js";
import { type PublicCommand, commandSummaries, threenativeCommands } from "./commands.js";
+import { deploy } from "./deploy.js";
import {
type DoctorMode,
type DoctorTarget,
@@ -13,6 +15,10 @@ import { fixAuthoringLayer } from "./index.js";
const DOCTOR_TARGETS: readonly DoctorTarget[] = ["web", "desktop", "android", "ios"];
const DOCTOR_MODES: readonly DoctorMode[] = ["debug", "release"];
+function isPublicCommand(value: string): value is PublicCommand {
+ return threenativeCommands.some((command) => command === value);
+}
+
export function cliHelp(command?: PublicCommand): string {
if (command === "build") return buildHelp();
if (command === "doctor") {
@@ -43,11 +49,52 @@ export function cliHelp(command?: PublicCommand): string {
"Exits 0 when nothing failed, 1 when a check failed.",
].join("\n")}\n`;
}
+ if (command === "login") {
+ return `${[
+ "Usage: threenative login [--no-browser]",
+ "",
+ "Opens threenative.com, asks you to authorize this machine, and saves the token it grants",
+ "in the threenative config directory, owner-only (0600).",
+ "--no-browser prints the link and the code instead of launching a browser, for signing in",
+ " here with a browser on another machine.",
+ "THREENATIVE_TOKEN overrides the saved token for every command that needs one, so CI can",
+ " publish without writing this file.",
+ "THREENATIVE_SITE names another site origin.",
+ "Exits 0 signed in, 2 bad arguments, 3 sign in again, 4 refused by the server, 5 no network.",
+ ].join("\n")}\n`;
+ }
+ if (command === "logout") {
+ return `${[
+ "Usage: threenative logout",
+ "",
+ "Revokes this machine's saved token on threenative.com first. The token file is deleted",
+ " only once the site confirms the revocation, or says the token is already invalid.",
+ "Otherwise the file is kept and the command exits 4 (refused) or 5 (no network), so it can",
+ " be run again and still revoke the token.",
+ "With no saved token it prints 'Not signed in.' and does nothing.",
+ "THREENATIVE_SITE names another site origin.",
+ "Exits 0 signed out, 4 the server refused the revocation, 5 no network.",
+ ].join("\n")}\n`;
+ }
+ if (command === "deploy") {
+ return `${[
+ "Usage: threenative deploy",
+ "",
+ "Runs this package's build:web script with its own package manager, then uploads dist/",
+ "to studio.threenative.com and prints the share link on its own line, last.",
+ ".threenative/share.json remembers the project id and the first deploy's key, so the next",
+ " deploy updates the same link instead of making another one. Commit it with the game.",
+ "THREENATIVE_STUDIO names another Studio origin; THREENATIVE_SITE is the site login uses;",
+ " THREENATIVE_TOKEN signs in for one run without a saved token.",
+ "Exits 0 published, 2 bad arguments (no build:web script), 3 sign in again, 4 the server",
+ " refused it or the build failed, 5 no network.",
+ ].join("\n")}\n`;
+ }
return `${[
"Usage: threenative [options]",
"",
"Commands:",
- ...threenativeCommands.map((command) => ` ${command.padEnd(6)} ${commandSummaries[command]}`),
+ ...threenativeCommands.map((command) => ` ${command.padEnd(7)} ${commandSummaries[command]}`),
"",
"Run 'threenative --help' for command-specific help.",
].join("\n")}\n`;
@@ -56,8 +103,7 @@ export function cliHelp(command?: PublicCommand): string {
function helpFor(argv: readonly string[]): string {
const command = argv[0];
if (command === undefined || command.startsWith("-")) return cliHelp();
- if (command === "build") return cliHelp("build");
- if (command === "doctor") return cliHelp("doctor");
+ if (isPublicCommand(command)) return cliHelp(command);
throw new Error(`Unknown threenative command '${command}'.\n${cliHelp()}`);
}
@@ -134,13 +180,39 @@ export async function runDoctorCommand(
return report.pass && kept === 0 ? 0 : 1;
}
+export async function runLoginCommand(argv: readonly string[]): Promise {
+ let open = true;
+ for (const arg of argv) {
+ if (arg === "--no-browser") {
+ open = false;
+ continue;
+ }
+ throw new CliExit(2, `login: unknown option '${arg}'. Try 'threenative login --no-browser'.`);
+ }
+ await login({ open });
+}
+
export async function main(argv = process.argv.slice(2)): Promise {
if (argv.includes("--help") || argv.includes("-h")) {
process.stdout.write(helpFor(argv));
return;
}
- if (argv[0] === "doctor") {
- process.exitCode = await runDoctorCommand(argv.slice(1));
+ const [command, ...rest] = argv;
+ if (command === "login") {
+ await runLoginCommand(rest);
+ return;
+ }
+ if (command === "logout" || command === "deploy") {
+ if (rest.length > 0) throw new CliExit(2, `${command} takes no arguments.`);
+ if (command === "logout") {
+ await logout();
+ return;
+ }
+ await deploy();
+ return;
+ }
+ if (command === "doctor") {
+ process.exitCode = await runDoctorCommand(rest);
return;
}
await build(parseBuildArgs(argv));
@@ -148,5 +220,5 @@ export async function main(argv = process.argv.slice(2)): Promise {
main().catch((error: unknown) => {
process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
- process.exitCode = 1;
+ process.exitCode = error instanceof CliExit ? error.code : 1;
});
From 496799b2c65966f93877d7e7eef8ddfd3a77d7a3 Mon Sep 17 00:00:00 2001
From: Joao Paulo Furtado
Date: Sat, 21 Nov 2026 23:34:18 -0700
Subject: [PATCH 3/3] chore(release): prepare the 0.3.21 cohort
Prepared with `pnpm release:prepare` and `pnpm scaffold:pin`: core and the cohort 0.3.20 -> 0.3.21,
create-threenative 0.2.25 -> 0.2.26. Carries #710 and #712 (PRD-904: threenative login, logout and deploy).
proof: prepare-release (17 packages, 6 MCP servers, nothing published), scaffold pins 16 kits
---
.../playtests/replay.playtest.json | 2 +-
packages/animation-mcp/package.json | 2 +-
packages/animation-mcp/src/index.ts | 2 +-
packages/assets/package.json | 2 +-
packages/blender-bridge/package.json | 2 +-
packages/core/mcp/animation-server.mjs | 2 +-
packages/core/mcp/engine-server.mjs | 2 +-
packages/core/mcp/servers.mjs | 6 +-
packages/core/package.json | 4 +-
packages/core/src/version.ts | 2 +-
.../__tests__/scaffold.spec.ts | 64 +++++++++----------
.../animation-mcp-tools.json | 6 +-
.../create-threenative/engine-mcp-tools.json | 2 +-
packages/create-threenative/package.json | 4 +-
.../templates/action-rpg/package.json | 14 ++--
.../templates/adventure/package.json | 14 ++--
.../templates/collectathon/package.json | 14 ++--
.../templates/kart/package.json | 12 ++--
.../templates/minimal/package.json | 12 ++--
.../templates/platformer/package.json | 14 ++--
.../templates/puzzle/package.json | 14 ++--
.../templates/racing/package.json | 14 ++--
.../templates/rain/package.json | 12 ++--
.../templates/rts/package.json | 12 ++--
.../templates/runner/package.json | 14 ++--
.../templates/sailing/package.json | 14 ++--
.../templates/shooter/package.json | 14 ++--
.../templates/snow/package.json | 14 ++--
.../templates/starter/package.json | 14 ++--
.../templates/tower-defense/package.json | 14 ++--
packages/engine-mcp/__tests__/server.spec.ts | 2 +-
packages/engine-mcp/package.json | 2 +-
packages/engine-mcp/src/index.ts | 2 +-
packages/metahuman/package.json | 2 +-
packages/physics/package.json | 4 +-
packages/playtest/package.json | 2 +-
packages/procedural-animals/package.json | 2 +-
packages/procedural-environment/package.json | 2 +-
packages/raw-unreal/package.json | 2 +-
packages/runtime-native/package.json | 2 +-
packages/terrain/package.json | 8 +--
packages/terrain/src/core/io.ts | 2 +-
packages/three-native/package.json | 2 +-
packages/ueformat/package.json | 2 +-
packages/ui/package.json | 4 +-
45 files changed, 179 insertions(+), 179 deletions(-)
diff --git a/examples/abyss-framework/playtests/replay.playtest.json b/examples/abyss-framework/playtests/replay.playtest.json
index a952ed033d..c8d153177d 100644
--- a/examples/abyss-framework/playtests/replay.playtest.json
+++ b/examples/abyss-framework/playtests/replay.playtest.json
@@ -17,7 +17,7 @@
"world": {
"runtime": {
"agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/151.0.0.0 Safari/537.36",
- "core": "0.3.20",
+ "core": "0.3.21",
"randomState": 90210,
"rapier": null,
"step": 0.016666666666666666
diff --git a/packages/animation-mcp/package.json b/packages/animation-mcp/package.json
index 7ff2c6537d..b5024d9e73 100644
--- a/packages/animation-mcp/package.json
+++ b/packages/animation-mcp/package.json
@@ -1,6 +1,6 @@
{
"name": "threenative-animation-mcp",
- "version": "0.1.17",
+ "version": "0.1.18",
"license": "MIT",
"description": "Author, repair and verify character animation through one MCP: inspect rigs, attach props, edit and verify clips, and open a calibrator view.",
"keywords": [
diff --git a/packages/animation-mcp/src/index.ts b/packages/animation-mcp/src/index.ts
index 5225a35fb4..01280ec8d5 100644
--- a/packages/animation-mcp/src/index.ts
+++ b/packages/animation-mcp/src/index.ts
@@ -280,7 +280,7 @@ function openView(input: z.output) {
}
export function createAnimationServer(): McpServer {
- const server = new McpServer({ name: "threenative-animation", version: "0.1.17" });
+ const server = new McpServer({ name: "threenative-animation", version: "0.1.18" });
server.registerTool(
"animation_inspect",
diff --git a/packages/assets/package.json b/packages/assets/package.json
index 08744a2699..5900a0838b 100644
--- a/packages/assets/package.json
+++ b/packages/assets/package.json
@@ -1,6 +1,6 @@
{
"name": "@threenative/assets",
- "version": "0.3.21",
+ "version": "0.3.22",
"license": "MIT",
"description": "Content-addressed asset compile step for ThreeNative games.",
"keywords": ["threenative", "three", "threejs", "assets", "gltf", "asset-pipeline", "webgpu"],
diff --git a/packages/blender-bridge/package.json b/packages/blender-bridge/package.json
index 1a2c92f78a..24529060db 100644
--- a/packages/blender-bridge/package.json
+++ b/packages/blender-bridge/package.json
@@ -1,6 +1,6 @@
{
"name": "@threenative/blender-bridge",
- "version": "0.2.13",
+ "version": "0.2.14",
"license": "MIT",
"description": "Runs an installed Blender headlessly so a downloaded .fbx becomes a GLB a ThreeNative game loads. Ships no Blender.",
"keywords": ["threenative", "blender", "fbx", "gltf"],
diff --git a/packages/core/mcp/animation-server.mjs b/packages/core/mcp/animation-server.mjs
index b2a9def20e..0942b1e450 100755
--- a/packages/core/mcp/animation-server.mjs
+++ b/packages/core/mcp/animation-server.mjs
@@ -252,7 +252,7 @@ void main() {
}`,$e={meshphysical_vert:yk,meshphysical_frag:Sk},ae={common:{diffuse:{value:new ft(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new Ce},alphaMap:{value:null},alphaMapTransform:{value:new Ce},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new Ce}},envmap:{envMap:{value:null},envMapRotation:{value:new Ce},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:.98},dfgLUT:{value:null}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1},aoMapTransform:{value:new Ce}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new Ce}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new Ce},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new Ce},normalScale:{value:new mn(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new Ce},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new Ce}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new Ce}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new Ce}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new ft(16777215)}},lights:{ambientLightColor:{value:[]},lightProbe:{value:[]},sunLights:{value:[],properties:{direction:{},color:{}}},sunLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},sunShadowMatrix:{value:[]},sunShadowCascade:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{}}},directionalLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{}}},spotLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},spotLightMap:{value:[]},spotLightMatrix:{value:[]},pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{}}},pointLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{},shadowCameraNear:{},shadowCameraFar:{}}},pointShadowMatrix:{value:[]},hemisphereLights:{value:[],properties:{direction:{},skyColor:{},groundColor:{}}},rectAreaLights:{value:[],properties:{color:{},position:{},width:{},height:{}}},ltc_1:{value:null},ltc_2:{value:null},probesSH:{value:[]},probesMin:{value:[]},probesMax:{value:[]},probesResolution:{value:[]}},points:{diffuse:{value:new ft(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:new Ce},alphaTest:{value:0},uvTransform:{value:new Ce}},sprite:{diffuse:{value:new ft(16777215)},opacity:{value:1},center:{value:new mn(.5,.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new Ce},alphaMap:{value:null},alphaMapTransform:{value:new Ce},alphaTest:{value:0}}},VE={basic:{uniforms:Nt([ae.common,ae.specularmap,ae.envmap,ae.aomap,ae.lightmap,ae.fog])},lambert:{uniforms:Nt([ae.common,ae.specularmap,ae.envmap,ae.aomap,ae.lightmap,ae.emissivemap,ae.bumpmap,ae.normalmap,ae.displacementmap,ae.fog,ae.lights,{emissive:{value:new ft(0)},envMapIntensity:{value:1}}])},phong:{uniforms:Nt([ae.common,ae.specularmap,ae.envmap,ae.aomap,ae.lightmap,ae.emissivemap,ae.bumpmap,ae.normalmap,ae.displacementmap,ae.fog,ae.lights,{emissive:{value:new ft(0)},specular:{value:new ft(1118481)},shininess:{value:30},envMapIntensity:{value:1}}])},standard:{uniforms:Nt([ae.common,ae.envmap,ae.aomap,ae.lightmap,ae.emissivemap,ae.bumpmap,ae.normalmap,ae.displacementmap,ae.roughnessmap,ae.metalnessmap,ae.fog,ae.lights,{emissive:{value:new ft(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}])},toon:{uniforms:Nt([ae.common,ae.aomap,ae.lightmap,ae.emissivemap,ae.bumpmap,ae.normalmap,ae.displacementmap,ae.gradientmap,ae.fog,ae.lights,{emissive:{value:new ft(0)}}])},matcap:{uniforms:Nt([ae.common,ae.bumpmap,ae.normalmap,ae.displacementmap,ae.fog,{matcap:{value:null}}])},points:{uniforms:Nt([ae.points,ae.fog])},dashed:{uniforms:Nt([ae.common,ae.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}])},depth:{uniforms:Nt([ae.common,ae.displacementmap])},normal:{uniforms:Nt([ae.common,ae.bumpmap,ae.normalmap,ae.displacementmap,{opacity:{value:1}}])},sprite:{uniforms:Nt([ae.sprite,ae.fog])},background:{uniforms:{uvTransform:{value:new Ce}}},backgroundCube:{uniforms:{backgroundRotation:{value:new Ce}}},distance:{uniforms:Nt([ae.common,ae.displacementmap,{referencePosition:{value:new qe},nearDistance:{value:1},farDistance:{value:1e3}}])},shadow:{uniforms:Nt([ae.lights,ae.fog,{color:{value:new ft(0)},opacity:{value:1}}])}};VE.physical={uniforms:Nt([VE.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new Ce},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new Ce},clearcoatNormalScale:{value:new mn(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new Ce},diffuseRoughness:{value:0},diffuseRoughnessMap:{value:null},diffuseRoughnessMapTransform:{value:new Ce},dispersion:{value:0},retroreflectivity:{value:0},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new Ce},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new Ce},sheen:{value:0},sheenColor:{value:new ft(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new Ce},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new Ce},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new Ce},transmissionSamplerSize:{value:new mn},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new Ce},attenuationDistance:{value:0},attenuationColor:{value:new ft(0)},specularColor:{value:new ft(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new Ce},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new Ce},anisotropyVector:{value:new mn},anisotropyMap:{value:null},anisotropyMapTransform:{value:new Ce}}]),vertexShader:$e.meshphysical_vert,fragmentShader:$e.meshphysical_frag};var Ik=new Ce;Ik.set(-1,0,0,0,1,0,0,0,1);var Ck=new Ce;Ck.set(-1,0,0,0,1,0,0,0,1);var Pk=t=>{let e=t.toLowerCase();if(e==="left")return t==="LEFT"?"RIGHT":"Right";if(e==="right")return t==="RIGHT"?"LEFT":"Left"};function jE(t){let e=t.replace(/left|right/giu,i=>Pk(i)??i);if(e!==t)return e;let r=t.replace(/(^|[._\s-])([lrLR])(?=$|[._\s-]|\d)/gu,(i,n,s)=>`${n}${s==="L"?"R":s==="R"?"L":s==="l"?"r":"l"}`);return r===t?void 0:r}function GE(t,e){let r=[],i=[];return t.forEach((n,s)=>{let o=e(n);o!==void 0&&(r.push(s),i.push(o));}),{source:r,times:i}}function HE(t,e){let r=new qe(t[0]??0,t[1]??0,t[2]??0).applyQuaternion(new Pt(e[0]??0,e[1]??0,e[2]??0,e[3]??1).invert());return [r.x,r.y,r.z]}var Nk=()=>new Jt().registerExtensions(Qt);function gn(t,e,r){let{times:i,values:n}=t,s=i.length,o=t.interpolation==="CUBICSPLINE",a=o?e*3:e,c=(_,y)=>n[_*a+(o?e:0)+y]??0,l=i[0]??0,u=i[s-1]??l,d=_=>Array.from({length:e},(y,R)=>c(_,R));if(s===0)return new Array(e).fill(0);if(r<=l)return d(0);if(r>=u)return d(s-1);let f=1;for(;f_+((v[y]??0)-_)*h)}function Ok(t,e,r){let i=e.get(t.getName()),n=[...t.getTranslation()],s=[...t.getRotation()],o=[...t.getScale()],a=i?.get("translation");a!==void 0&&n.splice(0,3,...gn(a,3,r));let c=i?.get("rotation");c!==void 0&&s.splice(0,4,...gn(c,4,r));let l=i?.get("scale");return l!==void 0&&o.splice(0,3,...gn(l,3,r)),{matrix:new nn().compose(new qe(n[0]??0,n[1]??0,n[2]??0),new Pt(s[0]??0,s[1]??0,s[2]??0,s[3]??1),new qe(o[0]??1,o[1]??1,o[2]??1)),translation:n}}function qE(t,e){let r=0;for(let i of e.get(t.getName())?.values()??[])r=Math.max(r,i.times.at(-1)??0);for(let i of t.listChildren())r=Math.max(r,qE(i,e));return r}async function jh(t,e,r=30){return v0(await Nk().read(t),e,r)}function v0(t,e,r=30){let i=t.getRoot().listAnimations().find(p=>p.getName()===e);if(i===void 0){let p=t.getRoot().listAnimations().map(g=>g.getName());throw new Error(`The GLB has no clip '${e}'. It carries: ${p.length===0?"none":p.join(", ")}.`)}let n=new Map;for(let p of i.listChannels()){let g=p.getTargetNode(),m=p.getSampler(),S=p.getTargetPath();if(g===null||m===null||S===null)continue;let h=m.getInput()?.getArray(),v=m.getOutput()?.getArray();if(h==null||v===null||v===void 0)continue;let _=n.get(g.getName())??new Map;_.set(S,{interpolation:m.getInterpolation(),times:h,values:v}),n.set(g.getName(),_);}let s=t.getRoot().listScenes().flatMap(p=>p.listChildren()),o=s.reduce((p,g)=>Math.max(p,qE(g,n)),0),a=t.getRoot().listSkins().flatMap(p=>p.listJoints()).map(p=>p.getName()),c=new Set(a.length>0?a:t.getRoot().listNodes().map(p=>p.getName()).filter(p=>p.length>0)),l=[...c],u={},d=Math.max(1,Math.round(o*r)),f=[];for(let p=0;p<=d;p+=1){let g=Math.min(o,p/r),m={},S={},h={},v=(_,y,R)=>{let T=y.clone().multiply(Ok(_,n,g).matrix),b=_.getName();if(c.has(b)){let E=new qe().setFromMatrixPosition(T),M=new Pt().setFromRotationMatrix(T),N=new Pt().setFromRotationMatrix(y);m[b]=[E.x,E.y,E.z],S[b]=[M.x,M.y,M.z,M.w],h[b]=[N.x,N.y,N.z,N.w],R!==void 0&&c.has(R)&&(u[b]=R);}for(let E of _.listChildren())v(E,T,b);};for(let _ of s)v(_,new nn);f.push({parents:h,positions:m,rotations:S,time:g});}return {bones:l,duration:o,fps:r,frames:f,parentsOf:u}}var zk=()=>new Jt().registerExtensions(Qt),Gh=t=>t==="rotation"?4:3;function xi(t){let e=t.getSampler(),r=e?.getInput()?.getArray(),i=e?.getOutput()?.getArray();if(!(e===null||r===null||r===void 0||i===null||i===void 0))return {interpolation:e.getInterpolation(),times:r,values:i}}function Fa(t,e,r,i,n){let s=e.getSampler();if(s===null)return;let o=t.getRoot().listBuffers()[0]??t.createBuffer(),a=t.createAccessor(`${e.getTargetNode()?.getName()}.time`).setType("SCALAR").setArray(new Float32Array(r)).setBuffer(o),c=t.createAccessor(`${e.getTargetNode()?.getName()}.${e.getTargetPath()}`).setType(n===4?"VEC4":"VEC3").setArray(new Float32Array(i)).setBuffer(o);s.setInput(a).setOutput(c).setInterpolation("LINEAR");}function WE(t,e,r,i){for(let n of e.listChannels()){let s=xi(n);if(s===void 0)continue;let o=n.getTargetPath()??"translation",a=Gh(o),c=s.interpolation==="CUBICSPLINE",l=c?a*3:a,{source:u,times:d}=GE([...s.times],r);if(d.length===0)throw new Error(`'${e.getName()}' keeps no keyframes in that window; the edit would leave an empty clip.`);let f=[];for(let p of u)for(let g=0;gv>g),S=m===-1?d.length:m;d.splice(S,0,g);let h=c?Array.from({length:3*a},(v,_)=>_>=a&&_=i)){f.push(m-r);for(let S=0;SMath.min(n,c/r));for(let a of i){let c=xi(a);if(c===void 0)continue;let l=Gh(a.getTargetPath()??"translation"),u=o.flatMap(d=>gn(c,l,d));Fa(t,a,o,u,l);}}function kk(t,e){let r=new Map(t.getRoot().listNodes().map(i=>[i.getName(),i]));for(let i of e.listChannels()){let n=i.getTargetNode(),s=xi(i);if(n===null||s===void 0)continue;let o=i.getTargetPath()??"translation",a=Gh(o),c=[];for(let d=0;d+a<=s.values.length;d+=a){let f=Array.from({length:a},(p,g)=>s.values[d+g]??0);o==="translation"&&(f[0]=-(f[0]??0)),o==="rotation"&&(f[1]=-(f[1]??0),f[2]=-(f[2]??0)),c.push(...f);}Fa(t,i,[...s.times],c,a);let l=jE(n.getName()),u=l===void 0?void 0:r.get(l);u!==void 0&&i.setTargetNode(u);}}function Uk(t,e,r){let i=v0(t,e.getName()),n=r.feet.length>0?r.feet:i.bones.filter(s=>/foot/iu.test(s));if(n.length===0)throw new Error("No foot bones to lock: name them with 'feet'.");for(let s of n){let o=i.frames.map(g=>g.positions[s]?.[1]??0),a=Math.min(...o),c=e.listChannels().find(g=>g.getTargetNode()?.getName()===s&&g.getTargetPath()==="translation");if(c===void 0)continue;let l=xi(c);if(l===void 0)continue;let u=[],d=[],f,p=false;i.frames.forEach((g,m)=>{let S=g.positions[s];if(S===void 0)return;(S[1]??0)<=a+r.contact?(f??=S,p=true):(p=false,f=void 0);let v=p&&f!==void 0?[(f[0]??0)-(S[0]??0),0,(f[2]??0)-(S[2]??0)]:[0,0,0],_=HE(v,g.parents[s]??[0,0,0,1]);u.push(g.time),d.push((gn(l,3,g.time)[0]??0)+_[0],(gn(l,3,g.time)[1]??0)+_[1],(gn(l,3,g.time)[2]??0)+_[2]);}),Fa(t,c,u,d,3);}}function Fk(t,e,r){switch(r.kind){case "trim":{if(r.end<=r.start)throw new Error("trim needs an end after its start.");let i=$k(e);if(r.start>=i||r.end>i+1e-6)throw new Error(`trim asks for ${r.start}\u2013${r.end}s but '${e.getName()}' is ${i}s long.`);Dk(t,e,r.start,r.end);return}case "retime":if(!(r.speed>0))throw new Error("retime needs a speed above zero.");WE(t,e,i=>i/r.speed);return;case "loop-point":WE(t,e,i=>i<=r.time?i:void 0,r.time);return;case "resample":if(!(r.fps>0))throw new Error("resample needs an fps above zero.");Lk(t,e,r.fps);return;case "mirror":kk(t,e);return;case "foot-lock":Uk(t,e,r);return}}function KE(t,e,r){let i=t.getRoot().listAnimations().filter(n=>n.getName()===e);if(i.length===0)throw new Error(`The GLB has no clip '${e}' to edit.`);for(let n of r)for(let s of i)Fk(t,s,n);}async function ZE(t){return zk().read(t)}function Bk(t){let e=new Map;for(let r of t)r.op==="modify"&&e.set(r.clip,[...e.get(r.clip)??[],r.edit]);return e}async function XE(t,e){let r=await ZE(t.host),i=t.ops.some(o=>o.op==="attach")?await Iy(r,t):void 0,n=Bk(t.ops);for(let[o,a]of n)KE(r,o,a);return await new Jt().registerExtensions(Qt).write(e,r),{clips:i?.clips??[],edits:[...n.values()].reduce((o,a)=>o+a.length,0),file:e,modified:[...n.keys()]}}var ks=Object.freeze({contact:.03,jitter:.05,penetration:.01,seam:5,skate:.02,stretch:.02}),y0=(t,e)=>Math.hypot((t[0]??0)-(e[0]??0),(t[1]??0)-(e[1]??0),(t[2]??0)-(e[2]??0)),Vk=(t,e)=>Math.hypot((t[0]??0)-(e[0]??0),(t[2]??0)-(e[2]??0));function jk(t,e){let r=n=>Math.hypot(n[0]??0,n[1]??0,n[2]??0,n[3]??1)||1,i=((t[0]??0)*(e[0]??0)+(t[1]??0)*(e[1]??0)+(t[2]??0)*(e[2]??0)+(t[3]??1)*(e[3]??1))/(r(t)*r(e));return 2*Math.acos(Math.min(1,Math.abs(i)))*180/Math.PI}function S0(t,e=2){let r=[],i,n;for(let s of t)(i===void 0||n===void 0||s-n>e)&&(i!==void 0&&n!==void 0&&r.push({from:i,to:n}),i=s),n=s;return i!==void 0&&n!==void 0&&r.push({from:i,to:n}),r}function Gk(t,e,r,i){let n=[];for(let s of e){let o=t.frames.map(p=>p.positions[s]?.[1]??0),a=Math.min(...o),c=t.frames.map((p,g)=>({index:g,frame:p})).filter(({frame:p})=>(p.positions[s]?.[1]??0)<=a+i),l,u,d=()=>{u!==void 0&&(u.worst>r&&n.push({bone:s,detail:`the planted foot slid ${(u.worst*1e3).toFixed(0)} mm between frames ${u.first} and ${u.last}`,fromFrame:u.first,fromTime:t.frames[u.first]?.time??0,kind:"foot-skate",limit:r,measured:u.worst,toFrame:u.last,toTime:t.frames[u.last]?.time??0}),u=void 0,l=void 0);},f;for(let{index:p,frame:g}of c){f!==void 0&&p-f>1&&d(),l??=g;let m=Vk(g.positions[s]??[0,0,0],l.positions[s]??[0,0,0]);u??={first:p,last:p,worst:0},u.last=p,u.worst=Math.max(u.worst,m),f=p;}d();}return n}function Hk(t,e,r){let i=[];for(let n of e){let s=t.frames.map((o,a)=>({index:a,y:o.positions[n]?.[1]})).filter(({y:o})=>o!==void 0&&o<-r);for(let o of S0(s.map(({index:a})=>a))){let a=s.filter(({index:c})=>c>=o.from&&c<=o.to).reduce((c,{y:l})=>Math.min(c,l??0),0);i.push({bone:n,detail:`reaches ${(Math.abs(a)*1e3).toFixed(0)} mm below the floor`,fromFrame:o.from,fromTime:t.frames[o.from]?.time??0,kind:"ground-penetration",limit:r,measured:Math.abs(a),toFrame:o.to,toTime:t.frames[o.to]?.time??0});}}return i}function qk(t,e){let r=t.frames[0],i=t.frames.at(-1);if(r===void 0||i===void 0||t.frames.length<3)return [];let n,s=0;for(let o of t.bones){let a=r.rotations[o],c=i.rotations[o];if(a===void 0||c===void 0)continue;let l=jk(a,c);l<=e||(s+=1,(n===void 0||l>n.angle)&&(n={angle:l,bone:o}));}return n===void 0?[]:[{bone:n.bone,detail:`the clip ends ${n.angle.toFixed(1)}\xB0 from where it started${s>1?`, and ${s-1} more bones with it`:""}`,fromFrame:0,fromTime:r.time,kind:"loop-seam",limit:e,measured:n.angle,toFrame:t.frames.length-1,toTime:i.time}]}function Wk(t,e,r){let i=[];for(let n of e){let s=t.frames.map(l=>l.positions[n]),o=[],a=new Map,c=0;for(let l=1;lr&&(o.push(l),a.set(l,Math.max(a.get(l)??0,p)),c=Math.max(c,p));}for(let l of S0(o.map(u=>u)))i.push({bone:n,detail:`a frame-direction spike of ${((a.get(l.from)??c)*1e3).toFixed(0)} mm`,fromFrame:l.from,fromTime:t.frames[l.from]?.time??0,kind:"jitter",limit:r,measured:c,toFrame:l.to,toTime:t.frames[l.to]?.time??0});}return i}function Kk(t,e){let r=t.frames[0];if(r===void 0)return [];let i=[];for(let[n,s]of Object.entries(t.parentsOf)){let o=y0(r.positions[n]??[0,0,0],r.positions[s]??[0,0,0]);if(o<=1e-6)continue;let a=t.frames.map((l,u)=>({index:u,ratio:Math.abs(y0(l.positions[n]??[0,0,0],l.positions[s]??[0,0,0])/o-1)})).filter(({ratio:l})=>l>e);if(a.length===0)continue;let c=a.reduce((l,{ratio:u})=>Math.max(l,u),0);for(let l of S0(a.map(({index:u})=>u)))i.push({bone:n,detail:`distance to its parent '${s}' changes by ${(c*100).toFixed(1)}%`,fromFrame:l.from,fromTime:t.frames[l.from]?.time??0,kind:"bone-stretch",limit:e,measured:c,toFrame:l.to,toTime:t.frames[l.to]?.time??0});}return i}var Zk=new Set(["left-foot","right-foot"]);async function JE(t,e,r={}){let i=r.scale??1,n={contact:(r.thresholds?.contact??ks.contact)/i,jitter:(r.thresholds?.jitter??ks.jitter)/i,penetration:(r.thresholds?.penetration??ks.penetration)/i,seam:r.thresholds?.seam??ks.seam,skate:(r.thresholds?.skate??ks.skate)/i,stretch:r.thresholds?.stretch??ks.stretch},s=await jh(t,e,r.fps??30),o=Sh(s.bones).filter(c=>Zk.has(c.id)).map(c=>c.node),a=[...Gk(s,o,n.skate,n.contact),...Hk(s,s.bones,n.penetration),...qk(s,n.seam),...Wk(s,s.bones,n.jitter),...Kk(s,n.stretch)];return {bones:s.bones.length,clip:e,defects:a,duration:s.duration,file:t,fps:s.fps,frames:s.frames.length,passed:a.length===0,scale:i,thresholds:n}}var Jk=(()=>{let t=new Uint32Array(256);for(let e=0;e<256;e+=1){let r=e;for(let i=0;i<8;i+=1)r=r&1?3988292384^r>>>1:r>>>1;t[e]=r>>>0;}return t})();function Yk(t){let e=4294967295;for(let r of t)e=(Jk[(e^r)&255]??0)^e>>>8;return (e^4294967295)>>>0}function x0(t,e){let r=Buffer.alloc(4);r.writeUInt32BE(e.length,0);let i=Buffer.concat([Buffer.from(t,"ascii"),Buffer.from(e)]),n=Buffer.alloc(4);return n.writeUInt32BE(Yk(i),0),Buffer.concat([r,i,n])}function YE(t,e,r){let i=Buffer.alloc(13);i.writeUInt32BE(t,0),i.writeUInt32BE(e,4),i[8]=8,i[9]=6,i[10]=0,i[11]=0,i[12]=0;let n=t*4,s=Buffer.alloc((n+1)*e);for(let o=0;o=t.width||d>=t.height)continue;let f=t.width*d+u<<2;t.data[f]=i[0]??0,t.data[f+1]=i[1]??0,t.data[f+2]=i[2]??0,t.data[f+3]=255;}}async function tw(t){let e=await jh(t.file,t.clip,t.fps??30),r=Math.max(1,t.columns??6),i=Math.max(48,t.height??160),n=Math.min(r,e.frames.length),s=Math.max(1,Math.floor((e.frames.length-1)/Math.max(1,n-1))),o=Array.from({length:n},(_,y)=>Math.min(e.frames.length-1,y*s)),a={data:new Uint8Array(i*n*i*4),height:i,width:i*n};for(let _=0;_e.bones.map(y=>e.frames[_]?.positions[y]).filter(y=>y!==void 0)),l=c.map(_=>_[0]),u=c.map(_=>_[1]),d=Math.min(...l,0),f=Math.max(...l,1),p=Math.min(...u,0),g=Math.max(...u,1),m=Math.max(1e-6,Math.max(f-d,g-p)),S=i*.12,h=(_,y,R)=>[Math.round(R*i+S+(_-d)/m*(i-S*2)),Math.round(i-S-(y-p)/m*(i-S*2))];o.forEach((_,y)=>{let R=e.frames[_];if(R!==void 0){ew(a,h(d,p,y),h(f,p,y),nU);for(let T of e.bones){let b=R.positions[T];b!==void 0&&ew(a,h(b[0],0,y),h(b[0],b[1],y),tU);}}});let v=YE(a.width,a.height,a.data);return await mkdir(Gr.dirname(Gr.resolve(t.output)),{recursive:true}),await writeFile(t.output,v),{bytes:v.length,columns:n,frames:e.frames.length}}var rU=String.raw`
:root{color-scheme:dark;font-family:"IBM Plex Mono","Azeret Mono",ui-monospace,monospace;background:#080b0a;color:#dce4de;--line:#27302c;--line2:#38433e;--panel:#111613;--panel2:#171d1a;--acid:#b7f34a;--cyan:#68d9d0;--muted:#77837c;--red:#ff705d}*{box-sizing:border-box}body{margin:0;overflow:hidden;background:#080b0a}button{cursor:pointer}.lab{height:100vh;display:grid;grid-template-rows:50px 1fr 26px}.bar{display:flex;align-items:center;gap:14px;padding:0 14px;border-bottom:1px solid var(--line);background:#0d120f}.brand{font:800 13px sans-serif;letter-spacing:.18em}.brand b{display:inline-grid;place-items:center;width:24px;height:24px;margin-right:9px;background:var(--acid);color:#101808}.bar small,.status{color:var(--muted)}.grow{flex:1}.bar button{border:1px solid #789e3f;border-radius:2px;background:var(--acid);color:#111908;padding:8px 14px;font:800 10px inherit}.body{min-height:0;display:grid;grid-template-columns:230px minmax(0,1fr) 285px}.side{overflow:auto;background:var(--panel)}.left{border-right:1px solid var(--line)}.right{border-left:1px solid var(--line)}.section{padding:13px;border-bottom:1px solid var(--line)}h2{margin:0 0 10px;color:var(--muted);font-size:9px;letter-spacing:.16em;text-transform:uppercase}label{display:grid;gap:5px;margin-bottom:10px;color:#91a097;font-size:9px;text-transform:uppercase}select,input{width:100%;border:1px solid var(--line);border-radius:2px;background:#090d0b;color:#dce4de;padding:8px;font:10px inherit;outline:none}select:focus,input:focus{border-color:var(--acid)}input:disabled{opacity:.38}.workspace{min-width:0;min-height:0;display:grid;grid-template-rows:minmax(280px,1fr) 224px;background:#090d0b}.viewport{position:relative;min-width:0;min-height:0}.viewport canvas{display:block;width:100%;height:100%}.title{position:absolute;top:18px;left:18px;pointer-events:none;font:800 23px sans-serif}.title small{display:block;margin-top:6px;color:var(--acid);font:9px ui-monospace;letter-spacing:.14em}.tools{position:absolute;bottom:16px;left:50%;display:flex;transform:translateX(-50%);border:1px solid var(--line2);background:#090d0be8}.tools button,.preset button{border:0;background:none;color:var(--muted);padding:9px 15px;font:9px inherit;text-transform:uppercase}.tools button.on{background:#263328;color:var(--acid)}.tools button:disabled{opacity:.28;cursor:not-allowed}.release-note{position:absolute;top:18px;right:18px;padding:7px 10px;border:1px solid #8b493d;background:#2b1713d9;color:#ff9b86;font-size:9px;letter-spacing:.13em}.landmarks{display:grid;gap:5px}.landmark{display:grid;grid-template-columns:8px 1fr auto;gap:8px;align-items:center;width:100%;padding:8px;border:1px solid transparent;border-radius:2px;background:#0c110f;color:var(--muted);font:10px inherit;text-align:left}.landmark.on{border-color:#668c34;color:#dce4de}.landmark i{width:6px;height:6px;border-radius:50%;background:#71b9ff}.landmark.detected i{background:var(--acid)}.landmark small{font-size:8px;color:#69756f}.axis{display:grid;grid-template-columns:repeat(3,1fr);gap:6px}.axis label{margin:0}.preset{display:grid;grid-template-columns:repeat(4,1fr);margin-top:8px}.preset button{padding:7px 2px;border:1px solid var(--line)}.wide,.editor-bar button,.segmented button{border:1px solid var(--line2);border-radius:2px;background:#1a211d;color:#dce4de;padding:8px;font:10px inherit}.wide{width:100%}.secondary{color:var(--muted)!important;background:#0d1210!important}.segmented{display:grid;grid-template-columns:1fr 1fr;gap:3px}.segmented button.on{border-color:var(--acid);color:var(--acid);background:#243021}.segmented button.danger.on{border-color:var(--red);color:#ff9b86;background:#321a16}.hint{margin:8px 0 0;color:var(--muted);font-size:9px;line-height:1.5}.status{display:flex;justify-content:space-between;align-items:center;padding:0 12px;border-top:1px solid var(--line);font-size:9px}.status b{color:var(--acid)}.error{position:absolute;top:18px;right:18px;max-width:360px;padding:10px;border:1px solid #81452f;background:#321a12;color:#ffb08a;font-size:10px}.saved{color:var(--acid);font-size:9px}.dope-editor{min-width:0;border-top:1px solid #46504b;background:#101512;box-shadow:0 -12px 30px #0008}.editor-bar{height:44px;display:flex;align-items:center;gap:7px;padding:6px 9px;border-bottom:1px solid var(--line2);background:#171c19}.editor-bar select{width:180px;padding:7px}.editor-bar button{white-space:nowrap;padding:7px 10px}.editor-bar button:disabled{opacity:.3;cursor:not-allowed}.editor-bar .transport{width:34px;border-color:#738d47;color:var(--acid);font-size:13px}.timecode{min-width:90px;color:#e1e7e3;font-size:11px;letter-spacing:.08em}.timecode i{color:var(--muted);font-style:normal}.compact{display:flex}.sheet{position:relative;height:179px;display:grid;grid-template-columns:132px 1fr;grid-template-rows:27px repeat(4,38px);overflow:hidden;background:repeating-linear-gradient(90deg,transparent 0,transparent calc(10% - 1px),#252d29 calc(10% - 1px),#252d29 10%)}.ruler-label{grid-column:1;grid-row:1}.ruler{position:relative;grid-column:2;grid-row:1;border-bottom:1px solid var(--line2);background:#0c100e}.ruler span{position:absolute;bottom:5px;transform:translateX(-50%);color:#68736d;font-size:8px}.lane-row{display:contents}.lane-label{z-index:3;display:flex;align-items:center;gap:8px;padding-left:13px;border-right:1px solid var(--line2);border-bottom:1px solid #222a26;background:#151a17;color:#87938c;font-size:9px;letter-spacing:.1em}.lane-label i{width:6px;height:6px;border:1px solid var(--cyan);transform:rotate(45deg)}.lane-track{position:relative;border-bottom:1px solid #222a26;background:#0d120f66}.key-diamond{position:absolute;z-index:4;top:14px;width:10px;height:10px;padding:0;transform:translate(-50%,-50%) rotate(45deg);border:1px solid #e2ffae;background:var(--acid);box-shadow:0 0 0 2px #0a0e0c}.attachment-lane .lane-label{grid-column:1;grid-row:5}.event-clip{align-self:center;grid-column:2;grid-row:5;height:23px;margin:0 8px;padding:6px 10px;border-left:3px solid var(--cyan);background:#17312d;color:#8ce7df;font-size:9px;letter-spacing:.08em}.event-clip.released{border-left-color:var(--red);background:#321a16;color:#ff9b86}.playhead{position:absolute;z-index:6;top:0;bottom:0;width:1px;background:#f3f7f4;pointer-events:none}.playhead b{position:absolute;top:0;left:-4px;width:9px;height:9px;background:#f3f7f4;clip-path:polygon(0 0,100% 0,50% 100%)}.scrubber{position:absolute;z-index:7;top:0;right:0;bottom:0;left:132px;width:calc(100% - 132px);height:100%;margin:0;padding:0;opacity:0;cursor:ew-resize}.ruler{grid-column:2;grid-row:1}.lane-row:nth-of-type(1) .lane-label,.lane-row:nth-of-type(1) .lane-track{grid-row:2}.lane-row:nth-of-type(2) .lane-label,.lane-row:nth-of-type(2) .lane-track{grid-row:3}.lane-row:nth-of-type(3) .lane-label,.lane-row:nth-of-type(3) .lane-track{grid-row:4}.lane-row .lane-label{grid-column:1}.lane-row .lane-track{grid-column:2}@media(max-width:980px){.body{grid-template-columns:210px 1fr}.right{display:none}.workspace{grid-template-rows:minmax(260px,1fr) 224px}.compact{display:none}}
`;function nw(t){return t.replaceAll("&","&").replaceAll("<","<").replaceAll('"',""")}function rw(t){return `Pose Lab \u2014 ${nw(t)}`}var aU=new URL("./client/app.js",import.meta.url),cU=256e3;function iw(t,e){if(e.length===0||Gr.isAbsolute(e)||e.split(/[\\/]/u).some(n=>n.length===0||n.startsWith(".")))return;let r=Gr.resolve(t),i=Gr.resolve(r,e);return i.startsWith(`${r}${Gr.sep}`)?i:void 0}async function lU(t){let e=[],r=new Set([".git","build","dist","node_modules"]),i=async(n,s,o)=>{if(o>6||e.length>=2e3)return;let a=await readdir(n,{withFileTypes:true}).catch(()=>[]);for(let c of a){if(c.name.startsWith(".")||r.has(c.name))continue;let l=s.length===0?c.name:`${s}/${c.name}`;c.isDirectory()?await i(Gr.join(n,c.name),l,o+1):c.name.toLowerCase().endsWith(".glb")&&e.push(l);}};return await i(t,"",0),e.sort((n,s)=>n.localeCompare(s))}async function uU(t){let e=[],r=0;for await(let i of t){let n=Buffer.from(i);if(r+=n.length,r>cU)throw new Error("Request exceeds 256 KB.");e.push(n);}return JSON.parse(Buffer.concat(e).toString("utf8"))}function Hh(t,e,r,i){t.writeHead(e,{"cache-control":"no-store","content-type":i,"x-content-type-options":"nosniff"}),t.end(r);}function Rn(t,e,r){Hh(t,e,JSON.stringify(r),"application/json; charset=utf-8");}async function ow(t={}){let e=Gr.resolve(t.project??process.cwd()),r=t.port??4192;await readdir(e).catch(()=>{throw new Error(`Project directory does not exist: ${e}`)});let i=createServer(async(s,o)=>{try{let a=new URL(s.url??"/","http://pose-lab");if(s.method==="GET"&&(a.pathname==="/"||a.pathname==="/pose"))return Hh(o,200,rw(Gr.basename(e)),"text/html; charset=utf-8");if(s.method==="GET"&&a.pathname==="/app.js")return Hh(o,200,await readFile(aU),"text/javascript; charset=utf-8");if(s.method==="GET"&&a.pathname==="/favicon.ico")return o.writeHead(204),o.end();if(s.method==="GET"&&a.pathname==="/api/models")return Rn(o,200,{models:await lU(e)});if(s.method==="GET"&&a.pathname==="/api/model"){let c=a.searchParams.get("path")??"",l=c.endsWith(".glb")?iw(e,c):void 0;if(l===void 0)return Rn(o,404,{error:"GLB not found."});let u=await readFile(l).catch(()=>{});return u===void 0?Rn(o,404,{error:"GLB not found."}):Hh(o,200,u,"model/gltf-binary")}if(a.pathname==="/api/recipe"){let c=a.searchParams.get("path")??"",l=c.endsWith(".json")?iw(e,c):void 0;if(l===void 0)return Rn(o,404,{error:"Recipe not found."});if(s.method==="GET"){let u=await readFile(l,"utf8").catch(()=>{});return u===void 0?Rn(o,404,{error:"Recipe not found."}):Rn(o,200,{recipe:JSON.parse(u),path:c})}if(s.method==="PUT"){let u=await uU(s);return typeof u.recipe!="object"||u.recipe===null?Rn(o,400,{error:"Body must contain a recipe object."}):(await mkdir(Gr.dirname(l),{recursive:!0}),await writeFile(l,`${JSON.stringify(u.recipe,null,2)}
-`,"utf8"),Rn(o,200,{path:c,saved:!0}))}}return Rn(o,404,{error:"Not found."})}catch(a){return Rn(o,500,{error:a instanceof Error?a.message:String(a)})}});await new Promise((s,o)=>{i.once("error",o),i.listen(r,"127.0.0.1",s);});let n=i.address();return {port:typeof n=="object"&&n!==null?n.port:r,close:()=>new Promise((s,o)=>i.close(a=>a?o(a):s()))}}var fU=B.object({position:B.tuple([B.number(),B.number(),B.number()]),rotation:B.tuple([B.number(),B.number(),B.number()]),scale:B.tuple([B.number(),B.number(),B.number()])}),_w=B.enum(yh.map(t=>t.id)),pU=B.object({attachment:B.enum(["attached","detached"]).optional(),clip:B.string().min(1).max(200),time:B.number().min(0).max(600),transform:fU}),mU=B.object({file:B.string().min(1)}),cw=B.object({bones:B.array(B.string()),bytes:B.number(),clips:B.array(B.object({channels:B.number(),duration:B.number(),horizontalTravel:B.number(),inPlace:B.boolean(),name:B.string()})),extensionsUsed:B.array(B.string()),file:B.string(),generator:B.string(),inPlace:B.boolean(),landmarks:B.array(B.object({id:B.string(),label:B.string(),node:B.string(),source:B.enum(["detected","estimated"])})),meshes:B.number(),rootBone:B.string().nullable(),skins:B.number(),warnings:B.array(B.string())}),lw=B.object({anchor:_w.default("right-hand"),attached:B.string().min(1).optional(),bone:B.string().min(1).optional(),host:B.string().min(1).optional(),keys:B.array(pU).max(2e3).optional(),log:B.string().min(1).optional(),output:B.string().min(1).optional(),recipe:B.string().min(1).optional()}),uw=B.object({anchor:B.string(),attached:B.string(),clips:B.array(B.string()),detached:B.array(B.string()),file:B.string(),log:B.string(),node:B.string()}),dw=B.object({clip:B.string().min(1).max(200),file:B.string().min(1),filmstrip:B.string().min(1).optional(),fps:B.number().int().min(1).max(240).default(30),scale:B.number().positive().default(1)}),hw=B.object({bones:B.number(),clip:B.string(),filmstrip:B.string().nullable(),defects:B.array(B.object({bone:B.string(),detail:B.string(),fromFrame:B.number(),fromTime:B.number(),kind:B.enum(["bone-stretch","foot-skate","ground-penetration","jitter","loop-seam"]),limit:B.number(),measured:B.number(),toFrame:B.number(),toTime:B.number()})),duration:B.number(),file:B.string(),fps:B.number(),frames:B.number(),passed:B.boolean(),scale:B.number(),thresholds:B.object({contact:B.number(),jitter:B.number(),penetration:B.number(),seam:B.number(),skate:B.number(),stretch:B.number()})}),gU=B.discriminatedUnion("kind",[B.object({end:B.number().min(0),kind:B.literal("trim"),start:B.number().min(0)}),B.object({kind:B.literal("retime"),speed:B.number().positive()}),B.object({kind:B.literal("loop-point"),time:B.number().min(0)}),B.object({fps:B.number().positive(),kind:B.literal("resample")}),B.object({kind:B.literal("mirror")}),B.object({contact:B.number().min(0).default(.03),feet:B.array(B.string().min(1)).max(8).default([]),kind:B.literal("foot-lock")})]),fw=B.object({clip:B.string().min(1).max(200),edits:B.array(gU).min(1).max(64),file:B.string().min(1),log:B.string().min(1).optional(),output:B.string().min(1).optional()}),pw=B.object({clips:B.array(B.string()),edits:B.number(),file:B.string(),log:B.string(),modified:B.array(B.string())}),R0=B.object({anchor:_w.default("right-hand"),attach:B.string().min(1).optional(),host:B.string().min(1).optional(),output:B.string().min(1).optional(),port:B.number().int().min(0).max(65535).optional(),project:B.string().min(1).optional()}),mw=B.object({port:B.number(),url:B.string()}),Ba=t=>({destructiveHint:false,idempotentHint:true,openWorldHint:false,readOnlyHint:t}),En=t=>[{type:"text",text:JSON.stringify(t)}];function _U(t,e,r){if(r!==void 0){let s=yh.find(o=>o.id===e);if(s===void 0)throw new Error(`Unknown anchor '${e}'.`);return {id:e,label:s.label,node:r,source:"detected"}}let i=t.find(s=>s.id===e);if(i!==void 0)return i;let n=t.map(s=>`${s.id} \u2192 ${s.node}`);throw new Error(`The host names no '${e}' landmark. It answers to: ${n.length===0?"none":n.join(", ")}. Pass 'bone' to name one directly.`)}function vU(t){return {position:t.position,rotation:t.rotation,scale:t.scale}}function vw(t){let e=Gr.parse(t);return Gr.join(e.dir,`${e.name}.anim.glb`)}async function yU(t){return t.filmstrip===void 0?null:(await tw({clip:t.clip,file:t.file,fps:t.fps,output:t.filmstrip}),Gr.resolve(t.filmstrip))}async function SU(t){let e=(t.keys??[]).map(s=>({attachment:s.attachment,clip:s.clip,op:"key",time:s.time,transform:vU(s.transform)})),r;if(t.recipe!==void 0){r=Ry(JSON.parse(await readFile(t.recipe,"utf8")));for(let s of e)r=Ey(r,s);}else {if(t.host===void 0||t.attached===void 0)throw new Error("Pass 'host' and 'attached', or a 'recipe' that names both.");let s=await Py(t.host);r={host:t.host,ops:[{anchor:_U(s.landmarks,t.anchor,t.bone),attached:t.attached,op:"attach"},...e],version:4};}let i=t.log??wy(r.host);return await My(i,r),{...await hE(r,t.output??vw(r.host)),log:Gr.resolve(i)}}var gw;function yw(t){return gw??=(async()=>{let e=await ow({...t.port===void 0?{}:{port:t.port},...t.project===void 0?{}:{project:t.project}}),r=new URLSearchParams;return t.host!==void 0&&r.set("host",t.host),t.attach!==void 0&&r.set("attach",t.attach),t.output!==void 0&&r.set("output",t.output),r.set("anchor",t.anchor),{port:e.port,url:`http://127.0.0.1:${e.port}/pose?${r.toString()}`}})(),gw}function xU(){let t=new Aa({name:"threenative-animation",version:"0.1.17"});return t.registerTool("animation_inspect",{annotations:Ba(true),description:"Inspect a local rigged GLB: bones, skeleton landmarks, clips with durations, root-motion travel and in-place detection, meshes, skins and extensions. Reads one local file and writes nothing.",inputSchema:mU,outputSchema:cw,title:"Inspect a rig and its clips"},async e=>{try{let r=cw.parse(await Py(e.file));return {content:En(r),structuredContent:r}}catch(r){return {content:En({message:r instanceof Error?r.message:String(r)}),isError:true}}}),t.registerTool("animation_attach",{annotations:Ba(false),description:"Attach a prop GLB to a bone, with per-clip keyed offsets, and bake it into an ordinary GLB beside the source. Writes the v4 op log (.anim.json) next to the source GLB and the baked GLB; a version 3 pose recipe loads as the same ops and still bakes.",inputSchema:lw,outputSchema:uw,title:"Attach a prop to a bone and bake it"},async e=>{try{let r=uw.parse(await SU(lw.parse(e)));return {content:En(r),structuredContent:r}}catch(r){return {content:En({message:r instanceof Error?r.message:String(r)}),isError:true}}}),t.registerTool("animation_verify",{annotations:Ba(true),description:"Measure one clip for the defects a still frame cannot show: a planted foot that slides (2 cm), ground penetration (1 cm), a loop seam (5\xB0), a one-frame jitter spike, and bones whose length changes. Every defect names the bone and the frame range it spans. Thresholds are in metres; pass `scale` for a model that is not (Mixamo and Quaternius are centimetres: 0.01).",inputSchema:dw,outputSchema:hw,title:"Verify a clip's motion"},async e=>{try{let r=dw.parse(e),i=hw.parse({...await JE(r.file,r.clip,{fps:r.fps,scale:r.scale}),filmstrip:await yU(r)});return {content:En(i),structuredContent:i}}catch(r){return {content:En({message:r instanceof Error?r.message:String(r)}),isError:true}}}),t.registerTool("animation_modify",{annotations:Ba(false),description:"Edit one clip \u2014 trim, retime, move the loop point, resample, mirror, lock planted feet \u2014 writing each edit into the op log and rendering the result from the source GLB. Rendering twice from one log gives the same bytes, so the log is the change and the GLB is derived.",inputSchema:fw,outputSchema:pw,title:"Edit a clip and render it from the log"},async e=>{try{let r=fw.parse(e),i=r.log??wy(r.file),s=await lE(i).catch(async()=>({host:r.file,ops:[],version:4}));for(let c of r.edits)s=Ey(s,{clip:r.clip,edit:c,op:"modify"});await My(i,s);let o=await XE(s,r.output??vw(r.file)),a=pw.parse({...o,log:Gr.resolve(i)});return {content:En(a),structuredContent:a}}catch(r){return {content:En({message:r instanceof Error?r.message:String(r)}),isError:true}}}),t.registerTool("animation_open_view",{annotations:Ba(false),description:"Start the animation calibrator page on 127.0.0.1 and return its URL. A human drags the prop into place there; the same operations an agent calls are what the page records.",inputSchema:R0,outputSchema:mw,title:"Open the animation calibrator"},async e=>{try{let r=mw.parse(await yw(R0.parse(e)));return {content:En(r),structuredContent:r}}catch(r){return {content:En({message:r instanceof Error?r.message:String(r)}),isError:true}}}),t}function bU(){nR(()=>xU());}function TU(){let t=process.argv[1];if(t===void 0)return false;try{return realpathSync(t)===realpathSync(fileURLToPath(import.meta.url))}catch{return false}}TU()&&(process.argv[2]==="--view"?yw(R0.parse({project:process.cwd()})).then(({url:t})=>process.stdout.write(`Animation view: ${t}
+`,"utf8"),Rn(o,200,{path:c,saved:!0}))}}return Rn(o,404,{error:"Not found."})}catch(a){return Rn(o,500,{error:a instanceof Error?a.message:String(a)})}});await new Promise((s,o)=>{i.once("error",o),i.listen(r,"127.0.0.1",s);});let n=i.address();return {port:typeof n=="object"&&n!==null?n.port:r,close:()=>new Promise((s,o)=>i.close(a=>a?o(a):s()))}}var fU=B.object({position:B.tuple([B.number(),B.number(),B.number()]),rotation:B.tuple([B.number(),B.number(),B.number()]),scale:B.tuple([B.number(),B.number(),B.number()])}),_w=B.enum(yh.map(t=>t.id)),pU=B.object({attachment:B.enum(["attached","detached"]).optional(),clip:B.string().min(1).max(200),time:B.number().min(0).max(600),transform:fU}),mU=B.object({file:B.string().min(1)}),cw=B.object({bones:B.array(B.string()),bytes:B.number(),clips:B.array(B.object({channels:B.number(),duration:B.number(),horizontalTravel:B.number(),inPlace:B.boolean(),name:B.string()})),extensionsUsed:B.array(B.string()),file:B.string(),generator:B.string(),inPlace:B.boolean(),landmarks:B.array(B.object({id:B.string(),label:B.string(),node:B.string(),source:B.enum(["detected","estimated"])})),meshes:B.number(),rootBone:B.string().nullable(),skins:B.number(),warnings:B.array(B.string())}),lw=B.object({anchor:_w.default("right-hand"),attached:B.string().min(1).optional(),bone:B.string().min(1).optional(),host:B.string().min(1).optional(),keys:B.array(pU).max(2e3).optional(),log:B.string().min(1).optional(),output:B.string().min(1).optional(),recipe:B.string().min(1).optional()}),uw=B.object({anchor:B.string(),attached:B.string(),clips:B.array(B.string()),detached:B.array(B.string()),file:B.string(),log:B.string(),node:B.string()}),dw=B.object({clip:B.string().min(1).max(200),file:B.string().min(1),filmstrip:B.string().min(1).optional(),fps:B.number().int().min(1).max(240).default(30),scale:B.number().positive().default(1)}),hw=B.object({bones:B.number(),clip:B.string(),filmstrip:B.string().nullable(),defects:B.array(B.object({bone:B.string(),detail:B.string(),fromFrame:B.number(),fromTime:B.number(),kind:B.enum(["bone-stretch","foot-skate","ground-penetration","jitter","loop-seam"]),limit:B.number(),measured:B.number(),toFrame:B.number(),toTime:B.number()})),duration:B.number(),file:B.string(),fps:B.number(),frames:B.number(),passed:B.boolean(),scale:B.number(),thresholds:B.object({contact:B.number(),jitter:B.number(),penetration:B.number(),seam:B.number(),skate:B.number(),stretch:B.number()})}),gU=B.discriminatedUnion("kind",[B.object({end:B.number().min(0),kind:B.literal("trim"),start:B.number().min(0)}),B.object({kind:B.literal("retime"),speed:B.number().positive()}),B.object({kind:B.literal("loop-point"),time:B.number().min(0)}),B.object({fps:B.number().positive(),kind:B.literal("resample")}),B.object({kind:B.literal("mirror")}),B.object({contact:B.number().min(0).default(.03),feet:B.array(B.string().min(1)).max(8).default([]),kind:B.literal("foot-lock")})]),fw=B.object({clip:B.string().min(1).max(200),edits:B.array(gU).min(1).max(64),file:B.string().min(1),log:B.string().min(1).optional(),output:B.string().min(1).optional()}),pw=B.object({clips:B.array(B.string()),edits:B.number(),file:B.string(),log:B.string(),modified:B.array(B.string())}),R0=B.object({anchor:_w.default("right-hand"),attach:B.string().min(1).optional(),host:B.string().min(1).optional(),output:B.string().min(1).optional(),port:B.number().int().min(0).max(65535).optional(),project:B.string().min(1).optional()}),mw=B.object({port:B.number(),url:B.string()}),Ba=t=>({destructiveHint:false,idempotentHint:true,openWorldHint:false,readOnlyHint:t}),En=t=>[{type:"text",text:JSON.stringify(t)}];function _U(t,e,r){if(r!==void 0){let s=yh.find(o=>o.id===e);if(s===void 0)throw new Error(`Unknown anchor '${e}'.`);return {id:e,label:s.label,node:r,source:"detected"}}let i=t.find(s=>s.id===e);if(i!==void 0)return i;let n=t.map(s=>`${s.id} \u2192 ${s.node}`);throw new Error(`The host names no '${e}' landmark. It answers to: ${n.length===0?"none":n.join(", ")}. Pass 'bone' to name one directly.`)}function vU(t){return {position:t.position,rotation:t.rotation,scale:t.scale}}function vw(t){let e=Gr.parse(t);return Gr.join(e.dir,`${e.name}.anim.glb`)}async function yU(t){return t.filmstrip===void 0?null:(await tw({clip:t.clip,file:t.file,fps:t.fps,output:t.filmstrip}),Gr.resolve(t.filmstrip))}async function SU(t){let e=(t.keys??[]).map(s=>({attachment:s.attachment,clip:s.clip,op:"key",time:s.time,transform:vU(s.transform)})),r;if(t.recipe!==void 0){r=Ry(JSON.parse(await readFile(t.recipe,"utf8")));for(let s of e)r=Ey(r,s);}else {if(t.host===void 0||t.attached===void 0)throw new Error("Pass 'host' and 'attached', or a 'recipe' that names both.");let s=await Py(t.host);r={host:t.host,ops:[{anchor:_U(s.landmarks,t.anchor,t.bone),attached:t.attached,op:"attach"},...e],version:4};}let i=t.log??wy(r.host);return await My(i,r),{...await hE(r,t.output??vw(r.host)),log:Gr.resolve(i)}}var gw;function yw(t){return gw??=(async()=>{let e=await ow({...t.port===void 0?{}:{port:t.port},...t.project===void 0?{}:{project:t.project}}),r=new URLSearchParams;return t.host!==void 0&&r.set("host",t.host),t.attach!==void 0&&r.set("attach",t.attach),t.output!==void 0&&r.set("output",t.output),r.set("anchor",t.anchor),{port:e.port,url:`http://127.0.0.1:${e.port}/pose?${r.toString()}`}})(),gw}function xU(){let t=new Aa({name:"threenative-animation",version:"0.1.18"});return t.registerTool("animation_inspect",{annotations:Ba(true),description:"Inspect a local rigged GLB: bones, skeleton landmarks, clips with durations, root-motion travel and in-place detection, meshes, skins and extensions. Reads one local file and writes nothing.",inputSchema:mU,outputSchema:cw,title:"Inspect a rig and its clips"},async e=>{try{let r=cw.parse(await Py(e.file));return {content:En(r),structuredContent:r}}catch(r){return {content:En({message:r instanceof Error?r.message:String(r)}),isError:true}}}),t.registerTool("animation_attach",{annotations:Ba(false),description:"Attach a prop GLB to a bone, with per-clip keyed offsets, and bake it into an ordinary GLB beside the source. Writes the v4 op log (.anim.json) next to the source GLB and the baked GLB; a version 3 pose recipe loads as the same ops and still bakes.",inputSchema:lw,outputSchema:uw,title:"Attach a prop to a bone and bake it"},async e=>{try{let r=uw.parse(await SU(lw.parse(e)));return {content:En(r),structuredContent:r}}catch(r){return {content:En({message:r instanceof Error?r.message:String(r)}),isError:true}}}),t.registerTool("animation_verify",{annotations:Ba(true),description:"Measure one clip for the defects a still frame cannot show: a planted foot that slides (2 cm), ground penetration (1 cm), a loop seam (5\xB0), a one-frame jitter spike, and bones whose length changes. Every defect names the bone and the frame range it spans. Thresholds are in metres; pass `scale` for a model that is not (Mixamo and Quaternius are centimetres: 0.01).",inputSchema:dw,outputSchema:hw,title:"Verify a clip's motion"},async e=>{try{let r=dw.parse(e),i=hw.parse({...await JE(r.file,r.clip,{fps:r.fps,scale:r.scale}),filmstrip:await yU(r)});return {content:En(i),structuredContent:i}}catch(r){return {content:En({message:r instanceof Error?r.message:String(r)}),isError:true}}}),t.registerTool("animation_modify",{annotations:Ba(false),description:"Edit one clip \u2014 trim, retime, move the loop point, resample, mirror, lock planted feet \u2014 writing each edit into the op log and rendering the result from the source GLB. Rendering twice from one log gives the same bytes, so the log is the change and the GLB is derived.",inputSchema:fw,outputSchema:pw,title:"Edit a clip and render it from the log"},async e=>{try{let r=fw.parse(e),i=r.log??wy(r.file),s=await lE(i).catch(async()=>({host:r.file,ops:[],version:4}));for(let c of r.edits)s=Ey(s,{clip:r.clip,edit:c,op:"modify"});await My(i,s);let o=await XE(s,r.output??vw(r.file)),a=pw.parse({...o,log:Gr.resolve(i)});return {content:En(a),structuredContent:a}}catch(r){return {content:En({message:r instanceof Error?r.message:String(r)}),isError:true}}}),t.registerTool("animation_open_view",{annotations:Ba(false),description:"Start the animation calibrator page on 127.0.0.1 and return its URL. A human drags the prop into place there; the same operations an agent calls are what the page records.",inputSchema:R0,outputSchema:mw,title:"Open the animation calibrator"},async e=>{try{let r=mw.parse(await yw(R0.parse(e)));return {content:En(r),structuredContent:r}}catch(r){return {content:En({message:r instanceof Error?r.message:String(r)}),isError:true}}}),t}function bU(){nR(()=>xU());}function TU(){let t=process.argv[1];if(t===void 0)return false;try{return realpathSync(t)===realpathSync(fileURLToPath(import.meta.url))}catch{return false}}TU()&&(process.argv[2]==="--view"?yw(R0.parse({project:process.cwd()})).then(({url:t})=>process.stdout.write(`Animation view: ${t}
`),t=>{process.stderr.write(`${t instanceof Error?t.message:String(t)}
`),process.exitCode=1;}):bU());/*! Bundled license information:
diff --git a/packages/core/mcp/engine-server.mjs b/packages/core/mcp/engine-server.mjs
index 44e99a63f7..9ce14bcc64 100755
--- a/packages/core/mcp/engine-server.mjs
+++ b/packages/core/mcp/engine-server.mjs
@@ -1437,7 +1437,7 @@ async function handleLine(line2, manifestFile) {
capabilities: { tools: { listChanged: false } },
instructions: AUTHORING_INSTRUCTIONS,
protocolVersion: "2025-06-18",
- serverInfo: { name: "threenative-engine-mcp", version: "0.2.20" }
+ serverInfo: { name: "threenative-engine-mcp", version: "0.2.21" }
});
}
if (request.method === "tools/list") {
diff --git a/packages/core/mcp/servers.mjs b/packages/core/mcp/servers.mjs
index 350b623b95..1fe174cdba 100644
--- a/packages/core/mcp/servers.mjs
+++ b/packages/core/mcp/servers.mjs
@@ -52,10 +52,10 @@ export const MCP_SERVERS = Object.freeze({
* checkout whose bundle has not been built. */
export const MCP_PACKAGES = Object.freeze({
assets: Object.freeze({ name: "threenative-asset-mcp", version: "0.18.0" }),
- terrain: Object.freeze({ name: "@threenative/terrain", version: "0.1.16" }),
+ terrain: Object.freeze({ name: "@threenative/terrain", version: "0.1.17" }),
sculpt: Object.freeze({ name: "threenative-sculpt-mcp", version: "0.2.2" }),
- engine: Object.freeze({ name: "threenative-engine-mcp", version: "0.2.20" }),
- animation: Object.freeze({ name: "threenative-animation-mcp", version: "0.1.17" }),
+ engine: Object.freeze({ name: "threenative-engine-mcp", version: "0.2.21" }),
+ animation: Object.freeze({ name: "threenative-animation-mcp", version: "0.1.18" }),
// `args` fixes the launch for every host. The Chrome flags are `WEBGPU_BROWSER_ARGS` from
// `@threenative/playtest`, so a DevTools trace profiles the same adapter a playtest does and not
// SwiftShader. An isolated profile keeps the user's own Chrome profile out, and the two opt-outs
diff --git a/packages/core/package.json b/packages/core/package.json
index a6f5f8e490..82647aa8eb 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -1,6 +1,6 @@
{
"name": "@threenative/core",
- "version": "0.3.20",
+ "version": "0.3.21",
"license": "MIT AND GPL-2.0-or-later",
"description": "The small vanilla Three.js game runtime foundation.",
"keywords": [
@@ -122,7 +122,7 @@
"@typescript/native": "catalog:"
},
"peerDependencies": {
- "@threenative/playtest": ">=0.3.20 <0.4.0",
+ "@threenative/playtest": ">=0.3.21 <0.4.0",
"react": ">=19.2.0 <20",
"react-reconciler": ">=0.33.0 <0.34"
},
diff --git a/packages/core/src/version.ts b/packages/core/src/version.ts
index 67dcc44e22..75ad9736f1 100644
--- a/packages/core/src/version.ts
+++ b/packages/core/src/version.ts
@@ -1,2 +1,2 @@
// Generated by scripts/generate-version.mjs - do not edit. Source: package.json.
-export const CORE_VERSION = "0.3.20";
+export const CORE_VERSION = "0.3.21";
diff --git a/packages/create-threenative/__tests__/scaffold.spec.ts b/packages/create-threenative/__tests__/scaffold.spec.ts
index f4f558f826..f837146e0f 100644
--- a/packages/create-threenative/__tests__/scaffold.spec.ts
+++ b/packages/create-threenative/__tests__/scaffold.spec.ts
@@ -116,68 +116,68 @@ const PACK_GENERATED_PAGES: readonly string[] = ["capability-reference.md"];
const SCAFFOLD_TREE_HASHES: Readonly> = {
// scaffold-pin:begin
"action-rpg": {
- shared: "56d80e5d00e8c2334eff6d82eb9f7d35ad76684f0c789b1865effeb2be499218",
- kit: "b0b01617d24d92a03379d6940ceb087d0c0ed9a7f1550571b84df30d43e51047",
+ shared: "a671faf56210d1f1af26bf10ba58cd9e7e09ec54818f56bf4fc37e4d271152c4",
+ kit: "17183254f8a2563d7a887262c71a3aa33f35dd4a6b1f13242c1d980a511b1a50",
},
adventure: {
- shared: "5bfc82a3a30c87b99648646ca8744fe0a0deb52176d2522881628030071cf5c7",
- kit: "0cd697ed54034dfcce7a2ae047435f604a798620185d6c8922fa9f45ec9eafd3",
+ shared: "ff13d98ca8d0c7498e75a5bb2c5e041d05a0914afe56537e05349df74e8ce047",
+ kit: "0d4db9968f6fa51b3a3fcb7fee1f199168db2e9bef750924cd6fdafdccccedc3",
},
collectathon: {
- shared: "4ecca8cf66d2b726f879c255e0a1753c29348372e2de9742254a3e1bce959d41",
- kit: "6891672ee2106a91d3a44762a4b2fe0f4c28ff21cebfe1db55425f1aaecb6337",
+ shared: "2975c7e3328bd6b77f2b111d05c83e4daf290081837faa029c8a6071b4b27262",
+ kit: "85b81184edb4ad7a580dffdc1173bcf7db5a40d3ad8484826885e0611126c164",
},
kart: {
- shared: "acdedaf64743e72a8125bbbb6306309be3f2dc38a2c4352ce856739128bb14f2",
- kit: "7ebc19d92a9e8806b25ddb19b7b85dedf9a3e77186e164b289830bd15081429a",
+ shared: "2dcaf4462389ad21b2de55e59bec6a7f425b06c801d047c98b45a511ef0a06f4",
+ kit: "cbf31303875eefae6f1a5b27149e5ea4bdb0f048f2f24c4d725723ec5ec0da0e",
},
minimal: {
- shared: "a50ee54777f63abfb360e7b0467263213ba0648984a4ff2a8d6191be4a4dde90",
- kit: "48c37070b41bb9e470b01c8179ca2c3a756d66177009bbd14c71136f7ba21239",
+ shared: "e1127fc7b42a5d62410d38947446407300e118fbc94086b2595c6c9d0e18b166",
+ kit: "7e02d4a455f50f683496220398508394a5a7bc64e2d0538023ecd26de68c7d5e",
},
platformer: {
- shared: "1ae29c77157d11e73f5628053644ff9c860663cf39002fb0ac72b1bd46ad7780",
- kit: "03d2e4c19b01995a13cfac0678392a66c583edb0c6708d3a5c58c33cd4ee530d",
+ shared: "528fa4580f731e0a0ed43b26874a3e341e9a84e82e5690364c730737b252bf5a",
+ kit: "f7c2bd5a0b299af1c2013a371fbb171b90d6f5d2d1de082600e63249646ab266",
},
puzzle: {
- shared: "d48d25a195b25e4ba5c5e059565873080c39d17ebe0080b6183395187a0184aa",
- kit: "5a2d7177faaeb07a26d3bd02925562ad4691f2e930cb9890ceea4612e6b29cea",
+ shared: "a876fbb77632ff836401f6f04a9a901d9c29c6dabc1f0c17ca5a985a58cac1e3",
+ kit: "9b70efac5dcd568ac6a7f2fe0cd0cd47cdf5cea7658955bf94cfede27332a632",
},
racing: {
- shared: "fb48c73d1d0aebc3cc22cfd20aa5853b2a21b9658d204dbd90dea987476bcbc0",
- kit: "c6043c350f4aeb14a0a942650ea2de14563380d1b5e49f18c14fe22e147a3ed1",
+ shared: "2fb2d4cc0f5ca3fc490701fbb36342887ff82db0d577b99e6f5d38d30824142d",
+ kit: "694d9c35ca3a5df124d896aef7fb1c6d24fa5d692542d9aaef2922aa1bf451a0",
},
rain: {
- shared: "588fae060e4c095420361c61e9079dc1296fc6ab3965d1538861d6da6d002cf8",
- kit: "e4ce646c66b1fa9cb12fc269be926777dcbf3664d4eee95d1b16b668b68835ab",
+ shared: "f08f8cf92cb12e98778d402b69aff6787d94283ebc7fe79fcb790bcbf5b4aea6",
+ kit: "9416ad6062803b2f70f269db8f1c9cb91d82c51eb39a8a53d3b47b008f00d34e",
},
rts: {
- shared: "69c96ef92853ac94163bf80daa2ac4177e6000df5e448463445d222475027ee8",
- kit: "79a4a6b7b350f296e90b83db6e08cd298d5f04aaf060dcd1098a7ad3e7e83659",
+ shared: "d10cf50e00ab22953f46080dfac6326b6815eeb636b2b4d31e9bd6ed2e6e1171",
+ kit: "7760647c7df027cac394b1cc1ba6a998dea8851467a0cf01561f2c3df0c796aa",
},
runner: {
- shared: "0076d19e3e5996d77fe4b725c949f8d35adb007cac72d4cd2027496fcf16837e",
- kit: "7510c280ebb5a1a4e6bb723f38c99699f2dc2e7f2a2d7697ca88e08f213500d5",
+ shared: "d7b3cdfb063ae81e20adfd844b3fd533c27c0e5981ce1d396039223cbbc8e2e2",
+ kit: "b5fbe57288c6caa9fa4326b93fd6e74e13a0789f1bf886ab105010a5d550c581",
},
sailing: {
- shared: "17d219bbdfe9e7eaf89c4781afcdb980ff08bca4d56dda6bdc3b6f9470fec622",
- kit: "f65f2cbdf411fe000688312491152cfca473232349ee069e7ab1a5caddf38a59",
+ shared: "284a049de6b193c5e4671e15b0fa7b146a7568ca28c04fadceb593934c1f9749",
+ kit: "c6fa7265c681283cbabcab33bbbc3e6568a994ad24e39abd5883eb11f15e45d7",
},
shooter: {
- shared: "c677531130532aaf4dc30ce0c93173e9f5c813d94ea73b39f8f50f732828b875",
- kit: "78261098f91e26b0516c707fece69fab1db2eb4df3e85271164a39d0292bf2e0",
+ shared: "339fe5fca996ffa5bdfbd75286366dab60a872e93ec0991c2dff2a5c74342481",
+ kit: "2315584df13a819d4ca1505673c4cb374a754ca56c0bece59f32c1b78c99f538",
},
snow: {
- shared: "cd08062be82f82eade10f7fab2c669fd2c12d859f8b0b36322ba8a730fdf6df4",
- kit: "3fe4c4f6b63edb7a9bd2c7bf8959fa4f849d487003e19267a5da0fceecb980a0",
+ shared: "427e25b8a47f68af7f69ee675415259f8db27f10b1dec086ca47dc9f2d216348",
+ kit: "53723edbc5ae587ad627f5e31f710ab2f3c9dc92a6f7a709033ab09e229440a8",
},
starter: {
- shared: "0408468161a132d6ecf334376bdd9eedc677d3427c98ed91cfa724875d198d84",
- kit: "1a14ce42c20ea70583e0d727afa01c64d4df891b487c69026de7695843f2f3a8",
+ shared: "263e5bcfdb9ace63488de015d65de6957e67c92f06c608362cf104943b98bccd",
+ kit: "9b7fb8c4d63aa8364b328674a162a356b5ea8513c0ed431ffecf48b46d79e442",
},
"tower-defense": {
- shared: "ea48e20cd9d831cbc7811bfb7d85cfc7d110adcfc4414d328538d230610e09de",
- kit: "bdc6b4f292389ba6c544279a3f27da9f060f15ae093d7f1573a2fbac58b738a8",
+ shared: "3aef2f1276a23059fe0a05e91048dfcd93d3c601c3e0d9e037f852f36268b16f",
+ kit: "ee300c53bc02a46e6eba6def1308e40f50d541cb51aa30bbd9f353418c2b855a",
},
// scaffold-pin:end
};
diff --git a/packages/create-threenative/animation-mcp-tools.json b/packages/create-threenative/animation-mcp-tools.json
index a96a3e3011..584c92ba8a 100644
--- a/packages/create-threenative/animation-mcp-tools.json
+++ b/packages/create-threenative/animation-mcp-tools.json
@@ -1,9 +1,9 @@
{
- "comment": "The animation MCP surface a generated project actually gets. `tools` is set-equal to the live tools/list response of version 0.1.17, packed from this workspace and installed from that tarball into a clean directory — never read from src/. `recommended` is the ordered loop the shipped agent docs describe. Regenerate with `pnpm tsx scripts/capture-mcp-tools.ts`.",
- "version": "0.1.17",
+ "comment": "The animation MCP surface a generated project actually gets. `tools` is set-equal to the live tools/list response of version 0.1.18, packed from this workspace and installed from that tarball into a clean directory — never read from src/. `recommended` is the ordered loop the shipped agent docs describe. Regenerate with `pnpm tsx scripts/capture-mcp-tools.ts`.",
+ "version": "0.1.18",
"serverInfo": {
"name": "threenative-animation",
- "version": "0.1.17"
+ "version": "0.1.18"
},
"recommended": ["animation_inspect", "animation_attach", "animation_open_view"],
"tools": [
diff --git a/packages/create-threenative/engine-mcp-tools.json b/packages/create-threenative/engine-mcp-tools.json
index e2af5aeb5a..1a5afb399c 100644
--- a/packages/create-threenative/engine-mcp-tools.json
+++ b/packages/create-threenative/engine-mcp-tools.json
@@ -1,6 +1,6 @@
{
"comment": "The engine capability MCP surface shipped through @threenative/core. The golden path also calls a mechanically explicit cross-system request so a packaged consumer proves full-request discovery without repository source.",
- "version": "0.2.20",
+ "version": "0.2.21",
"tools": [
"engine_capability_detail",
"engine_reference_detail",
diff --git a/packages/create-threenative/package.json b/packages/create-threenative/package.json
index 89d8106910..08c8bb667d 100644
--- a/packages/create-threenative/package.json
+++ b/packages/create-threenative/package.json
@@ -1,6 +1,6 @@
{
"name": "create-threenative",
- "version": "0.2.25",
+ "version": "0.2.26",
"license": "MIT",
"description": "Scaffold a readable ThreeNative game project.",
"keywords": [
@@ -108,6 +108,6 @@
"@types/estree": "1.0.8"
},
"peerDependencies": {
- "@threenative/assets": ">=0.3.21 <0.4.0"
+ "@threenative/assets": ">=0.3.22 <0.4.0"
}
}
diff --git a/packages/create-threenative/templates/action-rpg/package.json b/packages/create-threenative/templates/action-rpg/package.json
index 8cf7d4aedf..0f463ee99e 100644
--- a/packages/create-threenative/templates/action-rpg/package.json
+++ b/packages/create-threenative/templates/action-rpg/package.json
@@ -19,9 +19,9 @@
"format:check": "biome format src"
},
"dependencies": {
- "@threenative/core": ">=0.3.20",
- "@threenative/physics": ">=0.3.20",
- "@threenative/ui": ">=0.3.20",
+ "@threenative/core": ">=0.3.21",
+ "@threenative/physics": ">=0.3.21",
+ "@threenative/ui": ">=0.3.21",
"react": "19.2.0",
"react-dom": "19.2.0",
"three": "0.187.0"
@@ -29,13 +29,13 @@
"devDependencies": {
"@gltf-transform/cli": "4.4.2",
"@tailwindcss/vite": "4.3.3",
- "@threenative/assets": ">=0.3.21",
- "@threenative/playtest": ">=0.3.20",
+ "@threenative/assets": ">=0.3.22",
+ "@threenative/playtest": ">=0.3.21",
"@types/react": "19.2.0",
"@types/react-dom": "19.2.0",
"@types/three": "0.187.0",
"@vitejs/plugin-react": "6.0.5",
- "create-threenative": "0.2.25",
+ "create-threenative": "0.2.26",
"esbuild": "0.27.0",
"playwright": "1.62.1",
"tailwindcss": "4.3.3",
@@ -45,7 +45,7 @@
"eslint": "10.13.0"
},
"optionalDependencies": {
- "@threenative/runtime-native": ">=0.3.20"
+ "@threenative/runtime-native": ">=0.3.21"
},
"overrides": {
"sharp": ">=0.35.4",
diff --git a/packages/create-threenative/templates/adventure/package.json b/packages/create-threenative/templates/adventure/package.json
index eeb68a7959..151a1ec3bd 100644
--- a/packages/create-threenative/templates/adventure/package.json
+++ b/packages/create-threenative/templates/adventure/package.json
@@ -19,9 +19,9 @@
"format:check": "biome format src"
},
"dependencies": {
- "@threenative/core": ">=0.3.20",
- "@threenative/physics": ">=0.3.20",
- "@threenative/ui": ">=0.3.20",
+ "@threenative/core": ">=0.3.21",
+ "@threenative/physics": ">=0.3.21",
+ "@threenative/ui": ">=0.3.21",
"react": "19.2.0",
"react-dom": "19.2.0",
"three": "0.187.0"
@@ -30,11 +30,11 @@
"@tailwindcss/vite": "4.3.3",
"@vitejs/plugin-react": "6.0.5",
"@types/three": "0.187.0",
- "@threenative/assets": ">=0.3.21",
- "@threenative/playtest": ">=0.3.20",
+ "@threenative/assets": ">=0.3.22",
+ "@threenative/playtest": ">=0.3.21",
"@types/react": "19.2.0",
"@types/react-dom": "19.2.0",
- "create-threenative": "0.2.25",
+ "create-threenative": "0.2.26",
"esbuild": "0.27.0",
"playwright": "1.62.1",
"tailwindcss": "4.3.3",
@@ -45,7 +45,7 @@
"eslint": "10.13.0"
},
"optionalDependencies": {
- "@threenative/runtime-native": ">=0.3.20"
+ "@threenative/runtime-native": ">=0.3.21"
},
"overrides": {
"sharp": ">=0.35.4",
diff --git a/packages/create-threenative/templates/collectathon/package.json b/packages/create-threenative/templates/collectathon/package.json
index eeb68a7959..151a1ec3bd 100644
--- a/packages/create-threenative/templates/collectathon/package.json
+++ b/packages/create-threenative/templates/collectathon/package.json
@@ -19,9 +19,9 @@
"format:check": "biome format src"
},
"dependencies": {
- "@threenative/core": ">=0.3.20",
- "@threenative/physics": ">=0.3.20",
- "@threenative/ui": ">=0.3.20",
+ "@threenative/core": ">=0.3.21",
+ "@threenative/physics": ">=0.3.21",
+ "@threenative/ui": ">=0.3.21",
"react": "19.2.0",
"react-dom": "19.2.0",
"three": "0.187.0"
@@ -30,11 +30,11 @@
"@tailwindcss/vite": "4.3.3",
"@vitejs/plugin-react": "6.0.5",
"@types/three": "0.187.0",
- "@threenative/assets": ">=0.3.21",
- "@threenative/playtest": ">=0.3.20",
+ "@threenative/assets": ">=0.3.22",
+ "@threenative/playtest": ">=0.3.21",
"@types/react": "19.2.0",
"@types/react-dom": "19.2.0",
- "create-threenative": "0.2.25",
+ "create-threenative": "0.2.26",
"esbuild": "0.27.0",
"playwright": "1.62.1",
"tailwindcss": "4.3.3",
@@ -45,7 +45,7 @@
"eslint": "10.13.0"
},
"optionalDependencies": {
- "@threenative/runtime-native": ">=0.3.20"
+ "@threenative/runtime-native": ">=0.3.21"
},
"overrides": {
"sharp": ">=0.35.4",
diff --git a/packages/create-threenative/templates/kart/package.json b/packages/create-threenative/templates/kart/package.json
index eb43c7e622..2547f32729 100644
--- a/packages/create-threenative/templates/kart/package.json
+++ b/packages/create-threenative/templates/kart/package.json
@@ -19,8 +19,8 @@
"format:check": "biome format src"
},
"dependencies": {
- "@threenative/core": ">=0.3.20",
- "@threenative/ui": ">=0.3.20",
+ "@threenative/core": ">=0.3.21",
+ "@threenative/ui": ">=0.3.21",
"react": "19.2.0",
"react-dom": "19.2.0",
"three": "0.187.0"
@@ -29,11 +29,11 @@
"@tailwindcss/vite": "4.3.3",
"@vitejs/plugin-react": "6.0.5",
"@types/three": "0.187.0",
- "@threenative/assets": ">=0.3.21",
- "@threenative/playtest": ">=0.3.20",
+ "@threenative/assets": ">=0.3.22",
+ "@threenative/playtest": ">=0.3.21",
"@types/react": "19.2.0",
"@types/react-dom": "19.2.0",
- "create-threenative": "0.2.25",
+ "create-threenative": "0.2.26",
"esbuild": "0.27.0",
"playwright": "1.62.1",
"tailwindcss": "4.3.3",
@@ -44,7 +44,7 @@
"eslint": "10.13.0"
},
"optionalDependencies": {
- "@threenative/runtime-native": ">=0.3.20"
+ "@threenative/runtime-native": ">=0.3.21"
},
"overrides": {
"sharp": ">=0.35.4",
diff --git a/packages/create-threenative/templates/minimal/package.json b/packages/create-threenative/templates/minimal/package.json
index 83a54fbb9b..b75cb33d3c 100644
--- a/packages/create-threenative/templates/minimal/package.json
+++ b/packages/create-threenative/templates/minimal/package.json
@@ -19,15 +19,15 @@
"format:check": "biome format src"
},
"dependencies": {
- "@threenative/core": ">=0.3.20",
- "@threenative/physics": ">=0.3.20",
+ "@threenative/core": ">=0.3.21",
+ "@threenative/physics": ">=0.3.21",
"three": "0.187.0"
},
"devDependencies": {
- "@threenative/assets": ">=0.3.21",
- "@threenative/playtest": ">=0.3.20",
+ "@threenative/assets": ">=0.3.22",
+ "@threenative/playtest": ">=0.3.21",
"@types/three": "0.187.0",
- "create-threenative": "0.2.25",
+ "create-threenative": "0.2.26",
"esbuild": "0.27.0",
"playwright": "1.62.1",
"typescript": "7.0.2",
@@ -37,7 +37,7 @@
"eslint": "10.13.0"
},
"optionalDependencies": {
- "@threenative/runtime-native": ">=0.3.20"
+ "@threenative/runtime-native": ">=0.3.21"
},
"overrides": {
"sharp": ">=0.35.4",
diff --git a/packages/create-threenative/templates/platformer/package.json b/packages/create-threenative/templates/platformer/package.json
index eeb68a7959..151a1ec3bd 100644
--- a/packages/create-threenative/templates/platformer/package.json
+++ b/packages/create-threenative/templates/platformer/package.json
@@ -19,9 +19,9 @@
"format:check": "biome format src"
},
"dependencies": {
- "@threenative/core": ">=0.3.20",
- "@threenative/physics": ">=0.3.20",
- "@threenative/ui": ">=0.3.20",
+ "@threenative/core": ">=0.3.21",
+ "@threenative/physics": ">=0.3.21",
+ "@threenative/ui": ">=0.3.21",
"react": "19.2.0",
"react-dom": "19.2.0",
"three": "0.187.0"
@@ -30,11 +30,11 @@
"@tailwindcss/vite": "4.3.3",
"@vitejs/plugin-react": "6.0.5",
"@types/three": "0.187.0",
- "@threenative/assets": ">=0.3.21",
- "@threenative/playtest": ">=0.3.20",
+ "@threenative/assets": ">=0.3.22",
+ "@threenative/playtest": ">=0.3.21",
"@types/react": "19.2.0",
"@types/react-dom": "19.2.0",
- "create-threenative": "0.2.25",
+ "create-threenative": "0.2.26",
"esbuild": "0.27.0",
"playwright": "1.62.1",
"tailwindcss": "4.3.3",
@@ -45,7 +45,7 @@
"eslint": "10.13.0"
},
"optionalDependencies": {
- "@threenative/runtime-native": ">=0.3.20"
+ "@threenative/runtime-native": ">=0.3.21"
},
"overrides": {
"sharp": ">=0.35.4",
diff --git a/packages/create-threenative/templates/puzzle/package.json b/packages/create-threenative/templates/puzzle/package.json
index 939e357e32..ae7d48f191 100644
--- a/packages/create-threenative/templates/puzzle/package.json
+++ b/packages/create-threenative/templates/puzzle/package.json
@@ -18,9 +18,9 @@
"format:check": "biome format src"
},
"dependencies": {
- "@threenative/core": ">=0.3.20",
- "@threenative/physics": ">=0.3.20",
- "@threenative/ui": ">=0.3.20",
+ "@threenative/core": ">=0.3.21",
+ "@threenative/physics": ">=0.3.21",
+ "@threenative/ui": ">=0.3.21",
"react": "19.2.0",
"react-dom": "19.2.0",
"three": "0.187.0"
@@ -28,13 +28,13 @@
"devDependencies": {
"@gltf-transform/cli": "4.4.2",
"@tailwindcss/vite": "4.3.3",
- "@threenative/assets": ">=0.3.21",
- "@threenative/playtest": ">=0.3.20",
+ "@threenative/assets": ">=0.3.22",
+ "@threenative/playtest": ">=0.3.21",
"@types/react": "19.2.0",
"@types/react-dom": "19.2.0",
"@types/three": "0.187.0",
"@vitejs/plugin-react": "6.0.5",
- "create-threenative": "0.2.25",
+ "create-threenative": "0.2.26",
"esbuild": "0.27.0",
"playwright": "1.62.1",
"tailwindcss": "4.3.3",
@@ -44,7 +44,7 @@
"eslint": "10.13.0"
},
"optionalDependencies": {
- "@threenative/runtime-native": ">=0.3.20"
+ "@threenative/runtime-native": ">=0.3.21"
},
"overrides": {
"sharp": ">=0.35.4",
diff --git a/packages/create-threenative/templates/racing/package.json b/packages/create-threenative/templates/racing/package.json
index bc518bc726..5c04059a61 100644
--- a/packages/create-threenative/templates/racing/package.json
+++ b/packages/create-threenative/templates/racing/package.json
@@ -19,9 +19,9 @@
"format:check": "biome format src"
},
"dependencies": {
- "@threenative/core": ">=0.3.20",
- "@threenative/physics": ">=0.3.20",
- "@threenative/ui": ">=0.3.20",
+ "@threenative/core": ">=0.3.21",
+ "@threenative/physics": ">=0.3.21",
+ "@threenative/ui": ">=0.3.21",
"react": "19.2.0",
"react-dom": "19.2.0",
"three": "0.187.0"
@@ -29,13 +29,13 @@
"devDependencies": {
"@gltf-transform/cli": "4.4.2",
"@tailwindcss/vite": "4.3.3",
- "@threenative/assets": ">=0.3.21",
- "@threenative/playtest": ">=0.3.20",
+ "@threenative/assets": ">=0.3.22",
+ "@threenative/playtest": ">=0.3.21",
"@types/react": "19.2.0",
"@types/react-dom": "19.2.0",
"@types/three": "0.187.0",
"@vitejs/plugin-react": "6.0.5",
- "create-threenative": "0.2.25",
+ "create-threenative": "0.2.26",
"esbuild": "0.27.0",
"playwright": "1.62.1",
"tailwindcss": "4.3.3",
@@ -45,7 +45,7 @@
"eslint": "10.13.0"
},
"optionalDependencies": {
- "@threenative/runtime-native": ">=0.3.20"
+ "@threenative/runtime-native": ">=0.3.21"
},
"overrides": {
"sharp": ">=0.35.4",
diff --git a/packages/create-threenative/templates/rain/package.json b/packages/create-threenative/templates/rain/package.json
index ebe7cca7b7..6cce416cfb 100644
--- a/packages/create-threenative/templates/rain/package.json
+++ b/packages/create-threenative/templates/rain/package.json
@@ -18,8 +18,8 @@
"format:check": "biome format src"
},
"dependencies": {
- "@threenative/core": ">=0.3.20",
- "@threenative/ui": ">=0.3.20",
+ "@threenative/core": ">=0.3.21",
+ "@threenative/ui": ">=0.3.21",
"react": "19.2.0",
"react-dom": "19.2.0",
"react-reconciler": "0.33.0",
@@ -27,13 +27,13 @@
},
"devDependencies": {
"@tailwindcss/vite": "4.3.3",
- "@threenative/assets": ">=0.3.21",
- "@threenative/playtest": ">=0.3.20",
+ "@threenative/assets": ">=0.3.22",
+ "@threenative/playtest": ">=0.3.21",
"@types/react": "19.2.0",
"@types/react-dom": "19.2.0",
"@types/three": "0.187.0",
"@vitejs/plugin-react": "6.0.5",
- "create-threenative": "0.2.25",
+ "create-threenative": "0.2.26",
"esbuild": "0.27.0",
"playwright": "1.62.1",
"tailwindcss": "4.3.3",
@@ -45,7 +45,7 @@
"eslint": "10.13.0"
},
"optionalDependencies": {
- "@threenative/runtime-native": ">=0.3.20"
+ "@threenative/runtime-native": ">=0.3.21"
},
"overrides": {
"sharp": ">=0.35.4",
diff --git a/packages/create-threenative/templates/rts/package.json b/packages/create-threenative/templates/rts/package.json
index 5efd1d27e6..5545fed889 100644
--- a/packages/create-threenative/templates/rts/package.json
+++ b/packages/create-threenative/templates/rts/package.json
@@ -19,8 +19,8 @@
"format:check": "biome format src"
},
"dependencies": {
- "@threenative/core": ">=0.3.20",
- "@threenative/ui": ">=0.3.20",
+ "@threenative/core": ">=0.3.21",
+ "@threenative/ui": ">=0.3.21",
"react": "19.2.0",
"react-dom": "19.2.0",
"three": "0.187.0"
@@ -28,13 +28,13 @@
"devDependencies": {
"@gltf-transform/cli": "4.4.2",
"@tailwindcss/vite": "4.3.3",
- "@threenative/assets": ">=0.3.21",
- "@threenative/playtest": ">=0.3.20",
+ "@threenative/assets": ">=0.3.22",
+ "@threenative/playtest": ">=0.3.21",
"@types/react": "19.2.0",
"@types/react-dom": "19.2.0",
"@types/three": "0.187.0",
"@vitejs/plugin-react": "6.0.5",
- "create-threenative": "0.2.25",
+ "create-threenative": "0.2.26",
"esbuild": "0.27.0",
"playwright": "1.62.1",
"tailwindcss": "4.3.3",
@@ -44,7 +44,7 @@
"eslint": "10.13.0"
},
"optionalDependencies": {
- "@threenative/runtime-native": ">=0.3.20"
+ "@threenative/runtime-native": ">=0.3.21"
},
"overrides": {
"sharp": ">=0.35.4",
diff --git a/packages/create-threenative/templates/runner/package.json b/packages/create-threenative/templates/runner/package.json
index 939e357e32..ae7d48f191 100644
--- a/packages/create-threenative/templates/runner/package.json
+++ b/packages/create-threenative/templates/runner/package.json
@@ -18,9 +18,9 @@
"format:check": "biome format src"
},
"dependencies": {
- "@threenative/core": ">=0.3.20",
- "@threenative/physics": ">=0.3.20",
- "@threenative/ui": ">=0.3.20",
+ "@threenative/core": ">=0.3.21",
+ "@threenative/physics": ">=0.3.21",
+ "@threenative/ui": ">=0.3.21",
"react": "19.2.0",
"react-dom": "19.2.0",
"three": "0.187.0"
@@ -28,13 +28,13 @@
"devDependencies": {
"@gltf-transform/cli": "4.4.2",
"@tailwindcss/vite": "4.3.3",
- "@threenative/assets": ">=0.3.21",
- "@threenative/playtest": ">=0.3.20",
+ "@threenative/assets": ">=0.3.22",
+ "@threenative/playtest": ">=0.3.21",
"@types/react": "19.2.0",
"@types/react-dom": "19.2.0",
"@types/three": "0.187.0",
"@vitejs/plugin-react": "6.0.5",
- "create-threenative": "0.2.25",
+ "create-threenative": "0.2.26",
"esbuild": "0.27.0",
"playwright": "1.62.1",
"tailwindcss": "4.3.3",
@@ -44,7 +44,7 @@
"eslint": "10.13.0"
},
"optionalDependencies": {
- "@threenative/runtime-native": ">=0.3.20"
+ "@threenative/runtime-native": ">=0.3.21"
},
"overrides": {
"sharp": ">=0.35.4",
diff --git a/packages/create-threenative/templates/sailing/package.json b/packages/create-threenative/templates/sailing/package.json
index 1c9e28b95b..4946844bce 100644
--- a/packages/create-threenative/templates/sailing/package.json
+++ b/packages/create-threenative/templates/sailing/package.json
@@ -19,9 +19,9 @@
"format:check": "biome format src"
},
"dependencies": {
- "@threenative/core": ">=0.3.20",
- "@threenative/physics": ">=0.3.20",
- "@threenative/ui": ">=0.3.20",
+ "@threenative/core": ">=0.3.21",
+ "@threenative/physics": ">=0.3.21",
+ "@threenative/ui": ">=0.3.21",
"react": "19.2.0",
"react-dom": "19.2.0",
"react-reconciler": "0.33.0",
@@ -29,13 +29,13 @@
},
"devDependencies": {
"@tailwindcss/vite": "4.3.3",
- "@threenative/assets": ">=0.3.21",
- "@threenative/playtest": ">=0.3.20",
+ "@threenative/assets": ">=0.3.22",
+ "@threenative/playtest": ">=0.3.21",
"@types/react": "19.2.0",
"@types/react-dom": "19.2.0",
"@types/three": "0.187.0",
"@vitejs/plugin-react": "6.0.5",
- "create-threenative": "0.2.25",
+ "create-threenative": "0.2.26",
"esbuild": "0.27.0",
"playwright": "1.62.1",
"tailwindcss": "4.3.3",
@@ -46,7 +46,7 @@
"eslint": "10.13.0"
},
"optionalDependencies": {
- "@threenative/runtime-native": ">=0.3.20"
+ "@threenative/runtime-native": ">=0.3.21"
},
"overrides": {
"sharp": ">=0.35.4",
diff --git a/packages/create-threenative/templates/shooter/package.json b/packages/create-threenative/templates/shooter/package.json
index 6dbd0ca2b3..9718a28a92 100644
--- a/packages/create-threenative/templates/shooter/package.json
+++ b/packages/create-threenative/templates/shooter/package.json
@@ -19,9 +19,9 @@
"format:check": "biome format src"
},
"dependencies": {
- "@threenative/core": ">=0.3.20",
- "@threenative/physics": ">=0.3.20",
- "@threenative/ui": ">=0.3.20",
+ "@threenative/core": ">=0.3.21",
+ "@threenative/physics": ">=0.3.21",
+ "@threenative/ui": ">=0.3.21",
"react": "19.2.0",
"react-dom": "19.2.0",
"three": "0.187.0"
@@ -30,12 +30,12 @@
"@tailwindcss/vite": "4.3.3",
"@types/three": "0.187.0",
"@vitejs/plugin-react": "6.0.5",
- "@threenative/assets": ">=0.3.21",
- "@threenative/playtest": ">=0.3.20",
+ "@threenative/assets": ">=0.3.22",
+ "@threenative/playtest": ">=0.3.21",
"@types/react": "19.2.0",
"@types/react-dom": "19.2.0",
"playwright": "1.62.1",
- "create-threenative": "0.2.25",
+ "create-threenative": "0.2.26",
"esbuild": "0.27.0",
"tailwindcss": "4.3.3",
"typescript": "7.0.2",
@@ -45,7 +45,7 @@
"eslint": "10.13.0"
},
"optionalDependencies": {
- "@threenative/runtime-native": ">=0.3.20"
+ "@threenative/runtime-native": ">=0.3.21"
},
"overrides": {
"sharp": ">=0.35.4",
diff --git a/packages/create-threenative/templates/snow/package.json b/packages/create-threenative/templates/snow/package.json
index eb26c9fc12..910b61f359 100644
--- a/packages/create-threenative/templates/snow/package.json
+++ b/packages/create-threenative/templates/snow/package.json
@@ -19,9 +19,9 @@
"format:check": "biome format src"
},
"dependencies": {
- "@threenative/core": ">=0.3.20",
- "@threenative/physics": ">=0.3.20",
- "@threenative/ui": ">=0.3.20",
+ "@threenative/core": ">=0.3.21",
+ "@threenative/physics": ">=0.3.21",
+ "@threenative/ui": ">=0.3.21",
"react": "19.2.0",
"react-dom": "19.2.0",
"react-reconciler": "0.33.0",
@@ -29,13 +29,13 @@
},
"devDependencies": {
"@tailwindcss/vite": "4.3.3",
- "@threenative/assets": ">=0.3.21",
- "@threenative/playtest": ">=0.3.20",
+ "@threenative/assets": ">=0.3.22",
+ "@threenative/playtest": ">=0.3.21",
"@types/react": "19.2.0",
"@types/react-dom": "19.2.0",
"@types/three": "0.187.0",
"@vitejs/plugin-react": "6.0.5",
- "create-threenative": "0.2.25",
+ "create-threenative": "0.2.26",
"esbuild": "0.27.0",
"playwright": "1.62.1",
"tailwindcss": "4.3.3",
@@ -46,7 +46,7 @@
"eslint": "10.13.0"
},
"optionalDependencies": {
- "@threenative/runtime-native": ">=0.3.20"
+ "@threenative/runtime-native": ">=0.3.21"
},
"overrides": {
"sharp": ">=0.35.4",
diff --git a/packages/create-threenative/templates/starter/package.json b/packages/create-threenative/templates/starter/package.json
index 060784ac22..b79b2771b6 100644
--- a/packages/create-threenative/templates/starter/package.json
+++ b/packages/create-threenative/templates/starter/package.json
@@ -20,9 +20,9 @@
"format:check": "biome format src"
},
"dependencies": {
- "@threenative/core": ">=0.3.20",
- "@threenative/physics": ">=0.3.20",
- "@threenative/ui": ">=0.3.20",
+ "@threenative/core": ">=0.3.21",
+ "@threenative/physics": ">=0.3.21",
+ "@threenative/ui": ">=0.3.21",
"react": "19.2.0",
"react-dom": "19.2.0",
"react-reconciler": "0.33.0",
@@ -30,13 +30,13 @@
},
"devDependencies": {
"@tailwindcss/vite": "4.3.3",
- "@threenative/assets": ">=0.3.21",
- "@threenative/playtest": ">=0.3.20",
+ "@threenative/assets": ">=0.3.22",
+ "@threenative/playtest": ">=0.3.21",
"@types/react": "19.2.0",
"@types/react-dom": "19.2.0",
"@types/three": "0.187.0",
"@vitejs/plugin-react": "6.0.5",
- "create-threenative": "0.2.25",
+ "create-threenative": "0.2.26",
"esbuild": "0.27.0",
"playwright": "1.62.1",
"tailwindcss": "4.3.3",
@@ -47,7 +47,7 @@
"eslint": "10.13.0"
},
"optionalDependencies": {
- "@threenative/runtime-native": ">=0.3.20"
+ "@threenative/runtime-native": ">=0.3.21"
},
"overrides": {
"sharp": ">=0.35.4",
diff --git a/packages/create-threenative/templates/tower-defense/package.json b/packages/create-threenative/templates/tower-defense/package.json
index 939e357e32..ae7d48f191 100644
--- a/packages/create-threenative/templates/tower-defense/package.json
+++ b/packages/create-threenative/templates/tower-defense/package.json
@@ -18,9 +18,9 @@
"format:check": "biome format src"
},
"dependencies": {
- "@threenative/core": ">=0.3.20",
- "@threenative/physics": ">=0.3.20",
- "@threenative/ui": ">=0.3.20",
+ "@threenative/core": ">=0.3.21",
+ "@threenative/physics": ">=0.3.21",
+ "@threenative/ui": ">=0.3.21",
"react": "19.2.0",
"react-dom": "19.2.0",
"three": "0.187.0"
@@ -28,13 +28,13 @@
"devDependencies": {
"@gltf-transform/cli": "4.4.2",
"@tailwindcss/vite": "4.3.3",
- "@threenative/assets": ">=0.3.21",
- "@threenative/playtest": ">=0.3.20",
+ "@threenative/assets": ">=0.3.22",
+ "@threenative/playtest": ">=0.3.21",
"@types/react": "19.2.0",
"@types/react-dom": "19.2.0",
"@types/three": "0.187.0",
"@vitejs/plugin-react": "6.0.5",
- "create-threenative": "0.2.25",
+ "create-threenative": "0.2.26",
"esbuild": "0.27.0",
"playwright": "1.62.1",
"tailwindcss": "4.3.3",
@@ -44,7 +44,7 @@
"eslint": "10.13.0"
},
"optionalDependencies": {
- "@threenative/runtime-native": ">=0.3.20"
+ "@threenative/runtime-native": ">=0.3.21"
},
"overrides": {
"sharp": ">=0.35.4",
diff --git a/packages/engine-mcp/__tests__/server.spec.ts b/packages/engine-mcp/__tests__/server.spec.ts
index f39835bb31..ae140daac0 100644
--- a/packages/engine-mcp/__tests__/server.spec.ts
+++ b/packages/engine-mcp/__tests__/server.spec.ts
@@ -32,7 +32,7 @@ describe("threenative-engine-mcp stdio contract", async () => {
capabilities: { tools: { listChanged: false } },
instructions: expect.stringContaining("threenative-capabilities"),
protocolVersion: "2025-06-18",
- serverInfo: { name: "threenative-engine-mcp", version: "0.2.20" },
+ serverInfo: { name: "threenative-engine-mcp", version: "0.2.21" },
},
});
});
diff --git a/packages/engine-mcp/package.json b/packages/engine-mcp/package.json
index 44b383a3df..9b6d5e71de 100644
--- a/packages/engine-mcp/package.json
+++ b/packages/engine-mcp/package.json
@@ -1,6 +1,6 @@
{
"name": "threenative-engine-mcp",
- "version": "0.2.20",
+ "version": "0.2.21",
"license": "MIT",
"description": "Offline MCP capability discovery for ThreeNative authoring agents.",
"keywords": [
diff --git a/packages/engine-mcp/src/index.ts b/packages/engine-mcp/src/index.ts
index 7148ea2aaf..194c82be68 100644
--- a/packages/engine-mcp/src/index.ts
+++ b/packages/engine-mcp/src/index.ts
@@ -1646,7 +1646,7 @@ export async function handleLine(line: string, manifestFile: string): Promise=0.3.20 <0.4.0",
+ "@threenative/core": ">=0.3.21 <0.4.0",
"three": ">=0.187.0 <0.188.0"
},
"scripts": {
diff --git a/packages/playtest/package.json b/packages/playtest/package.json
index ab216202bc..c1e665a105 100644
--- a/packages/playtest/package.json
+++ b/packages/playtest/package.json
@@ -1,6 +1,6 @@
{
"name": "@threenative/playtest",
- "version": "0.3.20",
+ "version": "0.3.21",
"license": "MIT",
"description": "Scenario-driven playtest harness for Three.js games. Runs on plain Three.js with zero ThreeNative dependencies.",
"keywords": [
diff --git a/packages/procedural-animals/package.json b/packages/procedural-animals/package.json
index 4b0ca3c786..66ca92efa3 100644
--- a/packages/procedural-animals/package.json
+++ b/packages/procedural-animals/package.json
@@ -1,6 +1,6 @@
{
"name": "@threenative/procedural-animals",
- "version": "0.1.16",
+ "version": "0.1.17",
"license": "MIT",
"description": "Optional, bake-first procedural animal content for ThreeNative.",
"homepage": "https://github.com/ThreeNativeHQ/threenative#readme",
diff --git a/packages/procedural-environment/package.json b/packages/procedural-environment/package.json
index 7dab36b1a5..ea1661dbd6 100644
--- a/packages/procedural-environment/package.json
+++ b/packages/procedural-environment/package.json
@@ -1,6 +1,6 @@
{
"name": "@threenative/procedural-environment",
- "version": "0.1.6",
+ "version": "0.1.7",
"license": "MIT",
"description": "Optional, bake-first procedural nature GLBs for ThreeNative: trees and cover (Arbor), forest floor (forest-kit) and rocks, cliffs and mountains (Outcrop), found by biome.",
"homepage": "https://github.com/ThreeNativeHQ/threenative#readme",
diff --git a/packages/raw-unreal/package.json b/packages/raw-unreal/package.json
index 69e248a32d..0236de5b36 100644
--- a/packages/raw-unreal/package.json
+++ b/packages/raw-unreal/package.json
@@ -1,6 +1,6 @@
{
"name": "@threenative/raw-unreal",
- "version": "0.1.20",
+ "version": "0.1.21",
"license": "MIT",
"description": "Loads raw Unreal editor .uasset static meshes directly into Three.js geometry \u2014 UE5 FMeshDescription and UE4.18 FRawMesh layouts, with no interchange conversion.",
"keywords": ["threenative", "unreal", "uasset", "static-mesh", "three", "threejs", "loader"],
diff --git a/packages/runtime-native/package.json b/packages/runtime-native/package.json
index 4235293ed3..04e0521f89 100644
--- a/packages/runtime-native/package.json
+++ b/packages/runtime-native/package.json
@@ -1,6 +1,6 @@
{
"name": "@threenative/runtime-native",
- "version": "0.3.20",
+ "version": "0.3.21",
"description": "ThreeNative-owned native host for desktop and Android",
"keywords": [
"threenative",
diff --git a/packages/terrain/package.json b/packages/terrain/package.json
index 59eb6b0207..f46638eb5c 100644
--- a/packages/terrain/package.json
+++ b/packages/terrain/package.json
@@ -1,6 +1,6 @@
{
"name": "@threenative/terrain",
- "version": "0.1.16",
+ "version": "0.1.17",
"license": "MIT",
"description": "Headless terrain authoring \u2014 noise, erosion, sculpting, roads, rivers, material splats and scatter \u2014 evaluated into ordinary typed arrays and indexed Three.js geometry.",
"keywords": ["threenative", "terrain", "heightfield", "three", "threejs", "procedural", "webgpu"],
@@ -96,9 +96,9 @@
"@threenative/procedural-environment": "workspace:*"
},
"peerDependencies": {
- "@threenative/core": ">=0.3.20 <0.4.0",
- "@threenative/physics": ">=0.3.20 <0.4.0",
- "@threenative/procedural-environment": ">=0.1.6 <0.2.0",
+ "@threenative/core": ">=0.3.21 <0.4.0",
+ "@threenative/physics": ">=0.3.21 <0.4.0",
+ "@threenative/procedural-environment": ">=0.1.7 <0.2.0",
"three": ">=0.187.0 <0.188.0",
"vite": ">=7.0.0 <9.0.0"
},
diff --git a/packages/terrain/src/core/io.ts b/packages/terrain/src/core/io.ts
index 281e2e7146..883a4ccbec 100644
--- a/packages/terrain/src/core/io.ts
+++ b/packages/terrain/src/core/io.ts
@@ -405,7 +405,7 @@ export function encodeGLB(input: IBakedMesh | readonly IBakedMesh[]) {
}
const binary = join(chunks);
const doc = {
- asset: { version: "2.0", generator: "@threenative/terrain 0.1.16" },
+ asset: { version: "2.0", generator: "@threenative/terrain 0.1.17" },
scene: 0,
scenes: [{ nodes: meshes.map((_, i) => i) }],
nodes: meshes.map((m, i) => ({ mesh: i, name: m.name ?? `Terrain ${i}` })),
diff --git a/packages/three-native/package.json b/packages/three-native/package.json
index bf9b48931e..64c4249a7b 100644
--- a/packages/three-native/package.json
+++ b/packages/three-native/package.json
@@ -1,6 +1,6 @@
{
"name": "@threenative/three-native",
- "version": "0.3.20",
+ "version": "0.3.21",
"license": "MIT",
"description": "The native engine's machine-readable compatibility catalog and the generators that adapt it to TypeScript declarations and the C binding ABI.",
"keywords": ["threenative", "three", "native", "abi", "gamedev"],
diff --git a/packages/ueformat/package.json b/packages/ueformat/package.json
index 907f2ee59a..9e73cd2e5e 100644
--- a/packages/ueformat/package.json
+++ b/packages/ueformat/package.json
@@ -1,6 +1,6 @@
{
"name": "@threenative/ueformat",
- "version": "0.1.20",
+ "version": "0.1.21",
"license": "MIT",
"description": "UEFormat v10 .uemodel parser and Three.js loader for meshes exported from Unreal packages by CUE4Parse/FModel.",
"keywords": ["threenative", "unreal", "ueformat", "uemodel", "three", "threejs", "loader"],
diff --git a/packages/ui/package.json b/packages/ui/package.json
index 5ae0d06230..e4cf83207d 100644
--- a/packages/ui/package.json
+++ b/packages/ui/package.json
@@ -1,6 +1,6 @@
{
"name": "@threenative/ui",
- "version": "0.3.20",
+ "version": "0.3.21",
"license": "MIT",
"description": "React bindings for mounting a ThreeNative game and reading throttled state.",
"keywords": ["threenative", "react", "tailwind", "hud", "three", "threejs", "gamedev"],
@@ -30,7 +30,7 @@
},
"sideEffects": false,
"peerDependencies": {
- "@threenative/core": ">=0.3.20 <0.4.0",
+ "@threenative/core": ">=0.3.21 <0.4.0",
"react": ">=19.2.0 <20",
"react-dom": ">=19.2.0 <20"
},