@wildshard/engine 0.1.23 → 0.1.24

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (99) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/index.html +17 -4
  3. package/lint/engine-sides.json +7 -0
  4. package/package.json +29 -3
  5. package/scripts/app-build/titlePreloads.mjs +8 -5
  6. package/scripts/bake-road-surfaces.entry.ts +18 -0
  7. package/scripts/bake-road-surfaces.mjs +44 -0
  8. package/scripts/changelog.mjs +2 -1
  9. package/scripts/goldens/capture.mjs +18 -6
  10. package/scripts/goldens/native-residency.d.mts +1 -0
  11. package/scripts/goldens/native-residency.mjs +14 -1
  12. package/scripts/grid-road-lag.mjs +209 -0
  13. package/scripts/keep-copy.mjs +64 -12
  14. package/scripts/land.d.mts +4 -1
  15. package/scripts/land.mjs +85 -3
  16. package/scripts/loading-flow/benchmax.mjs +2 -0
  17. package/scripts/map-hash.mjs +1 -1
  18. package/scripts/nightly-tag.mjs +2 -4
  19. package/scripts/page-release/content.mjs +19 -10
  20. package/scripts/page-release/flow.d.mts +3 -2
  21. package/scripts/page-release/flow.mjs +31 -21
  22. package/scripts/page-release/packs.d.mts +5 -0
  23. package/scripts/page-release/packs.mjs +13 -3
  24. package/scripts/page-release/preview.d.mts +2 -0
  25. package/scripts/page-release/preview.mjs +74 -0
  26. package/scripts/page-release.mjs +13 -5
  27. package/scripts/road-drive-proof.mjs +269 -0
  28. package/scripts/road-memory-probe.mjs +129 -0
  29. package/scripts/scratch-dir.mjs +4 -4
  30. package/scripts/server-release/github.mjs +59 -26
  31. package/scripts/server-release/publish.mjs +15 -1
  32. package/scripts/server-release/sign.mjs +8 -4
  33. package/scripts/test_prebuilt_output.py +3 -1
  34. package/scripts/turn-in-shots.mjs +83 -0
  35. package/scripts/vitest-bench-observe-proof.py +168 -0
  36. package/scripts/vitest-bench.py +122 -77
  37. package/scripts/vps/rebuild.sh +3 -1
  38. package/scripts/worktree-reap.mjs +21 -9
  39. package/scripts/worktree.mjs +1 -1
  40. package/scripts/zone-gate-proof.mjs +93 -0
  41. package/src/client/engine/boot/sw.ts +3 -1
  42. package/src/client/engine/core/ktx2.ts +30 -9
  43. package/src/client/engine/models/place.ts +7 -5
  44. package/src/client/engine/pwa/sw.js +57 -2
  45. package/src/client/engine/render/precompile.ts +6 -0
  46. package/src/client/engine/render/tiers.ts +9 -0
  47. package/src/client/engine/ui/playerReload.ts +5 -5
  48. package/src/client/game/boot/bytes.generated.ts +4 -1
  49. package/src/client/game/boot/versions.generated.ts +8 -5
  50. package/src/client/game/grid/cellClip.ts +70 -6
  51. package/src/client/game/grid/gateCard.css +9 -0
  52. package/src/client/game/grid/gateCard.ts +67 -0
  53. package/src/client/game/grid/live.ts +17 -3
  54. package/src/client/game/grid/liveSession.ts +15 -5
  55. package/src/client/game/grid/neighbourLife.ts +10 -1
  56. package/src/client/game/grid/neighbourPanels.ts +29 -2
  57. package/src/client/game/grid/pageEntry.ts +21 -0
  58. package/src/client/game/grid/regionalWorld.ts +5 -0
  59. package/src/client/game/grid/roadCompressedSurfaces.ts +69 -0
  60. package/src/client/game/grid/roadLook.ts +5 -73
  61. package/src/client/game/grid/roadLookPlatform.ts +11 -6
  62. package/src/client/game/grid/roadSurfaceMaps.ts +80 -0
  63. package/src/client/game/grid/roadTilePool.ts +4 -0
  64. package/src/client/game/grid/session.ts +52 -12
  65. package/src/client/game/grid/softWallLook.ts +6 -1
  66. package/src/client/game/plugin/ui.ts +3 -0
  67. package/src/client/game/session/play.ts +3 -0
  68. package/src/client/game/shardfile/clientSource.ts +5 -2
  69. package/src/client/game/shardfile/clientWorker.ts +3 -2
  70. package/src/client/game/shardfile/slabLibrary.ts +37 -0
  71. package/src/client/game/shardfile/slabRanges.ts +145 -0
  72. package/src/client/host/online/shell.ts +2 -2
  73. package/src/client/host/standalone/shell.ts +4 -1
  74. package/src/server/game/grid/simulation.ts +27 -4
  75. package/src/server/game/plugin/simulation.ts +2 -0
  76. package/src/server/game/shardfile/dataRespawn.ts +47 -0
  77. package/src/server/host/standalone/cellWorld.ts +1 -1
  78. package/src/server/host/standalone/gridServer.ts +18 -6
  79. package/src/server/host/standalone/roadWorld.ts +30 -0
  80. package/src/server/host/standalone/serverHost.ts +2 -2
  81. package/src/shared/engine/entities/AnimalSim.ts +10 -0
  82. package/src/shared/engine/physics/transferWalls.ts +9 -4
  83. package/src/shared/game/grid/allocator.ts +8 -1
  84. package/src/shared/game/grid/gateCount.ts +27 -0
  85. package/src/shared/game/grid/zoneWalls.ts +64 -0
  86. package/src/shared/game/strings.ts +2 -0
  87. package/src/shared/host/standalone/harnessPlace.ts +4 -0
  88. package/src/test/engine/simState.ts +134 -0
  89. package/src/test/game/builtProduct.ts +6 -0
  90. package/src/test/game/headless/admittedProductCache.ts +61 -0
  91. package/src/test/game/headless/checkedReplayPipeline.ts +21 -0
  92. package/src/test/game/headless/nativeBounds.ts +27 -0
  93. package/src/test/game/headless/processUsage.ts +22 -0
  94. package/src/test/game/headless/productSession.ts +39 -0
  95. package/src/test/game/headless/ropeBodies.ts +60 -0
  96. package/src/test/game/headless/worker.ts +34 -0
  97. package/src/test/game/headlessNative.ts +114 -0
  98. package/src/test/game/headlessWorker.ts +43 -0
  99. package/src/test/tsconfig.game.json +3 -0
