@wildshard/shard-format 0.22.0 → 0.24.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.22.0",
3
+ "version": "0.24.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": {
@@ -2,6 +2,7 @@ import { acceptsShardfileCost, textureLibrarySource } from './deviceMemoryCost.t
2
2
  import { creaturePerchAdmissionRows } from './creature-perch.ts';
3
3
  import { admitScriptContract, decisionModuleContracts, type ScriptAdmissionRows } from './scriptContract.ts';
4
4
  import type { TextureTranscodeSupport } from './contentBounds.ts';
5
+ import { overHardLine } from './memory-line.ts';
5
6
  import { admitScript } from './scriptAdmission.ts';
6
7
  import { SCRIPT_LIMITS } from './scriptLimits.ts';
7
8
  import { worstContentCost } from './budget.ts';
@@ -64,7 +65,7 @@ function preflightDeclaredCosts(source: Shardfile, memory?: MemoryAdmission): {
64
65
  }
65
66
  const resident = Object.values(commons).reduce((total, cost) => total + cost.decoded + cost.gpu, 0);
66
67
  const worst = worstContentCost(source, resident);
67
- if (!acceptsShardfileCost(memory, source, 'declared', worst)) throw new Error(`declared worst-location total exceeds envelope: ${worst.playing}`);
68
+ if (!acceptsShardfileCost(memory, source, 'declared', worst)) throw new Error(`declared worst-location total exceeds envelope: play ${worst.playing}, load ${worst.loading}${overHardLine(Math.max(worst.playing, worst.loading))}`);
68
69
  return { commons, worst };
69
70
  }
70
71
 
