A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat(cache): protect offline versions during budget cleanup
yhh51aee8a83407
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 79fd71f6d..fcf91ee24 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -14,6 +14,10 @@ published separately; it ships inside the editor.## [Unreleased]+### Added++- **Disk cache budgets preserve offline content versions.** Node and capable mini-game hosts report resource usage, hashes, version ownership and protected bytes. Cleanup previews and applies LRU eviction while keeping current, pending, rollback and explicitly retained versions, coordinating with downloads and reporting actual released bytes. The editor's connected-device Profiler provides scans, budget previews, cleanup and version retention. Hosts without management report unavailable usage; saves and unknown files remain protected.+### Fixed- **Audio preferences survive game restart.** Audio-demo saves and restores master, music and SFX volumes through engine storage, validates saved values, and restores the displayed percentages and actual bus gains at startup. Golden verification uses independent browser processes with a stable origin and isolated profile, cycles master volume to mute and verifies that both the label and silent output survive restart.diff --git a/desktop b/desktopindex ba95cde51..e09e93d44 160000--- a/desktop+++ b/desktop@@ -1 +1 @@-Subproject commit ba95cde5127b5a6c8c24f2860f365397b20a0071+Subproject commit e09e93d447ec0505b42d07a81b4a25ac0092b372diff --git a/docs/CACHE_BUDGET.md b/docs/CACHE_BUDGET.mdnew file mode 100644index 000000000..64286ad00--- /dev/null+++ b/docs/CACHE_BUDGET.md@@ -0,0 +1,87 @@+# Disk cache budgets and offline version protection++The disk cache stores verified hot-update resource bytes. Its resource budget is+separate from the in-memory texture/audio residency budgets and from application+saves. A budget is an explicit cleanup target, not a promise that protected+versions can fit inside that target.++```ts+import { Assets } from 'esengine';++const assets = app.getResource(Assets);+const report = await assets.diskCacheReport();+if (report.capability === 'managed') {+ const budget = 128 * 1024 * 1024;+ const preview = await assets.cleanDiskCache(budget);+ // Show preview.releaseBytes, candidates and budgetMet before execution.+ const result = await assets.cleanDiskCache(budget, true);+ // result.releaseBytes counts successful deletions only.+}++// A version in the reported history can be kept independently of rollback.+await assets.retainDiskCacheVersion('content-revision');+await assets.retainDiskCacheVersion('content-revision', false);+await assets.diskCacheReport(true); // Reconcile and persist a directory rescan.+```++| Capability | Meaning |+|---|---|+| `managed` | Resource files can be enumerated, measured and safely removed. Node and mini-game hosts with the required filesystem APIs support this. |+| `storage-only` | Bytes can be cached, but usage and cleanup are unavailable. The current native bridge has this capability. |+| `unavailable` | No usable engine disk-cache store. Web is in this category; the browser HTTP cache is outside this API. |++Unavailable sizes are `null`, never a misleading zero. `usedBytes` measures+resource files, including interrupted temporary writes, while `indexBytes`+measures the index separately. Neither value measures all application saves or+the platform's entire storage quota. Leave room for those when selecting a budget.++The index records cache key, byte hash, actual size, last access, version ownership+and protection reasons. Update checks pin pending resources before download;+commits pin the active version and its previous version for rollback. If storing+the active manifest fails, the actual next-launch version and its rollback remain+pinned through later updates. Explicit retention survives movement of that pair.+Files shared between versions are protected whenever any owner still needs them.++Cleanup recomputes its candidates when executed, so changing versions after a+preview cannot make the preview authorize deletion of current resources. IO and+cleanup share a coordinator per adapter; deletion yields every sixteen files.+Protected files can keep usage above budget, which `budgetMet: false` reports.+Deletion failures and actual freed bytes are returned. If a full disk refuses the+final index write, `indexPersisted: false` reports that successful deletions will+be reconciled on the next scan.++Application save names are excluded from enumeration. Legacy files without an+index identity, corrupt-index survivors and interrupted temporary files remain+protected instead of guessing their ownership. A rescan reconciles sizes and+missing files; it does not prove a version can boot. The version's `missing`+count exposes incomplete offline resources. This coordinator assumes one runtime+owns the cache directory; it does not provide an interprocess filesystem lock.++In the editor, select a connected development device in **Profiler**. The disk+cache section provides rescan, resource budget, cleanup preview, execution and+explicit version retention. Unsupported or older device builds report capability+limitations or their query error. This is an authenticated development channel;+these controls are not shipped as a game UI.++Run the self-contained demonstration after installing workspace dependencies:++```text+node tools/cache-budget-demo.mjs+```++It serves three eight-byte resource versions over a local HTTP server, applies+two updates, removes the oldest version, closes the server and starts a new+process with network access rejected. The new process must read both current and+rollback bytes. Node's default key/value storage is session-local, so the fixture+explicitly supplies a durable host store for the active manifest. Mini-game and+native hosts already supply their own persistent key/value storage.++This example is a storage/update verification, not a rendered game or physical+mini-game device acceptance. See [the dated verification record](CACHE_BUDGET_REVIEW_2026-10-13.md).++After compiling the current Web and WeChat runtime targets, use+`pnpm verify:cache-budget` for exported mini-game rendering, three updates,+editor-channel controls, quota cleanup and an offline renderer restart. This+contract-host verification writes images and JSON under `output/cache-budget/render/`;+physical WeChat acceptance remains separate. `node tools/cache-budget-scale.mjs`+measures metadata report CPU time on a fixed 1200-file/three-version dataset.diff --git a/docs/CACHE_BUDGET_REVIEW_2026-10-13.md b/docs/CACHE_BUDGET_REVIEW_2026-10-13.mdnew file mode 100644index 000000000..15cffaa08--- /dev/null+++ b/docs/CACHE_BUDGET_REVIEW_2026-10-13.md@@ -0,0 +1,141 @@+# v0.78.0 card review and cache-budget verification — 2026-10-13++The latest fetched engine mainline is `acdc5ded8cc939d81cbb2128d12e93609c0b3da1`;+its editor submodule is `53e998badfa4dfce0d377c0c29b6107502bb893d`.+[v0.78.0](https://github.com/esengine/estella/releases/tag/v0.78.0) was published+on 2026-10-12. Existing uncommitted changes in `D:/estella` and its editor were+preserved. Work is on `codex/cache-version-budget` in a separate checkout.++The live GitHub Project #8 was fetched with pagination: 137 cards. The current+candidate version contains two unfinished cards:++| Card | Board status | Decision |+|---|---|---|+| RM-025 — disk cache budget / offline versions | Todo, P0 | Implement the shared runtime and editor workflow; this benefits 2D Web/mini-game delivery. |+| RM-136 — GPU baking / adaptive sampling | Todo, P2 | Defer specialized 3D work according to the repository's 2D production priority. |++RM-025's earlier static description is outdated: mini-game byte caches and native+URL-to-safe-name mapping already exist. Cache names use XXH64, not SHA256. The+actual missing work was management, version protection and author-facing controls.+Earlier pending device cards (including RM-033 and RM-054) still require their+specified physical-device evidence; their status was not inferred from releases.++The changes are local and unmerged. A `gh pr list --state all --search 'cache+budget'` query returned no matching engine PR at review time. No board completion+or device acceptance is claimed and no remote card was changed.++## Implemented++- Capability distinctions, actual resource/index usage, ownership/hash/access+ index, protected/missing-resource diagnostics and conservative scan repair.+- LRU preview and bounded batches of deletion coordinated with byte IO. Current,+ pending, rollback, next-launch and explicitly retained versions stay protected.+- Failed manifest persistence preserves the version a restart will actually use.+ Full-disk cleanup reports successful deletions even if the index write fails.+- Atomic mini-game writes when rename is supported; hosts without management+ remain usable for byte caching and accurately report their capability.+- Connected-device Profiler controls, localized English/Chinese labels, preview+ invalidation on edits/errors, stale-device-response rejection and retention.+- SDK API snapshots, published API inventory, changelog and runnable demonstration.++## Evidence++SDK targeted regression: **14 files, 164 tests passed, zero skipped**. The run+explicitly used `SDK_TEST_MODE=no-wasm` and `ESTELLA_NO_EMCC=1`; it did not build or+exercise the C++/WASM boundary. Cases included three resource versions, protected+budgets, old saves, retained versions, stale previews, concurrent writes, corrupt+indexes, quota failures, interrupted rename, failed deletions, offline reads,+consecutive manifest-store failures and debug-channel routing.++Editor interaction regression: **3 tests passed**. SDK declaration checks and+SDK build passed; the editor's typecheck and production build passed. API surface,+API declarations/inventory, chunk manifest, import maps, mini-game host/profile+installation, theme and CSS-variable checks passed.++`node tools/cache-budget-demo.mjs` produced:++| Stage | Result |+|---|---|+| Two updates | Each verified/applied/persisted/cached = true |+| Before cleanup | 24 bytes used; 16 protected; 8 reclaimable |+| Preview | One resource; eight bytes releasable |+| Execution | Eight bytes released; sixteen remain; budget met |+| Fresh process, server stopped, network rejected | v3 current and v2 rollback each read eight correct bytes |++The example deliberately supplies durable manifest storage because Node's default+key/value store is session-local. It uses real filesystem caching and a real HTTP+server, then launches a separate offline process. This is functional evidence,+not a performance benchmark.++The actual editor component was rendered in a hidden Electron fixture with the+production stylesheet and inspected at 440- and 760-pixel content widths. Chinese+labels, visible numeric values, version rows, preview and wrapping controls were+checked; no horizontal overflow was found. Screenshots are in local+`output/cache-budget/panel-narrow.png` and `panel-wide.png`. Fixture data does not+represent a physical device. Reproduce after the editor build with:++```text+pnpm exec electron desktop/scripts/cache-panel-preview.mjs+```++## Remaining acceptance++RM-025 remains unfinished as a board/release card: no new code has been merged or+published, and physical WeChat quota/offline-start acceptance is still pending.+Native cache enumeration/removal is not provided by the current host bridge and+therefore reports `storage-only`; Web reports `unavailable`. Interrupted temporary+files and unknown legacy files remain conservatively protected. Resource budgets+exclude saves and do not measure the platform's complete storage quota.++## Continuation: compiled runtimes, real exports and scale measurement++The current source was compiled into both Web and WeChat release WASM with the+existing Emscripten 5.0.0 / Binaryen 125 toolchain. The first parallel Binaryen+optimization failed its `call target must exist` validator. Setting+`BINARYEN_CORES=1` succeeded with unchanged source and release flags; this is the+build environment used for this evidence, not a proven permanent toolchain fix.+Web compiled in 91.23 s and WeChat in 69.76 s. Optional side modules were not built.++The existing `hotupdate-verify-fixture` exported the committed Web sample and a+changed-art update. Its real rendered verifier passed: green `[40,200,90]` became+red `[220,40,40]`; tampered and missing-resource updates were refused; relaunch+restored the red revision. Web accurately returned `cached: null`.++`pnpm verify:cache-budget` now exports four WeChat packages from the same authored+2D hot-update project, with `.wasm.br` and engine subpackages. The driver varies+the CDN art and supplies a test hook; the authored scene/gameplay remain intact.+The mini-game contract host supplies real files and a real authenticated socket+through the editor's shared debug-channel server. This is still a host simulation,+not physical WeChat, and the sample's existing optional-update-channel export+warnings are preserved in `output/cache-budget/render/exports.json`.++| Check | Evidence |+|---|---|+| Three updates | Green `[40,190,50]`, red `[210,40,40]`, blue `[40,70,220]`; each verified/applied/persisted/cached = true |+| Explicit retention | Keeping the oldest version made a zero-byte cleanup refuse all protected resource deletion |+| Full-store cleanup | 627 B before, 418 B protected and remaining, 209 B released; index write failure accurately returned `indexPersisted: false` |+| Pixels | Before/after cleanup RGBA buffers were identical |+| Renderer restart with CDN unavailable | Blue current revision restored; zero attempted CDN downloads; current/rollback missing counts both zero |++Results and images are local under `output/cache-budget/render/verification.json`,+`v1.png`, `v2.png`, `v3.png`, `before-cleanup.png`, `after-cleanup.png` and+`offline-restart.png`. The separate Node example above covers a literal new+process; this rendered run covers a new game window/renderer on the same host.++A synthetic metadata benchmark uses the same 1200-file, three-version index on+the same machine, with three runs on each implementation. Before: 3073.46,+2975.66, 2974.37 ms (median 2975.66). After: 12.14, 10.34, 11.01 ms (median 11.01).+Both report exactly 19,660,800 B used, 14,745,600 B protected and 4,915,200 B+reclaimable. Reverse indexing removes the repeated file × version-reference+search. This measures index CPU work, not device IO or gameplay frame rate.+Reproduce with `node tools/cache-budget-scale.mjs`; before/after JSON is in local+`output/cache-budget/scale-before.json` and `scale-after.json`.++A new regression verifies shared resources remain protected by another owner+after one owner retires its version. Packaged remote-group files with no CDN root+are excluded from cache-missing diagnostics, since those bytes ship in the+package. The compiled-runtime targeted run passed 72 tests before the additional+shared-owner case; the final rerun is recorded with the PR validation.++`adb devices -l` returned no attached devices. Physical-device acceptance remains+an explicit gap; neither rendered simulation nor an eventual merged PR closes it.diff --git a/docs/README.md b/docs/README.mdindex 21209fccf..96ba6cdf9 100644--- a/docs/README.md+++ b/docs/README.md@@ -17,6 +17,8 @@ three layers: the developer-facing guides below, the generated C++ API reference### Conventions+Disk-cache usage and offline-version protection: [CACHE_BUDGET.md](./CACHE_BUDGET.md).+| Document | What it is | Language ||---|---|---|| [CODING_STYLE.md](./CODING_STYLE.md) | C++ and TypeScript naming & formatting rules. | English |diff --git a/docs/astro/src/data/apiStability.generated.json b/docs/astro/src/data/apiStability.generated.jsonindex a386ac33b..e0df6f70e 100644--- a/docs/astro/src/data/apiStability.generated.json+++ b/docs/astro/src/data/apiStability.generated.json@@ -3,10 +3,10 @@"counts": {"public": 115,"beta": 103,- "experimental": 2171,+ "experimental": 2175,"deprecated": 3},- "total": 2389,+ "total": 2393,"subsystems": [{"id": "ecs",diff --git a/package.json b/package.jsonindex d8b40ac4b..59ecf3a67 100644--- a/package.json+++ b/package.json@@ -40,7 +40,8 @@"verify:cooked": "node tools/with-env.mjs ESTELLA_COOK_FIXTURE=1 -- pnpm --filter @estella/pipeline exec vitest run tests/cooked-verify-fixture.test.ts && node tools/run-electron.mjs tools/launchers/headless-cooked-verify.mjs","verify:glx": "node tools/verify-glx-fallback.mjs","verify:remote-capture": "node tools/verify-remote-capture.mjs --platform web && node tools/verify-remote-capture.mjs --platform wechat",- "verify:hotupdate": "node tools/with-env.mjs ESTELLA_HOTUPDATE_FIXTURE=1 -- pnpm --filter @estella/pipeline exec vitest run tests/hotupdate-verify-fixture.test.ts && node tools/run-electron.mjs tools/launchers/headless-hotupdate-verify.mjs"+ "verify:hotupdate": "node tools/with-env.mjs ESTELLA_HOTUPDATE_FIXTURE=1 -- pnpm --filter @estella/pipeline exec vitest run tests/hotupdate-verify-fixture.test.ts && node tools/run-electron.mjs tools/launchers/headless-hotupdate-verify.mjs",+ "verify:cache-budget": "node tools/run-electron.mjs tools/launchers/cache-budget-render-verify.mjs"},"dependencies": {"chalk": "^5.3.0",diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex f9cb1c175..8428ec744 100644--- a/sdk/etc/index.api.md+++ b/sdk/etc/index.api.md@@ -1,7 +1,7 @@# API surface — esengine/index<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 115 public · 91 beta · 1555 experimental · 3 deprecated+Symbols: 115 public · 91 beta · 1559 experimental · 3 deprecated## ABI_LAYOUT_HASH — const @experimental```@@ -989,6 +989,8 @@ backend: BackendbaseUrl: string | undefinedcatalog: CatalogcheckForUpdate: (options: CheckForUpdateOptions) => Promise<UpdatePlan>+cleanDiskCache: (budgetBytes: number, execute?: boolean) => Promise<CacheCleanupResult>+diskCacheReport: (rescan?: boolean) => Promise<ContentCacheReport>fetchBinary: (ref: string) => Promise<ArrayBuffer>fetchJson: <T = unknown>(ref: string) => Promise<T>fetchText: (ref: string) => Promise<string>@@ -1045,6 +1047,7 @@ resolveLoadPath: (ref: string) => stringresolveRef: (ref: string) => string | nullresolveSceneAssetPaths: (sceneData: SceneData, result: SceneAssetResult) => voidrestorePersistedUpdate: (key: string) => boolean+retainDiskCacheVersion: (revision: string, retain?: boolean) => Promise<ContentCacheReport>reuploadTexturesAfterDeviceLoss: () => Promise<number>setAssetRefResolver: (resolver: AssetRefResolver) => voidsetManifest: (manifest: AddressableManifest | ManifestModel | null) => void@@ -1796,6 +1799,29 @@ sprite: number | undefined"hit"```+## CacheCleanupPreview — interface @experimental+```+budgetBytes: number+budgetMet: boolean | null+candidates: string[]+releaseBytes: number+remainingBytes: number | null+report: ContentCacheReport+```++## CacheCleanupResult — interface @experimental+```+budgetBytes: number+budgetMet: boolean | null+candidates: string[]+failed: string[]+indexPersisted: boolean | undefined+releaseBytes: number+remainingBytes: number | null+removed: string[]+report: ContentCacheReport+```+## Camera — const @beta```BuiltinComponentDef<CameraData>@@ -2508,6 +2534,29 @@ type: "compressor"'info' | 'warn' | 'error'```+## ContentCacheEntry — interface @experimental+```+hash: string | undefined+key: string | undefined+lastAccess: number+name: string+protection: string[]+size: number+versions: string[]+```++## ContentCacheReport — interface @experimental+```+capability: "managed" | "storage-only" | "unavailable"+entries: ContentCacheEntry[]+indexBytes: number | null+owner: string | undefined+protectedBytes: number | null+reclaimableBytes: number | null+usedBytes: number | null+versions: { owner: string; revision: string; reason: CacheProtection | null; missing: number; retained: boolean; }[]+```+## ControllerState — interface @experimental```current: string@@ -2784,6 +2833,9 @@ url: string| { t: 'query'; reqId: number; kind: 'screen'; maxSide?: number }| { t: 'query'; reqId: number; kind: 'stats' }| { t: 'query'; reqId: number; kind: 'updateStatus' }+ | { t: 'query'; reqId: number; kind: 'diskCache'; rescan?: boolean }+ | { t: 'query'; reqId: number; kind: 'cleanDiskCache'; budgetBytes: number; execute?: boolean }+ | { t: 'query'; reqId: number; kind: 'retainDiskCacheVersion'; revision: string; retain?: boolean }| { t: 'query'; reqId: number; kind: 'snapshot'; selectedId: number | null; withTree: boolean }| ({ t: 'query'; reqId: number; kind: 'control' } & DebugControl)```@@ -5842,6 +5894,7 @@ Pick<World, 'getCppRegistry' | 'getWasmModule'>## PlatformAdapter — interface @experimental```bindInputEvents: (callbacks: InputEventCallbacks, target?: unknown) => void+canManageCache: (() => boolean) | undefinedcanPay: (() => boolean) | undefinedcanSignIn: (() => boolean) | undefinedcheckSession: (() => Promise<boolean>) | undefined@@ -5861,9 +5914,11 @@ family: "minigame" | undefinedfetch: (url: string, options?: PlatformRequestOptions) => Promise<PlatformResponse>fileExists: (path: string) => Promise<boolean>getStorageItem: (key: string) => string | null+hasCacheStorage: (() => boolean) | undefinedhasTouch: (() => boolean) | undefinedinstantiateWasm: (pathOrBuffer: string | ArrayBuffer, imports: WebAssembly.Imports) => Promise<WasmInstantiateResult>language: (() => string) | undefined+listCacheFiles: (() => Promise<{ name: string; size: number; lastAccess: number; }[]>) | undefinedloadImagePixels: (path: string) => Promise<ImageLoadResult>loadSubpackage: ((name: string) => Promise<void>) | undefinedlogin: (() => Promise<string>) | undefined@@ -5884,6 +5939,7 @@ readCacheFile: ((key: string) => Promise<ArrayBuffer | null>) | undefinedreadFile: (path: string) => Promise<ArrayBuffer>readTextFile: (path: string) => Promise<string>registerFont: ((family: string, bytes: ArrayBuffer) => Promise<void>) | undefined+removeCacheFile: ((name: string) => Promise<void>) | undefinedremoveStorageItem: (key: string) => voidrequestPayment: ((request: PlatformPaymentRequest) => Promise<void>) | undefinedsafeAreaInsets: (() => { top: number; bottom: number; left: number; right: number; }) | undefineddiff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex 1f4943165..30da789a9 100644--- a/sdk/etc/index.native.api.md+++ b/sdk/etc/index.native.api.md@@ -1,7 +1,7 @@# API surface — esengine/index.native<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 115 public · 96 beta · 1574 experimental · 3 deprecated+Symbols: 115 public · 96 beta · 1578 experimental · 3 deprecated## ABI_LAYOUT_HASH — const @experimental```@@ -989,6 +989,8 @@ backend: BackendbaseUrl: string | undefinedcatalog: CatalogcheckForUpdate: (options: CheckForUpdateOptions) => Promise<UpdatePlan>+cleanDiskCache: (budgetBytes: number, execute?: boolean) => Promise<CacheCleanupResult>+diskCacheReport: (rescan?: boolean) => Promise<ContentCacheReport>fetchBinary: (ref: string) => Promise<ArrayBuffer>fetchJson: <T = unknown>(ref: string) => Promise<T>fetchText: (ref: string) => Promise<string>@@ -1045,6 +1047,7 @@ resolveLoadPath: (ref: string) => stringresolveRef: (ref: string) => string | nullresolveSceneAssetPaths: (sceneData: SceneData, result: SceneAssetResult) => voidrestorePersistedUpdate: (key: string) => boolean+retainDiskCacheVersion: (revision: string, retain?: boolean) => Promise<ContentCacheReport>reuploadTexturesAfterDeviceLoss: () => Promise<number>setAssetRefResolver: (resolver: AssetRefResolver) => voidsetManifest: (manifest: AddressableManifest | ManifestModel | null) => void@@ -1796,6 +1799,29 @@ sprite: number | undefined"hit"```+## CacheCleanupPreview — interface @experimental+```+budgetBytes: number+budgetMet: boolean | null+candidates: string[]+releaseBytes: number+remainingBytes: number | null+report: ContentCacheReport+```++## CacheCleanupResult — interface @experimental+```+budgetBytes: number+budgetMet: boolean | null+candidates: string[]+failed: string[]+indexPersisted: boolean | undefined+releaseBytes: number+remainingBytes: number | null+removed: string[]+report: ContentCacheReport+```+## Camera — const @beta```BuiltinComponentDef<CameraData>@@ -2516,6 +2542,29 @@ type: "compressor"'info' | 'warn' | 'error'```+## ContentCacheEntry — interface @experimental+```+hash: string | undefined+key: string | undefined+lastAccess: number+name: string+protection: string[]+size: number+versions: string[]+```++## ContentCacheReport — interface @experimental+```+capability: "managed" | "storage-only" | "unavailable"+entries: ContentCacheEntry[]+indexBytes: number | null+owner: string | undefined+protectedBytes: number | null+reclaimableBytes: number | null+usedBytes: number | null+versions: { owner: string; revision: string; reason: CacheProtection | null; missing: number; retained: boolean; }[]+```+## ControllerState — interface @experimental```current: string@@ -2792,6 +2841,9 @@ url: string| { t: 'query'; reqId: number; kind: 'screen'; maxSide?: number }| { t: 'query'; reqId: number; kind: 'stats' }| { t: 'query'; reqId: number; kind: 'updateStatus' }+ | { t: 'query'; reqId: number; kind: 'diskCache'; rescan?: boolean }+ | { t: 'query'; reqId: number; kind: 'cleanDiskCache'; budgetBytes: number; execute?: boolean }+ | { t: 'query'; reqId: number; kind: 'retainDiskCacheVersion'; revision: string; retain?: boolean }| { t: 'query'; reqId: number; kind: 'snapshot'; selectedId: number | null; withTree: boolean }| ({ t: 'query'; reqId: number; kind: 'control' } & DebugControl)```@@ -5473,6 +5525,7 @@ devicePixelRatio: () => numberfetch: (url: string, options?: PlatformRequestOptions) => Promise<PlatformResponse>fileExists: (path: string) => Promise<boolean>getStorageItem: (key: string) => string | null+hasCacheStorage: () => booleaninstantiateWasm: (pathOrBuffer: string | ArrayBuffer, imports: WebAssembly.Imports) => Promise<WasmInstantiateResult>language: () => stringloadImagePixels: (path: string) => Promise<ImageLoadResult>@@ -6036,6 +6089,7 @@ Pick<World, 'getCppRegistry' | 'getWasmModule'>## PlatformAdapter — interface @experimental```bindInputEvents: (callbacks: InputEventCallbacks, target?: unknown) => void+canManageCache: (() => boolean) | undefinedcanPay: (() => boolean) | undefinedcanSignIn: (() => boolean) | undefinedcheckSession: (() => Promise<boolean>) | undefined@@ -6055,9 +6109,11 @@ family: "minigame" | undefinedfetch: (url: string, options?: PlatformRequestOptions) => Promise<PlatformResponse>fileExists: (path: string) => Promise<boolean>getStorageItem: (key: string) => string | null+hasCacheStorage: (() => boolean) | undefinedhasTouch: (() => boolean) | undefinedinstantiateWasm: (pathOrBuffer: string | ArrayBuffer, imports: WebAssembly.Imports) => Promise<WasmInstantiateResult>language: (() => string) | undefined+listCacheFiles: (() => Promise<{ name: string; size: number; lastAccess: number; }[]>) | undefinedloadImagePixels: (path: string) => Promise<ImageLoadResult>loadSubpackage: ((name: string) => Promise<void>) | undefinedlogin: (() => Promise<string>) | undefined@@ -6078,6 +6134,7 @@ readCacheFile: ((key: string) => Promise<ArrayBuffer | null>) | undefinedreadFile: (path: string) => Promise<ArrayBuffer>readTextFile: (path: string) => Promise<string>registerFont: ((family: string, bytes: ArrayBuffer) => Promise<void>) | undefined+removeCacheFile: ((name: string) => Promise<void>) | undefinedremoveStorageItem: (key: string) => voidrequestPayment: ((request: PlatformPaymentRequest) => Promise<void>) | undefinedsafeAreaInsets: (() => { top: number; bottom: number; left: number; right: number; }) | undefineddiff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex e3872f10e..833979894 100644--- a/sdk/etc/index.node.api.md+++ b/sdk/etc/index.node.api.md@@ -1,7 +1,7 @@# API surface — esengine/index.node<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 115 public · 93 beta · 1554 experimental · 3 deprecated+Symbols: 115 public · 93 beta · 1558 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -984,6 +984,8 @@ backend: BackendbaseUrl: string | undefinedcatalog: CatalogcheckForUpdate: (options: CheckForUpdateOptions) => Promise<UpdatePlan>+cleanDiskCache: (budgetBytes: number, execute?: boolean) => Promise<CacheCleanupResult>+diskCacheReport: (rescan?: boolean) => Promise<ContentCacheReport>fetchBinary: (ref: string) => Promise<ArrayBuffer>fetchJson: <T = unknown>(ref: string) => Promise<T>fetchText: (ref: string) => Promise<string>@@ -1040,6 +1042,7 @@ resolveLoadPath: (ref: string) => stringresolveRef: (ref: string) => string | nullresolveSceneAssetPaths: (sceneData: SceneData, result: SceneAssetResult) => voidrestorePersistedUpdate: (key: string) => boolean+retainDiskCacheVersion: (revision: string, retain?: boolean) => Promise<ContentCacheReport>reuploadTexturesAfterDeviceLoss: () => Promise<number>setAssetRefResolver: (resolver: AssetRefResolver) => voidsetManifest: (manifest: AddressableManifest | ManifestModel | null) => void@@ -1791,6 +1794,29 @@ sprite: number | undefined"hit"```+## CacheCleanupPreview — interface @experimental+```+budgetBytes: number+budgetMet: boolean | null+candidates: string[]+releaseBytes: number+remainingBytes: number | null+report: ContentCacheReport+```++## CacheCleanupResult — interface @experimental+```+budgetBytes: number+budgetMet: boolean | null+candidates: string[]+failed: string[]+indexPersisted: boolean | undefined+releaseBytes: number+remainingBytes: number | null+removed: string[]+report: ContentCacheReport+```+## Camera — const @beta```BuiltinComponentDef<CameraData>@@ -2503,6 +2529,29 @@ type: "compressor"'info' | 'warn' | 'error'```+## ContentCacheEntry — interface @experimental+```+hash: string | undefined+key: string | undefined+lastAccess: number+name: string+protection: string[]+size: number+versions: string[]+```++## ContentCacheReport — interface @experimental+```+capability: "managed" | "storage-only" | "unavailable"+entries: ContentCacheEntry[]+indexBytes: number | null+owner: string | undefined+protectedBytes: number | null+reclaimableBytes: number | null+usedBytes: number | null+versions: { owner: string; revision: string; reason: CacheProtection | null; missing: number; retained: boolean; }[]+```+## ControllerState — interface @experimental```current: string@@ -2779,6 +2828,9 @@ url: string| { t: 'query'; reqId: number; kind: 'screen'; maxSide?: number }| { t: 'query'; reqId: number; kind: 'stats' }| { t: 'query'; reqId: number; kind: 'updateStatus' }+ | { t: 'query'; reqId: number; kind: 'diskCache'; rescan?: boolean }+ | { t: 'query'; reqId: number; kind: 'cleanDiskCache'; budgetBytes: number; execute?: boolean }+ | { t: 'query'; reqId: number; kind: 'retainDiskCacheVersion'; revision: string; retain?: boolean }| { t: 'query'; reqId: number; kind: 'snapshot'; selectedId: number | null; withTree: boolean }| ({ t: 'query'; reqId: number; kind: 'control' } & DebugControl)```@@ -5837,6 +5889,7 @@ Pick<World, 'getCppRegistry' | 'getWasmModule'>## PlatformAdapter — interface @experimental```bindInputEvents: (callbacks: InputEventCallbacks, target?: unknown) => void+canManageCache: (() => boolean) | undefinedcanPay: (() => boolean) | undefinedcanSignIn: (() => boolean) | undefinedcheckSession: (() => Promise<boolean>) | undefined@@ -5856,9 +5909,11 @@ family: "minigame" | undefinedfetch: (url: string, options?: PlatformRequestOptions) => Promise<PlatformResponse>fileExists: (path: string) => Promise<boolean>getStorageItem: (key: string) => string | null+hasCacheStorage: (() => boolean) | undefinedhasTouch: (() => boolean) | undefinedinstantiateWasm: (pathOrBuffer: string | ArrayBuffer, imports: WebAssembly.Imports) => Promise<WasmInstantiateResult>language: (() => string) | undefined+listCacheFiles: (() => Promise<{ name: string; size: number; lastAccess: number; }[]>) | undefinedloadImagePixels: (path: string) => Promise<ImageLoadResult>loadSubpackage: ((name: string) => Promise<void>) | undefinedlogin: (() => Promise<string>) | undefined@@ -5879,6 +5934,7 @@ readCacheFile: ((key: string) => Promise<ArrayBuffer | null>) | undefinedreadFile: (path: string) => Promise<ArrayBuffer>readTextFile: (path: string) => Promise<string>registerFont: ((family: string, bytes: ArrayBuffer) => Promise<void>) | undefined+removeCacheFile: ((name: string) => Promise<void>) | undefinedremoveStorageItem: (key: string) => voidrequestPayment: ((request: PlatformPaymentRequest) => Promise<void>) | undefinedsafeAreaInsets: (() => { top: number; bottom: number; left: number; right: number; }) | undefineddiff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex a593086a4..5de77c1f5 100644--- a/sdk/etc/minigame.api.md+++ b/sdk/etc/minigame.api.md@@ -1,7 +1,7 @@# API surface — esengine/minigame<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 115 public · 91 beta · 1576 experimental · 3 deprecated+Symbols: 115 public · 91 beta · 1580 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -984,6 +984,8 @@ backend: BackendbaseUrl: string | undefinedcatalog: CatalogcheckForUpdate: (options: CheckForUpdateOptions) => Promise<UpdatePlan>+cleanDiskCache: (budgetBytes: number, execute?: boolean) => Promise<CacheCleanupResult>+diskCacheReport: (rescan?: boolean) => Promise<ContentCacheReport>fetchBinary: (ref: string) => Promise<ArrayBuffer>fetchJson: <T = unknown>(ref: string) => Promise<T>fetchText: (ref: string) => Promise<string>@@ -1040,6 +1042,7 @@ resolveLoadPath: (ref: string) => stringresolveRef: (ref: string) => string | nullresolveSceneAssetPaths: (sceneData: SceneData, result: SceneAssetResult) => voidrestorePersistedUpdate: (key: string) => boolean+retainDiskCacheVersion: (revision: string, retain?: boolean) => Promise<ContentCacheReport>reuploadTexturesAfterDeviceLoss: () => Promise<number>setAssetRefResolver: (resolver: AssetRefResolver) => voidsetManifest: (manifest: AddressableManifest | ManifestModel | null) => void@@ -1791,6 +1794,29 @@ sprite: number | undefined"hit"```+## CacheCleanupPreview — interface @experimental+```+budgetBytes: number+budgetMet: boolean | null+candidates: string[]+releaseBytes: number+remainingBytes: number | null+report: ContentCacheReport+```++## CacheCleanupResult — interface @experimental+```+budgetBytes: number+budgetMet: boolean | null+candidates: string[]+failed: string[]+indexPersisted: boolean | undefined+releaseBytes: number+remainingBytes: number | null+removed: string[]+report: ContentCacheReport+```+## Camera — const @beta```BuiltinComponentDef<CameraData>@@ -2503,6 +2529,29 @@ type: "compressor"'info' | 'warn' | 'error'```+## ContentCacheEntry — interface @experimental+```+hash: string | undefined+key: string | undefined+lastAccess: number+name: string+protection: string[]+size: number+versions: string[]+```++## ContentCacheReport — interface @experimental+```+capability: "managed" | "storage-only" | "unavailable"+entries: ContentCacheEntry[]+indexBytes: number | null+owner: string | undefined+protectedBytes: number | null+reclaimableBytes: number | null+usedBytes: number | null+versions: { owner: string; revision: string; reason: CacheProtection | null; missing: number; retained: boolean; }[]+```+## ControllerState — interface @experimental```current: string@@ -2779,6 +2828,9 @@ url: string| { t: 'query'; reqId: number; kind: 'screen'; maxSide?: number }| { t: 'query'; reqId: number; kind: 'stats' }| { t: 'query'; reqId: number; kind: 'updateStatus' }+ | { t: 'query'; reqId: number; kind: 'diskCache'; rescan?: boolean }+ | { t: 'query'; reqId: number; kind: 'cleanDiskCache'; budgetBytes: number; execute?: boolean }+ | { t: 'query'; reqId: number; kind: 'retainDiskCacheVersion'; revision: string; retain?: boolean }| { t: 'query'; reqId: number; kind: 'snapshot'; selectedId: number | null; withTree: boolean }| ({ t: 'query'; reqId: number; kind: 'control' } & DebugControl)```@@ -5207,6 +5259,10 @@ access: (opts: { path: string; success?: () => void; fail?: (err: { errMsg: striaccessSync: (path: string) => voidreadFile: (opts: { filePath: string; encoding?: string; success?: (res: { data: ArrayBuffer | string; }) => void; fail?: (err: { errMsg: string; }) => void; }) => voidreadFileSync: (path: string, encoding?: string) => ArrayBuffer | string+readdir: ((opts: { dirPath: string; success?: (res: { files: string[]; }) => void; fail?: (err: { errMsg: string; }) => void; }) => void) | undefined+rename: ((opts: { oldPath: string; newPath: string; success?: () => void; fail?: (err: { errMsg: string; }) => void; }) => void) | undefined+stat: ((opts: { path: string; recursive?: boolean; success?: (res: { stats: { size: number; lastAccessedTime: number; isFile(): boolean; }; }) => void; fail?: (err: { errMsg: string; }) => void; }) => void) | undefined+unlink: ((opts: { filePath: string; success?: () => void; fail?: (err: { errMsg: string; }) => void; }) => void) | undefinedwriteFile: (opts: { filePath: string; data: string | ArrayBuffer; encoding?: string; success?: () => void; fail?: (err: { errMsg: string; }) => void; }) => void```@@ -5302,6 +5358,7 @@ code: string```@internal host: MiniGameGlobalbindInputEvents: (callbacks: InputEventCallbacks, _target?: unknown) => void+canManageCache: () => booleancanPay: () => booleancanSignIn: () => booleancheckSession: () => Promise<boolean>@@ -5321,8 +5378,10 @@ family: "minigame"fetch: (url: string, options?: PlatformRequestOptions) => Promise<PlatformResponse>fileExists: (path: string) => Promise<boolean>getStorageItem: (key: string) => string | null+hasCacheStorage: () => booleaninstantiateWasm: (pathOrBuffer: string | ArrayBuffer, imports: WebAssembly.Imports) => Promise<WasmInstantiateResult>language: () => string+listCacheFiles: () => Promise<{ name: string; size: number; lastAccess: number; }[]>loadImagePixels: (path: string) => Promise<ImageLoadResult>loadSubpackage: (name: string) => Promise<void>login: () => Promise<string>@@ -5338,6 +5397,7 @@ openDataPostMessage: (message: Record<string, unknown>) => voidreadCacheFile: (key: string) => Promise<ArrayBuffer | null>readFile: (path: string) => Promise<ArrayBuffer>readTextFile: (path: string) => Promise<string>+removeCacheFile: (name: string) => Promise<void>removeStorageItem: (key: string) => voidrequestPayment: (request: PlatformPaymentRequest) => Promise<void>screenRecorder: () => PlatformScreenRecorder | null@@ -6110,6 +6170,7 @@ Pick<World, 'getCppRegistry' | 'getWasmModule'>## PlatformAdapter — interface @experimental```bindInputEvents: (callbacks: InputEventCallbacks, target?: unknown) => void+canManageCache: (() => boolean) | undefinedcanPay: (() => boolean) | undefinedcanSignIn: (() => boolean) | undefinedcheckSession: (() => Promise<boolean>) | undefined@@ -6129,9 +6190,11 @@ family: "minigame" | undefinedfetch: (url: string, options?: PlatformRequestOptions) => Promise<PlatformResponse>fileExists: (path: string) => Promise<boolean>getStorageItem: (key: string) => string | null+hasCacheStorage: (() => boolean) | undefinedhasTouch: (() => boolean) | undefinedinstantiateWasm: (pathOrBuffer: string | ArrayBuffer, imports: WebAssembly.Imports) => Promise<WasmInstantiateResult>language: (() => string) | undefined+listCacheFiles: (() => Promise<{ name: string; size: number; lastAccess: number; }[]>) | undefinedloadImagePixels: (path: string) => Promise<ImageLoadResult>loadSubpackage: ((name: string) => Promise<void>) | undefinedlogin: (() => Promise<string>) | undefined@@ -6152,6 +6215,7 @@ readCacheFile: ((key: string) => Promise<ArrayBuffer | null>) | undefinedreadFile: (path: string) => Promise<ArrayBuffer>readTextFile: (path: string) => Promise<string>registerFont: ((family: string, bytes: ArrayBuffer) => Promise<void>) | undefined+removeCacheFile: ((name: string) => Promise<void>) | undefinedremoveStorageItem: (key: string) => voidrequestPayment: ((request: PlatformPaymentRequest) => Promise<void>) | undefinedsafeAreaInsets: (() => { top: number; bottom: number; left: number; right: number; }) | undefineddiff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex 3a5d1d5dc..5810684cd 100644--- a/sdk/etc/wechat.api.md+++ b/sdk/etc/wechat.api.md@@ -1,7 +1,7 @@# API surface — esengine/wechat<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 115 public · 91 beta · 1567 experimental · 3 deprecated+Symbols: 115 public · 91 beta · 1571 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -984,6 +984,8 @@ backend: BackendbaseUrl: string | undefinedcatalog: CatalogcheckForUpdate: (options: CheckForUpdateOptions) => Promise<UpdatePlan>+cleanDiskCache: (budgetBytes: number, execute?: boolean) => Promise<CacheCleanupResult>+diskCacheReport: (rescan?: boolean) => Promise<ContentCacheReport>fetchBinary: (ref: string) => Promise<ArrayBuffer>fetchJson: <T = unknown>(ref: string) => Promise<T>fetchText: (ref: string) => Promise<string>@@ -1040,6 +1042,7 @@ resolveLoadPath: (ref: string) => stringresolveRef: (ref: string) => string | nullresolveSceneAssetPaths: (sceneData: SceneData, result: SceneAssetResult) => voidrestorePersistedUpdate: (key: string) => boolean+retainDiskCacheVersion: (revision: string, retain?: boolean) => Promise<ContentCacheReport>reuploadTexturesAfterDeviceLoss: () => Promise<number>setAssetRefResolver: (resolver: AssetRefResolver) => voidsetManifest: (manifest: AddressableManifest | ManifestModel | null) => void@@ -1791,6 +1794,29 @@ sprite: number | undefined"hit"```+## CacheCleanupPreview — interface @experimental+```+budgetBytes: number+budgetMet: boolean | null+candidates: string[]+releaseBytes: number+remainingBytes: number | null+report: ContentCacheReport+```++## CacheCleanupResult — interface @experimental+```+budgetBytes: number+budgetMet: boolean | null+candidates: string[]+failed: string[]+indexPersisted: boolean | undefined+releaseBytes: number+remainingBytes: number | null+removed: string[]+report: ContentCacheReport+```+## Camera — const @beta```BuiltinComponentDef<CameraData>@@ -2503,6 +2529,29 @@ type: "compressor"'info' | 'warn' | 'error'```+## ContentCacheEntry — interface @experimental+```+hash: string | undefined+key: string | undefined+lastAccess: number+name: string+protection: string[]+size: number+versions: string[]+```++## ContentCacheReport — interface @experimental+```+capability: "managed" | "storage-only" | "unavailable"+entries: ContentCacheEntry[]+indexBytes: number | null+owner: string | undefined+protectedBytes: number | null+reclaimableBytes: number | null+usedBytes: number | null+versions: { owner: string; revision: string; reason: CacheProtection | null; missing: number; retained: boolean; }[]+```+## ControllerState — interface @experimental```current: string@@ -2779,6 +2828,9 @@ url: string| { t: 'query'; reqId: number; kind: 'screen'; maxSide?: number }| { t: 'query'; reqId: number; kind: 'stats' }| { t: 'query'; reqId: number; kind: 'updateStatus' }+ | { t: 'query'; reqId: number; kind: 'diskCache'; rescan?: boolean }+ | { t: 'query'; reqId: number; kind: 'cleanDiskCache'; budgetBytes: number; execute?: boolean }+ | { t: 'query'; reqId: number; kind: 'retainDiskCacheVersion'; revision: string; retain?: boolean }| { t: 'query'; reqId: number; kind: 'snapshot'; selectedId: number | null; withTree: boolean }| ({ t: 'query'; reqId: number; kind: 'control' } & DebugControl)```@@ -5844,6 +5896,7 @@ Pick<World, 'getCppRegistry' | 'getWasmModule'>## PlatformAdapter — interface @experimental```bindInputEvents: (callbacks: InputEventCallbacks, target?: unknown) => void+canManageCache: (() => boolean) | undefinedcanPay: (() => boolean) | undefinedcanSignIn: (() => boolean) | undefinedcheckSession: (() => Promise<boolean>) | undefined@@ -5863,9 +5916,11 @@ family: "minigame" | undefinedfetch: (url: string, options?: PlatformRequestOptions) => Promise<PlatformResponse>fileExists: (path: string) => Promise<boolean>getStorageItem: (key: string) => string | null+hasCacheStorage: (() => boolean) | undefinedhasTouch: (() => boolean) | undefinedinstantiateWasm: (pathOrBuffer: string | ArrayBuffer, imports: WebAssembly.Imports) => Promise<WasmInstantiateResult>language: (() => string) | undefined+listCacheFiles: (() => Promise<{ name: string; size: number; lastAccess: number; }[]>) | undefinedloadImagePixels: (path: string) => Promise<ImageLoadResult>loadSubpackage: ((name: string) => Promise<void>) | undefinedlogin: (() => Promise<string>) | undefined@@ -5886,6 +5941,7 @@ readCacheFile: ((key: string) => Promise<ArrayBuffer | null>) | undefinedreadFile: (path: string) => Promise<ArrayBuffer>readTextFile: (path: string) => Promise<string>registerFont: ((family: string, bytes: ArrayBuffer) => Promise<void>) | undefined+removeCacheFile: ((name: string) => Promise<void>) | undefinedremoveStorageItem: (key: string) => voidrequestPayment: ((request: PlatformPaymentRequest) => Promise<void>) | undefinedsafeAreaInsets: (() => { top: number; bottom: number; left: number; right: number; }) | undefineddiff --git a/sdk/src/asset/Assets.ts b/sdk/src/asset/Assets.tsindex 43df1a6ee..9b8e9034f 100644--- a/sdk/src/asset/Assets.ts+++ b/sdk/src/asset/Assets.ts@@ -6,6 +6,9 @@ import { Catalog, type AtlasFrameInfo } from './Catalog';import { ManifestModel, normalizeBundleMode, type AddressableManifest, type AddressableAssetType } from './AddressableManifest';import { diffManifests, type UpdatePlan, type AssetChange } from './hotUpdate';import { contentHashHex } from './contentHash';+import { encodeUtf8 } from '../util/utf8';+import { getPlatform, isPlatformInitialized } from '../platform/base';+import { contentCacheFor, type CacheVersion, type ContentCacheReport, type CacheCleanupResult } from '../platform/contentCache';import { platformLoadSubpackage, platformGetStorageItem, platformSetStorageItem, platformRemoveStorageItem, platformWriteCacheFile } from '../platform';import type {AssetLoader, LoadContext, TextureResult, SpineResult,@@ -411,6 +414,11 @@ export class Assets {private persistKey_: string | null = null;/** The revision this package shipped, read when persistence is armed at boot. */private shippedRevision_: string | null = null;+ private cacheOwner_: string | null = null;+ private cacheRollback_: CacheVersion | null = null;+ private cacheLaunch_: CacheVersion | null = null;+ private cacheLaunchRollback_: CacheVersion | null = null;+ private activeUpdate_: PendingUpdate | null = null;private getAudio_: () => import('../audio/Audio').AudioAPI | null;private getSpriteAnimation_: () => import('../animation/SpriteAnimator').SpriteAnimationAPI | null;private getLocalization_: () => import('../i18n/Localization').LocalizationAPI | null;@@ -1078,6 +1086,7 @@ export class Assets {const plan = diffManifests(this.manifestModel_, model);const remoteRoot = options.remoteRoot ?? this.remoteRoot_ ?? null;this.pendingUpdate_ = { model, manifestJson: json, remoteRoot };+ await this.protectCacheVersions_();return plan;}@@ -1093,7 +1102,10 @@ export class Assets {*/async applyUpdate(onProgress?: (loaded: number, total: number) => void): Promise<ApplyUpdateResult> {this.applying_++;- const run = this.applyChain_.then(() => this.applyStaged_(onProgress));+ const run = this.applyChain_.then(async () => {+ try { return await this.applyStaged_(onProgress); }+ finally { this.activeUpdate_ = null; }+ });this.applyChain_ = run.catch(() => {});try {return await run;@@ -1115,6 +1127,8 @@ export class Assets {// finished in between moved the base, and its assets need no second download.const changed = diffManifests(this.manifestModel_, pending.model).changedAssets;const root = pending.remoteRoot ?? undefined;+ this.activeUpdate_ = pending;+ await this.protectCacheVersions_();// Phase 1 — download + verify EVERY changed asset WITHOUT touching the// active manifest. Content-addressed, so these are brand-new urls (nothing@@ -1151,6 +1165,17 @@ export class Assets {const tex = this.getTexture(c.key) ?? this.getTexture(`${UUID_REF_PREFIX}${c.key}`);if (tex) oldHandles.set(c.key, tex.handle);}+ const rollback = this.cacheVersion_(this.manifestModel_, this.remoteRoot_, 'rollback');+ // Protect both sides durably BEFORE committing: a crash may still boot+ // the old persisted manifest until the new one has been stored.+ const previousRollback = this.cacheRollback_;+ this.cacheRollback_ = rollback;+ try {+ await this.protectCacheVersions_(this.cacheVersion_(pending.model, root, 'current'));+ } catch (err) {+ this.cacheRollback_ = previousRollback;+ throw err;+ }if (pending.remoteRoot != null) this.setRemoteRoot(pending.remoteRoot);this.setManifest(pending.model);// A newer check staged while this one downloaded stays staged.@@ -1181,6 +1206,13 @@ export class Assets {// an app that is not ticking would never reach from here.await this.assetGraphSettled();const persisted = this.persistActiveManifest_(pending.manifestJson);+ // Until storage accepts the new manifest, the previous next-launch+ // version AND its rollback must remain pinned across subsequent updates.+ if (persisted === true) {+ this.cacheLaunch_ = this.cacheVersion_(pending.model, root, 'retained');+ this.cacheLaunchRollback_ = rollback ? { ...rollback, reason: 'retained' } : null;+ }+ await this.protectCacheVersions_().catch(e => log.warn('asset', 'updated content is protected but its cache index could not be refreshed', e));if (persisted !== true) {log.warn('asset', persisted === false? 'applyUpdate: the update runs now, but was not stored — the next launch starts on the previous version'@@ -1207,6 +1239,61 @@ export class Assets {};}+ private cacheVersion_(model: ManifestModel | null, root: string | undefined, reason: CacheVersion['reason']): CacheVersion | null {+ if (!model) return null;+ const keys = model.entries().filter(e => normalizeBundleMode(model.group(e.group)?.bundleMode) === 'remote')+ .map(e => this.backend.resolveUrl(this.manifestAssetUrl_(e.asset.path, true, root)))+ // A remote group with no CDN root is shipped in the package. Its+ // files need no cache protection and are not missing offline bytes.+ .filter(key => /^https?:\/\//i.test(key));+ return { revision: model.revision() ?? contentHashHex(encodeUtf8(JSON.stringify(keys))), reason, keys };+ }++ private async protectCacheVersions_(current?: CacheVersion | null): Promise<void> {+ if (!isPlatformInitialized()) return;+ const cache = contentCacheFor(getPlatform());+ if (cache.capability() !== 'managed') return;+ this.cacheOwner_ ??= `assets:${this.persistKey_ ?? this.remoteRoot_ ?? 'package'}`;+ this.cacheLaunch_ ??= this.cacheVersion_(this.manifestModel_, this.remoteRoot_, 'retained');+ const versions = [current ?? this.cacheVersion_(this.manifestModel_, this.remoteRoot_, 'current'),+ this.cacheRollback_, this.cacheLaunch_, this.cacheLaunchRollback_];+ for (const update of [this.pendingUpdate_, this.activeUpdate_]) if (update) {+ versions.push(this.cacheVersion_(update.model, update.remoteRoot ?? undefined, 'pending'));+ }+ await cache.protect(this.cacheOwner_, versions.filter((v): v is CacheVersion => v !== null));+ }++ /** Disk cache statistics, distinct from texture/audio residency budgets.+ * A scan reconciles interrupted writes/deletes; unknown files stay pinned. */+ async diskCacheReport(rescan = false): Promise<ContentCacheReport> {+ if (!isPlatformInitialized()) return { capability: 'unavailable', usedBytes: null, indexBytes: null,+ protectedBytes: null, reclaimableBytes: null, entries: [], versions: [] };+ // Keep in-memory protection even at quota: requiring an index write+ // before showing/cleaning a full disk would make it impossible to free.+ await this.protectCacheVersions_().catch(e => log.warn('asset', 'cache protection is active but its index could not be stored', e));+ return { ...await contentCacheFor(getPlatform()).report(rescan), owner: this.cacheOwner_ ?? undefined };+ }++ /** Preview by default; execution recomputes LRU against current protections. */+ async cleanDiskCache(budgetBytes: number, execute = false): Promise<CacheCleanupResult> {+ if (!Number.isSafeInteger(budgetBytes) || budgetBytes < 0) throw Error('cache budget must be a non-negative safe integer');+ await this.diskCacheReport();+ if (!isPlatformInitialized()) return { report: await this.diskCacheReport(), budgetBytes,+ candidates: [], releaseBytes: 0, remainingBytes: null, budgetMet: null, removed: [], failed: [] };+ const result = await contentCacheFor(getPlatform()).cleanup(budgetBytes, execute);+ result.report.owner = this.cacheOwner_ ?? undefined;+ return result;+ }++ /** Keep an older downloaded build, independently of the rolling rollback. */+ async retainDiskCacheVersion(revision: string, retain = true): Promise<ContentCacheReport> {+ await this.diskCacheReport();+ if (!isPlatformInitialized() || !this.cacheOwner_) throw Error('cache management unavailable');+ const cache = contentCacheFor(getPlatform());+ await cache.retainVersion(this.cacheOwner_, revision, retain);+ return { ...await cache.report(), owner: this.cacheOwner_ };+ }+/** Download one changed asset's bytes from its delivery source (remote → CDN* url against `root`, else the normal resolved path) and verify the content* hash. Null on success, else the failure reason. Uses the PENDING manifest +@@ -1251,7 +1338,7 @@ export class Assets {const raw = platformGetStorageItem(key);if (!raw) return false;try {- const parsed = JSON.parse(raw) as { manifest: AddressableManifest; remoteRoot?: string | null; base?: string | null };+ const parsed = JSON.parse(raw) as { manifest: AddressableManifest; remoteRoot?: string | null; base?: string | null; cacheRollback?: CacheVersion | null };if (parsed.base === undefined || parsed.base !== this.shippedRevision_) {log.info('asset', `a stored update (${parsed.manifest?.revision ?? '?'}) was made for another package `+ `(${parsed.base ?? 'unknown'}, this one ships ${this.shippedRevision_ ?? 'none'}) — starting on what shipped`);@@ -1260,6 +1347,12 @@ export class Assets {}if (parsed.remoteRoot) this.setRemoteRoot(parsed.remoteRoot);this.setManifest(parsed.manifest);+ if (parsed.cacheRollback && typeof parsed.cacheRollback.revision === 'string'+ && Array.isArray(parsed.cacheRollback.keys) && parsed.cacheRollback.keys.every(k => typeof k === 'string')) {+ this.cacheRollback_ = { ...parsed.cacheRollback, reason: 'rollback' };+ this.cacheLaunchRollback_ = { ...this.cacheRollback_, reason: 'retained' };+ }+ void this.protectCacheVersions_().catch(e => log.warn('asset', 'cache protection could not be persisted', e));return true;} catch (e) {log.warn('asset', 'failed to restore persisted manifest', e);@@ -1271,7 +1364,7 @@ export class Assets {* Null with no persistence key. */private persistActiveManifest_(json: AddressableManifest): boolean | null {if (!this.persistKey_) return null;- const value = JSON.stringify({ manifest: json, remoteRoot: this.remoteRoot_ ?? null, base: this.shippedRevision_ });+ const value = JSON.stringify({ manifest: json, remoteRoot: this.remoteRoot_ ?? null, base: this.shippedRevision_, cacheRollback: this.cacheRollback_ });try {platformSetStorageItem(this.persistKey_, value);return platformGetStorageItem(this.persistKey_) === value;diff --git a/sdk/src/asset/index.ts b/sdk/src/asset/index.tsindex 258d54cd5..d3aaa8a19 100644--- a/sdk/src/asset/index.ts+++ b/sdk/src/asset/index.ts@@ -13,6 +13,7 @@ export {ManifestModel,} from './AddressableManifest';export { diffManifests, type UpdatePlan, type AssetChange } from './hotUpdate';+export type { ContentCacheReport, ContentCacheEntry, CacheCleanupPreview, CacheCleanupResult } from '../platform/contentCache';export {resolveAssetGroup,activeRemoteRoot,diff --git a/sdk/src/core-content.ts b/sdk/src/core-content.tsindex 09386ef97..21c3a9a8c 100644--- a/sdk/src/core-content.ts+++ b/sdk/src/core-content.ts@@ -109,6 +109,10 @@ export {type ApplyUpdateResult,type UpdateStages,type UpdateStatus,+ type ContentCacheReport,+ type ContentCacheEntry,+ type CacheCleanupPreview,+ type CacheCleanupResult,} from './asset';/** When the live bindings that READ the asset graph have caught up with it —diff --git a/sdk/src/platform/base.ts b/sdk/src/platform/base.tsindex d30dc3327..2dab556a0 100644--- a/sdk/src/platform/base.ts+++ b/sdk/src/platform/base.ts@@ -9,6 +9,7 @@ import type { PlatformAdapter } from './types';import type { PlatformAudioBackend } from '../audio/PlatformAudioBackend';import { NullAudioBackend } from '../audio/NullAudioBackend';import { log } from '../util/logger';+import { contentCacheFor } from './contentCache';let cacheWriteFailureReported = false;@@ -208,7 +209,7 @@ export async function platformReadCacheFile(key: string): Promise<ArrayBuffer |const p = getPlatform();if (!p.readCacheFile) return null;try {- return await p.readCacheFile(key);+ return await contentCacheFor(p).read(key);} catch {return null;}@@ -222,7 +223,7 @@ export async function platformWriteCacheFile(key: string, bytes: ArrayBuffer): Pconst p = getPlatform();if (!p.writeCacheFile) return 'unsupported';try {- await p.writeCacheFile(key, bytes);+ await contentCacheFor(p).write(key, bytes);return 'stored';} catch (err) {if (!cacheWriteFailureReported) {diff --git a/sdk/src/platform/contentCache.ts b/sdk/src/platform/contentCache.tsnew file mode 100644index 000000000..c60e61ad8--- /dev/null+++ b/sdk/src/platform/contentCache.ts@@ -0,0 +1,286 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import type { PlatformAdapter } from './types';+import { cacheEntryName } from './cacheEntryName';+import { contentHashHex } from '../asset/contentHash';+import { encodeUtf8, decodeUtf8 } from '../util/utf8';++const INDEX_KEY = 'estella:content-cache:index:v1';+const INDEX_NAME = cacheEntryName(INDEX_KEY);+export type CacheProtection = 'current' | 'pending' | 'rollback' | 'retained';+export interface CacheVersion {+ revision: string;+ reason: CacheProtection | null;+ keys: string[];+}+interface Entry {+ name: string;+ key?: string;+ hash?: string;+ size: number;+ lastAccess: number;+}+interface Index {+ schema: 1;+ entries: Entry[];+ owners: Record<string, CacheVersion[]>;+}+export interface ContentCacheEntry extends Entry {+ versions: string[];+ protection: string[];+}+export interface ContentCacheReport {+ /** The Assets service issuing this report, when supplied by that service. */+ owner?: string;+ capability: 'managed' | 'storage-only' | 'unavailable';+ /** Resource bytes only; index bytes are reported separately. Null is unknown. */+ usedBytes: number | null;+ indexBytes: number | null;+ protectedBytes: number | null;+ reclaimableBytes: number | null;+ entries: ContentCacheEntry[];+ versions: { owner: string; revision: string; reason: CacheProtection | null; missing: number; retained: boolean }[];+}+export interface CacheCleanupPreview {+ report: ContentCacheReport;+ budgetBytes: number;+ candidates: string[];+ releaseBytes: number;+ remainingBytes: number | null;+ budgetMet: boolean | null;+}+export interface CacheCleanupResult extends CacheCleanupPreview {+ removed: string[];+ failed: string[];+ /** Cleanup can free a full disk even when updating its index is refused.+ * The next scan reconciles those successful deletions. */+ indexPersisted?: boolean;+}++/** One coordinator per adapter: byte IO, index changes and eviction share a+ * queue. A cleaner cannot unlink a read/write in flight. Unknown legacy files+ * stay protected until a verified write establishes their resource identity. */+export class ContentCache {+ private chain_: Promise<unknown> = Promise.resolve();+ private index_: Index | null = null;+ private indexBytes_ = 0;+ constructor(private readonly platform_: PlatformAdapter) {}++ capability(): ContentCacheReport['capability'] {+ const p = this.platform_;+ if (!p.readCacheFile || !p.writeCacheFile || p.hasCacheStorage?.() === false) return 'unavailable';+ return p.listCacheFiles && p.removeCacheFile && p.canManageCache?.() !== false ? 'managed' : 'storage-only';+ }++ private run_<T>(fn: () => Promise<T>): Promise<T> {+ const result = this.chain_.then(fn);+ this.chain_ = result.catch(() => {});+ return result;+ }++ private async load_(): Promise<Index> {+ if (this.index_) return this.index_;+ const bytes = await this.platform_.readCacheFile!(INDEX_KEY);+ if (bytes) {+ try {+ const parsed = JSON.parse(decodeUtf8(new Uint8Array(bytes))) as Index;+ if (parsed.schema !== 1 || !Array.isArray(parsed.entries) || !parsed.owners+ || !parsed.entries.every(e => /^[0-9a-f]{16}(?:\.\d+\.tmp)?$/.test(e.name)+ && Number.isFinite(e.size) && e.size >= 0 && Number.isFinite(e.lastAccess)+ && (e.key === undefined || (typeof e.key === 'string' && cacheEntryName(e.key) === e.name)))+ || !Object.values(parsed.owners).every(v => Array.isArray(v) && v.every(x =>+ typeof x.revision === 'string' && Array.isArray(x.keys) && x.keys.every(k => typeof k === 'string')+ && [null, 'current', 'pending', 'rollback', 'retained'].includes(x.reason)))) throw Error('invalid index');+ this.index_ = parsed;+ this.indexBytes_ = bytes.byteLength;+ return parsed;+ } catch { /* Crash/corruption: rescan conservatively; never infer ownership. */ }+ }+ return this.index_ = { schema: 1, entries: [], owners: {} };+ }++ private async save_(): Promise<void> {+ const bytes = encodeUtf8(JSON.stringify(this.index_));+ await this.platform_.writeCacheFile!(INDEX_KEY, bytes.buffer as ArrayBuffer);+ this.indexBytes_ = bytes.byteLength;+ }++ async read(key: string): Promise<ArrayBuffer | null> {+ if (this.capability() !== 'managed') return this.platform_.readCacheFile!(key);+ return this.run_(async () => {+ const index = await this.load_();+ const bytes = await this.platform_.readCacheFile!(key);+ const entry = index.entries.find(e => e.name === cacheEntryName(key));+ if (bytes && entry) {+ entry.lastAccess = Date.now();+ // An access-time write failure must not prevent an offline read.+ await this.save_().catch(() => {});+ }+ return bytes;+ });+ }++ async write(key: string, bytes: ArrayBuffer): Promise<void> {+ if (this.capability() !== 'managed') return this.platform_.writeCacheFile!(key, bytes);+ return this.run_(async () => {+ const index = await this.load_();+ await this.platform_.writeCacheFile!(key, bytes);+ const entry: Entry = { name: cacheEntryName(key), key, hash: contentHashHex(new Uint8Array(bytes)),+ size: bytes.byteLength, lastAccess: Date.now() };+ index.entries = index.entries.filter(e => e.name !== entry.name);+ index.entries.push(entry);+ await this.save_();+ });+ }++ /** Replaces this application's protected versions, preserving historical+ * ownership and other applications sharing the directory. Persists before+ * an updater starts downloading or switches its active manifest. */+ async protect(owner: string, versions: CacheVersion[]): Promise<void> {+ if (this.capability() !== 'managed') return;+ const merged = new Map<string, CacheVersion>();+ const ranks = [null, 'retained', 'rollback', 'pending', 'current'];+ for (const version of versions) {+ const prev = merged.get(version.revision);+ merged.set(version.revision, { revision: version.revision,+ reason: prev && ranks.indexOf(prev.reason) > ranks.indexOf(version.reason) ? prev.reason : version.reason,+ keys: [...new Set([...(prev?.keys ?? []), ...version.keys])] });+ }+ const snapshot = [...merged.values()];+ return this.run_(async () => {+ const index = await this.load_();+ const previous = index.owners[owner] ?? [];+ index.owners[owner] = [...previous.filter(v => !snapshot.some(n => n.revision === v.revision))+ .map(v => ({ ...v, reason: null })), ...snapshot];+ await this.save_();+ });+ }++ private async scan_(): Promise<void> {+ const index = await this.load_();+ const files = await this.platform_.listCacheFiles!();+ const known = new Map(index.entries.map(e => [e.name, e]));+ index.entries = files.filter(f => f.name !== INDEX_NAME).map(f => ({ ...known.get(f.name), ...f,+ lastAccess: Math.max(known.get(f.name)?.lastAccess ?? 0, f.lastAccess) }));+ this.indexBytes_ = files.find(f => f.name === INDEX_NAME)?.size ?? 0;+ }++ /** Explicit retention lives under its own owner, so advancing the automatic+ * current/rollback pair cannot silently release a developer's retained build. */+ async retainVersion(owner: string, revision: string, retain = true): Promise<void> {+ if (this.capability() !== 'managed') throw Error('cache management unavailable');+ return this.run_(async () => {+ const index = await this.load_();+ const retainedOwner = `retained:${owner}`;+ const retained = index.owners[retainedOwner] ?? [];+ const version = index.owners[owner]?.find(v => v.revision === revision);+ if (!version) throw Error('unknown cache version');+ index.owners[retainedOwner] = retained.filter(v => v.revision !== revision);+ if (retain) index.owners[retainedOwner].push({ ...version, keys: [...version.keys], reason: 'retained' });+ await this.save_();+ });+ }++ private report_(): ContentCacheReport {+ const capability = this.capability();+ if (capability !== 'managed') return { capability, usedBytes: null, indexBytes: null,+ protectedBytes: null, reclaimableBytes: null, entries: [], versions: [] };+ const index = this.index_!;+ // Invert version references once. Looking up every URL for every file+ // makes a modest cache report block the editor for seconds (E × R).+ const names = new Set(index.entries.map(e => e.name));+ const ownership = new Map<string, { versions: Set<string>; protection: Set<string> }>();+ const versionReports: ContentCacheReport['versions'] = [];+ for (const [owner, refs] of Object.entries(index.owners)) {+ const retainedVersions = new Set(index.owners[`retained:${owner}`]?.map(v => v.revision) ?? []);+ for (const version of refs) {+ let missing = 0;+ for (const key of version.keys) {+ const name = cacheEntryName(key);+ if (!names.has(name)) missing++;+ let refsForFile = ownership.get(name);+ if (!refsForFile) {+ refsForFile = { versions: new Set(), protection: new Set() };+ ownership.set(name, refsForFile);+ }+ refsForFile.versions.add(version.revision);+ if (version.reason) refsForFile.protection.add(`${owner}:${version.reason}`);+ }+ if (!owner.startsWith('retained:')) {+ const retained = retainedVersions.has(version.revision);+ versionReports.push({ owner, revision: version.revision,+ reason: version.reason ?? (retained ? 'retained' : null), retained, missing });+ }+ }+ }+ const entries = index.entries.map(e => {+ const refs = ownership.get(e.name);+ return { ...e, versions: [...(refs?.versions ?? [])],+ protection: [...(e.key ? [] : ['unindexed']), ...(refs?.protection ?? [])] };+ });+ const usedBytes = entries.reduce((n, e) => n + e.size, 0);+ const protectedBytes = entries.reduce((n, e) => n + (e.protection.length ? e.size : 0), 0);+ return { capability, usedBytes, indexBytes: this.indexBytes_, protectedBytes,+ reclaimableBytes: usedBytes - protectedBytes, entries,+ versions: versionReports };+ }++ async report(rescan = false): Promise<ContentCacheReport> {+ if (this.capability() !== 'managed') return this.report_();+ return this.run_(async () => {+ await this.scan_();+ if (rescan) await this.save_();+ return this.report_();+ });+ }++ private preview_(budgetBytes: number): CacheCleanupPreview {+ const report = this.report_();+ let remainingBytes = report.usedBytes;+ const candidates: string[] = [];+ let releaseBytes = 0;+ if (remainingBytes !== null) for (const e of [...report.entries]+ .filter(e => e.protection.length === 0).sort((a, b) => a.lastAccess - b.lastAccess || a.name.localeCompare(b.name))) {+ if (remainingBytes <= budgetBytes) break;+ candidates.push(e.name);+ releaseBytes += e.size;+ remainingBytes -= e.size;+ }+ return { report, budgetBytes, candidates, releaseBytes, remainingBytes,+ budgetMet: remainingBytes === null ? null : remainingBytes <= budgetBytes };+ }++ /** Re-evaluates protection at execution; never trusts a stale UI preview.+ * Serial deletion yields every batch and reports only successful unlinks. */+ async cleanup(budgetBytes: number, execute = false): Promise<CacheCleanupResult> {+ if (!Number.isSafeInteger(budgetBytes) || budgetBytes < 0) throw Error('cache budget must be a non-negative safe integer');+ return this.run_(async () => {+ if (this.capability() === 'managed') await this.scan_();+ const preview = this.preview_(budgetBytes);+ const removed: string[] = [], failed: string[] = [];+ if (!execute || preview.report.capability !== 'managed') return { ...preview, removed, failed };+ let released = 0;+ for (const name of preview.candidates) {+ try {+ await this.platform_.removeCacheFile!(name);+ released += this.index_!.entries.find(e => e.name === name)!.size;+ this.index_!.entries = this.index_!.entries.filter(e => e.name !== name);+ removed.push(name);+ } catch { failed.push(name); }+ if ((removed.length + failed.length) % 16 === 0) await new Promise(r => setTimeout(r, 0));+ }+ // If interrupted, a later scan reconciles the on-disk truth.+ const indexPersisted = await this.save_().then(() => true, () => false);+ const report = this.report_();+ return { ...preview, report, releaseBytes: released, remainingBytes: report.usedBytes,+ budgetMet: report.usedBytes! <= budgetBytes, removed, failed, indexPersisted };+ });+ }+}++const caches = new WeakMap<PlatformAdapter, ContentCache>();+export function contentCacheFor(platform: PlatformAdapter): ContentCache {+ let cache = caches.get(platform);+ if (!cache) { cache = new ContentCache(platform); caches.set(platform, cache); }+ return cache;+}diff --git a/sdk/src/platform/minigame/adapter.ts b/sdk/src/platform/minigame/adapter.tsindex 0b7a1abb3..0a429b9a8 100644--- a/sdk/src/platform/minigame/adapter.ts+++ b/sdk/src/platform/minigame/adapter.ts@@ -60,6 +60,7 @@ export class MiniGamePlatformAdapter implements PlatformAdapter {private openDataCtx_: MiniGameOpenDataContext | null = null;private openDataResolved_ = false;private recorder_: PlatformScreenRecorder | null | undefined;+ private cacheWriteId_ = 0;constructor(profile: MiniGameProfile) {this.profile_ = profile;@@ -111,14 +112,57 @@ export class MiniGamePlatformAdapter implements PlatformAdapter {}}- writeCacheFile(key: string, bytes: ArrayBuffer): Promise<void> {+ async writeCacheFile(key: string, bytes: ArrayBuffer): Promise<void> {const dir = this.g_.env?.USER_DATA_PATH;- if (!dir) return Promise.reject(new Error(`${this.profile_.hostLabel} names no user data directory`));- return new Promise((resolve, reject) => this.fs().writeFile({- filePath: `${dir}/${cacheEntryName(key)}`, data: bytes,+ if (!dir) throw new Error(`${this.profile_.hostLabel} names no user data directory`);+ const file = `${dir}/${cacheEntryName(key)}`;+ const fs = this.fs();+ const temp = fs.rename ? `${file}.${++this.cacheWriteId_}.tmp` : file;+ await new Promise<void>((resolve, reject) => fs.writeFile({+ filePath: temp, data: bytes,success: () => resolve(),fail: (err) => reject(new Error(err.errMsg)),}));+ if (fs.rename) {+ try {+ await new Promise<void>((resolve, reject) => fs.rename!({ oldPath: temp, newPath: file,+ success: resolve, fail: err => reject(new Error(err.errMsg)) }));+ } catch (err) {+ fs.unlink?.({ filePath: temp });+ throw err;+ }+ }+ }++ canManageCache(): boolean {+ const fs = this.fs();+ return Boolean(this.g_.env?.USER_DATA_PATH && fs.readdir && fs.stat && fs.unlink && fs.rename);+ }++ hasCacheStorage(): boolean { return Boolean(this.g_.env?.USER_DATA_PATH); }++ async listCacheFiles(): Promise<{ name: string; size: number; lastAccess: number }[]> {+ if (!this.canManageCache()) throw Error('cache management unavailable');+ const fs = this.fs();+ const dir = this.g_.env!.USER_DATA_PATH!;+ const names = await new Promise<string[]>((resolve, reject) => fs.readdir!({ dirPath: dir,+ success: r => resolve(r.files), fail: e => reject(new Error(e.errMsg)) }));+ const result: { name: string; size: number; lastAccess: number }[] = [];+ for (const name of names.filter(n => /^[0-9a-f]{16}(?:\.\d+\.tmp)?$/.test(n))) {+ const stats = await new Promise<{ size: number; lastAccessedTime: number; isFile(): boolean }>((resolve, reject) =>+ fs.stat!({ path: `${dir}/${name}`, recursive: false,+ success: r => resolve(r.stats), fail: e => reject(new Error(e.errMsg)) }));+ if (stats.isFile()) result.push({ name, size: stats.size, lastAccess: stats.lastAccessedTime * 1000 });+ }+ return result;+ }++ async removeCacheFile(name: string): Promise<void> {+ if (!this.canManageCache() || !/^[0-9a-f]{16}$/.test(name)) throw Error('invalid cache entry or unsupported host');+ await new Promise<void>((resolve, reject) => this.fs().unlink!({+ filePath: `${this.g_.env!.USER_DATA_PATH}/${name}`, success: resolve,+ fail: e => reject(new Error(e.errMsg)),+ }));}async loadImagePixels(path: string): Promise<ImageLoadResult> {diff --git a/sdk/src/platform/minigame/api.ts b/sdk/src/platform/minigame/api.tsindex 9084901a5..9b836a33d 100644--- a/sdk/src/platform/minigame/api.ts+++ b/sdk/src/platform/minigame/api.ts@@ -41,6 +41,10 @@ export interface MiniGameImage {}export interface MiniGameFileSystemManager {+ readdir?(opts: { dirPath: string; success?: (res: { files: string[] }) => void; fail?: (err: { errMsg: string }) => void }): void;+ stat?(opts: { path: string; recursive?: boolean; success?: (res: { stats: { size: number; lastAccessedTime: number; isFile(): boolean } }) => void; fail?: (err: { errMsg: string }) => void }): void;+ unlink?(opts: { filePath: string; success?: () => void; fail?: (err: { errMsg: string }) => void }): void;+ rename?(opts: { oldPath: string; newPath: string; success?: () => void; fail?: (err: { errMsg: string }) => void }): void;readFileSync(path: string, encoding?: string): ArrayBuffer | string;readFile(opts: {filePath: string;diff --git a/sdk/src/platform/native/adapter.ts b/sdk/src/platform/native/adapter.tsindex e9c123473..dd22ec952 100644--- a/sdk/src/platform/native/adapter.ts+++ b/sdk/src/platform/native/adapter.ts@@ -229,6 +229,8 @@ export class NativePlatformAdapter implements PlatformAdapter {return this.bridge_.readCacheFile ? this.bridge_.readCacheFile(key) : null;}+ hasCacheStorage(): boolean { return Boolean(this.bridge_.readCacheFile && this.bridge_.writeCacheFile); }+async writeCacheFile(key: string, bytes: ArrayBuffer): Promise<void> {if (this.bridge_.writeCacheFile) await this.bridge_.writeCacheFile(key, bytes);}diff --git a/sdk/src/platform/node.ts b/sdk/src/platform/node.tsindex 5b6450ccb..887924953 100644--- a/sdk/src/platform/node.ts+++ b/sdk/src/platform/node.ts@@ -11,7 +11,7 @@** @beta Pre-1.0: the node/headless host is young; the adapter surface may change.*/-import { readFile as fsReadFile, access, mkdir, writeFile, rename } from 'node:fs/promises';+import { readFile as fsReadFile, access, mkdir, writeFile, rename, readdir, stat, unlink } from 'node:fs/promises';import { join } from 'node:path';import { tmpdir } from 'node:os';import type {@@ -189,6 +189,23 @@ class NodePlatformAdapter implements PlatformAdapter {await writeFile(tmp, new Uint8Array(bytes));await rename(tmp, file);}++ canManageCache(): boolean { return true; }++ async listCacheFiles(): Promise<{ name: string; size: number; lastAccess: number }[]> {+ await mkdir(this.cacheDir_(), { recursive: true });+ const entries = await readdir(this.cacheDir_(), { withFileTypes: true });+ const files = entries.filter(e => e.isFile() && /^[0-9a-f]{16}(?:\.\d+\.tmp)?$/.test(e.name));+ return Promise.all(files.map(async e => {+ const s = await stat(join(this.cacheDir_(), e.name));+ return { name: e.name, size: s.size, lastAccess: s.atimeMs };+ }));+ }++ async removeCacheFile(name: string): Promise<void> {+ if (!/^[0-9a-f]{16}$/.test(name)) throw Error('invalid cache entry');+ await unlink(join(this.cacheDir_(), name));+ }}export const nodeAdapter = new NodePlatformAdapter();diff --git a/sdk/src/platform/types.ts b/sdk/src/platform/types.tsindex e040ca0db..a800be003 100644--- a/sdk/src/platform/types.ts+++ b/sdk/src/platform/types.ts@@ -519,6 +519,12 @@ export interface PlatformAdapter {*/readCacheFile?(key: string): Promise<ArrayBuffer | null>;writeCacheFile?(key: string, bytes: ArrayBuffer): Promise<void>;+ /** Cache management is separate from byte storage. Entries are opaque safe+ * names, never arbitrary paths; hosts must exclude application saves. */+ canManageCache?(): boolean;+ hasCacheStorage?(): boolean;+ listCacheFiles?(): Promise<{ name: string; size: number; lastAccess: number }[]>;+ removeCacheFile?(name: string): Promise<void>;/** Open a socket connection. Web → WebSocket, WeChat → wx.connectSocket,* Node → a ws wrapper. Optional — platforms without networking (playablediff --git a/sdk/src/runtime/debugChannel.ts b/sdk/src/runtime/debugChannel.tsindex ee4db70e2..194e5a196 100644--- a/sdk/src/runtime/debugChannel.ts+++ b/sdk/src/runtime/debugChannel.ts@@ -200,6 +200,15 @@ export function startDebugChannel(config: DebugChannelConfig): void {reply({ t: 'reply', reqId: q.reqId, data: game.hasResource(Assets) ? game.getResource(Assets).updateStatus() : null });return;}+ if (q.kind === 'diskCache' || q.kind === 'cleanDiskCache' || q.kind === 'retainDiskCacheVersion') {+ if (!game.hasResource(Assets)) throw Error('this game has no asset service');+ const assets = game.getResource(Assets);+ const data = q.kind === 'diskCache' ? await assets.diskCacheReport(q.rescan === true)+ : q.kind === 'retainDiskCacheVersion' ? await assets.retainDiskCacheVersion(q.revision, q.retain !== false)+ : await assets.cleanDiskCache(q.budgetBytes, q.execute === true);+ reply({ t: 'reply', reqId: q.reqId, data });+ return;+ }if (q.kind === 'snapshot') {reply({ t: 'reply', reqId: q.reqId, data: timed(() => worldSnapshot(game, q.selectedId, q.withTree)) });return;diff --git a/sdk/src/runtime/debugChannelProtocol.ts b/sdk/src/runtime/debugChannelProtocol.tsindex 7d3154fa4..19ee5e6e0 100644--- a/sdk/src/runtime/debugChannelProtocol.ts+++ b/sdk/src/runtime/debugChannelProtocol.ts@@ -34,6 +34,9 @@ export type DebugChannelQuery =| { t: 'query'; reqId: number; kind: 'screen'; maxSide?: number }| { t: 'query'; reqId: number; kind: 'stats' }| { t: 'query'; reqId: number; kind: 'updateStatus' }+ | { t: 'query'; reqId: number; kind: 'diskCache'; rescan?: boolean }+ | { t: 'query'; reqId: number; kind: 'cleanDiskCache'; budgetBytes: number; execute?: boolean }+ | { t: 'query'; reqId: number; kind: 'retainDiskCacheVersion'; revision: string; retain?: boolean }| { t: 'query'; reqId: number; kind: 'snapshot'; selectedId: number | null; withTree: boolean }| ({ t: 'query'; reqId: number; kind: 'control' } & DebugControl);diff --git a/sdk/tests/content-cache-budget.test.ts b/sdk/tests/content-cache-budget.test.tsnew file mode 100644index 000000000..efec4695c--- /dev/null+++ b/sdk/tests/content-cache-budget.test.ts@@ -0,0 +1,158 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import { afterEach, describe, expect, it, vi } from 'vitest';+import { mkdtemp, rm, writeFile, readFile } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { ContentCache } from '../src/platform/contentCache';+import { nodeAdapter } from '../src/platform/node';+import { cacheEntryName } from '../src/platform/cacheEntryName';+import type { PlatformAdapter } from '../src/platform/types';++const urls = ['v1', 'v2', 'v3', 'v4'].map(v => `https://cdn.test/${v}/a.bin`);+const bytes = (n = 8) => new Uint8Array(n).fill(42).buffer;+let dir: string | null = null;+const oldDir = process.env.ESENGINE_CACHE_DIR;+afterEach(async () => {+ if (dir) await rm(dir, { recursive: true, force: true });+ dir = null;+ if (oldDir === undefined) delete process.env.ESENGINE_CACHE_DIR;+ else process.env.ESENGINE_CACHE_DIR = oldDir;+ vi.restoreAllMocks();+});+async function cache() {+ dir = await mkdtemp(join(tmpdir(), 'estella-cache-budget-'));+ process.env.ESENGINE_CACHE_DIR = dir;+ return new ContentCache(nodeAdapter);+}++describe('disk cache budget and offline versions', () => {+ it('two updates release only v1; v3 and the v2 rollback survive an offline restart', async () => {+ const c = await cache();+ for (let i = 0; i < 3; i++) {+ await c.protect('game', [{ revision: `v${i + 1}`, reason: 'current', keys: [urls[i]] },+ ...(i ? [{ revision: `v${i}`, reason: 'rollback' as const, keys: [urls[i - 1]] }] : [])]);+ await c.write(urls[i], bytes());+ }+ const preview = await c.cleanup(16);+ expect(preview.candidates).toEqual([cacheEntryName(urls[0])]);+ expect(await nodeAdapter.readCacheFile(urls[0])).not.toBeNull();+ const done = await c.cleanup(16, true);+ expect(done.releaseBytes).toBe(8);+ expect(done.budgetMet).toBe(true);+ const restarted = new ContentCache(nodeAdapter);+ expect(await restarted.read(urls[0])).toBeNull();+ expect(await restarted.read(urls[1])).toEqual(bytes());+ expect(await restarted.read(urls[2])).toEqual(bytes());+ const impossible = await restarted.cleanup(0, true);+ expect(impossible.removed).toEqual([]);+ expect(impossible.budgetMet).toBe(false);+ expect(impossible.report.protectedBytes).toBe(16);+ });++ it('recomputes a preview after a version becomes pending and preserves saves and unknown files', async () => {+ const c = await cache();+ await c.write(urls[0], bytes());+ expect((await c.cleanup(0)).candidates).toHaveLength(1);+ await c.protect('game', [{ revision: 'v1', reason: 'pending', keys: [urls[0]] }]);+ await writeFile(join(dir!, 'player-save.json'), '{"level":8}');+ await writeFile(join(dir!, '0123456789abcdef'), new Uint8Array(3));+ const result = await c.cleanup(0, true);+ expect(result.removed).toEqual([]);+ expect(result.report.entries.find(e => e.name === '0123456789abcdef')?.protection).toEqual(['unindexed']);+ expect(await readFile(join(dir!, 'player-save.json'), 'utf8')).toBe('{"level":8}');+ });++ it('serializes a delayed download with cleanup so its staged version remains readable', async () => {+ const c = await cache();+ await c.protect('game', [{ revision: 'v1', reason: 'pending', keys: [urls[0]] }]);+ const original = nodeAdapter.writeCacheFile.bind(nodeAdapter);+ let release!: () => void;+ let started!: () => void;+ const waiting = new Promise<void>(r => { started = r; });+ vi.spyOn(nodeAdapter, 'writeCacheFile').mockImplementation(async (key, data) => {+ if (key === urls[0]) { started(); await new Promise<void>(r => { release = r; }); }+ await original(key, data);+ });+ const write = c.write(urls[0], bytes());+ await waiting;+ const clean = c.cleanup(0, true);+ release();+ await write;+ expect((await clean).removed).toEqual([]);+ expect(await c.read(urls[0])).toEqual(bytes());+ });++ it('repairs corrupt indexes conservatively and reports missing protected files', async () => {+ const c = await cache();+ await c.write(urls[0], bytes());+ const indexed = (await nodeAdapter.listCacheFiles()).find(f => f.name !== cacheEntryName(urls[0]))!;+ await writeFile(join(dir!, indexed.name), '{truncated');+ const restarted = new ContentCache(nodeAdapter);+ await restarted.protect('game', [{ revision: 'v2', reason: 'current', keys: [urls[1]] }]);+ const repaired = await restarted.report(true);+ expect(repaired.versions[0].missing).toBe(1);+ expect(repaired.entries[0].protection).toContain('unindexed');+ expect((await restarted.cleanup(0, true)).removed).toEqual([]);+ });++ it('reports real released bytes when a deletion fails and refuses invalid budgets', async () => {+ const c = await cache();+ await c.write(urls[0], bytes());+ await c.write(urls[1], bytes());+ const unlink = nodeAdapter.removeCacheFile.bind(nodeAdapter);+ vi.spyOn(nodeAdapter, 'removeCacheFile').mockImplementation(async n => {+ if (n === cacheEntryName(urls[0])) throw Error('busy');+ await unlink(n);+ });+ const result = await c.cleanup(0, true);+ expect(result.failed).toEqual([cacheEntryName(urls[0])]);+ expect(result.releaseBytes).toBe(8);+ expect(result.remainingBytes).toBe(8);+ await expect(c.cleanup(-1, true)).rejects.toThrow('budget');+ await expect(nodeAdapter.removeCacheFile('../save')).rejects.toThrow('invalid');+ });++ it('uses last access rather than file discovery order for LRU', async () => {+ const c = await cache();+ let tick = 1_900_000_000_000;+ vi.spyOn(Date, 'now').mockImplementation(() => tick++);+ await c.write(urls[0], bytes());+ await c.write(urls[1], bytes());+ await c.read(urls[0]);+ expect((await c.cleanup(8)).candidates).toEqual([cacheEntryName(urls[1])]);+ });++ it('reports deletion results at quota even if the index cannot be stored', async () => {+ const c = await cache();+ await c.write(urls[0], bytes());+ vi.spyOn(nodeAdapter, 'writeCacheFile').mockRejectedValue(Error('disk full'));+ const result = await c.cleanup(0, true);+ expect(result.releaseBytes).toBe(8);+ expect(result.indexPersisted).toBe(false);+ expect((await new ContentCache(nodeAdapter).report()).usedBytes).toBe(0);+ });++ it('keeps a file shared with another application after its first owner retires the version', async () => {+ const c = await cache();+ for (const url of urls) await c.write(url, bytes());+ await c.protect('game-a', [{ revision: 'a1', reason: 'current', keys: [urls[0], urls[1]] }]);+ await c.protect('game-b', [{ revision: 'b1', reason: 'current', keys: [urls[0], urls[2]] }]);+ await c.protect('game-a', [{ revision: 'a2', reason: 'current', keys: [urls[3]] }]);+ const report = await c.report();+ expect(report.entries.find(e => e.key === urls[0])).toMatchObject({+ versions: ['a1', 'b1'], protection: ['game-b:current'],+ });+ const cleaned = await c.cleanup(24, true);+ expect(cleaned.removed).toEqual([cacheEntryName(urls[1])]);+ expect(await c.read(urls[0])).toEqual(bytes());+ });++ it('distinguishes unsupported management from an empty cache', async () => {+ const noStorage = new ContentCache({} as PlatformAdapter);+ expect(await noStorage.report()).toMatchObject({ capability: 'unavailable', usedBytes: null });+ const storageOnly = new ContentCache({ readCacheFile: async () => null, writeCacheFile: async () => {} } as unknown as PlatformAdapter);+ expect(await storageOnly.report()).toMatchObject({ capability: 'storage-only', reclaimableBytes: null });+ expect((await storageOnly.cleanup(0, true)).budgetMet).toBeNull();+ });+});diff --git a/sdk/tests/debug-channel.test.ts b/sdk/tests/debug-channel.test.tsindex 6264aecb5..47a5fd94a 100644--- a/sdk/tests/debug-channel.test.ts+++ b/sdk/tests/debug-channel.test.ts@@ -102,6 +102,35 @@ describe('a device asked about its content', () => {});});+describe('a device asked about its disk cache', () => {+ it('routes scans, previews, explicit cleanup and version retention through its Assets service', async () => {+ vi.resetModules();+ const base = await import('../src/platform/base');+ const channel = await import('../src/runtime/debugChannel');+ const { Assets } = await import('../src/asset/AssetPlugin');+ const s = fakeSocket();+ base.setPlatform({ name: 'wechat', now: () => performance.now(), createSocket: () => s.socket } as unknown as PlatformAdapter);+ channel.startDebugChannel({ url: 'ws://editor:1/?token=t', project: 'Demo' });+ s.open();+ const disk = vi.fn(async () => ({ capability: 'managed', usedBytes: 16 }));+ const clean = vi.fn(async () => ({ releaseBytes: 8 }));+ const retain = vi.fn(async () => ({ capability: 'managed', usedBytes: 16 }));+ channel.attachDebugChannel({ hasResource: (r: unknown) => r === Assets,+ getResource: () => ({ getManifest: () => null, diskCacheReport: disk, cleanDiskCache: clean, retainDiskCacheVersion: retain }),+ onFrameEnd: () => () => {},+ } as unknown as App);+ s.receive({ t: 'query', reqId: 31, kind: 'diskCache', rescan: true });+ s.receive({ t: 'query', reqId: 32, kind: 'cleanDiskCache', budgetBytes: 8 });+ s.receive({ t: 'query', reqId: 33, kind: 'cleanDiskCache', budgetBytes: 8, execute: true });+ s.receive({ t: 'query', reqId: 34, kind: 'retainDiskCacheVersion', revision: 'v1', retain: false });+ await flush();+ expect(disk).toHaveBeenCalledWith(true);+ expect(clean.mock.calls).toEqual([[8, false], [8, true]]);+ expect(retain).toHaveBeenCalledWith('v1', false);+ expect(s.sent.find((m) => (m as { reqId?: number }).reqId === 33)).toEqual({ t: 'reply', reqId: 33, data: { releaseBytes: 8 } });+ });+});+describe('what the channel costs a device', () => {it('comes with the step of the device clock, so a 0 below it reads as unmeasured', async () => {vi.resetModules();diff --git a/sdk/tests/hot-update-cache-budget.test.ts b/sdk/tests/hot-update-cache-budget.test.tsnew file mode 100644index 000000000..f275000ad--- /dev/null+++ b/sdk/tests/hot-update-cache-budget.test.ts@@ -0,0 +1,137 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import { afterEach, beforeEach, expect, it, vi } from 'vitest';+import { mkdtemp, rm } from 'node:fs/promises';+import { join } from 'node:path';+import { tmpdir } from 'node:os';+import { Assets } from '../src/asset/Assets';+import { HttpBackend } from '../src/asset/Backend';+import type { AddressableManifest } from '../src/asset/AddressableManifest';+import { contentHashHex } from '../src/asset/contentHash';+import { setPlatform, platformWriteCacheFile } from '../src/platform/base';+import { nodeAdapter } from '../src/platform/node';+import type { PlatformAdapter } from '../src/platform/types';++const data = (v: number) => new Uint8Array(8).fill(v).buffer;+const root = 'https://cdn.test/game';+const url = (v: number) => `${root}/assets/${contentHashHex(new Uint8Array(data(v)))}.bin`;+const manifest = (v: number): AddressableManifest => ({ version: '2.0', revision: `v${v}`,+ groups: { cdn: { bundleMode: 'remote', labels: [], assets: { a: {+ path: url(v), type: 'json', size: 8, labels: [], contentHash: contentHashHex(new Uint8Array(data(v))),+ } } } } });+let dir: string;+let next = 2;+let offline = false;+let refuseStorage = false;+const storage = new Map<string, string>();+const oldDir = process.env.ESENGINE_CACHE_DIR;+const network = vi.fn(async (path: string) => {+ if (offline) throw Error('offline');+ const value = path.endsWith('manifest.json') ? JSON.stringify(manifest(next)) : '';+ return { ok: true, status: 200, statusText: 'OK', headers: {},+ text: async () => value, json: async () => JSON.parse(value), arrayBuffer: async () => data(next) };+});+function adapter(): PlatformAdapter {+ const p = Object.create(nodeAdapter) as PlatformAdapter;+ Object.assign(p, { fetch: network, getStorageItem: (key: string) => storage.get(key) ?? null,+ setStorageItem: (key: string, value: string) => { if (refuseStorage) throw Error('full'); storage.set(key, value); },+ removeStorageItem: (key: string) => storage.delete(key) });+ return p;+}+function assets() {+ const a = Assets.create({ module: null, backend: new HttpBackend({ baseUrl: '' }), manifest: manifest(1) });+ a.setRemoteRoot(root);+ a.restorePersistedUpdate('game:active');+ return a;+}+beforeEach(async () => {+ dir = await mkdtemp(join(tmpdir(), 'estella-hotupdate-budget-'));+ process.env.ESENGINE_CACHE_DIR = dir;+ next = 2; offline = false; refuseStorage = false; storage.clear(); network.mockClear();+ setPlatform(adapter());+});+afterEach(async () => {+ try {+ // Windows can briefly report ENOTEMPTY after the last unlink even when+ // readdir is already empty. Retry that host condition, and always reset+ // the cache path so a teardown failure cannot contaminate the next case.+ await rm(dir, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 });+ } finally {+ if (oldDir === undefined) delete process.env.ESENGINE_CACHE_DIR; else process.env.ESENGINE_CACHE_DIR = oldDir;+ }+});++it('applies two real updates, cleans v1, restores v3 and reads current/rollback bytes with no network', async () => {+ const a = assets();+ await platformWriteCacheFile(url(1), data(1));+ for (next of [2, 3]) {+ await a.checkForUpdate({ manifestUrl: `${root}/manifest.json` });+ expect((await a.applyUpdate()).stages).toMatchObject({ persisted: true, cached: true });+ }+ const clean = await a.cleanDiskCache(16, true);+ expect(clean.releaseBytes).toBe(8);+ expect(clean.report.versions).toEqual(expect.arrayContaining([+ expect.objectContaining({ revision: 'v3', reason: 'current', missing: 0 }),+ expect.objectContaining({ revision: 'v2', reason: 'rollback', missing: 0 }),+ ]));+ offline = true;+ setPlatform(adapter()); // Fresh coordinator, same durable bytes and active manifest.+ const restored = assets();+ expect(restored.updateStatus().revision).toBe('v3');+ network.mockClear();+ const backend = new HttpBackend({ baseUrl: '' });+ expect(await backend.fetchBinary(url(3))).toEqual(data(3));+ expect(await backend.fetchBinary(url(2))).toEqual(data(2));+ expect(network).not.toHaveBeenCalled();+ expect((await restored.cleanDiskCache(0, true)).removed).toEqual([]);+});++it('keeps the next-launch version and its rollback when two later manifest writes fail', async () => {+ const a = assets();+ await platformWriteCacheFile(url(1), data(1));+ await a.checkForUpdate({ manifestUrl: `${root}/manifest.json` });+ await a.applyUpdate();+ refuseStorage = true;+ for (next of [3, 4]) {+ await a.checkForUpdate({ manifestUrl: `${root}/manifest.json` });+ expect((await a.applyUpdate()).stages.persisted).toBe(false);+ }+ const result = await a.cleanDiskCache(0, true);+ expect(result.removed).toEqual([]);+ offline = true;+ setPlatform(adapter());+ const restored = assets();+ expect(restored.updateStatus().revision).toBe('v2');+ const backend = new HttpBackend({ baseUrl: '' });+ expect(await backend.fetchBinary(url(2))).toEqual(data(2));+ expect(await backend.fetchBinary(url(1))).toEqual(data(1));+});++it('does not misreport a committed update as failed when the final index write hits quota, and can still free old bytes', async () => {+ const p = adapter();+ let indexFull = false;+ const write = p.writeCacheFile!.bind(p);+ p.writeCacheFile = async (key, value) => { if (indexFull) throw Error('disk full'); await write(key, value); };+ p.setStorageItem = (key, value) => { storage.set(key, value); if (next === 3) indexFull = true; };+ setPlatform(p);+ const a = assets();+ await platformWriteCacheFile(url(1), data(1));+ for (next of [2, 3]) {+ await a.checkForUpdate({ manifestUrl: `${root}/manifest.json` });+ expect((await a.applyUpdate()).stages).toMatchObject({ applied: true, persisted: true, cached: true });+ }+ const clean = await a.cleanDiskCache(16, true);+ expect(clean.releaseBytes).toBe(8);+ expect(clean.indexPersisted).toBe(false);+ expect(clean.report.versions).toEqual(expect.arrayContaining([+ expect.objectContaining({ revision: 'v3', missing: 0 }), expect.objectContaining({ revision: 'v2', missing: 0 }),+ ]));+});++it('does not report packaged remote-group assets as missing offline cache files', async () => {+ const shipped = manifest(1);+ shipped.groups.cdn.assets.a.path = 'remote/cdn/a.bin';+ const a = Assets.create({ module: null, backend: new HttpBackend({ baseUrl: '' }), manifest: shipped });+ const report = await a.diskCacheReport();+ expect(report.versions).toEqual([expect.objectContaining({ revision: 'v1', reason: 'current', missing: 0 })]);+});diff --git a/sdk/tests/minigame-cache-budget.test.ts b/sdk/tests/minigame-cache-budget.test.tsnew file mode 100644index 000000000..93155d6df--- /dev/null+++ b/sdk/tests/minigame-cache-budget.test.ts@@ -0,0 +1,75 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import { expect, it } from 'vitest';+import { MiniGamePlatformAdapter } from '../src/platform/minigame/adapter';+import type { MiniGameFileSystemManager, MiniGameGlobal } from '../src/platform/minigame/api';+import { ContentCache } from '../src/platform/contentCache';+import { cacheEntryName } from '../src/platform/cacheEntryName';++function host() {+ const files = new Map<string, ArrayBuffer>();+ const dir = 'wxfile://usr';+ let failRename = false;+ let full = false;+ const fs: MiniGameFileSystemManager = {+ readFileSync: path => { const b = files.get(path); if (!b) throw Error('missing'); return b; },+ readFile: o => { const b = files.get(o.filePath); if (b) o.success?.({ data: b }); else o.fail?.({ errMsg: 'missing' }); },+ access: o => { if (files.has(o.path)) o.success?.(); else o.fail?.({ errMsg: 'missing' }); },+ accessSync: path => { if (!files.has(path)) throw Error('missing'); },+ writeFile: o => { if (full) o.fail?.({ errMsg: 'quota exceeded' }); else { files.set(o.filePath, o.data as ArrayBuffer); o.success?.(); } },+ readdir: o => o.success?.({ files: [...files.keys()].map(p => p.slice(dir.length + 1)) }),+ stat: o => { const b = files.get(o.path); if (b) o.success?.({ stats: { size: b.byteLength, lastAccessedTime: 1, isFile: () => true } }); else o.fail?.({ errMsg: 'missing' }); },+ unlink: o => { files.delete(o.filePath); o.success?.(); },+ rename: o => {+ if (failRename) { o.fail?.({ errMsg: 'interrupted' }); return; }+ files.set(o.newPath, files.get(o.oldPath)!); files.delete(o.oldPath); o.success?.();+ },+ };+ const make = () => new MiniGamePlatformAdapter({ id: 'wechat', hostLabel: 'Test',+ global: { env: { USER_DATA_PATH: dir }, getFileSystemManager: () => fs } as unknown as MiniGameGlobal });+ return { files, dir, make, renameFails: () => { failRename = true; }, fill: () => { full = true; } };+}++it('cleans only old resource bytes on the mini-game fs and retains a developer-selected version across restart', async () => {+ const h = host();+ const cache = new ContentCache(h.make());+ const urls = [1, 2, 3].map(i => `https://cdn.test/${i}.bin`);+ for (let i = 0; i < urls.length; i++) {+ await cache.protect('game', [{ revision: String(i + 1), reason: 'current', keys: [urls[i]] },+ ...(i ? [{ revision: String(i), reason: 'rollback' as const, keys: [urls[i - 1]] }] : [])]);+ await cache.write(urls[i], new ArrayBuffer(8));+ }+ h.files.set(`${h.dir}/player-save.json`, new ArrayBuffer(99));+ await cache.retainVersion('game', '1');+ const restarted = new ContentCache(h.make());+ expect((await restarted.cleanup(0, true)).removed).toEqual([]);+ await restarted.retainVersion('game', '1', false);+ expect((await restarted.cleanup(16, true)).releaseBytes).toBe(8);+ expect(h.files.has(`${h.dir}/${cacheEntryName(urls[0])}`)).toBe(false);+ expect(h.files.has(`${h.dir}/player-save.json`)).toBe(true);+ expect(await restarted.read(urls[2])).toEqual(new ArrayBuffer(8));+});++it('does not replace committed bytes when rename is interrupted, and rejects a full-cache write', async () => {+ const h = host();+ const adapter = h.make();+ const original = new Uint8Array([1, 2]).buffer;+ await adapter.writeCacheFile('key', original);+ h.renameFails();+ await expect(adapter.writeCacheFile('key', new ArrayBuffer(3))).rejects.toThrow('interrupted');+ expect(await adapter.readCacheFile('key')).toEqual(original);+ expect([...h.files.keys()].some(n => n.endsWith('.tmp'))).toBe(false);+ h.fill();+ await expect(new ContentCache(adapter).write('other', new ArrayBuffer(2))).rejects.toThrow('quota');+ expect(await adapter.readCacheFile('other')).toBeNull();+});++it('counts interrupted temporary writes conservatively without treating them as loadable assets', async () => {+ const h = host();+ h.files.set(`${h.dir}/0123456789abcdef.7.tmp`, new ArrayBuffer(4));+ const cache = new ContentCache(h.make());+ const report = await cache.report(true);+ expect(report.usedBytes).toBe(4);+ expect(report.protectedBytes).toBe(4);+ expect((await cache.cleanup(0, true)).removed).toEqual([]);+});diff --git a/tools/cache-budget-demo.mjs b/tools/cache-budget-demo.mjsnew file mode 100644index 000000000..281370620--- /dev/null+++ b/tools/cache-budget-demo.mjs@@ -0,0 +1,19 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+// Run from any cwd: node tools/cache-budget-demo.mjs+import { build } from 'esbuild';+import { mkdtemp, rm } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { fileURLToPath, pathToFileURL } from 'node:url';++const scratch = await mkdtemp(join(tmpdir(), 'estella-cache-demo-'));+try {+ const entry = fileURLToPath(new URL('./fixtures/cache-budget-demo.ts', import.meta.url));+ const bundle = join(scratch, 'demo.mjs');+ await build({ entryPoints: [entry], outfile: bundle, bundle: true, platform: 'node', format: 'esm', packages: 'external' });+ const demo = await import(pathToFileURL(bundle).href);+ console.log(JSON.stringify(await demo.run(scratch, bundle), null, 2));+} finally {+ await rm(scratch, { recursive: true, force: true });+}diff --git a/tools/cache-budget-render-fixture.mjs b/tools/cache-budget-render-fixture.mjsnew file mode 100644index 000000000..d01390b86--- /dev/null+++ b/tools/cache-budget-render-fixture.mjs@@ -0,0 +1,19 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import { build } from 'esbuild';+import { mkdir, mkdtemp, rm } from 'node:fs/promises';+import path from 'node:path';+import { fileURLToPath, pathToFileURL } from 'node:url';+const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');+const out = path.resolve(process.argv[2] ?? path.join(root, 'output/cache-budget/render'));+const channel = process.argv[3];+if (!channel) throw Error('usage: node tools/cache-budget-render-fixture.mjs <output> <debug-channel-url>');+await mkdir(path.join(root, 'pipeline/src'), { recursive: true });+const scratch = await mkdtemp(path.join(root, 'pipeline/src/.build-cache-render-'));+try {+ const bundle = path.join(scratch, 'fixture.mjs');+ await build({ entryPoints: [path.join(root, 'tools/fixtures/cache-budget-render-fixture.ts')], outfile: bundle,+ bundle: true, format: 'esm', platform: 'node', packages: 'external' });+ const { run } = await import(pathToFileURL(bundle).href);+ console.log(JSON.stringify(await run(root, out, channel)));+} finally { await rm(scratch, { recursive: true, force: true }); }diff --git a/tools/cache-budget-scale.mjs b/tools/cache-budget-scale.mjsnew file mode 100644index 000000000..2d9e71335--- /dev/null+++ b/tools/cache-budget-scale.mjs@@ -0,0 +1,17 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+// Same deterministic resource/three-version index for before/after CPU timing.+import { build } from 'esbuild';+import { mkdtemp, rm } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import path from 'node:path';+import { fileURLToPath, pathToFileURL } from 'node:url';+const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');+const scratch = await mkdtemp(path.join(tmpdir(), 'estella-cache-scale-'));+try {+ const bundle = path.join(scratch, 'scale.mjs');+ await build({ entryPoints: [path.join(root, 'tools/fixtures/cache-budget-scale.ts')],+ outfile: bundle, bundle: true, format: 'esm', platform: 'node' });+ const { run } = await import(pathToFileURL(bundle).href);+ console.log(JSON.stringify(await run(), null, 2));+} finally { await rm(scratch, { recursive: true, force: true }); }diff --git a/tools/fixtures/cache-budget-demo.ts b/tools/fixtures/cache-budget-demo.tsnew file mode 100644index 000000000..53a8b98e9--- /dev/null+++ b/tools/fixtures/cache-budget-demo.ts@@ -0,0 +1,79 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import { createServer } from 'node:http';+import { mkdirSync, readFileSync, writeFileSync, renameSync } from 'node:fs';+import { join } from 'node:path';+import { execFileSync } from 'node:child_process';+import { Assets } from '../../sdk/src/asset/Assets';+import { HttpBackend } from '../../sdk/src/asset/Backend';+import { contentHashHex } from '../../sdk/src/asset/contentHash';+import { nodeAdapter } from '../../sdk/src/platform/node';+import { setPlatform, platformWriteCacheFile } from '../../sdk/src/platform/base';+import type { AddressableManifest } from '../../sdk/src/asset/AddressableManifest';++const payload = (v: number) => new Uint8Array(8).fill(v);+const assetUrl = (root: string, v: number) => `${root}/${contentHashHex(payload(v))}.bin`;+const manifest = (root: string, v: number): AddressableManifest => ({ version: '2.0', revision: `v${v}`,+ groups: { cdn: { bundleMode: 'remote', labels: [], assets: { data: {+ path: assetUrl(root, v), contentHash: contentHashHex(payload(v)), type: 'json', size: 8, labels: [],+ } } } } });++/** Node's default key/value store is session-local. This fixture supplies a+ * durable host store (mini-games/native already have one) to prove a literal+ * process restart, while using the real engine disk-cache and update services. */+function host(scratch: string, offline: boolean) {+ process.env.ESENGINE_CACHE_DIR = join(scratch, 'cache');+ const stateDir = join(scratch, 'state');+ mkdirSync(stateDir, { recursive: true });+ const state = join(stateDir, 'active.json');+ nodeAdapter.getStorageItem = () => { try { return readFileSync(state, 'utf8'); } catch { return null; } };+ nodeAdapter.setStorageItem = (_key, value) => { writeFileSync(`${state}.tmp`, value); renameSync(`${state}.tmp`, state); };+ if (offline) nodeAdapter.fetch = async () => { throw Error('offline: network forbidden'); };+ setPlatform(nodeAdapter);+}+function assets(root: string) {+ const a = Assets.create({ module: null, backend: new HttpBackend({ baseUrl: '' }), manifest: manifest(root, 1) });+ a.setRemoteRoot(root);+ a.restorePersistedUpdate('cache-budget-demo');+ return a;+}+async function offline(scratch: string, root: string) {+ host(scratch, true);+ const a = assets(root);+ const backend = new HttpBackend({ baseUrl: '' });+ const current = new Uint8Array(await backend.fetchBinary(assetUrl(root, 3)));+ const rollback = new Uint8Array(await backend.fetchBinary(assetUrl(root, 2)));+ if (a.updateStatus().revision !== 'v3' || current.some(b => b !== 3) || rollback.some(b => b !== 2)) throw Error('offline verification failed');+ return { revision: a.updateStatus().revision, currentBytes: current.byteLength,+ rollbackBytes: rollback.byteLength, networkAllowed: false, freshProcess: true };+}++export async function run(scratch: string, bundle: string) {+ host(scratch, false);+ let revision = 2;+ let root = '';+ const server = createServer((req, res) => {+ if (req.url === '/manifest.json') res.end(JSON.stringify(manifest(root, revision)));+ else res.end(payload(revision));+ });+ await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));+ root = `http://127.0.0.1:${(server.address() as { port: number }).port}`;+ try {+ const a = assets(root);+ await platformWriteCacheFile(assetUrl(root, 1), payload(1).buffer);+ const stages = [];+ for (revision of [2, 3]) {+ await a.checkForUpdate({ manifestUrl: `${root}/manifest.json` });+ stages.push((await a.applyUpdate()).stages);+ }+ const before = await a.diskCacheReport();+ const preview = await a.cleanDiskCache(16);+ const cleaned = await a.cleanDiskCache(16, true);+ await new Promise<void>(resolve => server.close(() => resolve()));+ const restarted = JSON.parse(execFileSync(process.execPath, [bundle, '--offline', scratch, root], { encoding: 'utf8' }));+ return { stages, before: { bytes: before.usedBytes, protected: before.protectedBytes, reclaimable: before.reclaimableBytes },+ preview: { files: preview.candidates.length, releaseBytes: preview.releaseBytes },+ cleanup: { releaseBytes: cleaned.releaseBytes, remaining: cleaned.remainingBytes, budgetMet: cleaned.budgetMet }, offline: restarted };+ } finally { if (server.listening) server.close(); }+}+if (process.argv[2] === '--offline') console.log(JSON.stringify(await offline(process.argv[3], process.argv[4])));diff --git a/tools/fixtures/cache-budget-render-fixture.ts b/tools/fixtures/cache-budget-render-fixture.tsnew file mode 100644index 000000000..239da8214--- /dev/null+++ b/tools/fixtures/cache-budget-render-fixture.ts@@ -0,0 +1,47 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import { cp, mkdir, readFile, writeFile } from 'node:fs/promises';+import path from 'node:path';+import { exportGame } from '../../pipeline/src/export/exportGame';+import { solidPng } from '../../pipeline/tests/fixtures/solidPng.mjs';++const acceptance = `+import { Assets as CacheAssets, Res as cacheRes, defineSystem as cacheDefineSystem } from 'esengine';+addSystemToSchedule(Schedule.Update, cacheDefineSystem([cacheRes(CacheAssets)], (assets) => {+ globalThis.__cacheAcceptance = {+ async apply(manifestUrl, remoteRoot) {+ const plan = await assets.checkForUpdate({ manifestUrl, remoteRoot });+ return { plan, result: await assets.applyUpdate() };+ },+ status: () => assets.updateStatus(),+ };+}, { name: 'CacheBudgetAcceptance' }));+`;++/** Real project exports. Only the driver hook and remote art vary; gameplay,+ * authoring metadata, the scene and the exporter are the shipped ones. */+export async function run(root: string, out: string, channel: string) {+ const colors = [[80, 80, 80, 255], [40, 190, 50, 255], [210, 40, 40, 255], [40, 70, 220, 255]];+ const results = [];+ for (let v = 0; v < colors.length; v++) {+ const source = path.join(out, `source-v${v}`);+ await mkdir(source, { recursive: true });+ await cp(path.join(root, 'examples/hot-update-demo'), source, { recursive: true,+ filter: p => !/(?:^|[\\/])(?:node_modules|dist)(?:[\\/]|$)/.test(p) });+ await writeFile(path.join(source, 'assets/cdn/art.png'), solidPng(64, 64, colors[v]));+ const scripts = path.join(source, 'src/main.ts');+ await writeFile(scripts, await readFile(scripts, 'utf8') + acceptance);+ const result = await exportGame({ root: source, outDir: path.join(out, `v${v}`), platform: 'wechat',+ entryScene: 'assets/scenes/main.esscene', scriptsEntry: 'src/main.ts',+ hostsDir: path.join(root, 'pipeline/src/runtime'), packagesDir: path.join(root, 'plugins'),+ sdkDistDir: path.join(root, 'sdk/dist'), wasmDir: path.join(root, 'build/wasm/wechat'),+ title: 'Cache Budget Acceptance', contentAddressed: true, compressWasm: true, engineSubpackage: true,+ minify: false, debugChannel: { url: channel, project: 'Cache Budget Acceptance' },+ hotUpdate: { persistUpdateKey: 'estella:cache-budget:render' },+ });+ if (!result.ok) throw Error(`v${v}: ${result.errors.join('; ')}`);+ results.push({ version: v, platform: result.platform, included: result.included, warnings: result.warnings });+ }+ await writeFile(path.join(out, 'exports.json'), JSON.stringify(results, null, 2));+ return results;+}diff --git a/tools/fixtures/cache-budget-scale.ts b/tools/fixtures/cache-budget-scale.tsnew file mode 100644index 000000000..fb246b636--- /dev/null+++ b/tools/fixtures/cache-budget-scale.ts@@ -0,0 +1,30 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import { ContentCache } from '../../sdk/src/platform/contentCache';+import { cacheEntryName } from '../../sdk/src/platform/cacheEntryName';+import type { PlatformAdapter } from '../../sdk/src/platform/types';+export async function run() {+ const count = 1200, bytesPerEntry = 16 * 1024;+ const keys = Array.from({ length: count }, (_, i) => `https://cdn.example/game/assets/hash-${i}.png`);+ const entries = keys.map((key, i) => ({ name: cacheEntryName(key), key, size: bytesPerEntry, lastAccess: i }));+ const index = new TextEncoder().encode(JSON.stringify({ schema: 1, entries, owners: { game: [+ { revision: 'v1', reason: null, keys: keys.slice(0, 600) },+ { revision: 'v2', reason: 'rollback', keys: keys.slice(300, 900) },+ { revision: 'v3', reason: 'current', keys: keys.slice(600) },+ ] } }));+ const platform = { readCacheFile: async () => index.buffer, writeCacheFile: async () => {},+ listCacheFiles: async () => [...entries, { name: cacheEntryName('estella:content-cache:index:v1'), size: index.byteLength, lastAccess: 0 }],+ removeCacheFile: async () => {},+ } as unknown as PlatformAdapter;+ const times = [];+ let totals;+ for (let i = 0; i < 3; i++) {+ const start = performance.now();+ const report = await new ContentCache(platform).report();+ times.push(performance.now() - start);+ if (report.usedBytes !== count * bytesPerEntry || report.protectedBytes !== 900 * bytesPerEntry+ || report.reclaimableBytes !== 300 * bytesPerEntry) throw Error('scale index accounting changed');+ totals = { usedBytes: report.usedBytes, protectedBytes: report.protectedBytes, reclaimableBytes: report.reclaimableBytes };+ }+ return { entries: count, versions: 3, totals, milliseconds: times, medianMs: [...times].sort((a, b) => a - b)[1] };+}diff --git a/tools/launchers/cache-budget-render-verify.mjs b/tools/launchers/cache-budget-render-verify.mjsnew file mode 100644index 000000000..f1bafe4ea--- /dev/null+++ b/tools/launchers/cache-budget-render-verify.mjs@@ -0,0 +1,202 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+// An exported mini-game, on a contract host with real persistent resource files.+// This verifies the engine/export/editor channel; it is not physical WeChat.+import { app, BrowserWindow } from 'electron';+import http from 'node:http';+import { mkdir, readFile, writeFile, readdir, stat, rename, unlink } from 'node:fs/promises';+import path from 'node:path';+import { createRequire } from 'node:module';+import { execFileSync } from 'node:child_process';+import { randomUUID, createHash } from 'node:crypto';+import { fileURLToPath } from 'node:url';+import { HOST_PAGE } from './minigameHost.mjs';+import { createDebugChannelServer } from '../../desktop/shared/debugChannelServer.mjs';+import { onRendererConsole } from '../lib/rendererConsole.mjs';++const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..');+const OUT = path.join(ROOT, 'output/cache-budget/render');+const STORE = path.join(OUT, `cache-${randomUUID()}`);+const { WebSocketServer } = createRequire(path.join(ROOT, 'sdk/package.json'))('ws');+app.commandLine.appendSwitch('enable-unsafe-swiftshader');+app.commandLine.appendSwitch('disable-gpu-sandbox');+app.commandLine.appendSwitch('force-device-scale-factor', '1');+app.commandLine.appendSwitch('force-color-profile', 'srgb');+// The restart deliberately closes the sole window before opening its successor.+// Keep the verifier alive until its final evidence has been written.+app.on('window-all-closed', () => {});+const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));++/** Additional vendor filesystem methods are implemented over the fixture's+ * loopback store. The normal packaged-file reader/image/socket/wasm host stays+ * unchanged. The game and SDK see the same API contract as a mini-game device. */+function installCacheHost(wx, fs) {+ wx.env = { USER_DATA_PATH: '/__cache' };+ const request = async (op, options, body) => {+ const query = new URLSearchParams({ op });+ for (const key of ['filePath', 'oldPath', 'newPath']) if (options[key]) query.set(key, options[key]);+ const response = await fetch('/__fs?' + query, { method: body ? 'POST' : 'GET', body });+ if (!response.ok) throw Error(await response.text());+ return response.json();+ };+ const callbacks = (promise, options, transform = x => x) => promise.then(result => options.success?.(transform(result)))+ .catch(error => options.fail?.({ errMsg: String(error) }));+ fs.writeFile = o => callbacks(request('write', o, o.data), o);+ fs.rename = o => callbacks(request('rename', o), o);+ fs.unlink = o => callbacks(request('unlink', o), o);+ fs.readdir = o => callbacks(request('list', o), o);+ fs.stat = o => callbacks(request('stat', { filePath: o.path }), o,+ r => ({ stats: { ...r, isFile: () => true } }));+}++const marker = ' globalThis.wx = wx;';+const originalPage = HOST_PAGE('game.js');+if (!originalPage.includes(marker)) throw Error('mini-game host injection point changed');+const page = originalPage.replace(marker, ` (${installCacheHost.toString()})(wx, fs);\n${marker}`);+const MIME = { '.js': 'text/javascript', '.json': 'application/json', '.wasm': 'application/wasm',+ '.png': 'image/png', '.jpg': 'image/jpeg', '.css': 'text/css', '.html': 'text/html' };++app.whenReady().then(async () => {+ let channel, server, win;+ let code = 0;+ let offline = false, full = false;+ const blockedDownloads = [], diagnostics = [], requests = [], evidence = { host: 'mini-game contract host', physicalDevice: false };+ try {+ await mkdir(STORE, { recursive: true });+ channel = await createDebugChannelServer({ WebSocketServer, host: '127.0.0.1' });+ // Generate actual game packages using the current SDK and compiled wasm.+ execFileSync('node', [path.join(ROOT, 'tools/cache-budget-render-fixture.mjs'), OUT, channel.urlFor('127.0.0.1')],+ { cwd: ROOT, stdio: 'inherit', windowsHide: true });+ const cached = file => {+ const name = String(file ?? '').replace(/^\/__cache\//, '');+ if (!/^[A-Za-z0-9_.-]+$/.test(name) || name === '.' || name === '..') throw Error('invalid cache file');+ return path.join(STORE, name);+ };+ server = http.createServer(async (req, res) => {+ try {+ const url = new URL(req.url, 'http://fixture');+ if (url.pathname.startsWith('/cdn/')) requests.push(url.pathname);+ if (url.pathname === '/__fs') {+ const op = url.searchParams.get('op');+ let data = {};+ if (op === 'list') data = { files: await readdir(STORE) };+ else if (op === 'stat') {+ const s = await stat(cached(url.searchParams.get('filePath')));+ data = { size: s.size, lastAccessedTime: s.atimeMs / 1000 };+ } else if (op === 'write') {+ if (full) { res.writeHead(507).end('user storage quota exceeded'); return; }+ const parts = []; for await (const part of req) parts.push(part);+ await writeFile(cached(url.searchParams.get('filePath')), Buffer.concat(parts));+ } else if (op === 'rename') await rename(cached(url.searchParams.get('oldPath')), cached(url.searchParams.get('newPath')));+ else if (op === 'unlink') await unlink(cached(url.searchParams.get('filePath')));+ else throw Error('unknown filesystem operation');+ res.writeHead(200, { 'content-type': 'application/json' }).end(JSON.stringify(data));+ return;+ }+ if (url.pathname.startsWith('/__cache/')) {+ const bytes = await readFile(cached(url.pathname));+ res.writeHead(200, { 'content-type': 'image/png' }).end(bytes);+ return;+ }+ if (url.pathname === '/') { res.writeHead(200, { 'content-type': 'text/html' }).end(page); return; }+ let dir = path.join(OUT, 'v0');+ let relative = decodeURIComponent(url.pathname).replace(/^\/+/, '');+ const cdn = /^cdn\/v([123])\/(.*)$/.exec(relative);+ if (cdn) {+ if (offline) { blockedDownloads.push(url.pathname); res.writeHead(503).end('offline'); return; }+ dir = path.join(OUT, `v${cdn[1]}`); relative = cdn[2];+ }+ const file = path.resolve(dir, relative);+ if (!file.startsWith(dir + path.sep)) { res.writeHead(403).end(); return; }+ const compressed = file.endsWith('.br');+ const ext = path.extname(compressed ? file.slice(0, -3) : file);+ const bytes = await readFile(file);+ res.writeHead(200, { 'content-type': MIME[ext] ?? 'application/octet-stream',+ ...(compressed ? { 'content-encoding': 'br' } : {}) }).end(bytes);+ } catch (e) { if (!res.headersSent) res.writeHead(404); res.end(String(e)); }+ });+ await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));+ const base = `http://127.0.0.1:${server.address().port}`;+ const partition = `cache-budget-${randomUUID()}`;+ const boot = async () => {+ const w = new BrowserWindow({ show: false, width: 256, height: 256, useContentSize: true,+ webPreferences: { partition, backgroundThrottling: false } });+ onRendererConsole(w.webContents, message => { if (/error|fail|cache|update|exception/i.test(message)) diagnostics.push(message.slice(0, 300)); });+ await w.loadURL(base);+ const deadline = Date.now() + 30_000;+ while (!await w.webContents.executeJavaScript('!!globalThis.__cacheAcceptance').catch(() => false)) {+ if (Date.now() > deadline) throw Error('mini-game did not reach its first scene');+ await sleep(100);+ }+ return w;+ };+ win = await boot();+ const target = async () => {+ const deadline = Date.now() + 10_000;+ while (!channel.targets().length) { if (Date.now() > deadline) throw Error('device channel did not connect'); await sleep(50); }+ return channel.targets()[0].id;+ };+ const query = async (kind, extra) => channel.query(await target(), kind, extra);+ const capture = async name => {+ const shot = await win.webContents.capturePage();+ await writeFile(path.join(OUT, name + '.png'), shot.toPNG());+ const bitmap = shot.toBitmap(), width = shot.getSize().width, height = shot.getSize().height;+ const offset = ((height >> 1) * width + (width >> 1)) * 4;+ return { pixel: [bitmap[offset + 2], bitmap[offset + 1], bitmap[offset]], bitmap,+ hash: createHash('sha256').update(bitmap).digest('hex') };+ };+ const colors = [[40, 190, 50], [210, 40, 40], [40, 70, 220]];+ evidence.updates = [];+ for (let v = 1; v <= 3; v++) {+ const cdn = `${base}/cdn/v${v}`;+ const update = await win.webContents.executeJavaScript(`globalThis.__cacheAcceptance.apply(${JSON.stringify(cdn + '/asset-manifest.json')}, ${JSON.stringify(cdn)})`);+ evidence.lastUpdate = update;+ if (!update.result.ok || update.result.stages.cached !== true || !update.result.stages.persisted) throw Error(`v${v} update did not commit/cache/persist`);+ let shot;+ const deadline = Date.now() + 10_000;+ do { await sleep(100); shot = await capture(`v${v}`); }+ while (shot.pixel.some((c, i) => Math.abs(c - colors[v - 1][i]) > 15) && Date.now() < deadline);+ if (shot.pixel.some((c, i) => Math.abs(c - colors[v - 1][i]) > 15)) throw Error(`v${v} rendered ${shot.pixel} rather than ${colors[v - 1]}`);+ evidence.updates.push({ revision: update.result.revision, stages: update.result.stages, pixel: shot.pixel });+ }+ const before = await query('diskCache');+ const previous = evidence.updates[0].revision;+ await query('retainDiskCacheVersion', { revision: previous, retain: true });+ const retained = await query('cleanDiskCache', { budgetBytes: 0, execute: true });+ if (retained.removed.length || retained.budgetMet) throw Error('retained/current/rollback resources were not protected');+ await query('retainDiskCacheVersion', { revision: previous, retain: false });+ const preview = await query('cleanDiskCache', { budgetBytes: before.protectedBytes });+ if (preview.candidates.length !== 1 || preview.releaseBytes <= 0) throw Error('cleanup preview did not identify the oldest resource');+ const first = await capture('before-cleanup');+ full = true;+ const cleaned = await query('cleanDiskCache', { budgetBytes: before.protectedBytes, execute: true });+ if (cleaned.removed.length !== 1 || cleaned.releaseBytes !== preview.releaseBytes || cleaned.indexPersisted !== false) throw Error('quota cleanup result was incorrect');+ full = false;+ await query('diskCache', { rescan: true });+ const after = await capture('after-cleanup');+ if (!first.bitmap.equals(after.bitmap)) throw Error('cleanup changed rendered pixels');+ evidence.cleanup = { before: before.usedBytes, after: cleaned.remainingBytes, released: cleaned.releaseBytes,+ protected: before.protectedBytes, atQuota: true, indexPersisted: cleaned.indexPersisted, pixelIdentical: true };+ offline = true;+ win.destroy();+ win = await boot();+ await sleep(500);+ const restart = await capture('offline-restart');+ const status = await win.webContents.executeJavaScript('globalThis.__cacheAcceptance.status()');+ const report = await query('diskCache');+ if (restart.pixel.some((c, i) => Math.abs(c - colors[2][i]) > 15)+ || status.revision !== evidence.updates[2].revision || blockedDownloads.length+ || report.versions.some(v => v.reason && v.missing)) throw Error('offline mini-game restart did not preserve current/rollback');+ evidence.offline = { revision: status.revision, pixel: restart.pixel, blockedDownloads,+ protectedMissing: report.versions.filter(v => v.reason).map(v => ({ revision: v.revision, missing: v.missing })) };+ evidence.ok = true;+ } catch (e) { code = 1; evidence.ok = false; evidence.error = String(e?.stack ?? e); }+ finally {+ evidence.diagnostics = diagnostics.slice(-24);+ evidence.requests = requests;+ await mkdir(OUT, { recursive: true });+ await writeFile(path.join(OUT, 'verification.json'), JSON.stringify(evidence, null, 2));+ console.log('CACHE_RENDER_RESULT ' + JSON.stringify(evidence));+ win?.destroy(); await channel?.close(); server?.close(); app.exit(code);+ }+});