@wildshard/dev 0.0.0 → 0.4.0

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 (139) hide show
  1. package/bin/wildshard.mjs +75 -0
  2. package/lint/host-callbacks.d.mts +6 -0
  3. package/lint/host-callbacks.mjs +123 -0
  4. package/lint/ratchet.json +3 -0
  5. package/package.json +95 -4
  6. package/scripts/audit-assets.d.mts +10 -0
  7. package/scripts/audit-assets.mjs +151 -0
  8. package/scripts/bake/coatFiles.d.mts +6 -0
  9. package/scripts/bake/coatFiles.mjs +37 -0
  10. package/scripts/bake/navmeshGround.ts +22 -0
  11. package/scripts/bake/near-placeholder.mjs +331 -0
  12. package/scripts/bake/viewmodelBytes.ts +26 -0
  13. package/scripts/bake/viewmodelPage.ts +11 -0
  14. package/scripts/bake-catalogue.mjs +44 -0
  15. package/scripts/bake-check.mjs +54 -0
  16. package/scripts/bake-chunk.mjs +124 -0
  17. package/scripts/bake-cloud-field.mjs +24 -0
  18. package/scripts/bake-coats.mjs +110 -0
  19. package/scripts/bake-data-maps.d.mts +24 -0
  20. package/scripts/bake-data-maps.mjs +78 -0
  21. package/scripts/bake-entry-programs.mjs +126 -0
  22. package/scripts/bake-geometry.mjs +106 -0
  23. package/scripts/bake-ktx2.mjs +477 -0
  24. package/scripts/bake-map-glb.mjs +127 -0
  25. package/scripts/bake-map-rest.d.mts +7 -0
  26. package/scripts/bake-map-rest.mjs +50 -0
  27. package/scripts/bake-maps.mjs +200 -0
  28. package/scripts/bake-navmesh.mjs +259 -0
  29. package/scripts/bake-packs.mjs +129 -0
  30. package/scripts/bake-pickups.mjs +102 -0
  31. package/scripts/bake-query-terrain.mjs +64 -0
  32. package/scripts/bake-textures.mjs +80 -0
  33. package/scripts/bake-viewmodel-sets.mjs +137 -0
  34. package/scripts/bake-voxel-ao.mjs +119 -0
  35. package/scripts/bake-water-ripples.mjs +25 -0
  36. package/scripts/browser-imports.d.mts +2 -0
  37. package/scripts/browser-imports.mjs +40 -0
  38. package/scripts/browser-machine-loader-proof.mjs +39 -0
  39. package/scripts/browser-machine-loader.d.mts +8 -0
  40. package/scripts/browser-machine-loader.mjs +87 -0
  41. package/scripts/browser-playwright.d.mts +10 -0
  42. package/scripts/browser-playwright.mjs +5 -0
  43. package/scripts/browser-test.d.mts +4 -0
  44. package/scripts/browser-test.mjs +18 -0
  45. package/scripts/build-sdk.mjs +95 -0
  46. package/scripts/build-shardfiles.d.mts +7 -0
  47. package/scripts/build-shardfiles.mjs +230 -0
  48. package/scripts/capture-hero.mjs +211 -0
  49. package/scripts/chromium-keychain.d.mts +1 -0
  50. package/scripts/chromium-keychain.mjs +7 -0
  51. package/scripts/entry-reads/crawl.ts +152 -0
  52. package/scripts/gen-host-catalogue.d.mts +14 -0
  53. package/scripts/gen-host-catalogue.mjs +108 -0
  54. package/scripts/gen-shards.d.mts +17 -0
  55. package/scripts/gen-shards.mjs +311 -0
  56. package/scripts/goldens/plot-inputs.d.mts +12 -0
  57. package/scripts/goldens/plot-inputs.mjs +46 -0
  58. package/scripts/gpu-texmem.mjs +98 -0
  59. package/scripts/ktx2-ab.mjs +111 -0
  60. package/scripts/map-bake-frames.d.mts +4 -0
  61. package/scripts/map-bake-frames.mjs +23 -0
  62. package/scripts/map-world.mjs +162 -0
  63. package/scripts/memory-product.mjs +62 -0
  64. package/scripts/music/export-midi.mjs +69 -0
  65. package/scripts/named-blob-output.d.mts +8 -0
  66. package/scripts/named-blob-output.mjs +48 -0
  67. package/scripts/practice/verify_unimate_skin.mjs +356 -0
  68. package/scripts/preparation-browser.mjs +25 -0
  69. package/scripts/preparation-seed.mjs +15 -0
  70. package/scripts/prepare-product.d.mts +14 -0
  71. package/scripts/prepare-product.mjs +133 -0
  72. package/scripts/prove-walk.mjs +83 -0
  73. package/scripts/push-tables.d.mts +1 -0
  74. package/scripts/push-tables.mjs +28 -0
  75. package/scripts/record-shard-mounts.mjs +133 -0
  76. package/scripts/section-inventory.ts +209 -0
  77. package/scripts/shard-build-pool.d.mts +4 -0
  78. package/scripts/shard-build-pool.mjs +53 -0
  79. package/scripts/shard-milestones.d.mts +15 -0
  80. package/scripts/shard-milestones.mjs +105 -0
  81. package/scripts/shard-progress.mjs +212 -0
  82. package/scripts/shardfile-cold-boot.mjs +79 -0
  83. package/scripts/shardfile-rolldown.d.mts +2 -0
  84. package/scripts/shardfile-rolldown.mjs +32 -0
  85. package/scripts/shardfile-vite.d.mts +4 -0
  86. package/scripts/shardfile-vite.mjs +20 -0
  87. package/scripts/site-facts.mjs +88 -0
  88. package/scripts/test-template-gate.mjs +44 -0
  89. package/scripts/tex-tiers.mjs +240 -0
  90. package/scripts/unused-assets.mjs +173 -0
  91. package/scripts/wildshard.d.mts +4 -0
  92. package/scripts/wildshard.mjs +146 -0
  93. package/scripts/witness-generation.d.mts +10 -0
  94. package/scripts/witness-generation.mjs +45 -0
  95. package/src/.oxlintrc.json +12 -0
  96. package/src/cli/bin.mjs +8 -0
  97. package/src/cli/content-command.ts +44 -0
  98. package/src/cli/content.ts +287 -0
  99. package/src/cli/grid/command.ts +48 -0
  100. package/src/cli/grid/grid.ts +155 -0
  101. package/src/cli/help.ts +262 -0
  102. package/src/cli/hero/adopt.ts +109 -0
  103. package/src/cli/install-home.ts +40 -0
  104. package/src/cli/main.ts +142 -0
  105. package/src/cli/version.ts +63 -0
  106. package/src/server/app.ts +19 -0
  107. package/src/server/serve.ts +49 -0
  108. package/src/sharddev/bake/json.mjs +84 -0
  109. package/src/sharddev/bake/mapRest.ts +57 -0
  110. package/src/sharddev/bake/nativeRaster.ts +106 -0
  111. package/src/sharddev/bake/source-loader.mjs +55 -0
  112. package/src/sharddev/bake/splatLayers.ts +29 -0
  113. package/src/sharddev/bootInventory.ts +132 -0
  114. package/src/sharddev/check.ts +125 -0
  115. package/src/sharddev/checkProject.ts +134 -0
  116. package/src/sharddev/cli.ts +207 -0
  117. package/src/sharddev/dev.ts +150 -0
  118. package/src/sharddev/devClient.ts +120 -0
  119. package/src/sharddev/devRoot.ts +6 -0
  120. package/src/sharddev/engineMusic.ts +23 -0
  121. package/src/sharddev/projectEntryProof.ts +32 -0
  122. package/src/sharddev/test/diskScriptScenario.ts +88 -0
  123. package/src/sharddev/test/scriptScenario.ts +254 -0
  124. package/src/sharddev/tsconfig.json +3 -0
  125. package/src/sharddev/watch/page.ts +288 -0
  126. package/src/sharddev/watch/pageEntry.ts +44 -0
  127. package/src/sharddev/watch/parity-baseline.json +22 -0
  128. package/src/sharddev/watch/parity.mjs +194 -0
  129. package/src/sharddev/watch/proof.mjs +199 -0
  130. package/src/sharddev/watch/socket.ts +57 -0
  131. package/src/sharddev/watch/watch.ts +382 -0
  132. package/src/shared/health.ts +10 -0
  133. package/src/tools/build-web.ts +59 -0
  134. package/src/web/app.tsx +53 -0
  135. package/src/web/index.html +12 -0
  136. package/src/web/main.tsx +10 -0
  137. package/tsconfig.author.json +25 -0
  138. package/tsconfig.json +47 -0
  139. package/README.md +0 -3