@@ -251,7 +252,7 @@ function admitAfterFiles(state: AssetAdmission, assets: ReadonlyMap<string, Uint
251
252
  if (clientModules.size + new Set(scripts.filter(row => row.side === 'view').map(row => row.module)).size > SCRIPT_LIMITS.instances || clientMemory > SCRIPT_LIMITS.memoryBytes || libraryResident > s.budgets.library.resident) throw new Error('client script memory or view budget understated or above host cap');
252
253
  if (libraryResident + sketchResident > s.budgets.library.resident) throw new Error('compendium sketch raster budget understated');
253
254
  const cost = worstContentCost(textureLibrarySource(s, assets, textures), commons);
254
- if (!acceptsShardfileCost(memory, s, 'actual', cost)) throw new Error(`worst-location total exceeds envelope: ${cost.playing}`);
255
+ if (!acceptsShardfileCost(memory, s, 'actual', cost)) throw new Error(`worst-location total exceeds envelope: play ${cost.playing}, load ${cost.loading}${overHardLine(Math.max(cost.playing, cost.loading))}`);
255
256
  validateNavigationAssets(s, assets);
256
257
  validateNativeGround(s, assets);
257
258
  validateEntrywayTerrain(s, assets);
@@ -0,0 +1,123 @@
1
+ import { controlFileHashes } from './admissionControl.ts'
2
+ import { textureMipBytes } from './contentBounds.ts'
3
+ import { spawnViewSceneFiles } from './spawnView.ts'
4
+ import { parseWorldScenes, worldScenesForTier } from './worldScenes.ts'
5
+
6
+ import type { Shardfile } from './shardSchema.ts'
7
+ import type { WorldScenesSection } from './worldScenes.ts'
8
+
9
+ interface BootMemoryCosts {
10
+ readonly heldSpawnParts: number
11
+ readonly largestDecode: number
12
+ readonly shaderCompile: number
13
+ readonly farSlabIndices: number
14
+ readonly paintArrayGpu: number
15
+ readonly paintArrayStaging: number
16
+ }
17
+
18
+ const NO_BYTES = 0
19
+ const TRIANGLE_CORNERS = 3
20
+ const INDEX_COPIES = 2
21
+ const FAR_SLAB_INDEX_SHARE = 0.75
22
+ const RGBA_BYTES = 4
23
+ const BASE_LEVEL = 1
24
+ // MG6: Nine's cold phone-tier shader step rose by 193 MB in the mini's
25
+ // Chromium capture (04d76bcf). The calibrated increment rounds to 168 MB.
26
+ const SHADER_COMPILE_BYTES = 168_000_000
27
+
28
+ function spawnMemoryCosts(
29
+ // oxlint-disable-next-line typescript/prefer-readonly-parameter-types -- format's shard row, only read
30
+ shard: Shardfile,
31
+ sections: ReadonlyMap<string, unknown>,
32
+ ): Pick<BootMemoryCosts, 'heldSpawnParts' | 'largestDecode'> {
33
+ const controls = new Set([
34
+ ...controlFileHashes(shard),
35
+ ...spawnViewSceneFiles(sections),
36
+ ])
37
+ let heldSpawnParts = Object.values(shard.requires.commonsWire).reduce(
38
+ (sum, bytes): number => sum + bytes,
39
+ NO_BYTES,
40
+ )
41
+ let largestDecode = NO_BYTES
42
+ for (const file of shard.files) {
43
+ if (controls.has(file.hash)) {
44
+ heldSpawnParts += file.compressed
45
+ largestDecode = Math.max(largestDecode, file.decoded)
46
+ }
47
+ }
48
+ return { heldSpawnParts, largestDecode }
49
+ }
50
+
51
+ type SlabFile = Readonly<Pick<Shardfile['files'][number], 'hash' | 'triangles'>>
52
+
53
+ function farSlabBytes(
54
+ files: readonly SlabFile[],
55
+ // oxlint-disable-next-line typescript/prefer-readonly-parameter-types -- format's scene rows, only read
56
+ scene: WorldScenesSection | undefined,
57
+ ): number {
58
+ const slabs = new Set<string>()
59
+ for (const library of scene?.libraries ?? []) {
60
+ if (library.kind === 'slabs') {
61
+ for (const tile of library.tiles) {
62
+ for (const file of tile.files) {
63
+ slabs.add(file.file)
64
+ }
65
+ }
66
+ }
67
+ }
68
+ // NB23: engine's slabLibrary reserves 75% more indices for the far levels.
69
+ const triangles = files.reduce(
70
+ (sum, file): number =>
71
+ sum +
72
+ (slabs.has(file.hash)
73
+ ? Math.ceil(file.triangles * FAR_SLAB_INDEX_SHARE)
74
+ : NO_BYTES),
75
+ NO_BYTES,
76
+ )
77
+ return (
78
+ triangles * TRIANGLE_CORNERS * Uint32Array.BYTES_PER_ELEMENT * INDEX_COPIES
79
+ )
80
+ }
81
+
82
+ function paintArrayBytes(
83
+ // oxlint-disable-next-line typescript/prefer-readonly-parameter-types -- format's scene rows, only read
84
+ scene: WorldScenesSection | undefined,
85
+ ): Pick<BootMemoryCosts, 'paintArrayGpu' | 'paintArrayStaging'> {
86
+ let paintArrayGpu = NO_BYTES
87
+ let paintArrayStaging = NO_BYTES
88
+ for (const row of scene?.lent ?? []) {
89
+ if (row.kind === 'layers') {
90
+ const edge = row.size.phone
91
+ paintArrayGpu +=
92
+ textureMipBytes(
93
+ edge,
94
+ edge,
95
+ Math.floor(Math.log2(edge)) + BASE_LEVEL,
96
+ false,
97
+ ) * row.layers.length
98
+ paintArrayStaging += edge * edge * RGBA_BYTES * row.layers.length
99
+ }
100
+ }
101
+ return { paintArrayGpu, paintArrayStaging }
102
+ }
103
+
104
+ /** Boot memory that sits outside the steady-state file and tile budgets. */
105
+ function bootMemoryCosts(
106
+ // oxlint-disable-next-line typescript/prefer-readonly-parameter-types -- format's shard row, only read
107
+ shard: Shardfile,
108
+ sections: ReadonlyMap<string, unknown>,
109
+ ): BootMemoryCosts {
110
+ const rawScene = sections.get('world/scenes')
111
+ const scene =
112
+ rawScene === undefined
113
+ ? undefined
114
+ : worldScenesForTier(parseWorldScenes(rawScene), 'phone')
115
+ return {
116
+ ...spawnMemoryCosts(shard, sections),
117
+ shaderCompile: SHADER_COMPILE_BYTES,
118
+ farSlabIndices: farSlabBytes(shard.files, scene),
119
+ ...paintArrayBytes(scene),
120
+ }
121
+ }
122
+
123
+ export { type BootMemoryCosts, bootMemoryCosts }
@@ -2,6 +2,7 @@ import { CONTENT_CAPS as C } from './contentBounds.ts';
2
2
  import { contentCost } from './contentCost.ts';
3
3
  import type { Shardfile } from './shardSchema.ts';
4
4
  import { NEAR_PLACEHOLDER_LIMITS, nearPlaceholderCost } from './nearPlaceholder.ts';
5
+ import type { BootMemoryCosts } from './boot-memory-cost.ts';
5
6
 
6
7
  /** Category resident targets are tradeable warnings; only the complete playing/loading totals refuse memory. */
7
8
  export function memoryTargetWarnings(shard: Shardfile): { category: string; bytes: number; target: number }[] {
@@ -59,7 +60,12 @@ interface LocationModel {
59
60
  cost: (x: number, z: number) => LocationCost;
60
61
  }
61
62
 
62
- function locationModels(shard: Shardfile, commons: number): LocationModel[] {
63
+ interface BudgetOptions { readonly commons: number; readonly boot: BootMemoryCosts }
64
+ const NO_BYTES = 0;
65
+
66
+ function locationModels(shard: Shardfile, options: number | BudgetOptions): LocationModel[] {
67
+ const commons = typeof options === 'number' ? options : options.commons;
68
+ const boot = typeof options === 'number' ? undefined : options.boot;
63
69
  const bytesOf = ownTileBytes(shard), own = shard.tiles.filter(tile => tile.lod === 0).map(tile => {
64
70
  const bounds = tile.drawBounds ?? tile.bounds;
65
71
  return { x0: bounds.min[0], z0: bounds.min[2], x1: bounds.max[0], z1: bounds.max[2], bytes: bytesOf(tile) };
@@ -93,10 +99,10 @@ function locationModels(shard: Shardfile, commons: number): LocationModel[] {
93
99
  return l0;
94
100
  };
95
101
  models.push({
96
- neighbours: neighbours.map(({ cx, cz }) => [cx, cz] as const), fixed: l1 + far + sims + commons + nearBytes,
102
+ neighbours: neighbours.map(({ cx, cz }) => [cx, cz] as const), fixed: l1 + far + sims + commons + nearBytes + (boot?.farSlabIndices ?? NO_BYTES) + (boot?.paintArrayGpu ?? NO_BYTES),
97
103
  cost: (x, z) => {
98
104
  const l0 = l0At(x, z);
99
- return { ...contentCost({ l0, l1, far, libraries, sims, commons, near: nearBytes, overlap }), location: [x, z] };
105
+ return { ...contentCost({ l0, l1, far, libraries, sims, commons, near: nearBytes, overlap, boot }), location: [x, z] };
100
106
  },
101
107
  });
102
108
  }
@@ -104,10 +110,11 @@ function locationModels(shard: Shardfile, commons: number): LocationModel[] {
104
110
  }
105
111
 
106
112
  /** Conservative total around an actual player location, using the same neighbour assumptions as admission. */
107
- export function nearbyContentCost(shard: Shardfile, x: number, z: number, commons = 0): LocationCost {
113
+ export function nearbyContentCost(shard: Shardfile, x: number, z: number, options: number | BudgetOptions = 0): LocationCost {
114
+ const commons = typeof options === 'number' ? options : options.commons;
108
115
  if (![x, z, commons].every(Number.isFinite) || commons < 0) throw new Error('Invalid memory estimate location');
109
116
  let worst: LocationCost = { playing: 0, loading: 0, accounted: 0, location: [x, z] };
110
- for (const model of locationModels(shard, commons)) { const cost = model.cost(x, z); if (cost.playing > worst.playing) worst = cost; }
117
+ for (const model of locationModels(shard, options)) { const cost = model.cost(x, z); if (cost.playing > worst.playing) worst = cost; }
111
118
  return worst;
112
119
  }
113
120
 
@@ -118,14 +125,14 @@ const worstCache = new Map<string, LocationCost>();
118
125
  const syntheticCells = new Map<string, { l0: Uint8Array; active: Uint8Array }>();
119
126
 
120
127
  /** Worst disc with three synthetic neighbours at the platform targets; grid padding covers unsampled gaps. */
121
- export function worstContentCost(shard: Shardfile, commons = 0): LocationCost {
122
- const steps = worstContentCostSteps(shard, commons);
128
+ export function worstContentCost(shard: Shardfile, options: number | BudgetOptions = 0): LocationCost {
129
+ const steps = worstContentCostSteps(shard, options);
123
130
  for (;;) { const step = steps.next(); if (step.done === true) return step.value; }
124
131
  }
125
132
 
126
133
  /** `worstContentCost` in steps, one per own tile and synthetic neighbour tile the grids sum, then one per scanned row:
127
134
  * a live admission paints between them (Pine's activation spent ~90 ms of a frame in this scan at 4x CPU). */
128
- export function* worstContentCostSteps(shard: Shardfile, commons = 0): Generator<void, LocationCost> {
135
+ export function* worstContentCostSteps(shard: Shardfile, options: number | BudgetOptions = 0): Generator<void, LocationCost> {
129
136
  const bytesOf = ownTileBytes(shard);
130
137
  // The cache key is the JSON of every tile's [lod, bytes, x0, z0, x1, z1] and the shard's budgets, written row by row
131
138
  // (the same text, without an array per tile).
@@ -136,7 +143,7 @@ export function* worstContentCostSteps(shard: Shardfile, commons = 0): Generator
136
143
  const bounds = tile.drawBounds ?? tile.bounds;
137
144
  rows += `${i > 0 ? ',' : ''}[${json(tile.lod)},${json(bytesOf(tile))},${json(bounds.min[0])},${json(bounds.min[2])},${json(bounds.max[0])},${json(bounds.max[2])}]`;
138
145
  }
139
- const key = `[[${rows}],${JSON.stringify([shard.far === null ? null : [shard.far.decoded, shard.far.gpu], shard.budgets.library.resident, shard.budgets.sim.resident, shard.budgets.overlap, shard.serverBudget.memory, commons,
146
+ const key = `[[${rows}],${JSON.stringify([shard.far === null ? null : [shard.far.decoded, shard.far.gpu], shard.budgets.library.resident, shard.budgets.sim.resident, shard.budgets.overlap, shard.serverBudget.memory, options,
140
147
  shard.near === undefined ? 0 : nearPlaceholderCost(shard.near, shard).total.resident]).slice(1)}`;
141
148
  const cached = worstCache.get(key);
142
149
  if (cached !== undefined) return { ...cached, location: [...cached.location] };
@@ -193,7 +200,7 @@ export function* worstContentCostSteps(shard: Shardfile, commons = 0): Generator
193
200
  syntheticCells.set(id, made); return made;
194
201
  };
195
202
  let worstAccounted = Number.NEGATIVE_INFINITY;
196
- for (const model of locationModels(shard, commons)) {
203
+ for (const model of locationModels(shard, options)) {
197
204
  const found: { l0: Uint8Array; active: Uint8Array }[] = [];
198
205
  for (const neighbour of model.neighbours) found.push(yield* cellOf(neighbour));
199
206
  const [a, b, c] = found;
@@ -1,4 +1,17 @@
1
1
  import { CONTENT_CAPS as C } from './contentBounds.ts';
2
+ import type { BootMemoryCosts } from './boot-memory-cost.ts';
3
+
4
+ const NO_BYTES = 0;
5
+
6
+ function bootResident(boot: BootMemoryCosts | undefined): number {
7
+ return boot === undefined ? NO_BYTES : boot.farSlabIndices + boot.paintArrayGpu;
8
+ }
9
+
10
+ function bootOverlap(overlap: number, boot: BootMemoryCosts): number {
11
+ // Stores release their parts before compile. Charge the larger of the
12
+ // transport/decode phase and the compiler/paint upload phase.
13
+ return Math.max(overlap, boot.heldSpawnParts + boot.largestDecode, boot.shaderCompile + boot.paintArrayStaging);
14
+ }
2
15
 
3
16
  /** Shared resident-cost input: dependency-deduplicated category bytes, including persistent CPU and GPU data. */
4
17
  export interface ContentCostInput {
@@ -6,19 +19,25 @@ export interface ContentCostInput {
6
19
  products?: number; near?: number;
7
20
  /** Actual concurrent decode headroom; zero when no overlap is present. */
8
21
  overlap: number;
22
+ /** Additional resident and transient costs derived from the cold boot. */
23
+ boot?: BootMemoryCosts | undefined;
9
24
  /** Calibrated base after any explicitly split renderer-component credit. */
10
25
  engineBase?: number;
11
26
  /** Actual grid page allocations only. Standalone callers omit this; no grid
12
27
  * program cache, road or continuation allowance is implicit in this model. */
13
28
  page?: number;
14
29
  }
30
+
15
31
  /** Estimated resident cost, calibrated against the Simulator template census.
16
32
  * Process/GPU measurements remain observations, distinct from this prediction. */
17
33
  export function contentCost(input: ContentCostInput): { playing: number; loading: number; accounted: number } {
18
- const resident = input.l0 + input.l1 + input.far + input.libraries + input.sims + input.commons + (input.products ?? 0) + (input.near ?? 0);
34
+ const resident = input.l0 + input.l1 + input.far + input.libraries + input.sims + input.commons + (input.products ?? 0) + (input.near ?? 0) + bootResident(input.boot);
19
35
  const page = input.page ?? 0, accounted = resident + page;
20
- const playing = (input.engineBase ?? C.engineBase) + page + Math.ceil(resident * C.residentFactor) + input.overlap;
21
- return { playing, loading: playing + input.overlap, accounted };
36
+ const base = (input.engineBase ?? C.engineBase) + page + Math.ceil(resident * C.residentFactor);
37
+ const playing = base + input.overlap;
38
+ // The boot phases and playing churn share the same allocation headroom.
39
+ const loading = input.boot === undefined ? playing + input.overlap : base + bootOverlap(input.overlap, input.boot);
40
+ return { playing, loading, accounted };
22
41
  }
23
42
 
24
43
  /** G762: an advisory projection needs an independently measured engine base.
@@ -36,7 +55,7 @@ export interface ContentEstimate {
36
55
  /** Predict component costs without an accuracy pass/fail or a native-budget verdict.
37
56
  * The measured base must exclude the separately supplied content/page components.
38
57
  * Runtime admission retains its independent, conservative contentCost contract. */
39
- export function contentEstimate(input: Omit<ContentCostInput, 'engineBase'>, measuredEngineBytes: number | null): ContentEstimate {
58
+ export function contentEstimate(input: Omit<ContentCostInput, 'engineBase' | 'boot'>, measuredEngineBytes: number | null): ContentEstimate {
40
59
  if (measuredEngineBytes !== null && (!Number.isSafeInteger(measuredEngineBytes) || measuredEngineBytes < 0)) throw new RangeError('Invalid measured engine base');
41
60
  const components = { l0: input.l0, l1: input.l1, far: input.far, libraries: input.libraries, sims: input.sims, commons: input.commons,
42
61
  products: input.products ?? 0, near: input.near ?? 0, page: input.page ?? 0 };
@@ -1,4 +1,5 @@
1
1
  import { CONTENT_CAPS as C, type TextureTranscodeSupport } from './contentBounds.ts';
2
+ import { overHardLine } from './memory-line.ts';
2
3
  import { worstContentCostSteps, type worstContentCost } from './budget.ts';
3
4
  import type { Shardfile } from './shardSchema.ts';
4
5
  import type { MemoryAdmission } from './memoryAdmission.ts';
@@ -13,7 +14,7 @@ export function acceptsShardfileCost(memory: MemoryAdmission | undefined, source
13
14
 
14
15
  /** Reapply the current trusted memory policy to a previously validated exact declaration. */
15
16
  export function acceptValidatedCost(source: Shardfile, cost: ReturnType<typeof worstContentCost>, memory?: MemoryAdmission): void {
16
- if (!acceptsShardfileCost(memory, source, 'declared', cost)) throw new Error(`declared worst-location total exceeds envelope: ${cost.playing}`);
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))}`);
17
18
  }
18
19
 
19
20
  /** Device cost projection after byte admission; source ceilings retain their full RGBA fallback. A KTX2 file's declared
@@ -0,0 +1,57 @@
1
+ /** MEMORY-GATES MG5 (J408, Jake 2026-11-17: "a stale runtimeCost is refused"): the memory model a runtime home's
2
+ * `runtimeCost` reading must have been taken against. It rises when the model changes what it charges (MG6 adds shader
3
+ * compile, load transients, far slabs and paint arrays); from then a reading from an older epoch is refused until the
4
+ * shard re-measures. A reading with no `epoch` is epoch 1, the model before MG6. */
5
+ const MEMORY_EPOCH = 2
6
+ const LEGACY_EPOCH = 1
7
+
8
+ interface EpochRow {
9
+ readonly epoch?: number | undefined
10
+ readonly imagesFirst?: EpochRow | undefined
11
+ }
12
+ interface StaleRuntimeIssue {
13
+ readonly code: 'perf-native-resident-unmeasured'
14
+ readonly metric: string
15
+ readonly actual: number
16
+ readonly limit: number
17
+ readonly severity: 'refusal'
18
+ }
19
+
20
+ /** Why a runtime reading is stale against `current`, or empty when it is current. */
21
+ function staleRuntimeCost(
22
+ row: EpochRow,
23
+ current: number = MEMORY_EPOCH,
24
+ ): string {
25
+ const epoch = row.epoch ?? LEGACY_EPOCH
26
+ if (epoch >= current) {
27
+ return ''
28
+ }
29
+ return `native resident measurement is stale: memory epoch ${String(epoch)}, current ${String(current)} (J408): re-measure the runtime home`
30
+ }
31
+
32
+ /** A refusal, whatever the policy, for a runtime home's reading and for its images-first reading, each stale against
33
+ * `current`. Takes the shard's `runtime` (null for a data-only shard). */
34
+ function staleRuntimeIssues(
35
+ runtime: Readonly<{ cost?: EpochRow | undefined }> | null,
36
+ current: number = MEMORY_EPOCH,
37
+ ): StaleRuntimeIssue[] {
38
+ const rows: EpochRow[] = []
39
+ const cost = runtime === null ? undefined : runtime.cost
40
+ if (cost !== undefined) {
41
+ rows.push(cost)
42
+ if (cost.imagesFirst !== undefined) {
43
+ rows.push(cost.imagesFirst)
44
+ }
45
+ }
46
+ return rows
47
+ .filter((row: EpochRow): boolean => staleRuntimeCost(row, current) !== '')
48
+ .map((row: EpochRow): StaleRuntimeIssue => ({
49
+ code: 'perf-native-resident-unmeasured',
50
+ metric: staleRuntimeCost(row, current),
51
+ actual: row.epoch ?? LEGACY_EPOCH,
52
+ limit: current,
53
+ severity: 'refusal',
54
+ }))
55
+ }
56
+
57
+ export { MEMORY_EPOCH, staleRuntimeCost, staleRuntimeIssues }
@@ -0,0 +1,67 @@
1
+ import { bootMemoryCosts } from './boot-memory-cost.ts'
2
+ import { worstContentCost } from './budget.ts'
3
+ import { runtimeAccountedBytes } from './runtimeCost.ts'
4
+
5
+ import type { Shardfile } from './shardSchema.ts'
6
+
7
+ /** J408 (Jake, 2026-11-17, after Nine crashed his iPhone 17 Pro at boot): the hard line. An estimate over it
8
+ * refuses in every offline gate (check, shard CI, api-server, the cook) whatever the policy or the report-only switch.
9
+ * Engine's MEMORY_AMBER (src/client/game/grid/budgetOverlay.ts). Decimal bytes. MEMORY-GATES MG4. */
10
+ const MEMORY_HARD_BYTES = 1.5e9
11
+ const GB = 1e9
12
+ const DIGITS = 1
13
+ const EMPTY_BYTES = 0
14
+
15
+ /** The refusal's words for an estimate over the hard line; empty under it. */
16
+ function overHardLine(bytes: number): string {
17
+ if (bytes <= MEMORY_HARD_BYTES) {
18
+ return ''
19
+ }
20
+ return ` (over the ${(MEMORY_HARD_BYTES / GB).toFixed(DIGITS)} GB phone line, J408: a phone would close the page)`
21
+ }
22
+
23
+ /** J408 (MG4): the refusal for a worst-playing or loading estimate over the hard line. */
24
+ function hardLineIssue(
25
+ kind: 'playing' | 'loading',
26
+ bytes: number,
27
+ ): {
28
+ readonly code: 'perf-playing-memory' | 'perf-loading-memory'
29
+ readonly metric: string
30
+ readonly actual: number
31
+ readonly limit: number
32
+ readonly severity: 'refusal'
33
+ } {
34
+ return {
35
+ code: `perf-${kind}-memory`,
36
+ metric: `worst ${kind} total bytes${overHardLine(bytes)}`,
37
+ actual: bytes,
38
+ limit: MEMORY_HARD_BYTES,
39
+ severity: 'refusal',
40
+ }
41
+ }
42
+
43
+ /** Count cold-boot costs and any opaque runtime residency in offline admission. */
44
+ function offlineMemoryIssues(
45
+ // oxlint-disable-next-line typescript/prefer-readonly-parameter-types -- format's shard type, read only
46
+ source: Shardfile,
47
+ sections: ReadonlyMap<string, unknown>,
48
+ ): ReturnType<typeof hardLineIssue>[] {
49
+ const native = source.runtime?.cost
50
+ const runtime =
51
+ native === undefined ? EMPTY_BYTES : runtimeAccountedBytes(native)
52
+ const commons = Object.values(source.requires.commonsCosts).reduce(
53
+ (sum, row): number => sum + row.decoded + row.gpu,
54
+ EMPTY_BYTES,
55
+ )
56
+ const cost = worstContentCost(source, {
57
+ commons: runtime + commons,
58
+ boot: bootMemoryCosts(source, sections),
59
+ })
60
+ return (['playing', 'loading'] as const)
61
+ .filter((kind): boolean => cost[kind] > MEMORY_HARD_BYTES)
62
+ .map((kind): ReturnType<typeof hardLineIssue> =>
63
+ hardLineIssue(kind, cost[kind]),
64
+ )
65
+ }
66
+
67
+ export { MEMORY_HARD_BYTES, hardLineIssue, offlineMemoryIssues, overHardLine }
@@ -33,7 +33,9 @@ export class MemoryAdmission {
33
33
  private readonly warnings = new Map<string, MemoryAdmissionWarning>();
34
34
  private readonly listeners = new Set<() => void>();
35
35
  private readonly developer: () => boolean;
36
- constructor(developer: () => boolean = () => false) { this.developer = developer; }
36
+ private readonly hardBytes: number;
37
+ /** `hardBytes` (J408): applies to playing and loading even with an override. */
38
+ constructor(developer: () => boolean = () => false, hardBytes: number = Number.POSITIVE_INFINITY) { this.developer = developer; this.hardBytes = hardBytes; }
37
39
 
38
40
  /** True for an in-envelope request or a Developer override. False means the caller retains its original refusal path. */
39
41
  accept(request: MemoryAdmissionRequest): boolean {
@@ -42,6 +44,7 @@ export class MemoryAdmission {
42
44
  || ![playingCap, loadingCap].every(value => Number.isFinite(value) && value > 0)) throw new RangeError('Invalid memory admission report');
43
45
  const key = `${request.stage}:${request.owner}`;
44
46
  const playingOverBytes = Math.max(0, request.playingBytes - playingCap), loadingOverBytes = Math.max(0, request.loadingBytes - loadingCap);
47
+ if (Math.max(request.playingBytes, request.loadingBytes) > this.hardBytes) { return false; }
45
48
  if (playingOverBytes === 0 && loadingOverBytes === 0) { if (this.warnings.delete(key)) this.notify(); return true; }
46
49
  if (!this.developer()) return false;
47
50
  const warning = Object.freeze({ ...request, playingCap, loadingCap, playingOverBytes, loadingOverBytes,
@@ -2,14 +2,18 @@ import * as v from 'valibot';
2
2
  import { RUNTIME_RESIDENT_FACTOR } from './wireLimits.ts';
3
3
 
4
4
  const mb = v.pipe(v.number(), v.finite(), v.minValue(0));
5
+ const FIRST_EPOCH = 1;
6
+ const epochNumber = v.pipe(v.number(), v.integer(), v.minValue(FIRST_EPOCH));
5
7
  /** Reviewed trusted-runtime measurements, kept with their shard rather than presenting an empty data budget as its cost. */
6
- export const MemoryMeasurementSchema: v.StrictObjectSchema<{ readonly webContentMB: v.GenericSchema<MemoryMeasurementRowsInput['webContentMB'], MemoryMeasurementRows['webContentMB']>; readonly glMB: v.GenericSchema<MemoryMeasurementRowsInput['glMB'], MemoryMeasurementRows['glMB']>; readonly engineBaseMB: v.GenericSchema<MemoryMeasurementRowsInput['engineBaseMB'], MemoryMeasurementRows['engineBaseMB']>; readonly residentBaseMB: v.ExactOptionalSchema<v.GenericSchema<Exclude<MemoryMeasurementRowsInput['residentBaseMB'], undefined>, Exclude<MemoryMeasurementRows['residentBaseMB'], undefined>>, undefined>; readonly rev: v.GenericSchema<MemoryMeasurementRowsInput['rev'], MemoryMeasurementRows['rev']>; readonly device: v.GenericSchema<MemoryMeasurementRowsInput['device'], MemoryMeasurementRows['device']>; readonly evidence: v.GenericSchema<MemoryMeasurementRowsInput['evidence'], MemoryMeasurementRows['evidence']>; }, undefined> = v.strictObject({
8
+ export const MemoryMeasurementSchema: v.StrictObjectSchema<{ readonly webContentMB: v.GenericSchema<MemoryMeasurementRowsInput['webContentMB'], MemoryMeasurementRows['webContentMB']>; readonly glMB: v.GenericSchema<MemoryMeasurementRowsInput['glMB'], MemoryMeasurementRows['glMB']>; readonly engineBaseMB: v.GenericSchema<MemoryMeasurementRowsInput['engineBaseMB'], MemoryMeasurementRows['engineBaseMB']>; readonly residentBaseMB: v.ExactOptionalSchema<v.GenericSchema<Exclude<MemoryMeasurementRowsInput['residentBaseMB'], undefined>, Exclude<MemoryMeasurementRows['residentBaseMB'], undefined>>, undefined>; readonly rev: v.GenericSchema<MemoryMeasurementRowsInput['rev'], MemoryMeasurementRows['rev']>; readonly device: v.GenericSchema<MemoryMeasurementRowsInput['device'], MemoryMeasurementRows['device']>; readonly evidence: v.GenericSchema<MemoryMeasurementRowsInput['evidence'], MemoryMeasurementRows['evidence']>; readonly epoch: v.ExactOptionalSchema<v.GenericSchema<Exclude<MemoryMeasurementRowsInput['epoch'], undefined>, Exclude<MemoryMeasurementRows['epoch'], undefined>>, undefined>; }, undefined> = v.strictObject({
7
9
  webContentMB: mb, glMB: mb, engineBaseMB: mb,
8
10
  /** Matched settled pre-entry resident set. When present, subtract it instead of the dated engine-only calibration. */
9
11
  residentBaseMB: v.exactOptional(mb),
10
12
  rev: v.pipe(v.string(), v.regex(/^[a-f0-9]{9,40}$/u)),
11
13
  device: v.pipe(v.string(), v.minLength(1), v.maxLength(200)),
12
14
  evidence: v.pipe(v.string(), v.regex(/^progress\/memory\/[a-zA-Z0-9/_-]+\.json$/u)),
15
+ /** MEMORY-GATES MG5 (J408): the memory model the reading was taken against (memory-epoch.ts); absent reads as epoch 1. */
16
+ epoch: v.exactOptional(epochNumber),
13
17
  });
14
18
  /** The current runtime measurement may retain its separate images-first reading for cold phone texture selection. */
15
19
  export const RuntimeCostSchema: v.GenericSchema<RuntimeCostInput, RuntimeCost> = v.strictObject({ ...MemoryMeasurementSchema.entries, imagesFirst: v.optional(MemoryMeasurementSchema) });
@@ -58,6 +62,7 @@ interface MemoryMeasurementRowsFields {
58
62
  rev: string;
59
63
  device: string;
60
64
  evidence: string;
65
+ epoch?: number;
61
66
  }
62
67
  export type MemoryMeasurementRows = { [Key in keyof MemoryMeasurementRowsFields]: MemoryMeasurementRowsFields[Key] };
63
68
  export type RuntimeCostInput = Omit<MemoryMeasurementRowsInput, keyof ({
@@ -13,6 +13,9 @@ import type { Shardfile } from "./shardSchema.ts";
13
13
  import type { ShardTerrain } from "./terrain.ts";
14
14
  import { worstContentCost, memoryTargetWarnings, nearbyContentCost } from "./budget.ts";
15
15
  import { CONTENT_CAPS as C, MEMORY_GATES } from './contentBounds.ts';
16
+ import { staleRuntimeIssues } from './memory-epoch.ts';
17
+ import { MEMORY_HARD_BYTES, hardLineIssue } from './memory-line.ts';
18
+ import { bootMemoryCosts } from './boot-memory-cost.ts';
16
19
  import { VIEW_DRAWS, viewDraws } from './view-draws.ts';
17
20
  import { DEFAULT_GRAPH_BUDGET } from "./materialGraph.ts";
18
21
  import { SCRIPT_LIMITS } from './scriptLimits.ts';
@@ -20,11 +23,17 @@ import { runtimeAccountedBytes } from "./runtimeCost.ts";
20
23
  import { MemoryAdmission } from './memoryAdmission.ts';
21
24
  import { nearPlaceholderRoots } from './nearPlaceholder.ts';
22
25
  import type { IssueCodeOf } from './issue-codes.ts';
23
-
24
-
25
- /** Actual costs derived from a bounded parser, never trusted from the author declaration. */
26
26
  import { isNavigationData, navigationCost } from './navigationBytes.ts';
27
27
 
28
+ type PerformancePolicy = 'refuse' | 'warn';
29
+ interface PerformanceOptions { readonly policy: PerformancePolicy; readonly sections: ReadonlyMap<string, unknown> }
30
+
31
+ // oxlint-disable-next-line typescript/prefer-readonly-parameter-types -- format's shard row, only read
32
+ function reportMemory(source: Shardfile, nativeBytes: number, sections: ReadonlyMap<string, unknown>): PerformanceReport['memory'] {
33
+ const commons = nativeBytes + Object.values(source.requires.commonsCosts).reduce((sum, row) => sum + row.decoded + row.gpu, 0);
34
+ const budget = { commons, boot: bootMemoryCosts(source, sections) };
35
+ return { near: nearbyContentCost(source, source.spawn.x, source.spawn.z, budget), worst: worstContentCost(source, budget), playingLimit: C.playing, loadingLimit: C.loading };
36
+ }
28
37
  /** A performance issue's code and its metric words. */
29
38
  type Named = readonly [code: IssueCodeOf<'performance'>, metric: string];
30
39
 
@@ -298,11 +307,10 @@ export function validatePropDrawBounds(source: Shardfile, assets: ReadonlyMap<st
298
307
  }
299
308
 
300
309
  /** Report deterministic declared bounds and measured native execution; the caller supplies trusted provenance policy. */
301
- export function performanceReport(source: Shardfile, observations: PerformanceObservations, policy: 'refuse' | 'warn' = 'refuse'): PerformanceReport {
310
+ export function performanceReport(source: Shardfile, observations: PerformanceObservations, options: PerformancePolicy | PerformanceOptions = 'refuse'): PerformanceReport {
311
+ const { policy, sections } = typeof options === 'string' ? { policy: options, sections: new Map<string, unknown>() } : options;
302
312
  const native = { resident: source.runtime?.cost === undefined ? 0 : runtimeAccountedBytes(source.runtime.cost), evidence: source.runtime?.cost?.evidence ?? null, unmeasuredViewAndDownload: source.runtime !== null };
303
- const commons = native.resident + Object.values(source.requires.commonsCosts).reduce((sum, row) => sum + row.decoded + row.gpu, 0);
304
- const worst = worstContentCost(source, commons), spawn = source.spawn;
305
- const memory = { near: nearbyContentCost(source, spawn.x, spawn.z, commons), worst, playingLimit: C.playing, loadingLimit: C.loading };
313
+ const memory = reportMemory(source, native.resident, sections), { worst } = memory, spawn = source.spawn;
306
314
  const issues: PerformanceIssue[] = memoryTargetWarnings(source).map(row => ({ code: 'perf-memory-target', metric: `${row.category} resident target (tradeable)`, actual: row.bytes, limit: row.target, severity: 'warning' }));
307
315
  issues.push(...performanceTargetIssues(source, policy));
308
316
  const check = ([code, metric]: Named, actual: number, limit: number): void => {
@@ -310,11 +318,15 @@ export function performanceReport(source: Shardfile, observations: PerformanceOb
310
318
  };
311
319
  if (native.unmeasuredViewAndDownload) check(['perf-native-view-unmeasured', 'native view/download measurement required'], 1, 0);
312
320
  if (source.runtime !== null && source.runtime.cost === undefined) check(['perf-native-resident-unmeasured', 'native resident measurement required'], 1, 0);
313
- // G433: while src/format/memoryGates.json is report-only the totals print as warnings and never refuse a build.
314
- const total = ([code, metric]: Named, actual: number, limit: number): void => {
321
+ issues.push(...staleRuntimeIssues(source.runtime));
322
+ // G433 keeps the soft caps report-only. J408 applies to both estimates ahead of the soft caps.
323
+ const total = (kind: 'playing' | 'loading', actual: number, limit: number): void => {
324
+ if (actual > MEMORY_HARD_BYTES) { issues.push(hardLineIssue(kind, actual)); return; }
325
+ const code = `perf-${kind}-memory` as const, metric = `worst ${kind} total bytes`;
315
326
  if (MEMORY_GATES.reportOnly && actual > limit) issues.push({ code, metric: `${metric} (report-only, G433)`, actual, limit, severity: 'warning' }); else check([code, metric], actual, limit);
316
327
  };
317
- total(['perf-playing-memory', 'worst playing total bytes'], worst.playing, C.playing); total(['perf-loading-memory', 'worst loading total bytes'], worst.loading, C.loading);
328
+ total('playing', worst.playing, C.playing);
329
+ total('loading', worst.loading, C.loading);
318
330
  const library = reportCardClosure(source, source.library), critical = reportCardClosure(source, source.critical);
319
331
  const tileRoots = source.tiles.flatMap(tile => tile.files), farRoots = source.far?.files ?? [], nearRoots = nearPlaceholderRoots(source.near);
320
332
  const playable = reportCardClosure(source, [...source.critical, ...source.library, ...farRoots, ...source.tiles.filter(tile => tile.lod === 1 || near(tile, spawn.x, spawn.z)).flatMap(tile => tile.files)]);
@@ -361,8 +373,7 @@ export function performanceReportLines(report: PerformanceReport): string[] {
361
373
  ...report.issues.map(issue => `${issue.severity.toUpperCase()}: ${issue.metric}: ${issue.actual} > ${issue.limit}`)];
362
374
  }
363
375
 
364
- /** The memory admission an offline author build uses: strict for `refuse` unless src/format/memoryGates.json is
365
- * report-only (G433), when an over-envelope total is accepted and printed by the performance report instead. */
366
- export function offlineMemoryAdmission(policy: 'warn' | 'refuse'): MemoryAdmission | undefined {
367
- return policy === 'warn' || MEMORY_GATES.reportOnly ? new MemoryAdmission(() => true) : undefined;
376
+ /** Offline soft-cap policy and the fixed J408 line for playing and loading. */
377
+ export function offlineMemoryAdmission(policy: 'warn' | 'refuse'): MemoryAdmission {
378
+ return new MemoryAdmission(() => policy === 'warn' || MEMORY_GATES.reportOnly, MEMORY_HARD_BYTES);
368
379
  }
@@ -37,7 +37,7 @@ function admitHead(
37
37
  preflightDeclaredCosts(shard, offlineMemoryAdmission('warn'))
38
38
  })
39
39
  withIssueCode('performance-targets', (): void => {
40
- assertShardfileTargets(shard, 'warn')
40
+ assertShardfileTargets(shard, 'warn', payloads)
41
41
  })
42
42
  return shard
43
43
  }
@@ -20,6 +20,8 @@ import { assertScriptSides } from './script-sides.ts';
20
20
  import { shardfileRecordings } from './shardfile-audio.ts';
21
21
  import type { RecordingMeasure } from './audio-measure.ts';
22
22
  import { issueError, withIssueCode as coded } from './issue-codes.ts';
23
+ import { staleRuntimeIssues } from './memory-epoch.ts';
24
+ import { offlineMemoryIssues } from './memory-line.ts';
23
25
 
24
26
  /**
25
27
  * P1-F3 format validation of a built shardfile product (format 2: `shard.json`, sections, blobs, packs): the schema,
@@ -106,8 +108,8 @@ export function outputBlobExtension(kind: OutputFile['kind'], bytes: Uint8Array)
106
108
  }
107
109
 
108
110
  /** Refuse the declared targets a policy treats as refusals, before any byte is read or executed. */
109
- export function assertShardfileTargets(source: Shardfile, policy: 'warn' | 'refuse'): void {
110
- const issues = performanceTargetIssues(source, policy).filter(issue => issue.severity === 'refusal');
111
+ export function assertShardfileTargets(source: Shardfile, policy: 'warn' | 'refuse', sections: ReadonlyMap<string, unknown> = new Map()): void {
112
+ const issues = [...staleRuntimeIssues(source.runtime), ...offlineMemoryIssues(source, sections), ...performanceTargetIssues(source, policy).filter(issue => issue.severity === 'refusal')];
111
113
  if (issues.length === 0) return;
112
114
  throw issueError('performance-targets', issues.map(issue => `REFUSAL: ${issue.metric}: ${issue.actual} > ${issue.limit}`).join('\n'));
113
115
  }
@@ -117,7 +119,7 @@ export function admitShardfileFolder(input: unknown, assets: ReadonlyMap<string,
117
119
  policy: 'warn' | 'refuse' = 'refuse', scripts: ScriptAdmissionRows = [], sections?: ReadonlyMap<string, unknown>): Shardfile {
118
120
  const source = coded('shard-schema', (): Shardfile => parseShardfile(input, sections));
119
121
  coded('declared-costs', (): void => { preflightDeclaredCosts(source, offlineMemoryAdmission(policy)); });
120
- coded('performance-targets', (): void => { assertShardfileTargets(source, policy); });
122
+ coded('performance-targets', (): void => { assertShardfileTargets(source, policy, sections); });
121
123
  return coded('asset-admission', (): Shardfile => validateShardfileAssets(source, assets, hash, offlineMemoryAdmission(policy), undefined, scripts, sections));
122
124
  }
123
125
 
@@ -11,10 +11,11 @@ export const SkinClipNameSchema: v.GenericSchema<SkinClipNameRowsInput, SkinClip
11
11
  const joint = v.pipe(v.string(), v.regex(/^[A-Za-z][A-Za-z0-9_.-]*$/u), v.maxLength(64));
12
12
  const bytes = v.pipe(v.number(), v.integer(), v.minValue(0), v.maxValue(25_000_000));
13
13
 
14
- /** One exported skin as the export half writes it (`public/assets/baked/<shard>/skins.json`): the GLB's content hash and its rig. */
14
+ /** One exported skin: the GLB hash and rig. Clips may be empty for a poser-driven
15
+ * rig; loop bindings must still name a declared clip. */
15
16
  export const SkinRowSchema: v.GenericSchema<SkinRowInput, SkinRow> = v.object({
16
17
  id, file: hash, family: v.picklist(['toon', 'pbr']),
17
- rig: v.strictObject({ skeleton: v.pipe(v.string(), v.regex(/^[a-z][A-Za-z0-9.]*$/u), v.maxLength(128)), joints: v.pipe(v.array(v.pipe(v.array(joint), v.minLength(1), v.maxLength(128))), v.length(1)), clips: v.pipe(v.array(SkinClipNameSchema), v.minLength(1), v.maxLength(32)), sockets: v.pipe(v.array(joint), v.maxLength(32)) }),
18
+ rig: v.strictObject({ skeleton: v.pipe(v.string(), v.regex(/^[a-z][A-Za-z0-9.]*$/u), v.maxLength(128)), joints: v.pipe(v.array(v.pipe(v.array(joint), v.minLength(1), v.maxLength(128))), v.length(1)), clips: v.pipe(v.array(SkinClipNameSchema), v.maxLength(32)), sockets: v.pipe(v.array(joint), v.maxLength(32)) }),
18
19
  cost: v.strictObject({ decoded: bytes, gpu: bytes, triangles: v.pipe(v.number(), v.integer(), v.minValue(0), v.maxValue(400_000)), draws: v.pipe(v.number(), v.integer(), v.minValue(0), v.maxValue(512)) }),
19
20
  });
20
21
  /** A validated exported skin row. */