@wildshard/shard-format 0.25.0 → 0.27.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 (54) hide show
  1. package/package.json +4 -1
  2. package/src/format/actorMoves.ts +32 -0
  3. package/src/format/audio-mp4.ts +1 -1
  4. package/src/format/audioProfiles.ts +1 -1
  5. package/src/format/boot-memory-cost.ts +93 -2
  6. package/src/format/brains.ts +3 -3
  7. package/src/format/budget-tiers.ts +62 -0
  8. package/src/format/builtIndexes.ts +2 -2
  9. package/src/format/clientChannels.ts +3 -3
  10. package/src/format/clientScripts.ts +1 -1
  11. package/src/format/contentBounds.ts +1 -1
  12. package/src/format/contentCost.ts +2 -1
  13. package/src/format/creature-layers.ts +13 -1
  14. package/src/format/creature-ranks.ts +37 -0
  15. package/src/format/creature-sizes.ts +45 -4
  16. package/src/format/creature-volumes.ts +5 -4
  17. package/src/format/creatures.ts +20 -3
  18. package/src/format/crowds.ts +1 -1
  19. package/src/format/deviceMemoryCost.ts +2 -2
  20. package/src/format/directorStages.ts +3 -3
  21. package/src/format/flyers.ts +2 -2
  22. package/src/format/grazers.ts +2 -2
  23. package/src/format/items.ts +1 -1
  24. package/src/format/materialGraph.ts +7 -7
  25. package/src/format/materials.ts +10 -10
  26. package/src/format/memory-epoch.ts +1 -1
  27. package/src/format/memory-line.ts +48 -5
  28. package/src/format/memoryAdmission.ts +1 -1
  29. package/src/format/namedJsonContracts.ts +1 -1
  30. package/src/format/nativeGround.ts +3 -3
  31. package/src/format/navigation.ts +2 -2
  32. package/src/format/parsed-json.ts +91 -0
  33. package/src/format/placement-page-text.ts +281 -0
  34. package/src/format/questHost.ts +1 -1
  35. package/src/format/rows.ts +18 -5
  36. package/src/format/runtime-tier.ts +56 -0
  37. package/src/format/runtimeBinds.ts +6 -6
  38. package/src/format/runtimeCost.ts +1 -1
  39. package/src/format/runtimeSpawns.ts +2 -2
  40. package/src/format/scaledPostContract.ts +2 -2
  41. package/src/format/scriptAbi.ts +1 -1
  42. package/src/format/scriptWireV2.ts +1 -1
  43. package/src/format/shardSchema.ts +2 -2
  44. package/src/format/shardSections.ts +7 -1
  45. package/src/format/shardfile-assets.ts +9 -10
  46. package/src/format/shardfileValidation.ts +17 -11
  47. package/src/format/skin-file.ts +3 -0
  48. package/src/format/skinData.ts +39 -19
  49. package/src/format/skins.ts +21 -2
  50. package/src/format/sourceResidency.ts +1 -1
  51. package/src/format/standalone-catalogue.ts +1 -1
  52. package/src/format/terrain.ts +1 -1
  53. package/src/format/validationReceipt.ts +2 -2
  54. package/src/format/weaponProfiles.ts +2 -2
@@ -62,7 +62,24 @@ const phase = v.pipe(finite, v.minValue(-2 * Math.PI), v.maxValue(2 * Math.PI));
62
62
  const RESPAWN_MAX = 3600, RESPAWN_MIN = 1;
63
63
  const respawn = v.pipe(finite, v.minValue(RESPAWN_MIN), v.maxValue(RESPAWN_MAX));
64
64
  /** Social membership names no controller; the species temperament owns assistance. */
65
- const spawn = v.strictObject({ perchBody: v.exactOptional(id), group: v.exactOptional(id), phaseOffset: v.optional(phase), home: v.optional(CreatureHomeSchema), respawn: v.optional(respawn), id, species: id, variant: id, brain: v.nullable(id), strike: v.nullable(id), seed: v.pipe(finite, v.integer(), v.minValue(0), v.maxValue(0xffffffff)), scale: v.pipe(finite, v.minValue(0.1), v.maxValue(10)), at: v.tuple([coord, coord, coord]), yaw: finite });
65
+ /** OF28: the rank names of ./creature-ranks.ts (kept in step by its test); the engine applies the multipliers. */
66
+ const rank = v.picklist(['veteran', 'elite', 'champion', 'legendary'], 'unknown creature rank');
67
+ /** OF28b (Q-CC35): one row grows by one creature per `per` players in the cell, to `max`; the size class weighs `max`. */
68
+ const MOST_PER_ROW = 64;
69
+ const FIRST_GROWN = 2;
70
+ const LAST_STAGE = 255;
71
+ const LEAST_PER_ROW = 1;
72
+ const FIRST_STAGE = 0;
73
+ const countPart = v.pipe(finite, v.integer(), v.minValue(LEAST_PER_ROW), v.maxValue(MOST_PER_ROW));
74
+ const count = v.strictObject({ per: countPart, max: v.pipe(countPart, v.minValue(FIRST_GROWN)) });
75
+ /** OF28c: when a row lives. `quest`: from that stage on; `time`: only by day or by night; `wave`: wave `index` of a `set`,
76
+ * after the wave before it in that set has fallen. Respawn timers (`respawn`) and group mix (`group`) stay their own fields. */
77
+ const stage = v.pipe(finite, v.integer(), v.minValue(FIRST_STAGE), v.maxValue(LAST_STAGE));
78
+ const questWhen = v.strictObject({ id, stage });
79
+ const waveWhen = v.strictObject({ set: id, index: countPart });
80
+ const timeWhen = v.picklist(['day', 'night'], 'unknown spawn time');
81
+ const when = v.strictObject({ quest: v.exactOptional(questWhen), time: v.exactOptional(timeWhen), wave: v.exactOptional(waveWhen) }, 'unknown spawn condition');
82
+ const spawn = v.strictObject({ perchBody: v.exactOptional(id), group: v.exactOptional(id), rank: v.exactOptional(rank), count: v.exactOptional(count), when: v.exactOptional(when), phaseOffset: v.optional(phase), home: v.optional(CreatureHomeSchema), respawn: v.optional(respawn), id, species: id, variant: id, brain: v.nullable(id), strike: v.nullable(id), seed: v.pipe(finite, v.integer(), v.minValue(0), v.maxValue(0xffffffff)), scale: v.pipe(finite, v.minValue(0.1), v.maxValue(10)), at: v.tuple([coord, coord, coord]), yaw: finite });
66
83
  /** Pure-data creature archetypes and stable spawn layouts, expanded before the local sim boots. */
67
84
  export const CreaturesSchema: v.GenericSchema<ShardCreaturesInput, ShardCreatures> = v.pipe(v.strictObject({ perchBodies: v.exactOptional(CreaturePerchBodiesSchema), brains: v.pipe(v.array(v.variant('kind', [brain, SkirmisherSchema, GuardianSchema, PerchHunterSchema, ScriptBrainSchema, RamGrazerSchema, ChallengeGrazerSchema, OrbitDiverSchema, PatrolDiverSchema, BurstFlyerSchema, GrazerSchema, DiverSchema, GuardianPatternsSchema, StalkerSchema])), v.maxLength(64)), groups: v.optional(v.pipe(v.array(GroupBrainSchema), v.maxLength(64)), []), spawns: v.pipe(v.array(spawn), v.maxLength(10000)) }),
68
85
  v.check((c) => creatureRules(c).length === 0, 'creature reference rules'));