@@ -0,0 +1,6 @@
1
+ // oxlint-disable-next-line import/no-nodejs-modules -- Native scenarios run from the repository root.
2
+ import { resolve } from 'node:path';
3
+ import { readBuiltShardfile } from '../../../scripts/built-product.mjs';
4
+
5
+ /** Products come from CI's normal build or the matching immutable local cache, never a test build. */
6
+ export function builtProduct(name: string): string { return readBuiltShardfile(resolve('.'), name); }
@@ -0,0 +1,61 @@
1
+ // oxlint-disable-next-line import/no-nodejs-modules -- Exact product identity comes from its content-addressed index.
2
+ import { readFile } from 'node:fs/promises';
3
+ // oxlint-disable-next-line import/no-nodejs-modules -- Distinguish full products and slices with identical slugs.
4
+ import { resolve, sep } from 'node:path';
5
+ // oxlint-disable-next-line import/no-nodejs-modules -- Preserve native product URLs.
6
+ import { pathToFileURL } from 'node:url';
7
+ // oxlint-disable-next-line import/no-nodejs-modules -- Check the loaded descriptor against the cache identity.
8
+ import { createHash } from 'node:crypto';
9
+ import { loadHeadlessProduct } from '../../../server/host/headlessProduct';
10
+ import { carryOutputDescriptor, outputDescriptor } from '../../../shared/game/shardfile/outputDescriptor';
11
+ import { productClosureFile, type ShardProduct } from '../../../shared/game/shardfile/shardProduct';
12
+ import { shardProductData } from '../../../shared/game/shardfile/productData';
13
+ import { nodeNamedJsonCheck } from '../../../shared/game/shardfile/outputChecksNode';
14
+
15
+ export type ProductMode = 'full' | 'slice' | 'server';
16
+
17
+ /** A test file's admitted data only. Each borrower owns its source and byte arrays;
18
+ * worlds, residents and RNG never enter this cache. Rejected loads can retry. */
19
+ export function createAdmittedProductCache(load: typeof loadHeadlessProduct = loadHeadlessProduct) {
20
+ const products = new Map<string, Promise<{ product: ShardProduct; bytes: Map<string, Promise<Uint8Array>> }>>();
21
+ return async (directory: string, mode: ProductMode): Promise<{ product: ShardProduct; assets: Map<string, Uint8Array> }> => {
22
+ const root = resolve(directory);
23
+ // Read the index each time: a changed product at the same path cannot reuse
24
+ // a previous admission, even when its slug and revision stayed the same.
25
+ const identity = await readFile(`${root}/shard.json`, 'utf8');
26
+ const key = JSON.stringify([root, mode, identity]);
27
+ let pending = products.get(key);
28
+ if (pending === undefined) {
29
+ pending = load(root).then(product => {
30
+ if (outputDescriptor(product.shardfile)?.indexHash !== createHash('sha256').update(identity).digest('hex')) throw new Error('Headless product changed during cache admission');
31
+ return { product, bytes: new Map<string, Promise<Uint8Array>>() };
32
+ });
33
+ products.set(key, pending);
34
+ void pending.catch(() => { products.delete(key); });
35
+ }
36
+ const held = await pending;
37
+ const bytes = async (ref: string): Promise<Uint8Array> => {
38
+ let reading = held.bytes.get(ref);
39
+ if (reading === undefined) {
40
+ reading = productClosureFile(held.product, ref).then(value => value.slice());
41
+ held.bytes.set(ref, reading);
42
+ void reading.catch(() => { held.bytes.delete(ref); });
43
+ }
44
+ return (await reading).slice();
45
+ };
46
+ const source = structuredClone(held.product.shardfile);
47
+ carryOutputDescriptor(held.product.shardfile, source);
48
+ const product = shardProductData(source, pathToFileURL(root + sep).href, bytes, true, false, nodeNamedJsonCheck, { files: true });
49
+ const descriptor = outputDescriptor(source);
50
+ if (descriptor === undefined) throw new Error('Missing admitted headless inventory');
51
+ // Full inventory in every mode: the worker performs its own admission and
52
+ // must receive page assets too, not a filtered server-only bank.
53
+ const assets = new Map(await Promise.all(descriptor.index.files.map(async file => {
54
+ const ref = file.commons === true ? `commons:${file.hash}` : file.hash;
55
+ return [ref, await bytes(ref)] as const;
56
+ })));
57
+ return { product, assets };
58
+ };
59
+ }
60
+
61
+ export const admittedProduct = createAdmittedProductCache();
@@ -0,0 +1,21 @@
1
+ /** One checked replay request may run while its recorder captures the next
2
+ * bounded part. A failed request is observed immediately and drains before
3
+ * another part can be offered; no request or watchdog is replaced. */
4
+ export function checkedReplayPipeline<T>(consume:(part:T)=>Promise<void>):{
5
+ offer:(part:T)=>Promise<void>;check:()=>void;finish:()=>Promise<void>;stop:()=>Promise<void>;
6
+ } {
7
+ type Outcome={ok:true}|{ok:false;error:unknown};
8
+ let pending:Promise<Outcome>|undefined,failure:{error:unknown}|undefined,closed=false,offering=false;
9
+ const check=():void=>{if(failure!==undefined)throw failure.error;if(closed)throw new Error('Replay pipeline owner ended');};
10
+ const drain=async():Promise<void>=>{
11
+ const result=await pending;if(result!==undefined&&!result.ok)throw result.error;
12
+ };
13
+ return {check,offer:async part=>{
14
+ check();if(offering)throw new Error('Replay pipeline already has a pending offer');offering=true;
15
+ try{await drain();check();
16
+ pending=(async():Promise<Outcome>=>{try{await consume(part);return {ok:true};}
17
+ catch(error){failure={error};return {ok:false,error};}})();
18
+ }finally{offering=false;}
19
+ },finish:async()=>{check();if(offering)throw new Error('Replay pipeline has an unsettled offer');await drain();check();closed=true;},
20
+ stop:async()=>{closed=true;await pending;}};
21
+ }
@@ -0,0 +1,27 @@
1
+ import {installBounds} from '../../../client/engine/world/bounds';
2
+ import {floorBelow} from '../../../shared/engine/physics/query';
3
+ import type {Bounds} from '../../../shared/engine/level/spec';
4
+ import type {SimHost} from '../../../server/engine/sim';
5
+ import { leadPlayer } from '@wildshard/engine/sim/leadPlayer';
6
+
7
+ const declared=new WeakMap<SimHost,Bounds>();
8
+ const installed=new WeakSet<SimHost>();
9
+ /** Retain authored bounds without adding work to ordinary native replay. */
10
+ export function registerNativeWalkBounds(host:SimHost,bounds:Bounds|undefined):void {
11
+ if(bounds!==undefined)declared.set(host,bounds);
12
+ }
13
+ /** Activate the page's unchanged bounds owner only for native walk proofs. */
14
+ export function installNativeWalkBounds(host:SimHost):void {
15
+ const bounds=declared.get(host);if(bounds===undefined||installed.has(host))return;
16
+ installed.add(host);
17
+ const spawn=(x:number,z:number,yaw:number,y:number):void=>{leadPlayer(host).resetPose({x,y,z},yaw);};
18
+ installBounds({addSystem:(spec,scope)=>{
19
+ scope.onDispose(host.onStep(spec.id,dt=>{spec.run(dt,host.clock.now);},undefined,'afterBodies'));
20
+ }},host.scope,bounds,{
21
+ player:{position:leadPlayer(host).position,get yaw(){return leadPlayer(host).yaw;},
22
+ get onGround(){return leadPlayer(host).fall.grounded;},get hover(){return leadPlayer(host).board.on;},spawn},
23
+ suspended:()=>false,
24
+ floorAt:(x,z)=>floorBelow(host.physics,x,z,leadPlayer(host).position.y+0.6,1.2,leadPlayer(host).motor.collider),
25
+ toSpawn:()=>{const {at,yaw}=host.level.player;spawn(at.x,at.z,yaw,at.y);},
26
+ });
27
+ }
@@ -0,0 +1,22 @@
1
+ // oxlint-disable-next-line import/no-nodejs-modules -- Write only a short diagnostic to the native child's existing stdout.
2
+ import {writeSync} from 'node:fs';
3
+ // oxlint-disable-next-line import/no-nodejs-modules -- A process-wide CPU sample belongs to the recorder, not each worker thread.
4
+ import {isMainThread} from 'node:worker_threads';
5
+
6
+ let registered=false;
7
+
8
+ /** Observe complete real recorder processes without changing their verdict or simulation. */
9
+ export function recordNativeProcessUsage():void {
10
+ const entry=process.argv[1]?.replaceAll('\\','/').split('/').at(-1);
11
+ if(!isMainThread||registered)return;
12
+ registered=true;
13
+ process.once('exit',exitCode=>{
14
+ try{
15
+ const cpu=process.cpuUsage(),resources=process.resourceUsage();
16
+ writeSync(process.stdout.fd,JSON.stringify({diagnostic:'native-process-usage',entry,exitCode,
17
+ wallMs:process.uptime()*1000,userCpuMs:cpu.user/1000,systemCpuMs:cpu.system/1000,maxRssKiB:resources.maxRSS})+'\n');
18
+ }catch{
19
+ // A missing optional sample is no evidence; reporting cannot mask the original test verdict.
20
+ }
21
+ });
22
+ }
@@ -0,0 +1,39 @@
1
+ // oxlint-disable-next-line import/no-unassigned-import -- Install portable Math before simulation modules.
2
+ import '../../../shared/engine/core/portableMathFirst';
3
+ import {HeadlessSimulation} from '../../../server/host/headless';
4
+ import {loadHeadlessProduct} from '../../../server/host/headlessProduct';
5
+ import {productHeadlessSections} from '../../../shared/host/headlessSections';
6
+ import {outputDescriptor} from '../../../shared/game/shardfile/outputDescriptor';
7
+ import {builtProduct} from '../builtProduct';
8
+ import {createNativeProofWorker} from '../headlessWorker';
9
+ import {admittedProduct} from './admittedProductCache';
10
+
11
+ export type ProductSimulation = Pick<HeadlessSimulation, 'verbTape' | 'verbTapePart' | 'streamVerbTape' | 'journey' | 'walkLeg' | 'step' | 'dispose' | 'quarantined' | 'checkpoint'>;
12
+ export interface ProductSessionOptions {
13
+ /** Trusted proof composition owned by the consumer. Omit to run the product's ordinary native runtime. */
14
+ prepare?: URL;
15
+ snapshot?: string;
16
+ }
17
+
18
+ /** Start replay admission while its caller records native input. A failed
19
+ * admission is observed immediately, even before the caller asks for ready(). */
20
+ export async function beginProductSession(slug: string, options: ProductSessionOptions = {}): Promise<{
21
+ ready: () => Promise<ProductSimulation>; assets: ReadonlyMap<string, Uint8Array>;
22
+ product: Awaited<ReturnType<typeof loadHeadlessProduct>>;
23
+ }> {
24
+ const directory = builtProduct(slug), {product,assets} = await admittedProduct(directory,'full'), source = product.shardfile;
25
+ if (outputDescriptor(source) === undefined) throw new Error('Missing admitted headless inventory');
26
+ const sections = productHeadlessSections(product);
27
+ const pending = options.prepare === undefined
28
+ ? HeadlessSimulation.create(source, assets, options.snapshot, {deadline: 'advisory', sections, product: directory})
29
+ : createNativeProofWorker(source, assets, options.prepare, {sections, directory, ...(options.snapshot === undefined ? {} : {snapshot: options.snapshot})});
30
+ const outcome = (async () => {try {return {ok: true as const, sim: await pending};} catch (error) {return {ok: false as const, error};}})();
31
+ return {product, assets, ready: async () => {const result = await outcome; if (!result.ok) throw result.error; return result.sim;}};
32
+ }
33
+
34
+ export async function openProductSession(slug: string, options: ProductSessionOptions = {}): Promise<{
35
+ sim: ProductSimulation; product: Awaited<ReturnType<typeof loadHeadlessProduct>>;
36
+ }> {
37
+ const session = await beginProductSession(slug, options);
38
+ return {sim: await session.ready(), product: session.product};
39
+ }
@@ -0,0 +1,60 @@
1
+ import {rideable} from '../../../shared/engine/physics/CharacterMotor';
2
+ import {tagOf} from '../../../shared/engine/physics/surface';
3
+ import {isSimHostRestoring} from '../../../shared/engine/sim/snapshot';
4
+ import {RopeChain} from '../../../shared/engine/physics/ropeChain';
5
+ import type {SimHost} from '../../../server/engine/sim';
6
+ import type {ShardProduct} from '../../../shared/game/shardfile/shardProduct';
7
+ import type {WorldAssemblyStage} from '@wildshard/format/worldAssembly';
8
+
9
+ const restoredWalkBodies=new WeakSet<SimHost>();
10
+ /** The native restore transaction already owns its saved rope bodies/joints.
11
+ * Reinstalling their construction on the first framed request duplicates them.
12
+ * This fixture loan is allowed only while the real full restore is installing. */
13
+ export function retainRestoredWalkBodies(host:SimHost):void {
14
+ if(!isSimHostRestoring(host))throw new Error('Walk continuation requires a native restore transaction');
15
+ restoredWalkBodies.add(host);
16
+ }
17
+
18
+ /** Static native proof rows omit dynamic rope planks. Physics walks install
19
+ * the actual engine chain from the same admitted deck/chain stages as play.
20
+ * The chain consumes admitted rest poses, as RopeDeck.chainSpec does; its
21
+ * physics API has no terrain query. The model's separate analytic-ground
22
+ * admission remains in RopeDeckSite. No drawn or guessed deck enters Node. */
23
+ export function installWalkRopeBodies(host:SimHost,product:ShardProduct|undefined):()=>void {
24
+ const chains:RopeChain[]=[];
25
+ if(product?.has('client/plan')!==true)return ()=>{ /* No admitted rope inventory. */ };
26
+ const decks=new Map<string,Extract<WorldAssemblyStage,{kind:'rope-deck'}>>();
27
+ try {
28
+ for(const feature of product.section('client/plan').features){
29
+ if(feature.kind!=='world.assembly')continue;
30
+ for(const stage of feature.rows.stages){
31
+ if(stage.kind==='rope-deck'){
32
+ if(decks.has(stage.id))throw new Error('Duplicate native rope deck');decks.set(stage.id,stage);
33
+ }else if(stage.kind==='rope-chain'){
34
+ const deck=decks.get(stage.deck);if(deck===undefined)throw new Error('Native rope chain needs its declared deck');
35
+ const {span,site}=deck,rows=site.deck,key=JSON.stringify([span.a,span.b,span.width??rows.width,span.sag??rows.sag]);
36
+ const facts=site.spans.find(row=>row.key===key);if(facts===undefined)throw new Error('Unbaked native rope span');
37
+ if(facts.segments.length>rows.maxSegments)throw new Error('Native rope deck exceeds its segment bound');
38
+ if(restoredWalkBodies.has(host)){
39
+ const bodies=new Map<number,ReturnType<typeof host.physics.world.getRigidBody>>();
40
+ host.physics.world.forEachCollider(collider=>{
41
+ const tag=tagOf(collider),owner=tag?.owner,body=collider.parent();
42
+ if(tag?.material==='wood'&&owner!==null&&typeof owner==='object'&&'id' in owner&&'name' in owner
43
+ &&owner.id===rows.owner.id&&owner.name===rows.owner.name&&body?.isDynamic()===true)bodies.set(body.handle,body);
44
+ });
45
+ if(bodies.size!==facts.segments.length)throw new Error('Saved native rope chain differs from its admitted segment count');
46
+ // Rapier owns the saved bodies/joints; the motor's JS identity loan
47
+ // must be rebound to those exact bodies, without constructing any.
48
+ for(const body of bodies.values())rideable(body);
49
+ continue;
50
+ }
51
+ const copyOwner=()=>({...rows.owner});
52
+ const chain=new RopeChain(host.physics,{segments:structuredClone(facts.segments),hx:facts.width/2+rows.margin,hy:rows.halfY,mass:rows.mass,
53
+ owners:facts.segments.map(copyOwner)});chains.push(chain);
54
+ host.onStep(stage.capture,()=>{chain.capture();},undefined,'afterBodies');
55
+ }
56
+ }
57
+ }
58
+ }catch(error){for(const chain of chains)chain.dispose();throw error;}
59
+ return ()=>{for(const chain of chains)chain.dispose();};
60
+ }
@@ -0,0 +1,34 @@
1
+ // oxlint-disable-next-line import/no-unassigned-import -- Install portable Math before simulation modules.
2
+ import '../../../shared/engine/core/portableMathFirst';
3
+ // oxlint-disable-next-line import/no-nodejs-modules -- The isolated proof owns the native physics bytes.
4
+ import { readFileSync } from 'node:fs';
5
+ import * as v from 'valibot';
6
+ import { runTickWorker } from '../../../server/host/tickWorkerLoop';
7
+ import { parseShardfile } from '../../../shared/host/shardfile';
8
+ import { loadRapier } from '../../../shared/engine/physics/rapier';
9
+ import { prepareAssetDecoders, offlineMemoryAdmission } from '@wildshard/format/shardfileAssets';
10
+ import { validateShardfileAssets } from '@wildshard/format/assetAdmission';
11
+ import { scriptAdmissionRows } from '@wildshard/format/scriptContract';
12
+ import { hashImmutableBytes } from '../../../shared/host/immutable';
13
+ import { loadHeadlessProduct } from '../../../server/host/headlessProduct';
14
+ import { createShardProduct } from '../../../shared/game/shardfile/shardProduct';
15
+ import { createNativeProofAdapter } from '../headlessNative';
16
+ import type { PrepareHeadlessRuntime } from '../../../server/host/headlessRuntime';
17
+
18
+ await runTickWorker(async raw => {
19
+ const payload = v.parse(v.strictObject({ shard: v.unknown(), assets: v.map(v.string(), v.instance(Uint8Array)),
20
+ prepare: v.string(), directory: v.exactOptional(v.string()), binary: v.string(),
21
+ sections: v.map(v.string(), v.unknown()), snapshot: v.exactOptional(v.string()) }), raw);
22
+ const module = new URL(payload.prepare);
23
+ if (module.protocol !== 'file:') throw new Error('Native proof prepare module must be a file URL');
24
+ const shard = parseShardfile(payload.shard), rapier = await loadRapier(readFileSync(payload.binary));
25
+ await prepareAssetDecoders();
26
+ validateShardfileAssets(shard, payload.assets, hashImmutableBytes, offlineMemoryAdmission('refuse'), undefined, scriptAdmissionRows(payload.sections));
27
+ const loaded: {prepareHeadlessRuntime?: PrepareHeadlessRuntime} = await import(module.href);
28
+ if (typeof loaded.prepareHeadlessRuntime !== 'function') throw new Error('Native proof module needs prepareHeadlessRuntime');
29
+ const product = payload.directory === undefined
30
+ ? createShardProduct({ slug: shard.identity.slug, revision: shard.identity.revision, shardfile: shard, sections: payload.sections,
31
+ files: new Map(), read: () => Promise.reject(new Error('Inline native proof has no named files')) })
32
+ : await loadHeadlessProduct(payload.directory);
33
+ return createNativeProofAdapter({shard, assets: payload.assets, rapier, product}, loaded.prepareHeadlessRuntime, payload.snapshot);
34
+ });
@@ -0,0 +1,114 @@
1
+ // oxlint-disable-next-line import/no-unassigned-import -- The sim's Math goes in before any module body runs.
2
+ import '../../shared/engine/core/portableMathFirst';
3
+ import {createTrustedHeadlessTape} from '../../shared/host/headlessTape';
4
+ import { installNativeWalkBounds } from './headless/nativeBounds';
5
+ import { installWalkRopeBodies } from './headless/ropeBodies';
6
+ import { runHeadlessJourney } from '../../shared/host/headlessJourney';
7
+ import { fillNativeCombatFrame, headlessAssemblyPorts, validateHeadlessCommandOwners, type HeadlessRuntimeInput, type HeadlessRuntimeInstallation, type HeadlessRuntimePreparation, type HeadlessRuntimePlan, type PrepareHeadlessRuntime, type TrustedHeadlessResident } from '../../server/host/headlessRuntime';
8
+ import { prepareAssetDecoders } from '@wildshard/format/shardfileAssets';
9
+ import { loadHeadlessProduct } from '../../server/host/headlessProduct';
10
+ import { hasDeclaredClientPage } from '@wildshard/format/runtimeBinds';
11
+ import { prepareProductRuntimePlan } from '../../server/game/shardfile/nativePlan';
12
+ import { MoverScriptDriver, type MoverRuntime } from '../../server/game/plugin/mover';
13
+ import { installCableModes } from '../../shared/engine/player/modes';
14
+ import { createNativeCombatFrame } from '../../server/game/plugin/nativeItems';
15
+ import { createSimHost, type SimHost , type SimCommand } from '../../server/engine/sim';
16
+ import { createSimSnapshotSerializer, admitSimSnapshotBytes, decodeSimSnapshotBytes, snapshotSimHostBytes, type SimSnapshot, type SimSnapshotBytes } from '../../shared/engine/sim/snapshot';
17
+ import { restoreSimHost } from '../../server/engine/sim/restore';
18
+ import { simPlayerCommand, type HeadlessCommand, type HeadlessEffect } from '../../shared/host/tickProtocol';
19
+ import type { TickWorkerAdapter } from '../../server/host/tickWorkerLoop';
20
+ import { leadCommands, leadPlayer } from '@wildshard/engine/sim/leadPlayer';
21
+
22
+ /** The world a product's own native plan builds: what the tick worker runs, for proofs that wrap or drive it. */
23
+ export const prepareProductPlan: PrepareHeadlessRuntime = ({ product, assets, rapier }) => prepareProductRuntimePlan(product, assets, headlessAssemblyPorts(rapier));
24
+
25
+ /** Direct typed proof composition; no module URL, dynamic code lookup or authored factory selection. */
26
+ export async function prepareNativeProof(provided: HeadlessRuntimeInput, prepare: PrepareHeadlessRuntime): Promise<HeadlessRuntimePlan> {
27
+ if (!/^[a-z0-9][a-z0-9-]*$/u.test(provided.shard.identity.slug)) throw new Error('Invalid native product identity');
28
+ await prepareAssetDecoders();
29
+ const product=provided.product ?? await loadHeadlessProduct(`out/${provided.shard.identity.slug}`);
30
+ if(product.slug!==provided.shard.identity.slug || product.revision!==provided.shard.identity.revision) throw new Error('Native product and trusted identity differ');
31
+ const preparation: HeadlessRuntimePreparation={...provided,product};
32
+ const source=product.shardfile,plan=await prepare(preparation);
33
+ const identity = { id: source.identity.slug, seed: source.identity.seed };
34
+ if (plan.level.id !== identity.id || plan.level.seed !== identity.seed) throw new Error('Trusted runtime simulation identity mismatch');
35
+ return { ...plan, install: (host, context) => {
36
+ installCableModes(host.scope, source.modes?.traverse ?? [], host.flags).bindNative(host);
37
+ const carried = source.runtime?.binds?.includes('movers') === true || hasDeclaredClientPage(source)
38
+ ? source.movers.filter(row => row.carry !== undefined) : [];
39
+ if (carried.length > 0) {
40
+ let motion: MoverRuntime | null = null;
41
+ host.onStep('movers.commands', () => {
42
+ if (motion === null) throw new Error('Missing installed mover owner');
43
+ for (const command of context.commands()) if (command.kind === 'script' && carried.some(row => row.id === command.actorId)) {
44
+ if (command.value !== 1 && command.value !== 2) throw new Error('Invalid mover ride command');
45
+ motion.command(command.actorId, command.value);
46
+ }
47
+ });
48
+ motion = new MoverScriptDriver(carried, host).install(host, { content: { identity: source.identity,
49
+ sim: { ...source.sim, bindings: [] }, state: source.state }, assets: new Map(),
50
+ rules: { fields: {}, archetypes: [], events: [], maxEntities: 32 } },
51
+ { id: 'movers.carried', restoring: context.restoring, restoreFlags: new Set(host.flags.all), drive: true });
52
+ }
53
+ plan.install(host, context);
54
+ } };
55
+ }
56
+
57
+ /** Keep the native transaction, restore and tick fences in the direct gameplay proof. */
58
+ export async function createNativeProofResident(preparation: HeadlessRuntimeInput, prepare: PrepareHeadlessRuntime, snapshot?: string | Readonly<SimSnapshot | SimSnapshotBytes>): Promise<TrustedHeadlessResident> {
59
+ const plan = await prepareNativeProof(preparation, prepare);
60
+ let commands: readonly HeadlessCommand[] = [], effects: HeadlessEffect[] = [];
61
+ const saved = snapshot === undefined ? undefined : typeof snapshot === 'string' ? decodeSimSnapshotBytes(snapshot) : admitSimSnapshotBytes(snapshot);
62
+ const combat = createNativeCombatFrame();
63
+ const context: HeadlessRuntimeInstallation = { combat, restoring: saved !== undefined, ...(saved === undefined ? {} : { snapshot: saved }), commands: () => commands, emit: effect => { effects.push(effect); } };
64
+ const ports = { ...plan.ports, rapier: preparation.rapier };
65
+ let installing: SimHost | undefined;
66
+ let host: SimHost;
67
+ try {
68
+ if (saved === undefined) { installing = createSimHost(plan.level, ports); plan.install(installing, context); host = installing; }
69
+ else host = restoreSimHost(plan.level, ports, saved, fresh => {
70
+ installing = fresh; if (ports.heightAt !== undefined) fresh.setHeightQuery(ports.heightAt); plan.install(fresh, context);
71
+ });
72
+ if (effects.length > 0) throw new Error('Trusted runtime emitted gameplay effects during installation');
73
+ } catch (error) { installing?.dispose(); throw error; }
74
+ const lend = (input: readonly HeadlessCommand[]): void => {
75
+ validateHeadlessCommandOwners(host,input);
76
+ fillNativeCombatFrame(combat, input); commands = input; effects = []; };
77
+ return {
78
+ host, lend,
79
+ // A recorder holds no room, and a fact is a room's.
80
+ fact: () => undefined,
81
+ get effects() { return effects; },
82
+ step: input => {
83
+ lend(input);
84
+ let player: SimCommand | undefined;
85
+ for (const command of input) if (command.kind === 'player') player = simPlayerCommand(command);
86
+ host.step(leadCommands(host, player));
87
+ if (![leadPlayer(host).position, ...[...host.entities.values()].map(entity => entity.position)].every(point => [point.x, point.y, point.z].every(Number.isFinite))) throw new Error('Nonfinite trusted simulation state');
88
+ },
89
+ proveEntries: () => {
90
+ if (plan.proveEntries === undefined) throw new Error('Trusted runtime has no entry proof');
91
+ return plan.proveEntries(host);
92
+ },
93
+ dispose: () => { host.dispose(); },
94
+ };
95
+ }
96
+ /** Worker-side composition only: owns one trusted resident (its real SimHost, native continuation and scoped installers). */
97
+ export async function createNativeProofAdapter(preparation: HeadlessRuntimeInput, prepare: PrepareHeadlessRuntime, snapshot?: string): Promise<TickWorkerAdapter> {
98
+ const resident = await createNativeProofResident(preparation, prepare, snapshot), { host } = resident;
99
+ const serializer=createSimSnapshotSerializer();
100
+ const tape=createTrustedHeadlessTape(host,input=>resident.step(input),()=>resident.effects);
101
+ let retireWalkBodies=()=>{/* No temporary walk bodies exist before preparation. */},walkPrepared=false;
102
+ const prepareWalk=():void=>{
103
+ if(walkPrepared)return;
104
+ retireWalkBodies=installWalkRopeBodies(host,preparation.product);installNativeWalkBounds(host);walkPrepared=true;
105
+ };
106
+ return {
107
+ step: input => { resident.step(input); },
108
+ verbTape:plan=>{if(plan.segments.some(segment=>segment.route!==undefined||segment.frames!==undefined))prepareWalk();return tape(plan);},
109
+ journey: plan => { if(plan.start!==undefined)prepareWalk();return runHeadlessJourney(host,input=>resident.step(input),plan); },
110
+ commit: () => ({ tick: host.state.tick, snapshot: serializer.serialize(snapshotSimHostBytes(host)), effects: [...resident.effects] }),
111
+ finish: () => ({ ticks: host.state.tick, lanes: 0, steps: 0 }),
112
+ dispose: () => { try { retireWalkBodies();resident.dispose(); } finally { serializer.dispose(); } },
113
+ };
114
+ }
@@ -0,0 +1,43 @@
1
+ // oxlint-disable-next-line import/no-unassigned-import -- Install portable Math before simulation modules.
2
+ import '../../shared/engine/core/portableMathFirst';
3
+ // oxlint-disable-next-line import/no-nodejs-modules -- Locate the packaged loader and physics dependency, independently of the consumer's cwd.
4
+ import { createRequire, flushCompileCache } from 'node:module';
5
+ import { TickWorkerHost } from '../../server/host/tickWorkerHost';
6
+ import type { Shardfile } from '../../shared/host/shardfile';
7
+ import { headlessSections } from '../../shared/host/headlessSections';
8
+ import { outputDescriptor } from '../../shared/game/shardfile/outputDescriptor';
9
+ import { validateShardfileAssets } from '@wildshard/format/assetAdmission';
10
+ import { offlineMemoryAdmission, prepareAssetDecoders } from '@wildshard/format/shardfileAssets';
11
+ import { scriptAdmissionRows } from '@wildshard/format/scriptContract';
12
+ import { hashImmutableBytes } from '../../shared/host/immutable';
13
+
14
+ export interface NativeProofWorkerOptions {
15
+ snapshot?: string;
16
+ sections?: ReadonlyMap<string, unknown>;
17
+ /** A checked consumer build; omit only for an inline proof with no named files. */
18
+ directory?: string;
19
+ binary?: string;
20
+ }
21
+
22
+ /** Trusted Node proofs choose their own prepareHeadlessRuntime module. This is
23
+ * executable test code, never a URL supplied by a shardfile or a gameplay command. */
24
+ export async function createNativeProofWorker(shard: Shardfile, assets: ReadonlyMap<string, Uint8Array>, prepare: URL,
25
+ options: NativeProofWorkerOptions = {}): Promise<TickWorkerHost> {
26
+ if (prepare.protocol !== 'file:') throw new Error('Native proof prepare module must be a file URL');
27
+ const sections = headlessSections(options.sections ?? outputDescriptor(shard)?.sections);
28
+ const binary = options.binary ?? createRequire(import.meta.url).resolve('@dimforge/rapier3d-simd/rapier_wasm3d_bg.wasm');
29
+ flushCompileCache();
30
+ const worker = new TickWorkerHost(new URL('./headless/worker.ts', import.meta.url), undefined,
31
+ shard.serverBudget, ['--experimental-transform-types', '--import', new URL('../../../scripts/sim-node-loader.mjs', import.meta.url).href], 'advisory', async () => {
32
+ await prepareAssetDecoders();
33
+ validateShardfileAssets(shard, assets, hashImmutableBytes, offlineMemoryAdmission('refuse'), undefined, scriptAdmissionRows(sections));
34
+ const admitted = new Map<string, Uint8Array>();
35
+ for (const hash of [...shard.files.map(file => file.hash), ...shard.requires.commons.map(identity => `commons:${identity}`)]) {
36
+ const bytes = assets.get(hash); if (bytes === undefined) throw new Error('Missing admitted worker bytes'); admitted.set(hash, bytes);
37
+ }
38
+ return {shard, assets: admitted, prepare: prepare.href, sections, binary,
39
+ ...(options.directory === undefined ? {} : {directory: options.directory}),
40
+ ...(options.snapshot === undefined ? {} : {snapshot: options.snapshot})};
41
+ });
42
+ try { await worker.initialized(); return worker; } catch (error) { await worker.dispose(); throw error; }
43
+ }
@@ -16,6 +16,9 @@
16
16
  "references": [
17
17
  {
18
18
  "path": "../../tsconfig.game.json"
19
+ },
20
+ {
21
+ "path": "../../tsconfig.host.json"
19
22
  }
20
23
  ],
21
24
  "include": [