@@ -0,0 +1,120 @@
1
+ // SD-2 (meta HOW-WE-BUILD-PLAN, SHARD-AUTHORING SA15, J314): an installed `wildshard dev` serves engine's devserver client,
2
+ // the normal game page compiled in devserver mode. The package can't build it (it is engine's whole app build), so engine
3
+ // publishes it on the GitHub release of every tag (ENG-16: `scripts/devserver-client.mjs`, server-release.yml) and this
4
+ // fetches it once per engine pin into the user's cache.
5
+ // oxlint-disable-next-line import/no-nodejs-modules -- The author tool downloads and unpacks one archive into its cache.
6
+ import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
7
+ // oxlint-disable-next-line import/no-nodejs-modules -- `tar` unpacks the archive, as on every author machine.
8
+ import { execFileSync } from 'node:child_process';
9
+ // oxlint-disable-next-line import/no-nodejs-modules -- The default cache is under the user's home.
10
+ import { homedir } from 'node:os';
11
+ // oxlint-disable-next-line import/no-nodejs-modules -- Cache paths.
12
+ import { join, resolve } from 'node:path';
13
+
14
+ /** The release asset engine's `scripts/devserver-client.mjs` writes. */
15
+ export const DEV_CLIENT_ASSET = 'devserver-client.tar.gz';
16
+ /** SA43: the preparation client, `scripts/devserver-client.mjs --kind preparation`: engine's production build made with
17
+ * `WILDSHARD_PREPARATION_ONLY=1`, which `wildshard prepare` serves with the author's draft inline. */
18
+ export const PREPARATION_CLIENT_ASSET = 'preparation-client.tar.gz';
19
+ const RELEASES = 'https://github.com/project-wildshard/engine/releases/download';
20
+
21
+ /** The engine release that holds the client for this package's engine pin: a commit pin (a green main build) is its
22
+ * `server-staging-<sha>` release, a version pin is its `v<version>` tag. */
23
+ export function devClientTag(pin: string): string {
24
+ const commit = /#([0-9a-f]{40})$/u.exec(pin)?.[1];
25
+ if (commit !== undefined) return `server-staging-${commit}`;
26
+ const version = /^[~^]?(\d+\.\d+\.\d+)$/u.exec(pin)?.[1];
27
+ if (version !== undefined) return `v${version}`;
28
+ throw new Error(`wildshard: the engine pin ${pin} names no release (a 40-character commit or an exact version)`);
29
+ }
30
+
31
+ /** This package's engine pin, from its own package.json. */
32
+ export function enginePin(): string {
33
+ const manifest: unknown = JSON.parse(readFileSync(resolve(import.meta.dirname, '../../package.json'), 'utf8'));
34
+ const pin: unknown = typeof manifest === 'object' && manifest !== null && 'dependencies' in manifest && typeof manifest.dependencies === 'object' && manifest.dependencies !== null
35
+ ? (manifest.dependencies as Record<string, unknown>)['@wildshard/engine'] : undefined;
36
+ if (typeof pin !== 'string') throw new Error('wildshard dev: this package names no @wildshard/engine dependency');
37
+ return pin;
38
+ }
39
+
40
+ /** `$WILDSHARD_DEV_CLIENT_CACHE`, else `$XDG_CACHE_HOME/wildshard/dev-client`, else `~/.cache/wildshard/dev-client`. */
41
+ export function devClientCache(): string {
42
+ const env = process.env['WILDSHARD_DEV_CLIENT_CACHE'];
43
+ if (env !== undefined && env !== '') return env;
44
+ const xdg = process.env['XDG_CACHE_HOME'];
45
+ return join(xdg !== undefined && xdg !== '' ? xdg : join(homedir(), '.cache'), 'wildshard', 'dev-client');
46
+ }
47
+
48
+ function assertDevserver(folder: string): void {
49
+ if (!existsSync(join(folder, 'index.html'))) throw new Error(`wildshard dev: the dev client has no index.html (${folder})`);
50
+ const flags: unknown = JSON.parse(readFileSync(join(folder, 'build-flags.json'), 'utf8'));
51
+ if (typeof flags !== 'object' || flags === null || !('devserver' in flags) || flags.devserver !== true) throw new Error('wildshard dev: the dev client was not compiled in devserver mode');
52
+ }
53
+
54
+ /** The client `wildshard dev` serves: `$WILDSHARD_DEV_CLIENT` (a folder, such as an engine checkout's devserver build), a
55
+ * client packed into this package (`client-devserver` beside the author tools), else engine's release at the pin. */
56
+ export function devClient(): Promise<string> {
57
+ const named = process.env['WILDSHARD_DEV_CLIENT'];
58
+ if (named !== undefined && named !== '') { const folder = resolve(named); assertDevserver(folder); return Promise.resolve(folder); }
59
+ const packed = [resolve(import.meta.dirname, 'client-devserver'), resolve(import.meta.dirname, 'dist', 'client-devserver')].find((path) => existsSync(join(path, 'index.html')));
60
+ return packed === undefined ? fetchDevClient() : Promise.resolve(packed);
61
+ }
62
+
63
+ /** SA43: a preparation client is a production build (DEVSERVER off) whose version document says preparation-only. */
64
+ function assertPreparation(folder: string): void {
65
+ if (!existsSync(join(folder, 'index.html'))) throw new Error(`wildshard prepare: the preparation client has no index.html (${folder})`);
66
+ const read = (name: string): unknown => existsSync(join(folder, name)) ? JSON.parse(readFileSync(join(folder, name), 'utf8')) : null;
67
+ const flags = read('build-flags.json'), version = read('version.json');
68
+ if (typeof flags !== 'object' || flags === null || !('devserver' in flags) || flags.devserver !== false
69
+ || typeof version !== 'object' || version === null || !('preparationOnly' in version) || version.preparationOnly !== true) {
70
+ throw new Error('wildshard prepare: the preparation client is not a preparation-only production build');
71
+ }
72
+ }
73
+
74
+ /** The client `wildshard prepare` serves: `$WILDSHARD_PREPARATION_CLIENT` (a folder, such as an engine checkout's
75
+ * `devserver-client.mjs --kind preparation --keep <folder>`), else engine's release at this package's pin. */
76
+ export function preparationClient(): Promise<string> {
77
+ const named = process.env['WILDSHARD_PREPARATION_CLIENT'];
78
+ if (named !== undefined && named !== '') { const folder = resolve(named); assertPreparation(folder); return Promise.resolve(folder); }
79
+ return fetchPreparationClient();
80
+ }
81
+
82
+ /** The unpacked preparation client for `pin`, fetched on first use beside the dev client (`<tag>-preparation`). `url`
83
+ * replaces the GitHub download (`$WILDSHARD_PREPARATION_CLIENT_URL`). */
84
+ export function fetchPreparationClient(options: { pin?: string; cache?: string; url?: string } = {}): Promise<string> {
85
+ return fetchClient({ ...options, url: options.url ?? process.env['WILDSHARD_PREPARATION_CLIENT_URL'] }, {
86
+ asset: PREPARATION_CLIENT_ASSET, suffix: '-preparation', verb: 'prepare', label: 'preparation client', check: assertPreparation });
87
+ }
88
+
89
+ /** The unpacked client folder for `pin`, fetched on first use. `url` replaces the GitHub download (tests, mirrors:
90
+ * `$WILDSHARD_DEV_CLIENT_URL`). A failed or refused download keeps nothing. */
91
+ export function fetchDevClient(options: { pin?: string; cache?: string; url?: string } = {}): Promise<string> {
92
+ return fetchClient({ ...options, url: options.url ?? process.env['WILDSHARD_DEV_CLIENT_URL'] }, {
93
+ asset: DEV_CLIENT_ASSET, suffix: '', verb: 'dev', label: 'dev client', check: assertDevserver });
94
+ }
95
+
96
+ interface ClientAsset { asset: string; suffix: string; verb: string; label: string; check: (folder: string) => void }
97
+ async function fetchClient(options: { pin?: string; cache?: string; url?: string | undefined }, kind: ClientAsset): Promise<string> {
98
+ const tag = devClientTag(options.pin ?? enginePin()), cache = options.cache ?? devClientCache(), folder = join(cache, `${tag}${kind.suffix}`);
99
+ if (existsSync(join(folder, 'index.html'))) return folder;
100
+ const url = options.url ?? `${RELEASES}/${tag}/${kind.asset}`;
101
+ // prepare prints its result as JSON on stdout, so its progress goes to stderr
102
+ const progress = kind.verb === 'prepare' ? console.error : console.info;
103
+ progress(`wildshard ${kind.verb}: fetching engine's ${kind.label} (${tag}) once, into ${cache}`);
104
+ const response = await fetch(url);
105
+ if (!response.ok) throw new Error(`wildshard ${kind.verb}: engine release ${tag} has no ${kind.asset} (${url}: ${String(response.status)})`);
106
+ const announced = Number(response.headers.get('content-length'));
107
+ if (Number.isSafeInteger(announced) && announced > 0) progress(`wildshard ${kind.verb}: downloading ${(announced / 1e6).toFixed(1)} MB (first use only)`);
108
+ const bytes = Buffer.from(await response.arrayBuffer());
109
+ mkdirSync(cache, { recursive: true });
110
+ const part = join(cache, `${tag}${kind.suffix}.part-${String(process.pid)}`), archive = `${part}.tar.gz`;
111
+ rmSync(part, { recursive: true, force: true }); mkdirSync(part);
112
+ try {
113
+ writeFileSync(archive, bytes);
114
+ execFileSync('tar', ['-xzf', archive, '-C', part]);
115
+ kind.check(part);
116
+ if (!existsSync(join(folder, 'index.html'))) { rmSync(folder, { recursive: true, force: true }); renameSync(part, folder); }
117
+ } finally { rmSync(part, { recursive: true, force: true }); rmSync(archive, { force: true }); }
118
+ progress(`wildshard ${kind.verb}: engine's ${kind.label} ${tag}, ${(bytes.length / 1e6).toFixed(1)} MB`);
119
+ return folder;
120
+ }
@@ -0,0 +1,6 @@
1
+ // SDK-SPLIT SP8c: @wildshard/dev's root. A top-level file, so the bundled CLI (which gives every module of a package its
2
+ // package's src/sharddev as import.meta.dirname) and an unbundled run agree; a file in a subfolder imports this.
3
+ // oxlint-disable-next-line import/no-nodejs-modules -- the package root is a filesystem path.
4
+ import { resolve } from 'node:path';
5
+
6
+ export const DEV_ROOT: string = resolve(import.meta.dirname, '../..');
@@ -0,0 +1,23 @@
1
+ import { ENGINE_MUSIC_STYLE, engineMusicFiles, musicDir } from '@wildshard/engine/audio/bootAudio';
2
+ import { withAssetTables, type AssetTables } from '@wildshard/engine/boot/tables';
3
+ import { MUSIC_MANIFESTS, SFX_MANIFESTS } from '@wildshard/engine/game/boot/audio.generated';
4
+ import { PUBLIC_BYTES } from '@wildshard/engine/game/boot/bytes.generated';
5
+ import { ASSET_VERSIONS } from '@wildshard/engine/game/boot/versions.generated';
6
+ import { PACKS } from '@wildshard/engine/game/boot/packs.generated';
7
+ import type { AudioData } from '@wildshard/format/audio';
8
+
9
+ /** The engine's own boot tables, as the page installs them: which engine music ships, and each file's bytes. */
10
+ export const ENGINE_TABLES: AssetTables = { bytes: PUBLIC_BYTES, versions: ASSET_VERSIONS, music: MUSIC_MANIFESTS, sfx: SFX_MANIFESTS, packs: PACKS };
11
+
12
+ /** AUDIO AU18: the build log's line for the engine music a shard plays, derived from its `audio/audio` rows by name,
13
+ * in the engine cook's `engineMusicLine` format. Undefined when the shard has no audio section. Throws, naming each,
14
+ * when the rows name engine music this engine's style lacks. */
15
+ export function engineMusicLine(shard: string, section: unknown, tables: AssetTables = ENGINE_TABLES): string | undefined {
16
+ if (typeof section !== 'object' || section === null || !('audio' in section)) return undefined;
17
+ const data = section.audio as AudioData, dir = musicDir(ENGINE_MUSIC_STYLE);
18
+ let files: string[];
19
+ try { files = withAssetTables(tables, () => engineMusicFiles(data)); }
20
+ catch (error) { throw new Error(`${shard}: ${error instanceof Error ? error.message : String(error)}`, { cause: error }); }
21
+ const bytes = files.reduce((sum, url) => sum + (tables.bytes[url] ?? 0), 0);
22
+ return `${shard}: engine music: ${files.length} files, ${(bytes / 1e6).toFixed(2)} MB${files.length === 0 ? '' : ` (${files.map(url => url.slice(dir.length)).join(', ')})`}`;
23
+ }
@@ -0,0 +1,32 @@
1
+ // oxlint-disable-next-line import/no-nodejs-modules -- Resolve only the SDK's installed native physics binary, never author-selected files.
2
+ import { createRequire } from 'node:module';
3
+ // oxlint-disable-next-line import/no-nodejs-modules -- The fixed package binary is adjacent to its installed entry.
4
+ import { resolve } from 'node:path';
5
+ import { loadRapier } from '@wildshard/engine/physics/rapier';
6
+ import { Physics } from '@wildshard/engine/physics/Physics';
7
+ import { addBakedPieces } from '@wildshard/engine/game/plugin/simulation';
8
+ import { proveEntryways } from '@wildshard/engine/game/bake/entryways';
9
+ import { readBoundedFile } from '@wildshard/sdk/sourceReader';
10
+ import { parseShardfile, type Shardfile } from '@wildshard/format/shardSchema';
11
+
12
+ /** Actual static capsule walks and transfers, never a caller-supplied receipt. */
13
+ export interface StaticPortalEntryProof { readonly lanes: number; readonly steps: number; readonly portalTransfers: number }
14
+
15
+ /** Fresh build-only proof. Dynamic movers and ordinary edge entries require their existing world-specific proofs. */
16
+ export async function proveStaticPortalEntries(input: Shardfile, pieces: unknown): Promise<StaticPortalEntryProof> {
17
+ const source = parseShardfile(input);
18
+ if (source.entryways.length === 0 || source.entryways.some(entry => entry.kind !== 'portalLink')) {
19
+ throw new Error('Static portal proof requires only declared portal links');
20
+ }
21
+ const require = createRequire(resolve(import.meta.dirname, 'package.json'));
22
+ const binary = require.resolve('@dimforge/rapier3d-simd/rapier_wasm3d_bg.wasm');
23
+ const physics = new Physics(await loadRapier(readBoundedFile(binary, 25_000_000).slice()));
24
+ try {
25
+ addBakedPieces(physics, pieces); physics.step();
26
+ const proof = proveEntryways(source, new Map(), { world: () => ({ physics,
27
+ fixedStep: () => { /* Static portal entries have no moving owner. */ },
28
+ dispose: () => { /* This operation owns the single physics world. */ } }) });
29
+ if (proof.portalTransfers === undefined) throw new Error('Static portal proof produced no transfer evidence');
30
+ return { lanes: proof.lanes, steps: proof.steps, portalTransfers: proof.portalTransfers };
31
+ } finally { physics.dispose(); }
32
+ }
@@ -0,0 +1,88 @@
1
+ // oxlint-disable-next-line import/no-nodejs-modules -- The author-only scenario consumes published disk output.
2
+ import { existsSync, realpathSync } from 'node:fs';
3
+ // oxlint-disable-next-line import/no-nodejs-modules -- A validated output folder stays inside the explicit product root.
4
+ import { resolve } from 'node:path';
5
+ import { DecisionHost, type DecisionScript } from '@wildshard/engine/script/decision';
6
+ import { nativeRuntimeActorIds } from '@wildshard/format/nativeRuntimePlan';
7
+ import { buildDecisionRegistries, decisionBindingMap, decisionSpawnGroups } from '@wildshard/format/decisionBindings';
8
+ import { parseActorMoves } from '@wildshard/format/actorMoves';
9
+ import { readCreatureStrikes } from '@wildshard/format/creatures';
10
+ import { parseWorldTargets } from '@wildshard/format/worldTargets';
11
+ import { admitScriptContract, decisionScriptsFromSections } from '@wildshard/format/scriptContract';
12
+ import { SCRIPT_V1_READS, SCRIPT_V1_LISTS, type ScriptV1ReadName, type ScriptV1ListName } from '@wildshard/format/scriptAbiV1';
13
+ import { outputDescriptor } from '@wildshard/engine/game/shardfile/outputDescriptor';
14
+ import { loadHeadlessFolder } from '@wildshard/engine/host/headlessFolder';
15
+ import { createScriptScenario, type ScenarioActor, type DiskScenarioOptions, type DiskScriptScenario } from './scriptScenario';
16
+
17
+ /** Disk admission and the game use the same defining catalogue; the fixture never allocates actor ids. */
18
+ export async function readDiskScriptScenario(slug: string, id: string, options: DiskScenarioOptions): Promise<DiskScriptScenario> {
19
+ if (!/^_?[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(slug)) throw new Error('Invalid scenario output folder');
20
+ if (options.products !== undefined && options.productDirectory !== undefined) throw new Error('Scenario requires one product location');
21
+ const root = resolve(options.products ?? 'out'), directory = options.productDirectory === undefined ? resolve(root, slug) : resolve(options.productDirectory);
22
+ if (!existsSync(resolve(directory, 'shard.json'))) throw new Error(`Missing published scenario output ${slug}; run wildshard build first`);
23
+ const expected = options.productDirectory === undefined ? resolve(realpathSync(root), slug) : directory;
24
+ if (realpathSync(directory) !== expected) throw new Error('Scenario output cannot be a symlink');
25
+ const product = await loadHeadlessFolder(directory), shard = product.shardfile, descriptor = outputDescriptor(shard);
26
+ if (descriptor === undefined) throw new Error('Missing admitted scenario descriptor');
27
+ const { index, sections } = descriptor;
28
+ const rows = decisionScriptsFromSections(sections);
29
+ const row = rows.find(value => value.id === id), ordinal = rows.findIndex(value => value.id === id);
30
+ if (row === undefined) throw new Error(`Missing simulation scenario script ${id}`);
31
+ if (row.side !== 'sim') throw new Error('Scenario script must run on simulation side');
32
+ const moves = parseActorMoves(sections.get('actors/moves') ?? []), targets = sections.get('world/targets');
33
+ const nativePlan = sections.get('sim/runtime-plan');
34
+ const nativeActors = shard.runtime === null && nativePlan !== undefined ? nativeRuntimeActorIds(nativePlan) : [];
35
+ const registries = buildDecisionRegistries(shard, moves, targets === undefined ? undefined : parseWorldTargets(targets), readCreatureStrikes(sections.get('actors/strikes') ?? []), rows, nativeActors);
36
+ const map = decisionBindingMap(row, registries), handles = Object.values(map.ids.actors ?? {});
37
+ const script: DecisionScript = { ...row, side: row.side, ids: map.ids, state: [...row.state], reads: row.reads.filter((name): name is ScriptV1ReadName => Object.hasOwn(SCRIPT_V1_READS, name)),
38
+ lists: row.reads.filter((name): name is ScriptV1ListName => Object.hasOwn(SCRIPT_V1_LISTS, name)) };
39
+ const file = index.files.find(value => value.kind === 'wasm' && value.path === row.module);
40
+ if (file?.name === undefined) throw new Error('Scenario module requires an admitted logical blob name');
41
+ const bytes = await product.file(file.name);
42
+ admitScriptContract(bytes, { abi: 1, pages: row.pages });
43
+ const binding = row.binding;
44
+ const encounter = 'encounter' in binding ? shard.encounters.find(value => value.id === binding.encounter) : undefined;
45
+ if ('encounter' in binding && encounter === undefined) throw new Error('Missing scenario encounter binding');
46
+ if ('quest' in binding && !shard.quests.quests.some(quest => quest.id === binding.quest)) throw new Error('Missing scenario quest binding');
47
+ if ('zone' in binding && registries.zones?.has(binding.zone) !== true) throw new Error('Missing scenario zone binding');
48
+ const self = encounter === undefined ? ('spawnGroup' in binding ? handles[0] : 0) : registries.actors?.get(encounter.entity);
49
+ if (self === undefined || self > 0 && !handles.includes(self)) throw new Error('Scenario encounter actor is not owned');
50
+ const fields = shard.state.shared.filter(field => field.privacy === 'public' && field.type !== 'string');
51
+ const fieldValues = Object.fromEntries(fields.map(field => [field.id, Number(field.default)]));
52
+ const bounds = Object.fromEntries(fields.map(field => {
53
+ const low = field.type === 'bool' ? 0 : field.type === 'i32' ? -2147483648 : -Number.MAX_VALUE;
54
+ const high = field.type === 'bool' ? 1 : field.type === 'i32' ? 2147483647 : Number.MAX_VALUE;
55
+ return [field.id, { min: Math.max(field.min ?? low, low), max: Math.min(field.max ?? high, high), integer: field.type !== 'f64' }];
56
+ }));
57
+ const overrides = new Map<number, NonNullable<DiskScenarioOptions['actors']>[number]>();
58
+ for (const actor of options.actors ?? []) {
59
+ const alias = typeof actor.id === 'string' && Object.hasOwn(map.ids.actors ?? {}, actor.id) ? map.ids.actors?.[actor.id] : undefined;
60
+ const handle = typeof actor.id === 'number' ? actor.id : alias ?? registries.actors?.get(actor.id);
61
+ if (handle === undefined || ![...registries.actors?.values() ?? []].includes(handle) || overrides.has(handle)) throw new Error('Unknown or duplicate scenario actor override');
62
+ if (Object.keys(actor.fields ?? {}).some(key => !Object.hasOwn(fieldValues, key))) throw new Error('Unknown scenario public field');
63
+ overrides.set(handle, actor);
64
+ }
65
+ const actors: ScenarioActor[] = [];
66
+ for (const handle of new Set([...handles, ...overrides.keys()])) {
67
+ const name = [...registries.actors ?? []].find(([, value]) => value === handle)?.[0], authored = shard.creatures.spawns.find(actor => actor.id === name);
68
+ const override = overrides.get(handle), runtime = shard.runtime?.spawns;
69
+ const retained = [...runtime?.homes ?? [], ...runtime?.bosses ?? [], ...runtime?.actors ?? []].find(actor => actor.id === name);
70
+ if (override === undefined && authored === undefined) throw new Error(`Runtime actor ${name ?? handle} requires explicit scenario XYZ`);
71
+ const at = override?.at ?? authored?.at; if (at === undefined) throw new Error('Missing scenario actor position');
72
+ actors.push({ ...override, id: handle, at, yaw: override?.yaw ?? authored?.yaw ?? retained?.yaw ?? 0,
73
+ fields: { ...fieldValues, ...override?.fields }, fieldBounds: bounds });
74
+ }
75
+ const groups = decisionSpawnGroups(shard, rows);
76
+ const spawnGroups = [...registries.spawns ?? []].map(([name, groupId]) => {
77
+ const members = groups.get(name) ?? [name];
78
+ return { id: groupId, members: members.map(member => { const actor = registries.actors?.get(member); if (actor === undefined) throw new Error('Missing scenario group member'); return actor; }) };
79
+ });
80
+ const bindings = 'spawnGroup' in binding ? handles.map((actor, ordinalIndex) => ({ id: ordinalIndex + 1, script: row.id, self: actor, actors: [actor], instance: 0 }))
81
+ : [{ id: ordinal + 1, script: row.id, self, actors: handles, instance: 0 }];
82
+ const primary = bindings[0]; if (primary === undefined) throw new Error('Empty scenario binding');
83
+ if(Object.keys(options.fields??{}).some(key=>!Object.hasOwn(fieldValues,key)))throw new Error('Unknown scenario shared field');
84
+ const made = createScriptScenario(DecisionHost, { ...options, fields:{...fieldValues,...options.fields},fieldBounds:bounds,actors, spawnGroups, seed: options.seed, script, bytes, binding: primary, bindings });
85
+ const entry = index.sections.find(value => value.name === 'sim/scripts'); if (entry === undefined) throw new Error('Missing scenario section');
86
+ return Object.assign(made, { product: Object.freeze({ slug, script: row.id, sectionHash: entry.hash,
87
+ indexHash: descriptor.indexHash }) });
88
+ }
@@ -0,0 +1,254 @@
1
+ import { SCRIPT_V1_COMMANDS as commands, SCRIPT_V1_EVENTS as events, SCRIPT_V1_LAYOUT as layout, SCRIPT_V1_LISTS as lists, SCRIPT_V1_READS as reads, type ScriptV1Command, type ScriptV1Event, type ScriptV1EventName } from '@wildshard/format/scriptAbiV1';
2
+ import type { DecisionBinding, DecisionCommit, DecisionContext, DecisionHost, DecisionHostOptions, DecisionIdKind, DecisionScript, DecisionSnapshot, DecisionTrace, DecisionWorld } from '@wildshard/engine/script/decision';
3
+
4
+ /** Small declared world, not a second mechanics implementation. Tests explicitly supply completion events. */
5
+ export interface ScenarioActor {
6
+ id: number; at: readonly [number, number, number]; yaw?: number; hpShare?: number; alive?: boolean;
7
+ fields?: Readonly<Record<number, number>>; fieldBounds?: Readonly<Record<number, { min: number; max: number; integer?: boolean }>>; moving?: boolean; strikeState?: number; spawn?: number;
8
+ }
9
+ export interface ScenarioWorldInput {
10
+ /** Declared shared field writes use target zero, matching the real DecisionHost ABI. */
11
+ fields?: ScenarioActor['fields']; fieldBounds?: ScenarioActor['fieldBounds'];
12
+ actors?: readonly ScenarioActor[]; players?: readonly ScenarioActor[];
13
+ spawnGroups?: readonly { id: number; members: readonly number[] }[];
14
+ flags?: Readonly<Record<number, boolean>>; playerFlags?: Readonly<Record<number, Readonly<Record<number, boolean>>>>;
15
+ zones?: readonly { id: number; min: readonly [number, number, number]; max: readonly [number, number, number] }[];
16
+ /** Explicit answers for physics/navigation queries; missing fixtures refuse instead of inventing terrain. */
17
+ lists?: readonly { op: number; a: number; b: number; result: readonly number[] }[];
18
+ }
19
+ /** Only the actual DecisionHost constructor implements this port; the harness never interprets Wasm. */
20
+ export type ScenarioHostConstructor = new(options: DecisionHostOptions) => DecisionHost;
21
+ export interface ScriptScenarioInput extends ScenarioWorldInput {
22
+ script: DecisionScript; binding: DecisionBinding; bytes: Uint8Array; seed: number;
23
+ bindings?: readonly DecisionBinding[];
24
+ }
25
+ export interface ScenarioSnapshot { host: DecisionSnapshot; world: ScenarioWorldInput }
26
+ export type ScenarioCommand = readonly (string | number)[];
27
+ /** Disk fixtures name actor aliases or real platform ids; numeric handles must already be registered. */
28
+ export interface DiskScenarioOptions extends Omit<ScenarioWorldInput, 'actors' | 'fieldBounds'> {
29
+ seed: number;
30
+ /** Published output root, defaulting to out/ in the caller's working directory. */
31
+ products?: string;
32
+ /** Explicit read-only product directory, including a verified immutable cache entry.
33
+ * Mutually exclusive with products; normal product admission still checks every byte. */
34
+ productDirectory?: string;
35
+ actors?: readonly (Omit<ScenarioActor, 'id' | 'fieldBounds'> & { id: string | number })[];
36
+ }
37
+ export type DiskScriptScenario = ScriptScenario & { readonly product: {
38
+ readonly slug: string; readonly script: string; readonly sectionHash: string; readonly indexHash: string;
39
+ } };
40
+ /** Load a published format-2 product and run its declared Wasm on the real DecisionHost.
41
+ * Missing output refuses: the harness never builds, compiles, or imports author/runtime modules. */
42
+ export async function scenario(slug: string, id: string, options: DiskScenarioOptions): Promise<DiskScriptScenario> {
43
+ const { readDiskScriptScenario } = await import('./diskScriptScenario');
44
+ return readDiskScriptScenario(slug, id, options);
45
+ }
46
+ function finite(values: readonly number[]): void { if (!values.every(Number.isFinite)) throw new Error('Non-finite scenario value'); }
47
+ function checkFields(fields:ScenarioActor['fields'],bounds:ScenarioActor['fieldBounds']):void{
48
+ finite(Object.values(fields??{}));
49
+ for (const [key, bound] of Object.entries(bounds ?? {})) {
50
+ finite([bound.min, bound.max]); const value = fields?.[Number(key)];
51
+ if (bound.min > bound.max || value === undefined || value < bound.min || value > bound.max || (bound.integer === true && !Number.isInteger(value))) throw new Error('Invalid scenario field bounds');
52
+ }
53
+ }
54
+ function actorCopy(actor: ScenarioActor): ScenarioActor {
55
+ checkFields(actor.fields,actor.fieldBounds);
56
+ return { ...actor, at: [...actor.at], fields: { ...actor.fields }, fieldBounds: structuredClone(actor.fieldBounds ?? {}) };
57
+ }
58
+
59
+ /** Deterministic read-only query adapter. Commands are recorded by the host; it owns validation and timers/RNG. */
60
+ export class ScenarioWorld implements DecisionWorld {
61
+ private actors = new Map<number, ScenarioActor>();
62
+ private players = new Set<number>();
63
+ private input: ScenarioWorldInput;
64
+ constructor(input: ScenarioWorldInput = {}) { this.input = {}; this.restore(input); }
65
+ private actor(id: number): ScenarioActor {
66
+ const actor = this.actors.get(id); if (actor === undefined) throw new Error(`Unknown scenario actor ${id}`); return actor;
67
+ }
68
+ private inside(actor: ScenarioActor, zoneId: number): boolean {
69
+ const zone = this.input.zones?.find(value => value.id === zoneId);
70
+ if (zone === undefined) throw new Error(`Unknown scenario zone ${zoneId}`);
71
+ return actor.at.every((value, index) => value >= (zone.min[index] ?? 0) && value <= (zone.max[index] ?? 0));
72
+ }
73
+ private nearby(actor: number, radius: number): ScenarioActor[] {
74
+ const origin = this.actor(actor).at;
75
+ return [...this.players].map(id => this.actor(id)).filter(value => value.alive !== false)
76
+ .map(value => ({ actor: value, distance: Math.hypot(value.at[0] - origin[0], value.at[2] - origin[2]) }))
77
+ .filter(value => value.distance <= radius).sort((a, b) => a.distance - b.distance || a.actor.id - b.actor.id).map(value => value.actor);
78
+ }
79
+ read(op: number, a: number, b: number, _context: DecisionContext): number {
80
+ finite([a, b]);
81
+ if (op === reads.flag) return this.input.flags?.[a] === true ? 1 : 0;
82
+ if (op === reads.playerFlag) { if (!this.players.has(a)) throw new Error('Unknown scenario player'); return this.input.playerFlags?.[a]?.[b] === true ? 1 : 0; }
83
+ if (op === reads.nearestPlayer) return this.nearby(a, Number.POSITIVE_INFINITY)[0]?.id ?? 0;
84
+ if (op === reads.playersInZone) return [...this.players].filter(id => this.actor(id).alive !== false && this.inside(this.actor(id), a)).length;
85
+ if (op === reads.spawnGroupAlive) {
86
+ const group = this.input.spawnGroups?.find(value => value.id === a);
87
+ return group === undefined ? [...this.actors.values()].filter(actor => actor.spawn === a && actor.alive !== false).length
88
+ : group.members.filter(id => { const actor = this.actors.get(id); return actor !== undefined && actor.alive !== false; }).length;
89
+ }
90
+ if (op === reads.distance || op === reads.bearing) {
91
+ const from = this.actor(a).at, to = this.actor(b).at;
92
+ return op === reads.distance ? Math.hypot(to[0] - from[0], to[2] - from[2]) : Math.atan2(to[0] - from[0], to[2] - from[2]);
93
+ }
94
+ if (op === reads.actorInZone) return this.inside(this.actor(a), b) ? 1 : 0;
95
+ if (op === reads.field) {
96
+ const value = this.actor(a).fields?.[b]; if (value === undefined) throw new Error('Missing scenario field'); return value;
97
+ }
98
+ if (op === reads.x) return this.actor(a).at[0];
99
+ if (op === reads.y) return this.actor(a).at[1];
100
+ if (op === reads.z) return this.actor(a).at[2];
101
+ if (op === reads.yaw) return this.actor(a).yaw ?? 0;
102
+ if (op === reads.hpShare) return this.actor(a).hpShare ?? 1;
103
+ if (op === reads.alive) return this.actor(a).alive === false ? 0 : 1;
104
+ if (op === reads.moving) return this.actor(a).moving === true ? 1 : 0;
105
+ if (op === reads.strikeState) return this.actor(a).strikeState ?? 0;
106
+ throw new Error(`Unanswered scenario read ${op}; timers and random belong to DecisionHost`);
107
+ }
108
+ list(op: number, a: number, b: number, output: Float64Array, _context: DecisionContext): number {
109
+ finite([a, b]);
110
+ let values: readonly number[];
111
+ if (op === lists.playersWithin) {
112
+ if (b < 0) throw new Error('Negative scenario radius'); values = this.nearby(a, b).map(actor => actor.id);
113
+ } else if (op === lists.actorsInZone) values = [...this.actors.values()].filter(actor => this.inside(actor, a)).map(actor => actor.id).sort((x, y) => x - y);
114
+ else {
115
+ const answer = this.input.lists?.find(value => value.op === op && value.a === a && value.b === b);
116
+ if (answer === undefined) throw new Error(`Missing scenario list ${op}`); values = answer.result;
117
+ }
118
+ const count = Math.min(values.length, output.length); output.set(values.slice(0, count)); return count;
119
+ }
120
+ prepare(batch: readonly ScriptV1Command[], _context: DecisionContext): DecisionCommit {
121
+ // The host validates capabilities/known handles/quotas; the world knows actual actor kinds and ownership.
122
+ const player = (id: number): boolean => this.players.has(id) && _context.observed.has(id);
123
+ const owned = (id: number): ScenarioActor => {
124
+ if (!_context.binding.actors.includes(id) || this.players.has(id)) throw new Error('Scenario actor ownership refused');
125
+ return this.actor(id);
126
+ };
127
+ for (const [op, target, a, b] of batch) {
128
+ if(op===commands.field){
129
+ const value=target===0?this.input:owned(target),bound=value.fieldBounds?.[a];
130
+ if(value.fields?.[a]===undefined||!Number.isFinite(b)||(bound!==undefined&&(b<bound.min||b>bound.max||(bound.integer===true&&!Number.isInteger(b)))))throw new Error('Scenario field declaration or bounds refused');
131
+ }else if([commands.move,commands.stop,commands.strike,commands.despawn].some(value=>value===op))owned(target);
132
+ if ([commands.grant, commands.reward, commands.flag].some(value => value === op) && target !== 0 && !player(target)) throw new Error('Scenario target is not an observed player');
133
+ if ((op === commands.impulse || (op === commands.cue && target !== 0)) && !player(target)) owned(target);
134
+ if (op === commands.flag && b !== 0 && b !== 1) throw new Error('Scenario flag value refused');
135
+ }
136
+ const copy = batch.map((command): ScriptV1Command => [command[0], command[1], command[2], command[3], command[4]]);
137
+ return { commit: () => {
138
+ for (const [op, target, a, b] of copy) {
139
+ if (op === commands.flag) this.input = target === 0
140
+ ? { ...this.input, flags: { ...this.input.flags, [a]: b === 1 } }
141
+ : { ...this.input, playerFlags: { ...this.input.playerFlags, [target]: { ...this.input.playerFlags?.[target], [a]: b === 1 } } };
142
+ if(op===commands.field&&target===0)this.input={...this.input,fields:{...this.input.fields,[a]:b}};
143
+ const actor = this.actors.get(target); if (actor === undefined) continue;
144
+ if (op === commands.field) this.actors.set(target, { ...actor, fields: { ...actor.fields, [a]: b } });
145
+ if (op === commands.move || op === commands.stop) this.actors.set(target, { ...actor, moving: op === commands.move });
146
+ if (op === commands.strike) this.actors.set(target, { ...actor, strikeState: 1 });
147
+ if (op === commands.despawn) this.actors.set(target, { ...actor, alive: false });
148
+ }
149
+ } };
150
+ }
151
+ failed(_mode: DecisionScript['onFail'], _context: DecisionContext, _reason: string): void { /* Host metrics/trace retain the refusal; no invented fight reset. */ }
152
+ /** Explicit observation changes, e.g. a completed native move. No mechanics clock is simulated here. */
153
+ setActor(actor: ScenarioActor): void { this.actor(actor.id); finite([...actor.at, actor.yaw ?? 0, actor.hpShare ?? 1, ...Object.values(actor.fields ?? {})]); this.actors.set(actor.id, actorCopy(actor)); }
154
+ snapshot(): ScenarioWorldInput {
155
+ return structuredClone({ ...this.input, actors: [...this.actors.values()].filter(actor => !this.players.has(actor.id)), players: [...this.players].map(id => this.actor(id)) });
156
+ }
157
+ restore(input: ScenarioWorldInput): void {
158
+ const copy = structuredClone({ actors: input.actors ?? [], players: input.players ?? [], spawnGroups: input.spawnGroups ?? [], flags: input.flags ?? {}, playerFlags: input.playerFlags ?? {}, zones: input.zones ?? [], lists: input.lists ?? [],...(input.fields===undefined?{}:{fields:input.fields}),...(input.fieldBounds===undefined?{}:{fieldBounds:input.fieldBounds}) }), actors = new Map<number, ScenarioActor>();
159
+ checkFields(copy.fields,copy.fieldBounds);
160
+ for (const actor of [...copy.actors, ...copy.players]) {
161
+ if (!Number.isSafeInteger(actor.id) || actor.id <= 0 || actors.has(actor.id)) throw new Error('Invalid or duplicate scenario actor');
162
+ finite([...actor.at, actor.yaw ?? 0, actor.hpShare ?? 1, ...Object.values(actor.fields ?? {})]); actors.set(actor.id, actorCopy(actor));
163
+ }
164
+ for (const zone of copy.zones) { finite([...zone.min, ...zone.max]); if (zone.min.some((value, index) => value > (zone.max[index] ?? 0))) throw new Error('Invalid scenario zone'); }
165
+ for (const list of copy.lists) finite([list.op, list.a, list.b, ...list.result]);
166
+ this.input = copy; this.actors = actors; this.players = new Set(copy.players.map(actor => actor.id));
167
+ }
168
+ }
169
+
170
+ /** Translate validated wire commands back to the script's authored labels for readable expectations. */
171
+ export function scenarioCommand(script: DecisionScript, [op, target, a, b, c]: ScriptV1Command): ScenarioCommand {
172
+ const name = (kind: DecisionIdKind, id: number): string => {
173
+ const found = Object.entries(script.ids[kind] ?? {}).find(([, value]) => value === id)?.[0];
174
+ if (found === undefined) throw new Error(`Unknown scenario ${kind} id ${id}`); return found;
175
+ };
176
+ const actor = (id: number): string | number => Object.entries(script.ids.actors ?? {}).find(([, value]) => value === id)?.[0] ?? id;
177
+ if (op === commands.move || op === commands.strike) return [op === commands.move ? 'move' : 'strike', actor(target), name(op === commands.move ? 'moves' : 'strikes', a), ...(b === 0 ? [] : [actor(b)])];
178
+ if (op === commands.stop || op === commands.despawn) return [op === commands.stop ? 'stop' : 'despawn', actor(target)];
179
+ if (op === commands.field) return ['field', actor(target), name('fields', a), b];
180
+ if (op === commands.spawn) return ['spawn', name('spawns', a)];
181
+ if (op === commands.timer) return ['timer', name('timers', a), b];
182
+ if (op === commands.cue) return ['cue', ...(target === 0 ? [] : [actor(target)]), name('cues', a)];
183
+ if (op === commands.flag) return ['flag', name('flags', a), b];
184
+ if (op === commands.signal) return ['signal', name('signals', a), b];
185
+ if (op === commands.channel) return ['channel', name('channels', a), b];
186
+ if (op === commands.grant || op === commands.reward) return [op === commands.grant ? 'grant' : 'reward', actor(target), name(op === commands.grant ? 'facts' : 'rewards', a)];
187
+ if (op === commands.impulse) return ['impulse', actor(target), name('impulses', a)];
188
+ if (op === commands.weather) return ['weather', name('weather', a)];
189
+ if (op === commands.encounter) { const verb = ['phase', 'win', 'fail', 'guard'][a - 1]; if (verb === undefined) throw new Error('Unknown encounter verb'); return ['encounter', verb, b]; }
190
+ const view = Object.entries(commands).find(([key, value]) => key.startsWith('view.') && value === op)?.[0];
191
+ if (view !== undefined) return [view, target, a, b, c];
192
+ throw new Error(`Unknown scenario command ${op}`);
193
+ }
194
+
195
+ /** Simulation-only driver. Scheduling, RNG, timers, validation, fuel and saves are always the real host's. */
196
+ export class ScriptScenario {
197
+ private tick = 0;
198
+ private cursor = 0;
199
+ private saved: ScenarioSnapshot | undefined;
200
+ constructor(readonly host: DecisionHost, readonly world: ScenarioWorld, private readonly script: DecisionScript, private readonly binding: number, private readonly entries: DecisionTrace[],
201
+ private readonly bindings: readonly number[] = [binding]) {}
202
+ private advanceTicks(count: number): void { for (let index = 0; index < count; index++) this.host.step(++this.tick); }
203
+ /** Queue a raw ABI event, then reach its decision and following atomic commit step. */
204
+ sendRaw(event: ScriptV1Event): void {
205
+ this.cursor = this.entries.length;
206
+ for (const binding of event[0] === events.start || event[0] === events.stop ? this.bindings : [this.binding]) this.host.enqueue(binding, event);
207
+ this.advanceTicks(layout.decisionDivisor - this.tick % layout.decisionDivisor + 1);
208
+ }
209
+ /** Named event arguments follow the ABI: subject first, then a/b/c/d. */
210
+ send(event: ScriptV1EventName, ...args: readonly (string | number | boolean)[]): void {
211
+ if (args.length > 5) throw new Error('Too many scenario event arguments');
212
+ const kinds: Partial<Record<ScriptV1EventName, readonly (DecisionIdKind | null)[]>> = {
213
+ timer: ['timers'], 'zone.enter': ['zones', 'actors'], 'zone.leave': ['zones', 'actors'],
214
+ interact: ['spots', 'actors'], hit: ['actors', 'actors'], threshold: ['actors'], death: ['actors', 'actors'],
215
+ 'move.done': ['actors', 'moves'], 'strike.done': ['actors', 'strikes'], flag: ['flags'], signal: ['signals'],
216
+ 'strike.target': ['targets', 'actors'], 'player.join': ['actors'], 'player.leave': ['actors'], spawned: ['actors', 'spawns'],
217
+ };
218
+ const values = args.map((value, index) => {
219
+ if (typeof value === 'number') { finite([value]); return value; }
220
+ if (typeof value === 'boolean') return value ? 1 : 0;
221
+ const kind = kinds[event]?.[index], id = kind === undefined || kind === null ? undefined : this.script.ids[kind]?.[value];
222
+ if (id === undefined) throw new Error(`Unknown scenario event argument ${value}`); return id;
223
+ });
224
+ this.sendRaw([events[event], values[0] ?? 0, values[1] ?? 0, values[2] ?? 0, values[3] ?? 0, values[4] ?? 0]);
225
+ }
226
+ advance(seconds: number): void {
227
+ const count = seconds * layout.fixedHz;
228
+ if (!Number.isSafeInteger(count) || count < 0 || count > 1_000_000) throw new Error('Scenario time must be bounded whole simulation ticks');
229
+ this.cursor = this.entries.length; this.advanceTicks(count);
230
+ }
231
+ commands(): readonly ScenarioCommand[] {
232
+ return this.entries.slice(this.cursor).flatMap(entry => entry.kind === 'call' && entry.binding === this.binding && entry.ok ? entry.commands.map(command => scenarioCommand(this.script, command)) : []);
233
+ }
234
+ trace(): readonly DecisionTrace[] { return structuredClone(this.entries); }
235
+ state(): Readonly<Record<string, number | boolean>> { return this.host.state(this.binding); }
236
+ maxFuel(): number { const metrics = this.host.metrics().find(value => value.binding === this.binding); if (metrics === undefined || metrics.calls === 0) throw new Error('No scenario calls'); return metrics.maxFuel; }
237
+ save(): ScenarioSnapshot { const saved = { host: this.host.snapshot(), world: this.world.snapshot() }; this.saved = structuredClone(saved); return saved; }
238
+ restore(snapshot: ScenarioSnapshot | undefined = this.saved): void {
239
+ if (snapshot === undefined) throw new Error('No scenario save');
240
+ // Validate fixture data before changing either owner, then let the host validate its complete continuation.
241
+ const world = new ScenarioWorld(snapshot.world), before = this.world.snapshot(); this.world.restore(world.snapshot());
242
+ try { this.host.restore(snapshot.host); } catch (error) { this.world.restore(before); throw error; }
243
+ this.tick = snapshot.host.tick; this.cursor = this.entries.length;
244
+ }
245
+ }
246
+
247
+ /** Core constructor seam for the real KA2 host and built module bytes. No Wasm compiler or alternate host. */
248
+ export function createScriptScenario(Host: ScenarioHostConstructor, input: ScriptScenarioInput): ScriptScenario {
249
+ if (!Number.isSafeInteger(input.seed) || input.seed < 0 || input.seed > 0xffffffff) throw new Error('Invalid scenario seed');
250
+ const world = new ScenarioWorld(input), entries: DecisionTrace[] = [];
251
+ const host = new Host({ scripts: [input.script], bindings: input.bindings ?? [input.binding], modules: new Map([[input.script.module, input.bytes]]), seed: [input.seed, 0], world,
252
+ trace: entry => { entries.push(structuredClone(entry)); } });
253
+ return new ScriptScenario(host, world, input.script, input.binding.id, entries, input.bindings?.map(binding => binding.id));
254
+ }
@@ -0,0 +1,3 @@
1
+ {
2
+ "extends": "../../tsconfig.author.json"
3
+ }