@@ -168,8 +185,8 @@ export interface CreatureMemoryActionsRows { stateKey: string; states: (string)[
168
185
  export interface CreatureBodyRecipeRowsInput { actions?: CreatureMemoryActionsRowsInput; offset?: { field: string; from: number; to: number; }; kind: 'animal'; motion: 'ground' | 'flight'; attack: 'keeper' | 'unlimited'; stunned: 'none' | 'look-hold'; contact: ({ kind: 'environment'; halfArc: number; }) | ({ kind: 'actor'; halfArc: number; move: string; }); }
169
186
  export interface CreatureBodyRecipeRows { actions?: CreatureMemoryActionsRows; offset?: { field: string; from: number; to: number; }; kind: 'animal'; motion: 'ground' | 'flight'; attack: 'keeper' | 'unlimited'; stunned: 'none' | 'look-hold'; contact: ({ kind: 'environment'; halfArc: number; }) | ({ kind: 'actor'; halfArc: number; move: string; }); }
170
187
  // oxlint-disable-next-line typescript/consistent-type-definitions -- Valibot's readonly defaults need the alias's implicit dictionary compatibility.
171
- export type ShardCreaturesInput = { perchBodies?: CreaturePerchBodyInput[]; brains: (({ id: string; kind: 'pursue'; awareRadius: number; leashRadius: number; speed: number; returnSpeed: number; stopDistance: number; turnRate: number; thinkDivisor: number; attackCooldownTicks: number; wanderRadius: number; wanderEveryTicks: number; }) | (v.InferInput<typeof SkirmisherSchema>) | (v.InferInput<typeof GuardianSchema>) | (v.InferInput<typeof PerchHunterSchema>) | (v.InferInput<typeof ScriptBrainSchema>) | (v.InferInput<typeof RamGrazerSchema>) | (v.InferInput<typeof ChallengeGrazerSchema>) | (v.InferInput<typeof OrbitDiverSchema>) | (v.InferInput<typeof PatrolDiverSchema>) | (v.InferInput<typeof BurstFlyerSchema>) | (v.InferInput<typeof GrazerSchema>) | (v.InferInput<typeof DiverSchema>) | (v.InferInput<typeof GuardianPatternsSchema>) | (v.InferInput<typeof StalkerSchema>))[]; groups?: (v.InferInput<typeof GroupBrainSchema>)[] | undefined; spawns: ({ perchBody?: string; group?: string; phaseOffset?: number | undefined; respawn?: number | undefined; home?: ShardCreatureHomeInput | undefined; id: string; species: string; variant: string; brain: (string) | null; strike: (string) | null; seed: number; scale: number; at: [number, number, number]; yaw: number; })[]; };
172
- export interface ShardCreatures { perchBodies?: CreaturePerchBody[]; brains: (({ id: string; kind: 'pursue'; awareRadius: number; leashRadius: number; speed: number; returnSpeed: number; stopDistance: number; turnRate: number; thinkDivisor: number; attackCooldownTicks: number; wanderRadius: number; wanderEveryTicks: number; }) | (v.InferOutput<typeof SkirmisherSchema>) | (v.InferOutput<typeof GuardianSchema>) | (v.InferOutput<typeof PerchHunterSchema>) | (v.InferOutput<typeof ScriptBrainSchema>) | (v.InferOutput<typeof RamGrazerSchema>) | (v.InferOutput<typeof ChallengeGrazerSchema>) | (v.InferOutput<typeof OrbitDiverSchema>) | (v.InferOutput<typeof PatrolDiverSchema>) | (v.InferOutput<typeof BurstFlyerSchema>) | (v.InferOutput<typeof GrazerSchema>) | (v.InferOutput<typeof DiverSchema>) | (v.InferOutput<typeof GuardianPatternsSchema>) | (v.InferOutput<typeof StalkerSchema>))[]; groups: (v.InferOutput<typeof GroupBrainSchema>)[]; spawns: ({ perchBody?: string; group?: string; phaseOffset?: number | undefined; respawn?: number | undefined; home?: ShardCreatureHome | undefined; id: string; species: string; variant: string; brain: (string) | null; strike: (string) | null; seed: number; scale: number; at: [number, number, number]; yaw: number; })[]; }
188
+ export type ShardCreaturesInput = { perchBodies?: CreaturePerchBodyInput[]; brains: (({ id: string; kind: 'pursue'; awareRadius: number; leashRadius: number; speed: number; returnSpeed: number; stopDistance: number; turnRate: number; thinkDivisor: number; attackCooldownTicks: number; wanderRadius: number; wanderEveryTicks: number; }) | (v.InferInput<typeof SkirmisherSchema>) | (v.InferInput<typeof GuardianSchema>) | (v.InferInput<typeof PerchHunterSchema>) | (v.InferInput<typeof ScriptBrainSchema>) | (v.InferInput<typeof RamGrazerSchema>) | (v.InferInput<typeof ChallengeGrazerSchema>) | (v.InferInput<typeof OrbitDiverSchema>) | (v.InferInput<typeof PatrolDiverSchema>) | (v.InferInput<typeof BurstFlyerSchema>) | (v.InferInput<typeof GrazerSchema>) | (v.InferInput<typeof DiverSchema>) | (v.InferInput<typeof GuardianPatternsSchema>) | (v.InferInput<typeof StalkerSchema>))[]; groups?: (v.InferInput<typeof GroupBrainSchema>)[] | undefined; spawns: ({ perchBody?: string; group?: string; rank?: 'veteran' | 'elite' | 'champion' | 'legendary'; count?: { per: number; max: number }; when?: { quest?: { id: string; stage: number }; time?: 'day' | 'night'; wave?: { set: string; index: number } }; phaseOffset?: number | undefined; respawn?: number | undefined; home?: ShardCreatureHomeInput | undefined; id: string; species: string; variant: string; brain: (string) | null; strike: (string) | null; seed: number; scale: number; at: [number, number, number]; yaw: number; })[]; };
189
+ export interface ShardCreatures { perchBodies?: CreaturePerchBody[]; brains: (({ id: string; kind: 'pursue'; awareRadius: number; leashRadius: number; speed: number; returnSpeed: number; stopDistance: number; turnRate: number; thinkDivisor: number; attackCooldownTicks: number; wanderRadius: number; wanderEveryTicks: number; }) | (v.InferOutput<typeof SkirmisherSchema>) | (v.InferOutput<typeof GuardianSchema>) | (v.InferOutput<typeof PerchHunterSchema>) | (v.InferOutput<typeof ScriptBrainSchema>) | (v.InferOutput<typeof RamGrazerSchema>) | (v.InferOutput<typeof ChallengeGrazerSchema>) | (v.InferOutput<typeof OrbitDiverSchema>) | (v.InferOutput<typeof PatrolDiverSchema>) | (v.InferOutput<typeof BurstFlyerSchema>) | (v.InferOutput<typeof GrazerSchema>) | (v.InferOutput<typeof DiverSchema>) | (v.InferOutput<typeof GuardianPatternsSchema>) | (v.InferOutput<typeof StalkerSchema>))[]; groups: (v.InferOutput<typeof GroupBrainSchema>)[]; spawns: ({ perchBody?: string; group?: string; rank?: 'veteran' | 'elite' | 'champion' | 'legendary'; count?: { per: number; max: number }; when?: { quest?: { id: string; stage: number }; time?: 'day' | 'night'; wave?: { set: string; index: number } }; phaseOffset?: number | undefined; respawn?: number | undefined; home?: ShardCreatureHome | undefined; id: string; species: string; variant: string; brain: (string) | null; strike: (string) | null; seed: number; scale: number; at: [number, number, number]; yaw: number; })[]; }
173
190
  export type CreatureStrikeRowsInput = CreatureStrikeRows;
174
191
  export interface CreatureStrikeRows { debris?: StrikeDebrisPolicy; id: string; shape: ({ kind: 'arc'; radius: number; halfAngle: number; yawOffset?: number; }) | ({ kind: 'lane'; length: number; width: number; }) | ({ kind: 'ring'; inner: number; outer: number; }) | ({ kind: 'wedge'; length: number; halfAngle: number; }) | ({ kind: 'point'; radius: number; exclusive?: boolean; }) | ({ kind: 'sphere'; radius: number; }); windup: number; active: number; recover: number; cooldown: number; range: (number) | null; damage: number; tags: (`${string}.${string}`)[]; weight: ({ kind: 'constant'; value: number; }) | ({ kind: 'horizontal-distance'; above: number; far: number; near: number; }); units?: 'world' | 'actor'; alternatives?: (({ kind: 'arc'; radius: number; halfAngle: number; yawOffset?: number; }) | ({ kind: 'lane'; length: number; width: number; }) | ({ kind: 'ring'; inner: number; outer: number; }) | ({ kind: 'wedge'; length: number; halfAngle: number; }) | ({ kind: 'point'; radius: number; exclusive?: boolean; }) | ({ kind: 'sphere'; radius: number; }))[]; motion?: { speed?: number; delay?: number; track?: 'none' | 'lead' | 'follow'; overshoot?: number; skid?: number; }; eligibility?: { maxDy?: number; jumpDodges?: boolean; }; }
175
192
  export type CreatureStrikesInput = unknown;
@@ -6,7 +6,7 @@ const finite = v.pipe(v.number(), v.finite());
6
6
  const coordinate = v.pipe(finite, v.minValue(-100000), v.maxValue(100000));
7
7
  const speed = v.pipe(finite, v.minValue(0), v.maxValue(15));
8
8
 
9
- /** Ordered instanced flock declaration; terrain, native view, prey and distance scheduling remain trusted ports. */
9
+ /** Ordered instanced flock declaration; terrain, native view, prey and distance scheduling remain native ports. */
10
10
  export const FlockSchema: v.GenericSchema<ShardFlockInput, ShardFlock> = v.strictObject({
11
11
  id: key, kind: v.literal('flock'), x: coordinate, z: coordinate,
12
12
  count: v.pipe(v.number(), v.integer(), v.minValue(1), v.maxValue(256)),
@@ -12,7 +12,7 @@ export function acceptsShardfileCost(memory: MemoryAdmission | undefined, source
12
12
  claimedBytes: cost.accounted, accountedBytes: cost.accounted, playingBytes: cost.playing, loadingBytes: cost.loading });
13
13
  }
14
14
 
15
- /** Reapply the current trusted memory policy to a previously validated exact declaration. */
15
+ /** Reapply the current host-owned memory policy to a previously validated exact declaration. */
16
16
  export function acceptValidatedCost(source: Shardfile, cost: ReturnType<typeof worstContentCost>, memory?: MemoryAdmission): void {
17
17
  if (!acceptsShardfileCost(memory, source, 'declared', cost)) throw new Error(`declared worst-location total exceeds envelope: play ${cost.playing}, load ${cost.loading}${overHardLine(Math.max(cost.playing, cost.loading))}`);
18
18
  }
@@ -44,7 +44,7 @@ export function textureLibrarySource(source: Shardfile, assets: ReadonlyMap<stri
44
44
  return { ...source, budgets: { ...source.budgets, library: { ...source.budgets.library, resident: Math.max(0, source.budgets.library.resident - saving) } } };
45
45
  }
46
46
 
47
- /** Trusted device's exact library projection, with all existing conservative neighbour and fallback ceilings retained. */
47
+ /** Host-owned device's exact library projection, with all existing conservative neighbour and fallback ceilings retained. */
48
48
  export function* deviceLibraryCostSteps(source: Shardfile, assets: ReadonlyMap<string, Uint8Array>, support?: TextureTranscodeSupport, deviceCosts?: ReadonlyMap<string, Ktx2DeviceCosts>): Generator<void, ReturnType<typeof worstContentCost>> {
49
49
  const commons = Object.values(source.requires.commonsCosts).reduce((sum, row) => sum + row.decoded + row.gpu, 0);
50
50
  return yield* worstContentCostSteps(textureLibrarySource(source, assets, support, deviceCosts), commons);
@@ -69,14 +69,14 @@ export type DirectorAction = DirectorStagesData['stages'][number]['do'][number];
69
69
  export function parseDirectorStages(input: unknown): DirectorStagesData { return v.parse(DirectorStagesSchema, input); }
70
70
 
71
71
 
72
- /** Root-owned pacing rows with distinct identities; an AS handler is installed only through explicit trusted bindings. */
72
+ /** Root-owned pacing rows with distinct identities; an AS handler is installed only through explicit native bindings. */
73
73
  export const DirectorsSchema: v.GenericSchema<DirectorsDataInput, DirectorsData> = v.pipe(v.array(DirectorStagesSchema), v.maxLength(16), v.check(rows => new Set(rows.map(row => row.id)).size === rows.length, 'Unique director identities'));
74
74
 
75
75
  /** Describe stock data-only support: quest flags, bounded day inputs and flag actions.
76
- * Other admitted actions need trusted native owners; emit is not AssemblyScript delivery. */
76
+ * Other admitted actions need native owners; emit is not AssemblyScript delivery. */
77
77
  export function directorDataHostIssues(data: DirectorStagesData): readonly string[] {
78
78
  const issues: string[] = [];
79
- if (data.script !== null) issues.push('script requires a trusted typed director host');
79
+ if (data.script !== null) issues.push('script requires a host-owned typed director host');
80
80
  for (const [inputName, binding] of Object.entries(data.inputs)) {
81
81
  if (!binding.startsWith('flag:') && directorDayRange(binding) === null) issues.push(`input ${inputName} (${binding}) requires a native observation owner`);
82
82
  }
@@ -22,7 +22,7 @@ export const OrbitDiverSchema: v.SchemaWithPipe<readonly [v.StrictObjectSchema<{
22
22
  noticeRadius: radius, giveUpRadius: radius, initialRestSeconds: radius, stalkMaxSeconds: positive,
23
23
  riseMargin: radius, targetHeight: radius, alignRadius: positive, alignTolerance: positive,
24
24
  }), v.check(row => orderedOrbit(row), 'Ordered orbit perception'));
25
- /** Admitted orbit/dive policy; native flight, token and contact execution remain trusted host ports. */
25
+ /** Admitted orbit/dive policy; native flight, token and contact execution remain native host ports. */
26
26
  export type ShardOrbitDiver = v.InferOutput<typeof OrbitDiverSchema>;
27
27
  /** Validate overhead dive data without instantiating a creature or executing its native flight recipe. */
28
28
  export function parseOrbitDiver(data: unknown): ShardOrbitDiver { return v.parse(OrbitDiverSchema, data); }
@@ -41,7 +41,7 @@ export type ShardPatrolDiver = v.InferOutput<typeof PatrolDiverSchema>;
41
41
  /** Refuse invalid patrol timing, memory fields and speed before any callbacks register. */
42
42
  export function parsePatrolDiver(data: unknown): ShardPatrolDiver { return v.parse(PatrolDiverSchema, data); }
43
43
 
44
- /** Small-circle drift and telegraphed chest dart; contact shove is declared data and applied only by a trusted port. */
44
+ /** Small-circle drift and telegraphed chest dart; contact shove is declared data and applied only by a native port. */
45
45
  export const BurstFlyerSchema: v.StrictObjectSchema<{ readonly id: v.GenericSchema<BurstFlyerRowsInput['id'], BurstFlyerRows['id']>; readonly kind: v.GenericSchema<BurstFlyerRowsInput['kind'], BurstFlyerRows['kind']>; readonly thinkDivisor: v.OptionalSchema<v.GenericSchema<Exclude<BurstFlyerRowsInput['thinkDivisor'], undefined>, Exclude<BurstFlyerRows['thinkDivisor'], undefined>>, 6>; readonly strike: v.GenericSchema<BurstFlyerRowsInput['strike'], BurstFlyerRows['strike']>; readonly home: v.GenericSchema<BurstFlyerRowsInput['home'], BurstFlyerRows['home']>; readonly circleSpeed: v.GenericSchema<BurstFlyerRowsInput['circleSpeed'], BurstFlyerRows['circleSpeed']>; readonly dartSpeed: v.GenericSchema<BurstFlyerRowsInput['dartSpeed'], BurstFlyerRows['dartSpeed']>; readonly noticeRadius: v.GenericSchema<BurstFlyerRowsInput['noticeRadius'], BurstFlyerRows['noticeRadius']>; readonly shoveSpeed: v.GenericSchema<BurstFlyerRowsInput['shoveSpeed'], BurstFlyerRows['shoveSpeed']>; readonly liftSpeed: v.GenericSchema<BurstFlyerRowsInput['liftSpeed'], BurstFlyerRows['liftSpeed']>; readonly targetHeight: v.GenericSchema<BurstFlyerRowsInput['targetHeight'], BurstFlyerRows['targetHeight']>; }, undefined> = v.strictObject({
46
46
  id: key, kind: v.literal('burst-flyer'), thinkDivisor: cadence, strike: key, home,
47
47
  circleSpeed: speed, dartSpeed: speed, noticeRadius: radius, shoveSpeed: speed, liftSpeed: speed, targetHeight: radius,
@@ -35,7 +35,7 @@ export const ChallengeGrazerSchema: v.SchemaWithPipe<readonly [v.StrictObjectSch
35
35
  windupField: v.pipe(v.string(), v.regex(/^[a-z][a-z0-9._:-]*$/u), v.maxLength(128)),
36
36
  recoveryField: v.pipe(v.string(), v.regex(/^[a-z][a-z0-9._:-]*$/u), v.maxLength(128)),
37
37
  }), v.check(row => distinctChallenge(row), 'Distinct challenge strikes and fields, ordered perception'));
38
- /** Admitted timed challenge policy; stable actor phase and contact recipes arrive from trusted loader ports. */
38
+ /** Admitted timed challenge policy; stable actor phase and contact recipes arrive from native loader ports. */
39
39
 
40
40
  /** Reject nonfinite tuning, unknown fields and conflicting identities before installation. */
41
41
  export function parseChallengeGrazer(data: unknown): ShardChallengeGrazer { return v.parse(ChallengeGrazerSchema, data); }
@@ -56,7 +56,7 @@ export const GrazerSchema: v.VariantSchema<'pattern', readonly [
56
56
  v.pipe(v.strictObject({ ...ChallengeGrazerSchema.pipe[0].entries, kind: v.literal('grazer'), pattern: v.literal('circle-challenge') }),
57
57
  v.check(row => distinctChallenge(row), 'Distinct challenge strikes and fields, ordered perception')),
58
58
  ]);
59
- /** Admitted grazer data; floor, RNG and body authority remain trusted pattern-specific ports. */
59
+ /** Admitted grazer data; floor, RNG and body authority remain native pattern-specific ports. */
60
60
 
61
61
  /** Admit either pattern without constructing a policy, body or random stream. */
62
62
  export function parseGrazer(data: unknown): ShardGrazer { return v.parse(GrazerSchema, data); }
@@ -5,7 +5,7 @@ import * as v from 'valibot';
5
5
  import { MeleeContactsSchema, NativeMeleeRowSchema, WeaponProfileSchema, type MeleeContactRow } from './weaponProfiles.ts';
6
6
  import { isJsonData } from './json.ts';
7
7
 
8
- /** The bounded authored family/context name, also checked by the trusted family installer. */
8
+ /** The bounded authored family/context name, also checked by the native family installer. */
9
9
  export const ItemFamilyNameSchema: v.GenericSchema<ItemFamilyNameRowsInput, ItemFamilyNameRows> = v.pipe(v.string(), v.regex(/^[a-z][a-zA-Z0-9.-]*$/u), v.maxLength(128));
10
10
  const name = ItemFamilyNameSchema;
11
11
  const weaponId: v.GenericSchema<`weapon.${string}`> = v.custom<`weapon.${string}`>((value) => typeof value === 'string' && /^weapon\.[a-z][a-zA-Z0-9.-]*$/u.test(value) && value.length <= 128);
@@ -111,7 +111,7 @@ export interface GraphParam {
111
111
  readonly max?: number;
112
112
  readonly bind?: GraphBinding;
113
113
  /**
114
- * Texture only: data bypasses sRGB conversion; absent retains the colour role. `lent`: no admitted file, a trusted
114
+ * Texture only: data bypasses sRGB conversion; absent retains the colour role. `lent`: no admitted file, a host-owned
115
115
  * runtime lends the sampled texture (`setTexture`, swapped without a program change; a 1×1 black stand-in until then)
116
116
  * and `value` only names the slot; a texture it decodes at run time (a baked sky key) is sampled as it is.
117
117
  */
@@ -218,7 +218,7 @@ export interface GraphStages {
218
218
  /** a graph */
219
219
  export interface GraphIr {
220
220
  readonly version: typeof GRAPH_IR_VERSION;
221
- /** Explicit per-program ceilings. Raising the defaults requires trusted runtime authority. */
221
+ /** Explicit per-program ceilings. Raising the defaults requires native runtime authority. */
222
222
  readonly budget?: GraphBudget;
223
223
  /** a material (vertex.offset + surface), a screen pass (post) or a shard's declared fog (fog, selected by materials) */
224
224
  readonly kind: 'material' | 'post' | 'fog';
@@ -252,10 +252,10 @@ export interface GraphBudget {
252
252
  }
253
253
  /** the default ceilings (a starter graph: the measure preset is ≈ 60 nodes, ≈ 170 instructions) */
254
254
  export const DEFAULT_GRAPH_BUDGET: GraphBudget = { nodes: 160, samplers: 4, instructions: 480 };
255
- /** Hard ceilings for a trusted declaration; loop trips remain charged to the estimated cost. */
255
+ /** Hard ceilings for a native declaration; loop trips remain charged to the estimated cost. */
256
256
  export const MAX_GRAPH_BUDGET: GraphBudget = Object.freeze({ nodes: 4096, samplers: 16, instructions: 8192 });
257
257
 
258
- /** Raw graph JSON bounds, enforced before typing or compiler work; trusted presets supply their own node budget. */
258
+ /** Raw graph JSON bounds, enforced before typing or compiler work; host-owned presets supply their own node budget. */
259
259
  export const GRAPH_ADMISSION_LIMITS: Readonly<{ bytes: 96000; depth: 64; }> = Object.freeze({ bytes: 96_000, depth: 64 });
260
260
  /** whether JSON writes `value` as itself in quotes: printable ASCII with no quote or backslash (a loop, not a regex: Node's
261
261
  * type stripping rewrote the regex's escaped bracket and broke it) */
@@ -560,7 +560,7 @@ export interface GraphValidationOptions {
560
560
  readonly stateFields?: readonly string[];
561
561
  readonly budget?: GraphBudget;
562
562
  /** Host authority to use an explicit declaration; content cannot grant this. */
563
- readonly trustedBudget?: boolean;
563
+ readonly declaredBudget?: boolean;
564
564
  /** the directional lights a `sun` sub-graph is built for (1 … SUN_CASCADES_MAX; SUN_CASCADES when absent) */
565
565
  readonly cascades?: number;
566
566
  }
@@ -624,7 +624,7 @@ interface Scope {
624
624
  * every reason it is refused.
625
625
  */
626
626
  export function validateGraph(input: unknown, opts: GraphValidationOptions = {}): GraphValidation {
627
- const rawErrors = graphAdmissionErrors(input, opts.trustedBudget === true ? MAX_GRAPH_BUDGET.nodes : opts.budget?.nodes ?? DEFAULT_GRAPH_BUDGET.nodes);
627
+ const rawErrors = graphAdmissionErrors(input, opts.declaredBudget === true ? MAX_GRAPH_BUDGET.nodes : opts.budget?.nodes ?? DEFAULT_GRAPH_BUDGET.nodes);
628
628
  if (rawErrors.length > 0) return { ok: false, errors: rawErrors };
629
629
  const errors: string[] = [];
630
630
  const fail = (msg: string): null => { errors.push(msg); return null; };
@@ -639,7 +639,7 @@ export function validateGraph(input: unknown, opts: GraphValidationOptions = {})
639
639
  const value = declared[key];
640
640
  if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 1 || value > MAX_GRAPH_BUDGET[key]) return { ok: false, errors: [`graph: declared budget ${key} must be 1–${MAX_GRAPH_BUDGET[key]}`] };
641
641
  }
642
- if (opts.trustedBudget !== true) return { ok: false, errors: ['graph: declared budget requires trusted runtime authority'] };
642
+ if (opts.declaredBudget !== true) return { ok: false, errors: ['graph: declared budget requires native runtime authority'] };
643
643
  budget = { nodes: Number(declared.nodes), samplers: Number(declared['samplers']), instructions: Number(declared['instructions']) };
644
644
  }
645
645
  if (input.version !== GRAPH_IR_VERSION) fail(`graph: version ${String(input.version)} (this engine reads ${GRAPH_IR_VERSION})`);
@@ -11,7 +11,7 @@ import type { Shardfile } from './shardSchema.ts';
11
11
 
12
12
  const graph = v.pipe(v.unknown(), v.rawTransform(({ dataset, addIssue, NEVER }): GraphIr => {
13
13
  if (!isJsonData(dataset.value)) { addIssue({ message: 'material graph is plain JSON data' }); return NEVER; }
14
- const checked = validateGraph(dataset.value, { trustedBudget: true });
14
+ const checked = validateGraph(dataset.value, { declaredBudget: true });
15
15
  if (!checked.ok) { addIssue({ message: checked.errors.join('; ') }); return NEVER; }
16
16
  // a catalogue slot holds a material or the shard's declared fog (O11: a material selects it by id), never a post pass
17
17
  if (checked.graph.kind === 'post') { addIssue({ message: 'material slot requires a material or fog graph, not a post pass' }); return NEVER; }
@@ -38,7 +38,7 @@ export function presetLooks(familyLooks: Shardfile['look']['familyLooks']): { to
38
38
  /**
39
39
  * A graph file's JSON (SF59): `file` returns an admitted file's bytes (undefined: not present). Throws when the file is
40
40
  * missing, past the inline slot's byte bound, or not UTF-8 JSON; the graph itself is validated by the caller under the
41
- * author caps (a graph file is authored content, never a trusted preset).
41
+ * author caps (a graph file is authored content, never a native preset).
42
42
  */
43
43
  export function graphFileJson(hash: string, file: (hash: string) => Uint8Array | undefined): unknown {
44
44
  const bytes = file(hash);
@@ -47,13 +47,13 @@ export function graphFileJson(hash: string, file: (hash: string) => Uint8Array |
47
47
  try { return JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes)); } catch { throw new Error(`material graph file ${hash} is not UTF-8 JSON`); }
48
48
  }
49
49
  /**
50
- * A graph material's IR (D74: graph files): a graph file's JSON, its bytes from `file`, validated under the trusted budget
50
+ * A graph material's IR (D74: graph files): a graph file's JSON, its bytes from `file`, validated under the host-owned budget
51
51
  * (product admission already held it to its caps and bindings, `graphFileRules`), or an inline entry's IR. Throws for a
52
52
  * preset reference or a missing or invalid file.
53
53
  */
54
54
  export function materialGraphIr(entry: MaterialEntry, file: (hash: string) => Uint8Array | undefined): GraphIr {
55
55
  if (entry.family !== 'graph' || !('file' in entry)) throw new Error('material graph IR needs a graph file (a built shard file carries no inline graph)');
56
- const checked = validateGraph(graphFileJson(entry.file, file), { trustedBudget: true });
56
+ const checked = validateGraph(graphFileJson(entry.file, file), { declaredBudget: true });
57
57
  if (!checked.ok) throw new Error(`material graph file ${entry.file}: ${checked.errors.join('; ')}`);
58
58
  return checked.graph;
59
59
  }
@@ -130,7 +130,7 @@ export interface GraphBindingSources { readonly day: ReadonlyMap<string, 'float'
130
130
  /**
131
131
  * The admitted binding names of a shardfile (SF59): the canonical dotted day-key channels its look keys carry and its
132
132
  * declared public i32 / f64 state fields as `shared.<field>` / `player.<field>`, plus, as for material curves
133
- * (`curveStateFields`), its host-owned numeric fields when a trusted runtime binds `state` (the runtime hands the client
133
+ * (`curveStateFields`), its host-owned numeric fields when a native runtime binds `state` (the runtime hands the client
134
134
  * their live values). Admission and the client's compile both use these lists, never a compiler default that allows any name.
135
135
  */
136
136
  export function graphBindingSources(source: Pick<Shardfile, 'look' | 'state'> & Partial<Pick<Shardfile, 'runtime' | 'questHost'>>): GraphBindingSources {
@@ -151,7 +151,7 @@ function numericFields(state: Shardfile['state'], privacy: 'public' | 'host'): s
151
151
 
152
152
  /**
153
153
  * Check graph uniform bindings against admitted day channels and public numeric state declarations. A preset reference
154
- * must be expressible as a built-in preset (`presetRefusal`, the rule the engine's preset door applies; the trusted preset
154
+ * must be expressible as a built-in preset (`presetRefusal`, the rule the engine's preset door applies; the native preset
155
155
  * programs are held to `PRESET_GRAPH_BUDGET` by the engine's own tests, never the author caps); a graph file must be a
156
156
  * JSON file of the library closure (`files` / `library` given: its bytes are validated by product admission, `graphFileRules`).
157
157
  */
@@ -167,7 +167,7 @@ export function materialGraphRules(source: Pick<Shardfile, 'look' | 'state'> & P
167
167
  continue;
168
168
  }
169
169
  if ('preset' in material) { const refusal = presetRefusal(material.preset); if (refusal !== null) errors.push(`material ${materialId}: ${refusal}`); continue; }
170
- const checked = validateGraph(material.graph, { dayKeys: [...dayChannels.keys()], stateFields, trustedBudget: source.runtime !== null && source.runtime !== undefined || hasDeclaredClientPage(source) });
170
+ const checked = validateGraph(material.graph, { dayKeys: [...dayChannels.keys()], stateFields, declaredBudget: source.runtime !== null && source.runtime !== undefined || hasDeclaredClientPage(source) });
171
171
  if (!checked.ok) { errors.push(...checked.errors.map((error) => `material ${materialId}: ${error}`)); continue; }
172
172
  errors.push(...bindingTypeErrors(materialId, checked.graph, dayChannels));
173
173
  const fog = checked.graph.effectState?.fog;
@@ -192,7 +192,7 @@ export function graphFileRules(source: Pick<Shardfile, 'look' | 'state' | 'files
192
192
  if (material.family !== 'graph' || !('file' in material)) continue;
193
193
  let ir: unknown;
194
194
  try { ir = graphFileJson(material.file, bytes); } catch (error) { errors.push(`material ${materialId}: ${error instanceof Error ? error.message : 'graph file'}`); continue; }
195
- const checked = validateGraph(ir, { dayKeys: [...dayChannels.keys()], stateFields, trustedBudget: source.runtime !== null && source.runtime !== undefined || hasDeclaredClientPage(source) });
195
+ const checked = validateGraph(ir, { dayKeys: [...dayChannels.keys()], stateFields, declaredBudget: source.runtime !== null && source.runtime !== undefined || hasDeclaredClientPage(source) });
196
196
  if (!checked.ok) { errors.push(...checked.errors.map((error) => `material ${materialId}: ${error}`)); continue; }
197
197
  if (checked.graph.kind === 'post') { errors.push(`material ${materialId}: a graph file in a material slot holds a material or fog graph, not a post pass`); continue; }
198
198
  const fog = checked.graph.effectState?.fog, target = typeof fog === 'string' ? source.look.materials[fog] : undefined;
@@ -261,7 +261,7 @@ export function curveAt(curve: Curve, d: number): number {
261
261
 
262
262
  /**
263
263
  * State-bound material curves (`look.curves`): per catalogue family entry, numbers that move with a declared public numeric
264
- * state field (`shared.<name>` / `player.<name>`), or a host-owned numeric shared field when a trusted runtime binds
264
+ * state field (`shared.<name>` / `player.<name>`), or a host-owned numeric shared field when a native runtime binds
265
265
  * `state` (its runtime hands the client the live value), each the curve's value at the field's live value (clamped 0 … 1). A
266
266
  * `param` is a dot path into the entry with its defaults filled (`ground.shade.tint.0`) that resolves to a number its
267
267
  * family can move without a new program (`MOVABLE_FAMILY_PARAMS`). The client evaluates them in its material tick, only
@@ -291,7 +291,7 @@ export function curvedParams(params: FamilyMaterialParams, curves: readonly { re
291
291
  return out;
292
292
  }
293
293
  /**
294
- * The fields a material curve may read: every public numeric field, and, when a trusted runtime binds `state`
294
+ * The fields a material curve may read: every public numeric field, and, when a native runtime binds `state`
295
295
  * (`runtime.binds`), its host-owned numeric shared fields too (the runtime hands the client their live values).
296
296
  */
297
297
  function curveStateFields(source: Pick<Shardfile, 'state' | 'runtime'> & Partial<Pick<Shardfile, 'questHost'>>): ReadonlySet<string> {
@@ -2,7 +2,7 @@
2
2
  * `runtimeCost` reading must have been taken against. It rises when the model changes what it charges (MG6 adds shader
3
3
  * compile, load transients, far slabs and paint arrays); from then a reading from an older epoch is refused until the
4
4
  * shard re-measures. A reading with no `epoch` is epoch 1, the model before MG6. */
5
- const MEMORY_EPOCH = 2
5
+ const MEMORY_EPOCH = 3
6
6
  const LEGACY_EPOCH = 1
7
7
 
8
8
  interface EpochRow {
@@ -1,6 +1,8 @@
1
+ import { parse } from 'valibot'
2
+
1
3
  import { bootMemoryCosts } from './boot-memory-cost.ts'
2
4
  import { worstContentCost } from './budget.ts'
3
- import { runtimeAccountedBytes } from './runtimeCost.ts'
5
+ import { runtimeAccountedBytes, RuntimeCostSchema } from './runtimeCost.ts'
4
6
 
5
7
  import type { Shardfile } from './shardSchema.ts'
6
8
 
@@ -40,22 +42,55 @@ function hardLineIssue(
40
42
  }
41
43
  }
42
44
 
45
+ /**
46
+ * MG6 epoch 3 (mini-estcal, 2026-11-17): the offline gates charge a runtime home from the engine base, never less a
47
+ * matched pre-entry resident set. The phone-tier probe found that set live at the boot peak: the renderer's
48
+ * ArrayBuffers stay at their peak after ready (Nalati 509 of 531 MB, Pine 484, Driftwood 284), so subtracting
49
+ * `residentBaseMB` (Nalati 685, Pine 671 MB against a 299 MB engine) dropped 386 and 372 MB from the estimate.
50
+ */
51
+ function runtimeOfflineBytes(input: unknown): number {
52
+ const row = parse(RuntimeCostSchema, input)
53
+ return runtimeAccountedBytes({
54
+ ...row,
55
+ residentBaseMB: row.engineBaseMB,
56
+ imagesFirst: undefined,
57
+ })
58
+ }
59
+
60
+ /** What the offline estimate knows of the product beyond its sections: the decoded engine images its cook mounts. */
61
+ type MemoryContext =
62
+ | ReadonlyMap<string, unknown>
63
+ | Readonly<{ sections: ReadonlyMap<string, unknown>; mountedImages: number }>
64
+
65
+ function memoryContext(
66
+ context: MemoryContext,
67
+ ): Readonly<{ sections: ReadonlyMap<string, unknown>; mountedImages: number }> {
68
+ return context instanceof Map
69
+ ? { sections: context, mountedImages: EMPTY_BYTES }
70
+ : // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- the union's other arm
71
+ (context as Readonly<{
72
+ sections: ReadonlyMap<string, unknown>
73
+ mountedImages: number
74
+ }>)
75
+ }
76
+
43
77
  /** Count cold-boot costs and any opaque runtime residency in offline admission. */
44
78
  function offlineMemoryIssues(
45
79
  // oxlint-disable-next-line typescript/prefer-readonly-parameter-types -- format's shard type, read only
46
80
  source: Shardfile,
47
- sections: ReadonlyMap<string, unknown>,
81
+ context: MemoryContext,
48
82
  ): ReturnType<typeof hardLineIssue>[] {
83
+ const { sections, mountedImages } = memoryContext(context)
49
84
  const native = source.runtime?.cost
50
85
  const runtime =
51
- native === undefined ? EMPTY_BYTES : runtimeAccountedBytes(native)
86
+ native === undefined ? EMPTY_BYTES : runtimeOfflineBytes(native)
52
87
  const commons = Object.values(source.requires.commonsCosts).reduce(
53
88
  (sum, row): number => sum + row.decoded + row.gpu,
54
89
  EMPTY_BYTES,
55
90
  )
56
91
  const cost = worstContentCost(source, {
57
92
  commons: runtime + commons,
58
- boot: bootMemoryCosts(source, sections),
93
+ boot: bootMemoryCosts(source, sections, mountedImages),
59
94
  })
60
95
  return (['playing', 'loading'] as const)
61
96
  .filter((kind): boolean => cost[kind] > MEMORY_HARD_BYTES)
@@ -64,4 +99,12 @@ function offlineMemoryIssues(
64
99
  )
65
100
  }
66
101
 
67
- export { MEMORY_HARD_BYTES, hardLineIssue, offlineMemoryIssues, overHardLine }
102
+ export {
103
+ MEMORY_HARD_BYTES,
104
+ type MemoryContext,
105
+ hardLineIssue,
106
+ memoryContext,
107
+ offlineMemoryIssues,
108
+ overHardLine,
109
+ runtimeOfflineBytes,
110
+ }
@@ -8,7 +8,7 @@ export interface AdmissionMeasurement {
8
8
  readonly residentBaseBytes?: number;
9
9
  readonly rev: string; readonly device: string; readonly evidence: string;
10
10
  }
11
- /** Trusted callers report only the total-memory envelope here. Parser, hash, script and content-understatement guards are separate. */
11
+ /** Host-owned callers report only the total-memory envelope here. Parser, hash, script and content-understatement guards are separate. */
12
12
  export interface MemoryAdmissionRequest {
13
13
  readonly stage: 'runtime' | 'declared' | 'actual' | 'resident';
14
14
  readonly owner: string; readonly id: string;
@@ -54,7 +54,7 @@ export const PageReturnRowsSchema: v.GenericSchema<PageReturnRowsInput, PageRetu
54
54
 
55
55
  export const ReturnProgramSchema: v.StrictObjectSchema<{ readonly script: v.GenericSchema<ReturnProgramRowsInput['script'], ReturnProgramRows['script']>; readonly bytes: v.GenericSchema<ReturnProgramRowsInput['bytes'], ReturnProgramRows['bytes']>; readonly v2: v.ExactOptionalSchema<v.GenericSchema<Exclude<ReturnProgramRowsInput['v2'], undefined>, Exclude<ReturnProgramRows['v2'], undefined>>, undefined>; }, undefined> = v.strictObject({ script: v.unknown(), bytes: v.string(),v2: v.exactOptional(ReturnProjectionV2Schema) });
56
56
  const operations = ['$ref', '$call', '$new', '$fn', '$set', '$if', '$or', '$coalesce', '$eq', '$not', '$sequence'];
57
- /** Draft-07 wire contract for the trusted assembly language. Constants and
57
+ /** Draft-07 wire contract for the host-owned assembly language. Constants and
58
58
  * operands are bounded JSON values; tag names and row/module shapes are closed.
59
59
  * checkedHeadlessAssembly additionally checks depth, references and real exports. */
60
60
  export const HEADLESS_ASSEMBLY_JSON_SCHEMA: { $schema: string; type: string; additionalProperties: boolean; required: string[]; definitions: { key: { type: string; minLength: number; maxLength: number; not: { enum: string[]; }; }; value: { anyOf: ({ type: string[]; maxItems?: never; items?: never; maxProperties?: never; propertyNames?: never; additionalProperties?: never; minProperties?: never; } | { type: string; maxItems: number; items: { $ref: string; }; maxProperties?: never; propertyNames?: never; additionalProperties?: never; minProperties?: never; } | { type: string; maxProperties: number; propertyNames: { allOf: ({ $ref: string; pattern?: never; } | { pattern: string; $ref?: never; })[]; enum?: never; }; additionalProperties: { $ref: string; }; maxItems?: never; items?: never; minProperties?: never; } | { type: string; minProperties: number; maxProperties: number; propertyNames: { enum: string[]; allOf?: never; }; additionalProperties: { $ref: string; }; maxItems?: never; items?: never; })[]; }; rows: { type: string; maxItems: number; items: { type: string; additionalProperties: boolean; required: string[]; properties: { name: { $ref: string; }; value: { $ref: string; }; }; }; }; installRows: { type: string; maxItems: number; items: { type: string; additionalProperties: boolean; required: string[]; properties: { name: { $ref: string; }; value: { anyOf: ({ $ref: string; type?: never; additionalProperties?: never; required?: never; properties?: never; } | { type: string; additionalProperties: boolean; required: string[]; properties: { $native: { anyOf: ({ const: string; type?: never; additionalProperties?: never; required?: never; properties?: never; } | { type: string; additionalProperties: boolean; required: string[]; properties: { kind: { const: string; }; speed: { type: string; exclusiveMinimum: number; }; }; const?: never; })[]; }; }; $ref?: never; })[]; }; }; }; }; }; properties: { version: { const: number; }; modules: { type: string; propertyNames: { type: string; pattern: string; }; additionalProperties: { type: string; maxItems: number; uniqueItems: boolean; items: { $ref: string; }; }; }; constants: { $ref: string; }; prepare: { $ref: string; }; install: { $ref: string; }; level: { $ref: string; }; ports: { $ref: string; }; entries: { $ref: string; }; }; } = {
@@ -1,7 +1,7 @@
1
1
  import * as v from 'valibot';
2
2
  import type { ShardEntryways } from './entryways.ts';
3
3
 
4
- /** Original native WSTR terrain retained by a trusted world-only hybrid; this declaration never installs collision. */
4
+ /** Original native WSTR terrain retained by a native world-only runtime shard; this declaration never installs collision. */
5
5
  export const NativeGroundSchema: v.GenericSchema<NativeGroundInput, NativeGround> = v.strictObject({ version: v.literal(1), file: v.pipe(v.string(), v.regex(/^[a-f0-9]{64}$/u)) });
6
6
  /** The immutable native payload; resolution, seed and landscape identity derive from admitted bytes. */
7
7
 
@@ -17,11 +17,11 @@ export interface NativeGroundSource {
17
17
  edge: Record<ShardEntryways[number]['edge'], { heights: readonly number[] }>;
18
18
  entryways: ShardEntryways;
19
19
  }
20
- /** Native ground is an independent critical root with one trusted collision owner, never another compiled collider. */
20
+ /** Native ground is an independent critical root with one host-owned collision owner, never another compiled collider. */
21
21
  export function nativeGroundRules(source: NativeGroundSource): string[] {
22
22
  const data = source.nativeGround; if (data === null) return [];
23
23
  const errors: string[] = [];
24
- if (source.runtime === null) errors.push('native ground requires a trusted runtime declaration');
24
+ if (source.runtime === null) errors.push('native ground requires a native runtime declaration');
25
25
  if (source.terrain !== null || source.meshCollision !== null) errors.push('native ground and compiled collision are mutually exclusive');
26
26
  const file = source.files.find(row => row.hash === data.file);
27
27
  if (file?.kind !== 'binary' || file.dependencies.length > 0 || !source.critical.includes(data.file)) errors.push('native ground is an independent critical binary root');
@@ -14,9 +14,9 @@ export const NavigationSchema: v.GenericSchema<NavigationInput, Navigation> = v.
14
14
  origin: point, tileSize: positive, tiles: v.pipe(v.array(v.tuple([coordinate, coordinate])), v.maxLength(4096)) })), v.minLength(1), v.maxLength(16)) });
15
15
  /** An admitted immutable navigation declaration, with exact WSNM bounds and ordered agent tile grids. */
16
16
 
17
- /** Trusted level transport: admitted product bytes or the manifest's declared immutable URL. */
17
+ /** Native level transport: admitted product bytes or the manifest's declared immutable URL. */
18
18
  export type NavigationContent = { row: unknown; bytes: Uint8Array } | { row: unknown; url: string };
19
- /** Validate a declaration supplied by a trusted manifest or author boundary before any transport read. */
19
+ /** Validate a declaration supplied by a native manifest or author boundary before any transport read. */
20
20
  export function parseNavigation(input: unknown): Navigation { return v.parse(NavigationSchema, input); }
21
21
  /** Build the declaration from original bytes without resampling, re-encoding or sorting tiles/layers. */
22
22
  export function describeNavigation(file: string, bytes: Uint8Array): Navigation {
@@ -0,0 +1,91 @@
1
+ // MG10 / ENGINE-MEMORY EM17: checks for a value fresh from `JSON.parse`, which
2
+ // is plain data by construction: own enumerable data properties, ordinary
3
+ // prototypes, dense arrays, and no symbols, accessors or cycles. `isJsonData`
4
+ // reads a property descriptor for every key to prove that of any value; for
5
+ // parsed text only its node and depth bounds and canonical numbers are left,
6
+ // and this walk checks them without allocating.
7
+
8
+ type Fields = Readonly<Record<string, unknown>>
9
+ type Check = (value: unknown) => boolean
10
+
11
+ const NONE = 0
12
+ const ONE = 1
13
+ const NEGATIVE_ZERO = -0
14
+ const NODE_LIMIT = 100_000
15
+ const DEPTH_LIMIT = 64
16
+
17
+ const fields = (value: unknown): value is Fields =>
18
+ typeof value === 'object' && value !== null && !Array.isArray(value)
19
+ const items = (value: unknown): readonly unknown[] | undefined =>
20
+ Array.isArray(value) ? value : undefined
21
+ const own = (value: Fields, key: string): unknown =>
22
+ Object.hasOwn(value, key) ? value[key] : undefined
23
+ const canonical = (value: number): boolean =>
24
+ Number.isFinite(value) && !Object.is(value, NEGATIVE_ZERO)
25
+
26
+ /** One walk's node count, against `isJsonData`'s bound. */
27
+ class Walk {
28
+ private nodes = NONE
29
+
30
+ public fits(value: unknown, depth: number, skip?: string): boolean {
31
+ this.nodes += ONE
32
+ if (this.nodes > NODE_LIMIT || depth > DEPTH_LIMIT) {
33
+ return false
34
+ }
35
+ if (typeof value === 'number') {
36
+ return canonical(value)
37
+ }
38
+ const list = items(value)
39
+ if (list !== undefined) {
40
+ return this.fitsItems(list, depth + ONE)
41
+ }
42
+ return !fields(value) || this.fitsFields(value, depth + ONE, skip)
43
+ }
44
+
45
+ private fitsItems(list: readonly unknown[], depth: number): boolean {
46
+ for (const item of list) {
47
+ if (!this.fits(item, depth)) {
48
+ return false
49
+ }
50
+ }
51
+ return true
52
+ }
53
+
54
+ private fitsFields(value: Fields, depth: number, skip?: string): boolean {
55
+ for (const key in value) {
56
+ if (
57
+ Object.hasOwn(value, key) &&
58
+ key !== skip &&
59
+ !this.fits(value[key], depth)
60
+ ) {
61
+ return false
62
+ }
63
+ }
64
+ return true
65
+ }
66
+ }
67
+
68
+ /**
69
+ * `isJsonData`'s verdict for a `JSON.parse` value: at most 100,000 values,
70
+ * none deeper than 64, every number finite and not -0. `skip` leaves one key
71
+ * of the root object out. Only for `JSON.parse` output.
72
+ */
73
+ const parsedJsonFits = (value: unknown, skip?: string): boolean =>
74
+ new Walk().fits(value, NONE, skip)
75
+
76
+ /** An array of at most `max` items, each passing `check`. */
77
+ function listOf(value: unknown, max: number, check: Check): boolean {
78
+ const list = items(value)
79
+ if (list === undefined || list.length > max) {
80
+ return false
81
+ }
82
+ for (const item of list) {
83
+ if (!check(item)) {
84
+ return false
85
+ }
86
+ }
87
+ return true
88
+ }
89
+
90
+ export { fields, items, listOf, own, parsedJsonFits }
91
+ export type { Check, Fields }