@wildshard/shard-format 0.82.12 → 0.84.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wildshard/shard-format",
3
- "version": "0.82.12",
3
+ "version": "0.84.0",
4
4
  "description": "The raw shardfile format: the spec, the validator and a validate CLI. The public, versioned contract every other repo builds on.",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {
@@ -114,6 +114,8 @@
114
114
  "./dayCycle": "./src/format/dayCycle.ts",
115
115
  "./dayLook": "./src/format/dayLook.ts",
116
116
  "./decisionBindings": "./src/format/decisionBindings.ts",
117
+ "./decisionFrameV2": "./src/format/decision-frame-v2.ts",
118
+ "./numericFrameV2": "./src/format/numeric-frame-v2.ts",
117
119
  "./decisionPublication": "./src/format/decisionPublication.ts",
118
120
  "./decisionScripts": "./src/format/decisionScripts.ts",
119
121
  "./declaredQuestPage": "./src/format/declaredQuestPage.ts",
@@ -342,6 +344,7 @@
342
344
  "./sectionVersions": "./src/format/section-versions.ts",
343
345
  "./scriptContract": "./src/format/scriptContract.ts",
344
346
  "./scriptFuelV2": "./src/format/scriptFuelV2.ts",
347
+ "./scriptFuelPathV2": "./src/format/script-fuel-path-v2.ts",
345
348
  "./scriptGroupBankV2": "./src/format/scriptGroupBankV2.ts",
346
349
  "./scriptGroupStepV2": "./src/format/scriptGroupStepV2.ts",
347
350
  "./scriptInputStateV2": "./src/format/scriptInputStateV2.ts",
@@ -40,7 +40,7 @@ const ENGINE_PINS =
40
40
  /** ZS3 (J507): the next releases, production's and staging's, as engine pins them. */
41
41
  const LIVE_PINS = `${ENGINE_PINS}/shardfiles.json,${ENGINE_PINS}/staging.json`
42
42
  /** The signed release and placement files api-server's prune reads, public: R2 layout RL10 moved them from
43
- * `packs.wildshard.io/releases/` to the root of `wildshard-releases` and removed the old keys. */
43
+ * the retired packs bucket's `releases/` to the root of `wildshard-releases` and removed the old keys. */
44
44
  const RELEASES = 'https://releases.wildshard.io'
45
45
 
46
46
  interface LiveSet {
@@ -2,6 +2,7 @@ import { acceptsShardfileCost, textureLibrarySource } from './deviceMemoryCost.t
2
2
  import { retainedActorIds } from './retained-actors.ts';
3
3
  import { creaturePerchAdmissionRows } from './creature-perch.ts';
4
4
  import { admitScriptContract, decisionModuleContracts, type ScriptAdmissionRows } from './scriptContract.ts';
5
+ import { isNumericContract, withoutNumericModules } from './numeric-frame-v2.ts';
5
6
  import type { TextureTranscodeSupport } from './contentBounds.ts';
6
7
  import { overHardLine } from './memory-line.ts';
7
8
  import { admitScript } from './scriptAdmission.ts';
@@ -100,7 +101,8 @@ function assetAdmission(input: unknown, memory: MemoryAdmission | undefined, scr
100
101
  const combined = [...scripts, ...perchRows];
101
102
  const contracts = decisionModuleContracts(combined, s.files);
102
103
  const legacyModules = new Set([...s.sim.scripts, ...s.clientScripts.bindings.map(row => row.module), ...s.movers.filter(row => row.execution !== 'native').map(row => row.module)]);
103
- if ([...contracts.keys()].some(hash => legacyModules.has(hash))) throw new Error('Decision module cannot also use a legacy script host');
104
+ // WASM-HOST H13: a numeric host (script lane, client script, mover) runs ABI v2 modules over the numeric frame.
105
+ if ([...contracts.keys()].some(hash => legacyModules.has(hash) && !isNumericContract(contracts.get(hash) ?? { abi: 0 }))) throw new Error('Decision module cannot also use a legacy script host');
104
106
  preflightAssetGraph(s);
105
107
  const declared = preflightDeclaredCosts(s, memory).commons;
106
108
  const closure = (roots: readonly string[]): Set<string> => {
@@ -189,7 +191,7 @@ function admitAfterFiles(state: AssetAdmission, assets: ReadonlyMap<string, Uint
189
191
  if (s.sim.scripts.some((id) => !id.startsWith('commons:') && files.get(id)?.kind !== 'wasm')) throw new Error('script reference is not an admitted Wasm file');
190
192
  for (const t of s.tiles) {
191
193
  const roots = closure(t.files);
192
- // Meta J551 (Jake, 2026-11-30): a texture shared by several tiles loads once, with the library, so a coarse tile may
194
+ // Meta ZONE-SIZE-LIMITS D3 (Jake, 2026-11-30): a texture shared by several tiles loads once, with the library, so a coarse tile may
193
195
  // name a library image; a library model stays fine-only
194
196
  if (t.lod === 1 && coarseLibraryModel(roots, library, (r) => files.get(r)?.kind)) throw new Error('coarse dependency on library');
195
197
  const cost = sum(t.files, library);
@@ -235,7 +237,8 @@ function admitAfterFiles(state: AssetAdmission, assets: ReadonlyMap<string, Uint
235
237
  scriptMemory += admission.maximumPages * 65536 * 3;
236
238
  }
237
239
  let decisionSim = 0, decisionView = 0;
238
- for (const [hash, contract] of contracts) {
240
+ // WASM-HOST H13: a numeric module keeps the placement and memory rules of the host that names it (above).
241
+ for (const [hash, contract] of withoutNumericModules(contracts)) {
239
242
  if (scripts.some(row => row.module === `blobs/wasm/${hash}.wasm` && row.side === 'sim')) {
240
243
  if (!critical.has(hash) || library.has(hash)) throw new Error('Decision sim module must be critical, outside the render library');
241
244
  decisionSim += contract.pages * 65536 * 2;
@@ -1,4 +1,4 @@
1
- /** The file kinds a coarse tile may share with the library (meta J551): images, not models. */
1
+ /** The file kinds a coarse tile may share with the library (meta ZONE-SIZE-LIMITS D3): images, not models. */
2
2
  const LIBRARY_IMAGE_KINDS: ReadonlySet<string> = new Set(['image', 'ktx2'])
3
3
 
4
4
  /** True when a coarse tile's closure names a library file that is not an image (a model, a script): refused. */
@@ -44,7 +44,7 @@ export const MEMORY_GATES: Readonly<{ reportOnly: boolean; explorerMB: number; l
44
44
  });
45
45
  /** Provisional phone content caps; shadow draws count in each draw cap. */
46
46
  export const CONTENT_CAPS: { readonly l0: { readonly size: 62.5; readonly resident: number; readonly compressed: number; readonly triangles: 40000; readonly draws: 8; }; readonly l1: { readonly size: 125; readonly resident: number; readonly compressed: number; readonly triangles: 10000; readonly draws: 2; }; readonly far: { readonly resident: number; readonly compressed: 1000000; readonly triangles: 8000; readonly draws: 1; }; readonly library: { readonly resident: number; readonly compressed: number; }; readonly sim: { readonly resident: number; readonly compressed: number; }; readonly engineBase: number; readonly playing: number; readonly loading: number; readonly l0Count: 40; readonly l1Count: 32; readonly farCount: 9; readonly simCount: 4; readonly libraryCount: 4; readonly overlap: number; readonly residentFactor: 1.11; readonly nearRadius: 150; readonly shadowRadius: 80; readonly pitch: 562.5; } = {
47
- // Meta J551 (Jake, 2026-11-30): the far target 2 MB and the library 28 MB; J557 (Jake, 2026-11-30): the fine-tile
47
+ // Meta ZONE-SIZE-LIMITS D3 (Jake, 2026-11-30): the far target 2 MB and the library 28 MB; meta ZONE-SIZE-LIMITS D5 (Jake, 2026-11-30): the fine-tile
48
48
  // download line is 720 kB and the coarse 240 kB (Mossgate's 649 kB and 211 kB tiles plus 10%, J439)
49
49
  l0: { size: 62.5, resident: 4 * CONTENT_MB, compressed: 0.72 * CONTENT_MB, triangles: 40_000, draws: 8 },
50
50
  l1: { size: 125, resident: 2 * CONTENT_MB, compressed: 0.24 * CONTENT_MB, triangles: 10_000, draws: 2 },
@@ -0,0 +1,59 @@
1
+ import { SCRIPT_V2_REVISIONS } from './scriptAdmissionV2.ts'
2
+ import { layoutV2 } from './scriptWireV2.ts'
3
+
4
+ import type { DecisionScriptRow } from './decisionScripts.ts'
5
+ import type { ScriptContract } from './scriptContract.ts'
6
+ import type { V2Layout } from './scriptWireV2.ts'
7
+
8
+ /** WASM-HOST H13: an event decision row's ABI v2 module (abi '2.0') runs one binding per entry over this fixed frame,
9
+ * bank kind to row capacity: bindings 1, state and candidate 16, params 32, events 16, commands 32, read misses 32,
10
+ * replies 128 with 512 list values, one RNG stream. Its I/O base is 0, so its I/O size follows from its pages alone. */
11
+ const CAPACITY: Readonly<Record<number, number>> = {
12
+ 1: 1,
13
+ 2: 16,
14
+ 3: 16,
15
+ 4: 32,
16
+ 9: 16,
17
+ 10: 32,
18
+ 11: 32,
19
+ 12: 128,
20
+ 13: 512,
21
+ 21: 1,
22
+ 22: 1,
23
+ }
24
+ const capacities = new Map<number, number>()
25
+ for (const [kind, capacity] of Object.entries(CAPACITY)) {
26
+ capacities.set(Number(kind), capacity)
27
+ }
28
+ const DECISION_V2_CAPACITIES: ReadonlyMap<number, number> = capacities
29
+ /** List replies are keyed `DECISION_V2_LIST_KEY + list op`, apart from read ops. */
30
+ const DECISION_V2_LIST_KEY = 1000
31
+ const DECISION_V2_IO = 0
32
+ /** The I/O frame a decision module of `pages` pages admits under. */
33
+ function decisionLayoutV2(pages: number): V2Layout {
34
+ return layoutV2(DECISION_V2_IO, pages, DECISION_V2_CAPACITIES)
35
+ }
36
+ /** A decision row's byte contract: ABI 1 by its pages, or (abi '2.0') the ABI 2 sim lane over its fixed decision frame. */
37
+ function decisionContract(
38
+ row: Readonly<Pick<DecisionScriptRow, 'abi' | 'pages'>>,
39
+ ): Extract<ScriptContract, { pages: number }> {
40
+ if (row.abi === '1.0') {
41
+ return { abi: 1, pages: row.pages }
42
+ }
43
+ return {
44
+ abi: 2,
45
+ lane: 'sim',
46
+ pages: row.pages,
47
+ ioBytes: decisionLayoutV2(row.pages).bytes,
48
+ compilerRevision: SCRIPT_V2_REVISIONS.compiler,
49
+ admissionRevision: SCRIPT_V2_REVISIONS.admission,
50
+ }
51
+ }
52
+
53
+ export {
54
+ DECISION_V2_CAPACITIES,
55
+ DECISION_V2_IO,
56
+ DECISION_V2_LIST_KEY,
57
+ decisionContract,
58
+ decisionLayoutV2,
59
+ }
@@ -1,4 +1,5 @@
1
1
  import * as v from 'valibot';
2
+ import { decisionContract } from './decision-frame-v2.ts';
2
3
  import { isJsonData } from './json.ts';
3
4
  import { SCRIPT_V1_COMMANDS, SCRIPT_V1_EVENTS, SCRIPT_V1_LISTS, SCRIPT_V1_READS } from './scriptAbiV1.ts';
4
5
  import { SCRIPT_LIMITS } from './scriptLimits.ts';
@@ -24,7 +25,8 @@ export type ScriptV1ReferenceKind = typeof SCRIPT_V1_REFERENCE_KINDS[number];
24
25
  const rowEntries = {
25
26
  // SERVER-PARITY SS7: `sim` is server-owned gameplay; `view` runs on the page only and writes no gameplay (row rules).
26
27
  // Per-frame view is still the v2 view lane's (view/modules, client view.program).
27
- id, abi: v.literal('1.0'), side: v.picklist(SCRIPT_V1_SIDES),
28
+ // WASM-HOST H13: '2.0' is the same row compiled as an ABI v2 sim module (scriptWireV2 decisionLayoutV2).
29
+ id, abi: v.picklist(['1.0', '2.0']), side: v.picklist(SCRIPT_V1_SIDES),
28
30
  module: v.pipe(v.string(), v.regex(/^blobs\/wasm\/[a-f0-9]{64}\.wasm$/u)),
29
31
  source: v.pipe(v.string(), v.maxLength(256), v.regex(/^behaviour\/(?:[A-Za-z0-9_-][A-Za-z0-9_.-]*\/)*[A-Za-z0-9_-][A-Za-z0-9_.-]*\.as$/u),
30
32
  v.check(value => !value.split('/').includes('generated'), 'authored script source, not generated glue')),
@@ -78,6 +80,7 @@ export function decisionScriptRowRules(script: DecisionScriptRow): string[] {
78
80
  if (script.tags !== undefined && !validNames(Object.keys(script.tags))) { errors.push('unique nonreserved generated binding names'); }
79
81
  if (script.on.some(name => SCRIPT_V1_EVENTS[name] >= 30) || script.commands.some(name => SCRIPT_V1_COMMANDS[name] >= 100)) errors.push('simulation script uses only simulation ops');
80
82
  if (script.side === 'view' && !script.commands.every(isViewCommand)) { errors.push(VIEW_WRITES_GAMEPLAY); }
83
+ if (script.abi === '2.0' && script.side !== 'sim') { errors.push('an ABI 2 decision row is a sim module'); }
81
84
  for (const names of [...SCRIPT_V1_REFERENCE_KINDS.map(kind => Object.keys(script[kind] ?? {})), script.timers, script.state.map(slot => slot.name), Object.keys(script.params)]) {
82
85
  if (!validNames(names)) errors.push('unique nonreserved generated binding names');
83
86
  }
@@ -173,7 +176,7 @@ export function decisionScriptRules(scripts: readonly DecisionScriptRow[], refer
173
176
  for (const script of scripts) {
174
177
  errors.push(...decisionScriptRowRules(script));
175
178
  const module = references.modules.get(script.module);
176
- if (module?.abi !== 1 || module.pages !== script.pages) errors.push('script module has matching admitted ABI and fixed pages');
179
+ if (module?.abi !== decisionContract(script).abi || module.pages !== script.pages) errors.push('script module has matching admitted ABI and fixed pages');
177
180
  for (const kind of SCRIPT_V1_REFERENCE_KINDS) for (const value of Object.values(script[kind] ?? {})) {
178
181
  if (references.ids[kind]?.has(value) !== true) errors.push(`script ${kind} reference resolves in its platform section`);
179
182
  }
@@ -204,7 +207,7 @@ export type BorrowedDecision = v.InferOutput<typeof BorrowedDecisionSchema>;
204
207
  /** Admitted data contracts, independent of validator implementation metadata. */
205
208
  interface DecisionScriptRowInputFields {
206
209
  id: string;
207
- abi: '1.0';
210
+ abi: '1.0' | '2.0';
208
211
  side: 'sim' | 'view';
209
212
  module: string;
210
213
  source: string;
@@ -262,7 +265,7 @@ interface DecisionScriptRowInputFields {
262
265
  export type DecisionScriptRowInput = { [Key in keyof DecisionScriptRowInputFields]: DecisionScriptRowInputFields[Key] };
263
266
  interface DecisionScriptRowFields {
264
267
  id: string;
265
- abi: '1.0';
268
+ abi: '1.0' | '2.0';
266
269
  side: 'sim' | 'view';
267
270
  module: string;
268
271
  source: string;
@@ -5,6 +5,7 @@ import { parsePlatformDataSection } from './platformDataSections.ts'
5
5
  /** One defining context catalogue for author-build intake and worker transport. */
6
6
  export const HEADLESS_CONTEXT_SECTIONS = [
7
7
  'view/modules',
8
+ 'sim/modules',
8
9
  'sim/scripts',
9
10
  'actors/spawn-scripts',
10
11
  'actors/return-scripts',
@@ -192,6 +192,7 @@ import {
192
192
  QuestNpcBindingSchema,
193
193
  QuestNpcBindingsSchema,
194
194
  } from './npcs.ts'
195
+ import { SimModulesSchema } from './numeric-frame-v2.ts'
195
196
  import { PageLifeSchema } from './pageLife.ts'
196
197
  import {
197
198
  PaintedAirSchema,
@@ -572,6 +573,7 @@ const finiteNumbers = new Set<object>([
572
573
  // Only the exact retained defining roots grant action bridges. A caller's new check or transform never joins.
573
574
  const wireRoots: Readonly<Record<string, GenericSchema>> = {
574
575
  'audioScene.AudioScene': AudioSceneSchema,
576
+ 'numericFrameV2.SimModules': SimModulesSchema,
575
577
  'forestPage.LivingPageSites': LivingPageSitesSchema,
576
578
  'fixedDraws.FixedDrawRows': FixedDrawRowsSchema,
577
579
  'forestPage.ForestPage': ForestPageSchema,
@@ -0,0 +1,143 @@
1
+ import { array, check, literal, maxLength, pipe, strictObject } from 'valibot'
2
+
3
+ import { SCRIPT_V2_REVISIONS } from './scriptAdmissionV2.ts'
4
+ import { ViewModuleSchema } from './scriptContract.ts'
5
+ import { layoutV2 } from './scriptWireV2.ts'
6
+
7
+ import type {
8
+ OwnedSimModuleRows,
9
+ OwnedSimModuleRowsInput,
10
+ ScriptV2ContractRows,
11
+ } from './scriptContract.ts'
12
+ import type { V2Layout } from './scriptWireV2.ts'
13
+ import type { GenericSchema } from 'valibot'
14
+
15
+ /** WASM-HOST H13: a numeric script (a script-lane binding, an item hook, a chapter director) on ABI v2. Its host keeps
16
+ * the numeric call it had (inputs, events, effect records, queries); the module runs one call per entry over this
17
+ * fixed frame, bank kind to row capacity: one binding, 16 state and candidate slots, 32 inputs (kind 6, field = input
18
+ * index), 32 events, 128 effect records (kind 10), 16 query misses with 16 replies of up to 96 values. Its I/O base
19
+ * is 0, so its I/O size follows from its pages alone. */
20
+ const CAPACITY: Readonly<Record<number, number>> = {
21
+ 1: 1,
22
+ 2: 16,
23
+ 3: 16,
24
+ 6: 32,
25
+ 9: 32,
26
+ 10: 128,
27
+ 11: 16,
28
+ 12: 16,
29
+ 13: 1536,
30
+ }
31
+ const capacities = new Map<number, number>()
32
+ for (const [kind, capacity] of Object.entries(CAPACITY)) {
33
+ capacities.set(Number(kind), capacity)
34
+ }
35
+ const NUMERIC_V2_CAPACITIES: ReadonlyMap<number, number> = capacities
36
+ const NUMERIC_V2_IO = 0
37
+ /** The ABI a numeric module speaks. */
38
+ const NUMERIC_ABI = 2
39
+ /** At most this many numeric modules in one shard. */
40
+ const SIM_MODULE_LIMIT = 64
41
+ /** The I/O frame a numeric module of `pages` pages admits under. */
42
+ function numericLayoutV2(pages: number): V2Layout {
43
+ return layoutV2(NUMERIC_V2_IO, pages, NUMERIC_V2_CAPACITIES)
44
+ }
45
+ /** A numeric module's byte contract: the ABI 2 sim lane over the fixed numeric frame. */
46
+ function numericContract(pages: number): ScriptV2ContractRows {
47
+ return {
48
+ abi: NUMERIC_ABI,
49
+ lane: 'sim',
50
+ pages,
51
+ ioBytes: numericLayoutV2(pages).bytes,
52
+ compilerRevision: SCRIPT_V2_REVISIONS.compiler,
53
+ admissionRevision: SCRIPT_V2_REVISIONS.admission,
54
+ }
55
+ }
56
+ /** A contract a numeric host may run: ABI 2's sim lane over the numeric frame. */
57
+ function isNumericContract(
58
+ contract: Readonly<{
59
+ abi: number
60
+ lane?: string
61
+ pages?: number
62
+ ioBytes?: number
63
+ }>,
64
+ ): boolean {
65
+ return (
66
+ contract.abi === NUMERIC_ABI &&
67
+ contract.lane === 'sim' &&
68
+ contract.pages !== undefined &&
69
+ contract.ioBytes === numericLayoutV2(contract.pages).bytes
70
+ )
71
+ }
72
+ /** The contracts that are not a numeric module's, as [hash, contract] pairs. */
73
+ function withoutNumericModules<
74
+ Contract extends Readonly<{
75
+ abi: number
76
+ lane?: string
77
+ pages?: number
78
+ ioBytes?: number
79
+ }>,
80
+ >(contracts: ReadonlyMap<string, Contract>): [string, Contract][] {
81
+ const out: [string, Contract][] = []
82
+ for (const [hash, contract] of contracts) {
83
+ if (!isNumericContract(contract)) {
84
+ out.push([hash, contract])
85
+ }
86
+ }
87
+ return out
88
+ }
89
+ /** Each id and each module path once. */
90
+ function uniqueModules(rows: readonly Readonly<OwnedSimModuleRows>[]): boolean {
91
+ const ids = new Set<string>()
92
+ const modules = new Set<string>()
93
+ for (const row of rows) {
94
+ ids.add(row.id)
95
+ modules.add(row.module)
96
+ }
97
+ return ids.size === rows.length && modules.size === rows.length
98
+ }
99
+ /** Every row's contract is the numeric frame's for its pages. */
100
+ function onNumericFrame(
101
+ rows: readonly Readonly<OwnedSimModuleRows>[],
102
+ ): boolean {
103
+ for (const row of rows) {
104
+ const want = numericContract(row.pages)
105
+ if (row.ioBytes !== want.ioBytes) {
106
+ return false
107
+ }
108
+ }
109
+ return true
110
+ }
111
+ /** `sim/modules`: the ABI v2 modules numeric hosts run (a script-lane binding, an item hook, a chapter director, a
112
+ * brain, a mover, a client script), each a sim module over the numeric frame. */
113
+ const SimModuleSchema = strictObject({
114
+ ...ViewModuleSchema.entries,
115
+ side: literal('sim'),
116
+ lane: literal('sim'),
117
+ })
118
+ const SimModuleListSchema = array(SimModuleSchema)
119
+ const SimModulesSchema: GenericSchema<
120
+ OwnedSimModuleRowsInput[],
121
+ OwnedSimModuleRows[]
122
+ > = pipe(
123
+ SimModuleListSchema,
124
+ maxLength(SIM_MODULE_LIMIT),
125
+ check<OwnedSimModuleRows[], string>(
126
+ uniqueModules,
127
+ 'Unique sim module ids and paths',
128
+ ),
129
+ check<OwnedSimModuleRows[], string>(
130
+ onNumericFrame,
131
+ 'A sim module runs over the numeric frame',
132
+ ),
133
+ )
134
+
135
+ export {
136
+ isNumericContract,
137
+ NUMERIC_V2_CAPACITIES,
138
+ NUMERIC_V2_IO,
139
+ numericContract,
140
+ numericLayoutV2,
141
+ SimModulesSchema,
142
+ withoutNumericModules,
143
+ }
@@ -65,6 +65,7 @@ const DATA_SECTION_NAMES: Readonly<Record<keyof PlatformDataSections, true>> = {
65
65
  "server/patrol": true,
66
66
  "server/world": true,
67
67
  "view/modules": true,
68
+ "sim/modules": true,
68
69
  "held/arms": true,
69
70
  "held/gear": true,
70
71
  "held/finishes": true,
@@ -34,6 +34,7 @@ import { UiStringsSchema, type UiStrings } from './uiStrings.ts';
34
34
  import { WorldPhysicsSchema, type WorldPhysics } from './worldPhysics.ts';
35
35
  import { WorldTargetsSchema, type WorldTargets } from './worldTargets.ts';
36
36
  import { WorldMoversSchema } from './movers.ts';
37
+ import { SimModulesSchema } from './numeric-frame-v2.ts';
37
38
  import { ReturnModulesSchema, type ReturnModuleRow, ViewModulesSchema, type ViewModuleRow } from './scriptContract.ts';
38
39
  import { NativeRuntimePlanSchema, type NativeRuntimePlanData } from './nativeRuntimePlan.ts';
39
40
  import { TreeSetSchema, type TreeSetRows } from './treeSetRows.ts';
@@ -61,6 +62,7 @@ export interface PlatformDataSections {
61
62
  'server/patrol': ServerHosts;
62
63
  'server/world': ServerWorld;
63
64
  'view/modules': ViewModuleRow[];
65
+ 'sim/modules': v.InferOutput<typeof SimModulesSchema>;
64
66
  'held/arms': HeldArmsRows;
65
67
  'held/gear': HeldGearRows;
66
68
  'held/finishes': HeldFinishesRows;
@@ -103,6 +105,7 @@ export const PLATFORM_DATA_SECTIONS: Readonly<{ [Name in keyof PlatformDataSecti
103
105
  'server/patrol': { schema: ServerHostsSchema },
104
106
  'server/world': { schema: ServerWorldSchema },
105
107
  'view/modules': { schema: ViewModulesSchema },
108
+ 'sim/modules': { schema: SimModulesSchema },
106
109
  'held/arms': { schema: HeldArmsSchema },
107
110
  'held/gear': { schema: HeldGearSchema },
108
111
  'held/finishes': { schema: HeldFinishesSchema },
@@ -0,0 +1,83 @@
1
+ /* oxlint-disable capitalized-comments, complexity, curly, id-length, max-depth, max-lines-per-function, max-statements, no-magic-numbers, no-plusplus, sort-vars, typescript/explicit-function-return-type, typescript/prefer-readonly-parameter-types, unicorn/no-array-callback-reference, unicorn/number-literal-case -- the region walk of scriptFuelV2.ts's v2BlockCosts, in its form; engine test/fixtures/v2Path.ts copies it line for line until engine takes this format */
2
+ /** WASM-HOST H2c: v2 fuel regions priced at their longest path. */
3
+ import type { V2Instruction } from './scriptModuleV2.ts'
4
+
5
+ /** WASM-HOST H2c: the same regions, each priced at its longest path instead of every instruction it holds. A call that
6
+ * takes one `if` arm, one `br_table` case or an early exit runs no more than that path, so the charge still covers every
7
+ * instruction run and no charge is added; an if/else or a switch pays for its longest arm, not all of them (H2b read
8
+ * up to 4.18x over-billing on the hot path; meta support/wasm-host/H2C-*). Edges: fall-through, `if` to its arm or
9
+ * past it, `else` past its `end`, a branch to past its block's `end`, and from a nested loop to wherever its body can
10
+ * leave to. A return, `unreachable`, a branch to a loop (the loop charges again) or past the region ends a path. */
11
+ export function v2PathCosts(
12
+ code: readonly V2Instruction[],
13
+ constantCalls: ReadonlyMap<number, number> = new Map(),
14
+ ): ReadonlyMap<number, number> {
15
+ const exit = -1,
16
+ ends = new Map<number, number>(),
17
+ arms = new Map<number, number>(),
18
+ open: number[] = []
19
+ for (let i = 0; i < code.length; i++) {
20
+ const op = code[i]?.op
21
+ if (op === 0x02 || op === 0x03 || op === 0x04) open.push(i)
22
+ else if (op === 0x05) {
23
+ const at = open.at(-1)
24
+ if (at !== undefined) arms.set(at, i)
25
+ } else if (op === 0x0b) {
26
+ const at = open.pop()
27
+ if (at !== undefined) ends.set(at, i)
28
+ }
29
+ }
30
+ const end = (at: number): number => ends.get(at) ?? code.length - 1,
31
+ next: (readonly number[])[] = [],
32
+ labels: number[] = []
33
+ const target = (depth: number): number => {
34
+ const at = labels[labels.length - 1 - depth]
35
+ return at === undefined || code[at]?.op === 0x03 ? exit : end(at) + 1
36
+ }
37
+ for (let i = 0; i < code.length; i++) {
38
+ const value = code[i],
39
+ op = value?.op
40
+ if (op === 0x0c) next.push([target(value?.args[0] ?? 0)])
41
+ else if (op === 0x0d) next.push([i + 1, target(value?.args[0] ?? 0)])
42
+ else if (op === 0x0e) next.push((value?.args ?? []).map(target))
43
+ else if (op === 0x0f || op === 0x00) next.push([exit])
44
+ else if (op === 0x04) next.push([i + 1, (arms.get(i) ?? end(i)) + 1])
45
+ else if (op === 0x05) next.push([end(labels.at(-1) ?? -1) + 1])
46
+ else next.push([i + 1])
47
+ if (op === 0x02 || op === 0x03 || op === 0x04) labels.push(i)
48
+ else if (op === 0x0b) labels.pop()
49
+ }
50
+ const costs = new Map<number, number>(),
51
+ longest: number[] = []
52
+ for (const [start, close] of [
53
+ [0, code.length - 1],
54
+ ...[...ends]
55
+ .filter(([at]) => code[at]?.op === 0x03)
56
+ .map(([at, last]) => [at + 1, last]),
57
+ ]) {
58
+ if (start === undefined || close === undefined)
59
+ throw new Error('Invalid v2 region')
60
+ for (let at = close; at >= start; at--) {
61
+ const op = code[at]?.op
62
+ let after = next[at] ?? [exit]
63
+ if (op === 0x03) {
64
+ // a nested loop is its own region; the path goes on wherever its body can leave to
65
+ const last = end(at),
66
+ out = new Set([last + 1])
67
+ for (let j = at + 1; j <= last; j++)
68
+ for (const to of next[j] ?? [])
69
+ if (to !== exit && (to <= at || to > last + 1)) out.add(to)
70
+ after = [...out]
71
+ }
72
+ let best = 0
73
+ for (const to of after)
74
+ if (to >= start && to <= close) best = Math.max(best, longest[to] ?? 0)
75
+ longest[at] =
76
+ 1 +
77
+ (op === 0x10 ? (constantCalls.get(code[at]?.args[0] ?? -1) ?? 0) : 0) +
78
+ best
79
+ }
80
+ costs.set(start, longest[start] ?? 0)
81
+ }
82
+ return costs
83
+ }
@@ -5,11 +5,14 @@ const CREATURE_COMMANDS = { lockable: 23, heal: 24, pull: 25, root: 26, ability:
5
5
  /** ONE-FORMAT CC59: a brain hook hears `part.broken` [actor, volume index]; `ability` [own actor, strike] replaces its
6
6
  * brain's next pick. A hit event's last slot is the mask of the row's `tags` the hit carried (bit i: i-th alias). */
7
7
  const CREATURE_EVENTS = { 'part.broken': 19 } as const;
8
+ /** WASM-HOST H25 (Jake's W27): `wake` [0, seconds slept] reaches a subscribed sim binding once when its slept cell next
9
+ * seats a player. Timers keep counting sim ticks; the script decides its own catch-up. */
10
+ const WAKE_EVENTS = { wake: 20 } as const;
8
11
  /** ABI-v1 numeric transport. These ids are shared by admission, generated bindings and the decision host. */
9
- export const SCRIPT_V1_EVENTS: Readonly<{ start: 1; tick: 2; timer: 3; 'zone.enter': 4; 'zone.leave': 5; interact: 6; hit: 7; threshold: 8; death: 9; 'move.done': 10; 'strike.done': 11; flag: 12; signal: 13; 'strike.target': 14; 'player.join': 15; 'player.leave': 16; spawned: 17; stop: 18; field: 30; cue: 31; channel: 32; } & typeof CREATURE_EVENTS> = Object.freeze({
12
+ export const SCRIPT_V1_EVENTS: Readonly<{ start: 1; tick: 2; timer: 3; 'zone.enter': 4; 'zone.leave': 5; interact: 6; hit: 7; threshold: 8; death: 9; 'move.done': 10; 'strike.done': 11; flag: 12; signal: 13; 'strike.target': 14; 'player.join': 15; 'player.leave': 16; spawned: 17; stop: 18; field: 30; cue: 31; channel: 32; } & typeof CREATURE_EVENTS & typeof WAKE_EVENTS> = Object.freeze({
10
13
  start: 1, tick: 2, timer: 3, 'zone.enter': 4, 'zone.leave': 5, interact: 6, hit: 7, threshold: 8,
11
14
  death: 9, 'move.done': 10, 'strike.done': 11, flag: 12, signal: 13, 'strike.target': 14,
12
- 'player.join': 15, 'player.leave': 16, spawned: 17, stop: 18, ...CREATURE_EVENTS, field: 30, cue: 31, channel: 32,
15
+ 'player.join': 15, 'player.leave': 16, spawned: 17, stop: 18, ...CREATURE_EVENTS, ...WAKE_EVENTS, field: 30, cue: 31, channel: 32,
13
16
  });
14
17
  /** Scalar reads; timer and random are answered by the host's own binding state. */
15
18
  export const SCRIPT_V1_READS: Readonly<{ x: 1; y: 2; z: 3; yaw: 4; hpShare: 5; alive: 6; field: 7; distance: 8; nearestPlayer: 9; flag: 10; timerLeft: 11; random: 12; actorInZone: 13; playersInZone: 14; moving: 15; strikeState: 16; playerFlag: 17; spawnGroupAlive: 18; bearing: 19; bodyX: 20; bodyY: 21; bodyZ: 22; bodyAlive: 23; bodyYaw: 24; bodyVisible: 25; playerIntent: 26; }> = Object.freeze({
@@ -4,6 +4,7 @@ import * as v from 'valibot';
4
4
  import { admitScript, type ScriptAdmission } from './scriptAdmission.ts';
5
5
  import { admitScriptV2, SCRIPT_V2_REVISIONS, type ScriptAdmissionV2 } from './scriptAdmissionV2.ts';
6
6
  import { DecisionScriptsSchema, parseDecisionScripts, type DecisionScripts } from './decisionScripts.ts';
7
+ import { decisionContract } from './decision-frame-v2.ts';
7
8
 
8
9
  /** Fixed ABI2 byte admission metadata, independent of execution or source sniffing. */
9
10
  export const ScriptV2ContractSchema: v.StrictObjectSchema<{ readonly abi: v.GenericSchema<ScriptV2ContractRowsInput['abi'], ScriptV2ContractRows['abi']>; readonly lane: v.GenericSchema<ScriptV2ContractRowsInput['lane'], ScriptV2ContractRows['lane']>; readonly pages: v.GenericSchema<ScriptV2ContractRowsInput['pages'], ScriptV2ContractRows['pages']>; readonly ioBytes: v.GenericSchema<ScriptV2ContractRowsInput['ioBytes'], ScriptV2ContractRows['ioBytes']>; readonly compilerRevision: v.GenericSchema<ScriptV2ContractRowsInput['compilerRevision'], ScriptV2ContractRows['compilerRevision']>; readonly admissionRevision: v.GenericSchema<ScriptV2ContractRowsInput['admissionRevision'], ScriptV2ContractRows['admissionRevision']>; }, undefined> = v.strictObject({ abi: v.literal(2), lane: v.picklist(['sim', 'project', 'view']), pages: v.pipe(v.number(), v.integer(), v.minValue(1), v.maxValue(4)),
@@ -69,7 +70,7 @@ export function decisionModuleContracts(input: ScriptAdmissionRows, files: reado
69
70
  const file = files.find(value => value.kind === 'wasm' && `blobs/wasm/${value.hash}.wasm` === row.module && (value.path === undefined || value.path === row.module));
70
71
  if (file === undefined) throw new Error('Decision script module is not an exact declared Wasm path');
71
72
  const contract = row.abi === 2 ? v.parse(ScriptV2ContractSchema, { abi: row.abi, lane: row.lane, pages: row.pages, ioBytes: row.ioBytes,
72
- compilerRevision: row.compilerRevision, admissionRevision: row.admissionRevision }) : { abi: 1 as const, pages: row.pages };
73
+ compilerRevision: row.compilerRevision, admissionRevision: row.admissionRevision }) : decisionContract(row);
73
74
  const old = contracts.get(file.hash);
74
75
  if (old !== undefined && (JSON.stringify(old) !== JSON.stringify(contract) || sides.get(file.hash) !== row.side)) throw new Error('Conflicting decision module contracts');
75
76
  contracts.set(file.hash, contract); sides.set(file.hash, row.side);
@@ -84,7 +85,7 @@ export function scriptAdmissionRows(sections?: ReadonlyMap<string, unknown>): Sc
84
85
  const decisions = parseDecisionScripts([...decisionScriptsFromSections(sections), ...spawn.map(row => row.script),
85
86
  ...returns.filter(row=>row.abi!==2)]);
86
87
  const owned = spawn.flatMap(row => row.v2 === undefined ? [] : [{ abi: 2 as const,id: `${row.step}:v2`,side: 'sim' as const,lane: 'sim' as const,module: `blobs/wasm/${row.v2.artifact.hash}.wasm`,pages: row.v2.artifact.pages,ioBytes: row.v2.artifact.ioBytes,compilerRevision: row.v2.artifact.compilerRevision,admissionRevision: row.v2.artifact.admissionRevision }]);
87
- return [...decisions, ...v.parse(ViewModulesSchema, sections?.get('view/modules') ?? []),...owned,...returns.filter(row=>row.abi===2)];
88
+ return [...decisions, ...v.parse(ViewModulesSchema, sections?.get('view/modules') ?? []), ...v.parse(v.array(OwnedSimModuleSchema), sections?.get('sim/modules') ?? []),...owned,...returns.filter(row=>row.abi===2)];
88
89
  }
89
90
 
90
91
  /** Fresh v1 memory is consumed only by stateful sim decisions, once per module.
@@ -95,7 +96,7 @@ export function decisionMemoryPreparationPages(sections?: ReadonlyMap<string, un
95
96
  const decisions = new Set(decisionScriptsFromSections(sections).map(row => row.id));
96
97
  const modules = new Map<string, number>();
97
98
  for (const row of inventory) {
98
- if (row.abi === 2 || !decisions.has(row.id)) continue;
99
+ if (row.abi === 2 || row.abi === '2.0' || !decisions.has(row.id)) continue;
99
100
  const previous = modules.get(row.module);
100
101
  if (previous !== undefined && previous !== row.pages) throw new Error('Conflicting decision memory pages');
101
102
  modules.set(row.module, row.pages);
@@ -2,6 +2,7 @@
2
2
  * not permission to instantiate an image by itself. */
3
3
  import { SCRIPT_ABI } from './scriptAbi.ts';
4
4
  import { readV2Module,type V2Instruction,type V2Module,type V2Signature } from './scriptModuleV2.ts';
5
+ import { v2PathCosts } from './script-fuel-path-v2.ts';
5
6
 
6
7
  export const V2_ENTRY_SIGNATURES: Readonly<Record<string,readonly number[]>> = Object.freeze({
7
8
  ws_init: [0x7f,0x7f,0x7f], ws_step: [0x7f,0x7f], ws_project: [0x7f], ws_view: [0x7c,0x7c,0x7f],
@@ -107,8 +108,9 @@ export function inspectV2Fuel(bytes: Uint8Array,options: { readonly lane?: V2Lan
107
108
  }
108
109
  plain.push(value);
109
110
  }
110
- const costs = v2BlockCosts(plain,new Map([...getters].map(target => [target,2])));
111
- if (costs.size !== charges.size || [...costs].some(([at,cost]) => charges.get(at) !== cost)) throw new Error('Missing or underpriced v2 basic block region');
111
+ // H2c: each region pays at least its longest path (script-fuel-path-v2.ts); H0's whole-region price is no less
112
+ const costs = v2PathCosts(plain,new Map([...getters].map(target => [target,2])));
113
+ if (costs.size !== charges.size || [...costs].some(([at,cost]) => (charges.get(at) ?? Number.NEGATIVE_INFINITY) < cost)) throw new Error('Missing or underpriced v2 basic block region');
112
114
  unmetered.push(plain); calls.push(edges);
113
115
  }
114
116
  const depths = new Map<number,number>(), active = new Set<number>();
@@ -13,7 +13,7 @@ import type { QuestServer } from './quest-server.ts';
13
13
  import type { ServerHosts } from './server-hosts.ts';
14
14
  import type { ServerWorld } from './server-world.ts';
15
15
  import type { NativeSweptPolicyRows } from './items.ts';
16
- import type { ReturnModuleRow, ViewModuleRow } from './scriptContract.ts';
16
+ import type { OwnedSimModuleRows, ReturnModuleRow, ViewModuleRow } from './scriptContract.ts';
17
17
  import type { WorldScenesSection } from './worldScenes.ts';
18
18
  import type { TreeSetRows } from './treeSetRows.ts';
19
19
  import type { Vehicles } from './vehicles.ts';
@@ -54,6 +54,8 @@ export interface PlatformSections {
54
54
  'models/island-library': ResolvedIslandLibraryRows;
55
55
  'player/stealth':StealthRows;
56
56
  'view/modules': ViewModuleRow[];
57
+ /** WASM-HOST H13: the ABI v2 modules numeric hosts run. */
58
+ 'sim/modules': OwnedSimModuleRows[];
57
59
  /** Client-only ordered model references, ignored by simulation. */
58
60
  'explore/catalogue': ExplorerCatalogue;
59
61
  'look/toon': ToonLookRow;
@@ -33,7 +33,7 @@ const vec3 = v.tuple([ShardFiniteSchema, ShardFiniteSchema, ShardFiniteSchema]);
33
33
  export const CellBoundsSchema: v.GenericSchema<CellBoundsInput, CellBounds> = v.pipe(v.strictObject({ min: vec3, max: vec3 }), v.check((b) => b.min.every((n, i) => n <= (b.max[i] ?? -Infinity)), 'ordered bounds'), v.check((b) => b.min[0] >= -CHUNK_HALF && b.max[0] <= CHUNK_HALF && b.min[2] >= -CHUNK_HALF && b.max[2] <= CHUNK_HALF && b.min[1] >= -CELL_BELOW && b.max[1] <= CELL_ABOVE, 'cell bounds'));
34
34
  const drawBounds = CellBoundsSchema;
35
35
  const costs = { compressed: ShardNaturalSchema, decoded: ShardNaturalSchema, gpu: ShardNaturalSchema, triangles: ShardNaturalSchema, draws: ShardNaturalSchema };
36
- /** Meta ZONE-SIZE-LIMITS ZL29 (J551): a fine tile's draws the engine merges for the view, one per (key, 250 m block) across
36
+ /** Meta ZONE-SIZE-LIMITS ZL29 (D3): a fine tile's draws the engine merges for the view, one per (key, 250 m block) across
37
37
  * resident tiles: their keys, the tile draws they account for and the shadow draws the tile keeps for them. */
38
38
  const merged = v.strictObject({ keys: ShardNamesSchema, draws: ShardNaturalSchema, shadows: ShardNaturalSchema, vertices: v.exactOptional(v.array(ShardNaturalSchema)) });
39
39
  const tile: v.GenericSchema<ShardTileRowsInput, ShardTileRows> = v.strictObject({ lod: v.picklist([0, 1]), x: ShardNaturalSchema, z: ShardNaturalSchema, bounds: CellBoundsSchema, drawBounds: v.exactOptional(drawBounds), merged: v.exactOptional(merged), geometricError: v.pipe(ShardFiniteSchema, v.minValue(0)), files: ShardReferencesSchema, ...costs });
@@ -1,6 +1,6 @@
1
1
  import { CONTENT_CAPS } from './contentBounds.ts'
2
2
 
3
- // Meta J557 (Jake, 2026-11-30): Mossgate's worst view count (287) plus 10%
3
+ // Meta ZONE-SIZE-LIMITS D5 (Jake, 2026-11-30): Mossgate's worst view count (287) plus 10%
4
4
  const PHONE_VIEW = 320
5
5
  const DESKTOP_VIEW = 400
6
6
  const FINE = 0
@@ -148,6 +148,12 @@
148
148
  "sim/hooks": {
149
149
  "hosts": ["server createShardfileScriptLane"]
150
150
  },
151
+ "sim/modules": {
152
+ "hosts": [
153
+ "shard-format SimModulesSchema",
154
+ "shard-format admitScriptContract"
155
+ ]
156
+ },
151
157
  "sim/plumbing": {
152
158
  "hosts": ["page installDeclaredPlumbing"]
153
159
  },