@wildshard/shard-format 0.68.0 → 0.69.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.68.0",
3
+ "version": "0.69.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": {
@@ -344,7 +344,7 @@
344
344
  "./shardSchema": "./src/format/shardSchema.ts",
345
345
  "./emptyShardfile": "./src/format/empty-shardfile.ts",
346
346
  "./migrate": "./src/format/format-migrate.ts",
347
- "./migrations": "./src/format/format-migrations.ts",
347
+ "./formatMigrations": "./src/format/format-migrations.ts",
348
348
  "./shardSections": "./src/format/shardSections.ts",
349
349
  "./sketch": "./src/format/sketch.ts",
350
350
  "./skinAssets": "./src/format/skinAssets.ts",
@@ -3,20 +3,36 @@ import { createReadStream } from 'node:fs'
3
3
 
4
4
  import { nodeStreamPorts } from '../format/shardfile-stream-node.ts'
5
5
  import { validateShardfileStream } from '../format/shardfile-stream.ts'
6
+ import { migratedVerdict } from './corpus-migrated.ts'
6
7
 
7
8
  import type { CorpusRow } from './corpus.ts'
8
9
 
9
- /** Validate one stored original (brotli unless `plain`) as the API stored it; the deprecated paths it uses. Throws on a
10
- * refusal. */
10
+ /** A valid original's deprecated paths, and the chain steps that made it valid when it was refused as stored. */
11
+ interface StoredVerdict {
12
+ readonly deprecations: readonly string[]
13
+ /** `migrated: <steps>` when the chain's copy is what validated. */
14
+ readonly reason?: string
15
+ }
16
+
17
+ /** Validate one stored original (brotli unless `plain`) as the API stored it; one the format refuses is judged again
18
+ * through the migration chain (J486). Throws the copy's refusal when that fails too. */
11
19
  async function storedDeprecations(
12
20
  file: string,
13
21
  plain: boolean,
14
- ): Promise<readonly string[]> {
15
- const validated = await validateShardfileStream(
16
- (): AsyncIterable<Uint8Array> => createReadStream(file),
17
- { ...nodeStreamPorts({ brotli: !plain }), judged: 'stored' },
18
- )
19
- return validated.deprecations
22
+ ): Promise<StoredVerdict> {
23
+ try {
24
+ const validated = await validateShardfileStream(
25
+ (): AsyncIterable<Uint8Array> => createReadStream(file),
26
+ { ...nodeStreamPorts({ brotli: !plain }), judged: 'stored' },
27
+ )
28
+ return { deprecations: validated.deprecations }
29
+ } catch (error: unknown) {
30
+ const copy = await migratedVerdict(file, plain, error)
31
+ return {
32
+ deprecations: copy.deprecations,
33
+ reason: `migrated: ${copy.applied.join(', ')}`,
34
+ }
35
+ }
20
36
  }
21
37
 
22
38
  /** FE7: one line per deprecated path a kept original uses, with how many and which. */
@@ -38,4 +54,4 @@ function deprecationLines(
38
54
  )
39
55
  }
40
56
 
41
- export { deprecationLines, storedDeprecations }
57
+ export { type StoredVerdict, deprecationLines, storedDeprecations }
@@ -0,0 +1,114 @@
1
+ import {
2
+ array,
3
+ minLength,
4
+ number,
5
+ parse,
6
+ pipe,
7
+ regex,
8
+ safeInteger,
9
+ strictObject,
10
+ string,
11
+ } from 'valibot'
12
+
13
+ import type { CorpusRow } from './corpus.ts'
14
+
15
+ // SHARD-COMPAT FE5 (meta, J486, Q51): the corpus gates a format release. A stored original that fails blocks the
16
+ // release unless `corpus/known-failures.json` lists it with the row that owns its repair; a listed one that passes
17
+ // again is named as stale, so the list only shrinks.
18
+
19
+ /** A stored original known to fail, and the row that owns its repair. */
20
+ interface KnownFailure {
21
+ readonly hash: string
22
+ readonly slug: string
23
+ readonly revision: number
24
+ readonly owner: string
25
+ }
26
+
27
+ /** What the gate decided: the failures that block, the stale entries, and one line for each. */
28
+ interface CorpusGate {
29
+ readonly blocking: readonly CorpusRow[]
30
+ readonly stale: readonly KnownFailure[]
31
+ readonly lines: readonly string[]
32
+ }
33
+
34
+ const HASH = pipe(string(), regex(/^[a-f0-9]{64}$/u))
35
+ const REVISION = pipe(number(), safeInteger())
36
+ const NAMED = 1
37
+ const OWNER = pipe(string(), minLength(NAMED))
38
+ const KnownFailuresSchema = array(
39
+ strictObject({
40
+ hash: HASH,
41
+ slug: string(),
42
+ revision: REVISION,
43
+ owner: OWNER,
44
+ }),
45
+ )
46
+
47
+ /** Parse `corpus/known-failures.json`. */
48
+ function readKnownFailures(text: string): readonly KnownFailure[] {
49
+ const input: unknown = JSON.parse(text)
50
+ return parse(KnownFailuresSchema, input)
51
+ }
52
+
53
+ function named(found: Readonly<{ slug: string; revision: number }>): string {
54
+ return `${found.slug} r${String(found.revision)}`
55
+ }
56
+
57
+ /** The failing rows, each with its owner when the list knows it. */
58
+ function failures(
59
+ rows: readonly CorpusRow[],
60
+ owners: ReadonlyMap<string, string>,
61
+ ): readonly (readonly [CorpusRow, string | undefined])[] {
62
+ return rows
63
+ .filter((found: Readonly<CorpusRow>): boolean => found.verdict === 'fails')
64
+ .map((found: CorpusRow): readonly [CorpusRow, string | undefined] => [
65
+ found,
66
+ owners.get(found.hash),
67
+ ])
68
+ }
69
+
70
+ /** Split the corpus rows by the known failures. */
71
+ function corpusGate(
72
+ rows: readonly CorpusRow[],
73
+ known: readonly KnownFailure[],
74
+ ): CorpusGate {
75
+ const owners = new Map(
76
+ known.map((entry: KnownFailure): readonly [string, string] => [
77
+ entry.hash,
78
+ entry.owner,
79
+ ]),
80
+ )
81
+ const failing = failures(rows, owners)
82
+ const valid = new Set(
83
+ rows
84
+ .filter(
85
+ (found: Readonly<CorpusRow>): boolean => found.verdict === 'valid',
86
+ )
87
+ .map((found: Readonly<CorpusRow>): string => found.hash),
88
+ )
89
+ const blocking = failing
90
+ .filter(([, owner]): boolean => owner === undefined)
91
+ .map(([found]): CorpusRow => found)
92
+ const stale = known.filter((entry: KnownFailure): boolean =>
93
+ valid.has(entry.hash),
94
+ )
95
+ const lines = [
96
+ ...failing
97
+ .filter(([, owner]): boolean => owner !== undefined)
98
+ .map(
99
+ ([found, owner]): string =>
100
+ `known failure ${named(found)} (${owner ?? ''})`,
101
+ ),
102
+ ...stale.map(
103
+ (entry: KnownFailure): string =>
104
+ `stale known failure ${named(entry)}: it passes now; drop it from corpus/known-failures.json`,
105
+ ),
106
+ ...blocking.map(
107
+ (found: Readonly<CorpusRow>): string =>
108
+ `BLOCKS THE RELEASE: ${named(found)} ${found.reason ?? ''}`,
109
+ ),
110
+ ]
111
+ return { blocking, stale, lines }
112
+ }
113
+
114
+ export { type CorpusGate, type KnownFailure, corpusGate, readKnownFailures }
@@ -0,0 +1,68 @@
1
+ /** The corpus judges an older original through the migration chain (J486, SHARD-COMPAT CP1): a file the current
2
+ * format refuses as stored still counts as valid when the chain's copy validates, with the author's own preparation
3
+ * when the steps leave it sealed. */
4
+ import { createHash } from 'node:crypto'
5
+ import { readFile } from 'node:fs/promises'
6
+ import { promisify } from 'node:util'
7
+ import { brotliDecompress } from 'node:zlib'
8
+
9
+ import { migrateShardfile, validateMigrated } from '../format/format-migrate.ts'
10
+ import { prepareAssetDecoders } from '../format/shardfile-assets.ts'
11
+ import { readTar } from '../format/tar.ts'
12
+
13
+ /** What the chain did to a refused original whose copy validates. */
14
+ interface MigratedVerdict {
15
+ readonly applied: readonly string[]
16
+ readonly deprecations: readonly string[]
17
+ }
18
+
19
+ const NONE = 0
20
+ const unbrotli = promisify(brotliDecompress)
21
+
22
+ function sha256(bytes: Readonly<Uint8Array>): string {
23
+ return createHash('sha256').update(bytes).digest('hex')
24
+ }
25
+
26
+ /** The chain's copy of an original tarball, or `undefined` when it cannot be read or the chain cannot run on it. */
27
+ function tryChain(
28
+ tar: Readonly<Uint8Array>,
29
+ ): ReturnType<typeof migrateShardfile> | undefined {
30
+ try {
31
+ return migrateShardfile(readTar(tar), { hash: sha256 })
32
+ } catch {
33
+ return undefined
34
+ }
35
+ }
36
+
37
+ /** The chain's copy of an original, or the stored refusal when the chain cannot run or changes nothing. */
38
+ function chainCopy(
39
+ tar: Readonly<Uint8Array>,
40
+ refused: unknown,
41
+ ): ReturnType<typeof migrateShardfile> {
42
+ const copy = tryChain(tar)
43
+ if (copy === undefined || copy.applied.length === NONE) {
44
+ throw refused
45
+ }
46
+ return copy
47
+ }
48
+
49
+ /** Migrate one stored original (brotli unless `plain`) and validate the copy. Throws the copy's refusal; when the chain cannot
50
+ * run or changes nothing, the stored refusal (`refused`). */
51
+ async function migratedVerdict(
52
+ file: string,
53
+ plain: boolean,
54
+ refused: unknown,
55
+ ): Promise<MigratedVerdict> {
56
+ const stored = new Uint8Array(await readFile(file))
57
+ const tar = plain ? stored : new Uint8Array(await unbrotli(stored))
58
+ const copy = chainCopy(tar, refused)
59
+ await prepareAssetDecoders()
60
+ const validated = validateMigrated(copy.files, {
61
+ hash: sha256,
62
+ judged: 'stored',
63
+ preparation: copy.preparation === 'stale' ? 'migrated' : 'author',
64
+ })
65
+ return { applied: copy.applied, deprecations: validated.deprecations }
66
+ }
67
+
68
+ export { type MigratedVerdict, migratedVerdict }
package/src/cli/corpus.ts CHANGED
@@ -181,8 +181,8 @@ async function judge(
181
181
  }
182
182
  }
183
183
  const plain = isPlainTar(await firstBytes(file))
184
- const deprecations = await storedDeprecations(file, plain)
185
- return { verdict: 'valid', deprecations, transient: false }
184
+ const stored = await storedDeprecations(file, plain)
185
+ return { verdict: 'valid', ...stored, transient: false }
186
186
  } catch (error: unknown) {
187
187
  return { verdict: 'fails', reason: shortReason(error), transient: false }
188
188
  } finally {
package/src/cli/main.ts CHANGED
@@ -1,6 +1,8 @@
1
1
  #!/usr/bin/env node
2
+ import { readFile } from 'node:fs/promises'
2
3
  import { parseArgs } from 'node:util'
3
4
 
5
+ import { corpusGate, readKnownFailures } from './corpus-gate.ts'
4
6
  import { corpusReport, runCorpus } from './corpus.ts'
5
7
  import { packFolder } from './pack.ts'
6
8
  import { summary, validateShardfile } from './validate.ts'
@@ -16,6 +18,7 @@ const NONE = 0
16
18
  const FIRST_CLI_ARG = 2
17
19
  const DEFAULT_API = 'https://api.wildshard.io'
18
20
  const DEFAULT_CACHE = 'tmp/corpus'
21
+ const KNOWN_FAILURES = 'corpus/known-failures.json'
19
22
 
20
23
  const USAGE = `Usage: shard-format <command> [options]
21
24
 
@@ -137,9 +140,15 @@ async function corpus(args: CliArgs): Promise<number> {
137
140
  validator: await readVersion(),
138
141
  })
139
142
  process.stdout.write(`${corpusReport(rows)}\n`)
140
- return rows.some((found): boolean => found.verdict === 'fails')
141
- ? EXIT_INVALID
142
- : EXIT_OK
143
+ // SHARD-COMPAT FE5: only a failure not listed with its owner blocks a release.
144
+ const listed = await readFile(KNOWN_FAILURES, 'utf8').catch(
145
+ (): string => '[]',
146
+ )
147
+ const gate = corpusGate(rows, readKnownFailures(listed))
148
+ if (gate.lines.length > NONE) {
149
+ process.stdout.write(`${gate.lines.join('\n')}\n`)
150
+ }
151
+ return gate.blocking.length > NONE ? EXIT_INVALID : EXIT_OK
143
152
  }
144
153
 
145
154
  async function runCommand(args: CliArgs): Promise<number> {
package/src/cli/pack.ts CHANGED
@@ -58,7 +58,7 @@ interface HeldIndex {
58
58
  readonly build: Readonly<{ sourceHash: string }>
59
59
  readonly files: readonly Listed[]
60
60
  readonly packs?: readonly PackRow[] | undefined
61
- readonly schemas: readonly Listed[]
61
+ readonly schemas?: readonly Listed[] | undefined
62
62
  readonly sections: readonly Section[]
63
63
  }
64
64
 
@@ -279,3 +279,7 @@ export {
279
279
  } from './creature-attackable.ts'
280
280
  export type { CreatureAttackable } from './creature-attackable.ts'
281
281
  export type { CreatureBody } from './creature-body.ts'
282
+
283
+ // ONE-FORMAT OF30: a declared species row's optional view projection (rows.ts), lent from its own module
284
+ export { ActorProjectionV2Schema } from './actorProjectionV2.ts'
285
+ export type { ActorProjectionV2Rows } from './actorProjectionV2.ts'
@@ -30,6 +30,25 @@ interface DeprecationRule extends Deprecation {
30
30
  }
31
31
 
32
32
  const LEGACY_SPELLING = '0.1'
33
+ const NONE = 0
34
+ /** Deprecated in the current format with no data change: a shard file of any version may still carry it. */
35
+ const CURRENT = '0.1.0.1'
36
+ /** Format 0.1.0.2's envelope (SHARD-COMPAT CP14, FORMAT-PRUNE FP4 and FP25). */
37
+ const ENVELOPE = '0.1.0.2'
38
+ const LEGACY_LAYOUT = 2
39
+ /** FORMAT-PRUNE FP4: always empty, never read. */
40
+ const EMPTY_INDEX_FIELDS: readonly (readonly [string, string | undefined])[] = [
41
+ ['schemas', undefined],
42
+ ['runtime', 'files'],
43
+ ['runtime', 'lines'],
44
+ ['requires', 'capabilities'],
45
+ ]
46
+ /** FORMAT-PRUNE FP15: OF30 cut B leaves these as plain JSON nothing reads. */
47
+ const SPECIES_PROGRAM_FAMILY: readonly string[] = [
48
+ 'actors/species-programs',
49
+ 'look/hull-book',
50
+ 'look/rigged-hulls',
51
+ ]
33
52
 
34
53
  function field(value: unknown, key: string): unknown {
35
54
  return typeof value === 'object' && value !== null && !Array.isArray(value)
@@ -37,6 +56,22 @@ function field(value: unknown, key: string): unknown {
37
56
  : undefined
38
57
  }
39
58
 
59
+ /** Whether `key` names a field anywhere inside `value`. */
60
+ function hasKey(value: unknown, key: string): boolean {
61
+ const pending: unknown[] = [value]
62
+ while (pending.length > NONE) {
63
+ const next = pending.pop()
64
+ if (typeof next === 'object' && next !== null) {
65
+ if (!Array.isArray(next) && Object.hasOwn(next, key)) {
66
+ return true
67
+ }
68
+ const children: readonly unknown[] = Object.values(next)
69
+ pending.push(...children)
70
+ }
71
+ }
72
+ return false
73
+ }
74
+
40
75
  const RULES: readonly DeprecationRule[] = [
41
76
  {
42
77
  id: 'version.two-part',
@@ -47,6 +82,30 @@ const RULES: readonly DeprecationRule[] = [
47
82
  uses: (shard: Readonly<DeprecationInput>): boolean =>
48
83
  field(shard.index, 'version') === LEGACY_SPELLING,
49
84
  },
85
+ {
86
+ id: 'shard.version',
87
+ path: 'shard.json version beside the layout marker formatVersion 2 (SHARD-COMPAT CP14)',
88
+ since: ENVELOPE,
89
+ replacement:
90
+ 'formatVersion: the four-part format version, with no version field',
91
+ migration: 'cp14-format-version',
92
+ uses: (shard: Readonly<DeprecationInput>): boolean =>
93
+ field(shard.index, 'formatVersion') === LEGACY_LAYOUT,
94
+ },
95
+ {
96
+ id: 'shard.empty-fields',
97
+ path: 'shard.json schemas, runtime.files, runtime.lines and requires.capabilities (FORMAT-PRUNE FP4)',
98
+ since: ENVELOPE,
99
+ replacement: 'nothing: each is always empty and no reader reads it',
100
+ migration: 'fp4-drop-empty-index-fields',
101
+ uses: (shard: Readonly<DeprecationInput>): boolean =>
102
+ EMPTY_INDEX_FIELDS.some(
103
+ ([outer, inner]: readonly [string, string | undefined]): boolean =>
104
+ inner === undefined
105
+ ? field(shard.index, outer) !== undefined
106
+ : field(field(shard.index, outer), inner) !== undefined,
107
+ ),
108
+ },
50
109
  {
51
110
  id: 'manifest.gridShardfile',
52
111
  path: 'sections/ui/level manifest.gridShardfile (and the discovery mount)',
@@ -68,6 +127,75 @@ const RULES: readonly DeprecationRule[] = [
68
127
  uses: (shard: Readonly<DeprecationInput>): boolean =>
69
128
  field(field(shard.index, 'runtime'), 'trust') !== undefined,
70
129
  },
130
+ ...SPECIES_PROGRAM_FAMILY.map((name: string): DeprecationRule => ({
131
+ id: `section.${name}`,
132
+ path: `sections/${name} (the species-program family, FORMAT-PRUNE FP15)`,
133
+ since: CURRENT,
134
+ replacement:
135
+ 'species rows and authored looks (actors/species); nothing reads it once OF30 lands',
136
+ migration: undefined,
137
+ uses: (shard: Readonly<DeprecationInput>): boolean =>
138
+ shard.sections.has(name),
139
+ })),
140
+ {
141
+ id: 'items.legacySlot',
142
+ path: 'an item equipment row legacySlot: a closed list of engine-native weapon names (FORMAT-PRUNE FP17)',
143
+ since: CURRENT,
144
+ replacement:
145
+ 'none yet: it goes with engine native weapon slots, so a new item names no slot',
146
+ migration: undefined,
147
+ uses: (shard: Readonly<DeprecationInput>): boolean =>
148
+ [...shard.sections.values()].some((section: unknown): boolean =>
149
+ hasKey(section, 'legacySlot'),
150
+ ),
151
+ },
152
+ {
153
+ id: 'admission.server',
154
+ path: 'shard.json admission.server (native assembly, FORMAT-PRUNE FP16)',
155
+ since: CURRENT,
156
+ replacement:
157
+ 'the server primitives: the server derives every host (OF17b3)',
158
+ migration: undefined,
159
+ uses: (shard: Readonly<DeprecationInput>): boolean =>
160
+ field(field(shard.index, 'admission'), 'server') !== undefined,
161
+ },
162
+ ]
163
+
164
+ /** A `legacy*` field that maps an old save key or saved shape: it stays, undeprecated, until a save wipe (J149), so a
165
+ * shard that keeps old players' saves working is not warned (FORMAT-PRUNE FP17). */
166
+ interface SaveBridge {
167
+ readonly path: string
168
+ /** The engine code that reads old saves through it. */
169
+ readonly reader: string
170
+ }
171
+
172
+ /** FP17's sort of the `legacy*` fields. `items.legacySlot` is shard data only, so it is a deprecation above; the
173
+ * species book's `piercing.legacy` goes with the species-program family (FP15); none can be migrated by data alone. */
174
+ const SAVE_BRIDGES: readonly SaveBridge[] = [
175
+ {
176
+ path: 'loadout bow.legacyItem',
177
+ reader: 'engine client/game/loadout/held.ts',
178
+ },
179
+ {
180
+ path: 'quest persistence legacyNamespace',
181
+ reader: 'engine shared/game/quest/persistence.ts',
182
+ },
183
+ {
184
+ path: 'quest story repair legacyObservation',
185
+ reader: 'engine client/game/plugin/ui.ts',
186
+ },
187
+ {
188
+ path: 'quest story persistence reward.legacy',
189
+ reader: 'engine shared/game/quest/persistence.ts',
190
+ },
191
+ {
192
+ path: 'elite feature legacy (versions, scripts, stun, upgrades)',
193
+ reader: 'engine server/game/quest/eliteFeature.ts',
194
+ },
195
+ {
196
+ path: 'spawn script legacy (spec, acc, rng, groups)',
197
+ reader: 'engine server/game/population/spawnScript.ts',
198
+ },
71
199
  ]
72
200
 
73
201
  /** Every deprecated path, without its test. */
@@ -123,6 +251,8 @@ function deprecationReport(
123
251
 
124
252
  export {
125
253
  DEPRECATIONS,
254
+ SAVE_BRIDGES,
255
+ type SaveBridge,
126
256
  type DeprecationReport,
127
257
  deprecationReport,
128
258
  type Deprecation,
@@ -17,6 +17,10 @@ import {
17
17
  verifyInventory,
18
18
  } from './format-migrate-inventory.ts'
19
19
  import { rebuildInventory } from './format-migrate-rebuild.ts'
20
+ import {
21
+ declaredShardfileFormat,
22
+ writeShardfileFormat,
23
+ } from './format-migration-envelope.ts'
20
24
  import {
21
25
  FORMAT_MIGRATIONS,
22
26
  checkMigrations,
@@ -117,7 +121,7 @@ function admitOriginal(files: Files, hash: Hash, to: string): Admitted {
117
121
  const cook = rawCook === undefined ? undefined : readCookData(rawCook)
118
122
  // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- read only for its slug, sdk, files and cook row
119
123
  requireCookPreparation(index as unknown as OutputIndex, cook, hash)
120
- return { index, cook, from: checkWindow(index['version'], to) }
124
+ return { index, cook, from: checkWindow(declaredShardfileFormat(index), to) }
121
125
  }
122
126
 
123
127
  const MOUNT = /^mounts\/.*\.json$/u
@@ -154,7 +158,7 @@ function runSteps(
154
158
  ): void {
155
159
  for (const step of steps) {
156
160
  step.apply(shard)
157
- shard.index['version'] = step.to
161
+ writeShardfileFormat(shard.index, step.to)
158
162
  }
159
163
  }
160
164
 
@@ -254,7 +258,7 @@ function migrateShardfile(
254
258
  return {
255
259
  files: copy,
256
260
  from: admitted.from,
257
- to: String(admitted.index['version']),
261
+ to: String(declaredShardfileFormat(admitted.index)),
258
262
  applied: steps.map((step: Readonly<FormatMigration>): string => step.id),
259
263
  chainId: chainId(migrations, options.hash),
260
264
  digest: options.hash(copy.get(INDEX) ?? new Uint8Array()),
@@ -0,0 +1,74 @@
1
+ // oxlint-disable typescript/prefer-readonly-parameter-types -- a step edits the shard it is handed, in place
2
+ /** Format 0.1.0.2's chain steps (SHARD-COMPAT CP14, FORMAT-PRUNE FP4 and FP25, J486). The runner writes the copy's
3
+ * version into `formatVersion` from 0.1.0.2 on (`writeShardfileFormat`), replacing the frozen layout marker `2`; these
4
+ * steps drop the fields the new envelope no longer carries. Every dropped field held nothing: `version` repeats the
5
+ * format version, and the other four are always empty with no reader. */
6
+ import { LEGACY_LAYOUT, writesIndexFormatVersion } from './version.ts'
7
+
8
+ import type { FormatMigration, MigratingShard } from './format-migrations.ts'
9
+
10
+ type JsonRecord = Record<string, unknown>
11
+
12
+ const ENVELOPE = '0.1.0.2'
13
+
14
+ function isRecord(value: unknown): value is JsonRecord {
15
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
16
+ }
17
+
18
+ /** SHARD-COMPAT CP14 (FP25): `version` becomes `formatVersion`; the layout marker goes in the same step. */
19
+ const formatVersionField: FormatMigration = {
20
+ id: 'cp14-format-version',
21
+ to: ENVELOPE,
22
+ touches: 'data',
23
+ affects: [],
24
+ apply: (shard: MigratingShard): void => {
25
+ Reflect.deleteProperty(shard.index, 'version')
26
+ },
27
+ }
28
+
29
+ /** FORMAT-PRUNE FP4: `schemas`, `runtime.files`, `runtime.lines` and `requires.capabilities`, always empty, never read. */
30
+ const dropEmptyIndexFields: FormatMigration = {
31
+ id: 'fp4-drop-empty-index-fields',
32
+ to: ENVELOPE,
33
+ touches: 'data',
34
+ affects: [],
35
+ apply: (shard: MigratingShard): void => {
36
+ const { index } = shard
37
+ Reflect.deleteProperty(index, 'schemas')
38
+ const { runtime, requires } = index
39
+ if (isRecord(runtime)) {
40
+ Reflect.deleteProperty(runtime, 'files')
41
+ Reflect.deleteProperty(runtime, 'lines')
42
+ }
43
+ if (isRecord(requires)) {
44
+ Reflect.deleteProperty(requires, 'capabilities')
45
+ }
46
+ },
47
+ }
48
+
49
+ /** The format version a `shard.json` declares, as written, or `undefined`: `formatVersion` from 0.1.0.2, else the
50
+ * legacy `version` beside the layout marker. */
51
+ function declaredShardfileFormat(index: Readonly<JsonRecord>): unknown {
52
+ const declared: unknown = index['formatVersion']
53
+ return declared === LEGACY_LAYOUT || declared === undefined
54
+ ? index['version']
55
+ : declared
56
+ }
57
+
58
+ /** Write a copy's format version the way that version spells it: `formatVersion` from 0.1.0.2 (with no `version`),
59
+ * else `version` beside the layout marker. */
60
+ function writeShardfileFormat(index: JsonRecord, version: string): void {
61
+ if (writesIndexFormatVersion(version)) {
62
+ Reflect.deleteProperty(index, 'version')
63
+ index['formatVersion'] = version
64
+ } else {
65
+ index['version'] = version
66
+ }
67
+ }
68
+
69
+ export {
70
+ declaredShardfileFormat,
71
+ dropEmptyIndexFields,
72
+ formatVersionField,
73
+ writeShardfileFormat,
74
+ }
@@ -2,6 +2,10 @@
2
2
  /** The migration chain's registry (SHARD-COMPAT CP1, J486). A migration is one pure, data-only step that rewrites an
3
3
  * older shard file's JSON to a newer format version. It is not a save migration (`migrations.ts`) and not a catalogue
4
4
  * schema change (api-server). The change's author adds its migration here in the same release (J486, Q49). */
5
+ import {
6
+ dropEmptyIndexFields,
7
+ formatVersionField,
8
+ } from './format-migration-envelope.ts'
5
9
  import { journalGlyphImages } from './format-migration-journal.ts'
6
10
  import { dropRuntimeTrust, shardfilePointer } from './format-migration-prune.ts'
7
11
  import {
@@ -65,6 +69,8 @@ const FORMAT_MIGRATIONS: readonly FormatMigration[] = [
65
69
  journalGlyphImages,
66
70
  shardfilePointer,
67
71
  dropRuntimeTrust,
72
+ formatVersionField,
73
+ dropEmptyIndexFields,
68
74
  ]
69
75
 
70
76
  /** Whether a file at `version` still needs a step that writes `to`. The legacy two-part spelling sits just below its
@@ -0,0 +1,33 @@
1
+ /** The two `shard.json` envelopes' version fields (SHARD-COMPAT CP14, FORMAT-PRUNE FP25), shared by every index
2
+ * reader: the full parser (`outputIndex.ts`), the lineage reader and the download reader. */
3
+ import { exactOptional, literal, picklist, union } from 'valibot'
4
+
5
+ import {
6
+ INDEX_FORMAT_VERSIONS,
7
+ LEGACY_INDEX_VERSIONS,
8
+ LEGACY_LAYOUT,
9
+ } from './version.ts'
10
+
11
+ import type {
12
+ ExactOptionalSchema,
13
+ LiteralSchema,
14
+ PicklistSchema,
15
+ UnionSchema,
16
+ } from 'valibot'
17
+
18
+ /** `formatVersion`: the frozen layout marker `2` (formats 0.1 to 0.1.0.1), or the format version itself (0.1.0.2 on). */
19
+ const IndexFormatVersionSchema: UnionSchema<
20
+ [
21
+ LiteralSchema<typeof LEGACY_LAYOUT, undefined>,
22
+ PicklistSchema<typeof INDEX_FORMAT_VERSIONS, undefined>,
23
+ ],
24
+ undefined
25
+ > = union([literal(LEGACY_LAYOUT), picklist(INDEX_FORMAT_VERSIONS)])
26
+
27
+ /** `version`: only the legacy envelope carries it, beside the layout marker. */
28
+ const LegacyIndexVersionSchema: ExactOptionalSchema<
29
+ PicklistSchema<typeof LEGACY_INDEX_VERSIONS, undefined>,
30
+ undefined
31
+ > = exactOptional(picklist(LEGACY_INDEX_VERSIONS))
32
+
33
+ export { IndexFormatVersionSchema, LegacyIndexVersionSchema }
@@ -8,12 +8,15 @@ const completeReturn:v.GenericSchema<v.InferInput<typeof ReturnProgramSchema>,v.
8
8
  const finite = v.pipe(v.number(), v.finite());
9
9
  const key = v.pipe(v.string(), v.minLength(1), v.maxLength(128));
10
10
  const point = v.strictObject({ x: finite, z: finite });
11
+ /** FORMAT-PRUNE FP3: no reader in any repo; optional now, and Driftwood stops writing it at its Track F row (SM1). */
12
+ const legacyMemory = v.exactOptional(v.array(v.strictObject({ from: key, to: key, axis: v.picklist(['x', 'z', 'zero']) })));
11
13
  /** Mixed native roster policy, pose, reserve and physical volley composition. */
12
14
  export const MixedPopulationSchema: v.StrictObjectSchema<{ readonly step: v.GenericSchema<MixedPopulationRowsInput['step'], MixedPopulationRows['step']>; readonly limit: v.GenericSchema<MixedPopulationRowsInput['limit'], MixedPopulationRows['limit']>; readonly attackTurnCap: v.GenericSchema<MixedPopulationRowsInput['attackTurnCap'], MixedPopulationRows['attackTurnCap']>; readonly hunted: v.GenericSchema<MixedPopulationRowsInput['hunted'], MixedPopulationRows['hunted']>; readonly floorKinds: v.GenericSchema<MixedPopulationRowsInput['floorKinds'], MixedPopulationRows['floorKinds']>; readonly practice: v.GenericSchema<MixedPopulationRowsInput['practice'], MixedPopulationRows['practice']>; readonly reserve: v.GenericSchema<MixedPopulationRowsInput['reserve'], MixedPopulationRows['reserve']>; readonly volley: v.GenericSchema<MixedPopulationRowsInput['volley'], MixedPopulationRows['volley']>; readonly poses: v.GenericSchema<MixedPopulationRowsInput['poses'], MixedPopulationRows['poses']>; readonly perch: v.GenericSchema<MixedPopulationRowsInput['perch'], MixedPopulationRows['perch']>; }, undefined> = v.strictObject({
13
15
  step: key, limit: v.pipe(finite, v.integer(), v.minValue(1), v.maxValue(256)),
14
16
  attackTurnCap: finite, hunted: v.array(key), floorKinds: v.array(key),
15
17
  practice: v.strictObject({ at: point, fade: finite, delay: finite, away: finite }),
16
- reserve: v.strictObject({ kind: key, variant: key, scale: v.tuple([finite, finite]), legacyMemory: v.array(v.strictObject({ from: key, to: key, axis: v.picklist(['x', 'z', 'zero']) })) }),
18
+ reserve: v.strictObject({ kind: key, variant: key, scale: v.tuple([finite, finite]),
19
+ legacyMemory }),
17
20
  volley: v.strictObject({ owner: key, strike: key, tags: v.array(v.custom<`${string}.${string}`>(value => typeof value === 'string' && /^[a-z][a-zA-Z0-9.-]*\.[a-zA-Z0-9.-]+$/u.test(value))) }),
18
21
  poses: v.array(v.strictObject({ kind: key, clips: v.array(NumericPoseSchema),
19
22
  lift: v.exactOptional(v.tuple([finite, finite, finite, finite])) })),
@@ -66,7 +69,7 @@ interface MixedPopulationRowsInputFields {
66
69
  number,
67
70
  number
68
71
  ];
69
- legacyMemory: ({
72
+ legacyMemory?: ({
70
73
  from: string;
71
74
  to: string;
72
75
  axis: 'x' | 'z' | 'zero';
@@ -154,7 +157,7 @@ interface MixedPopulationRowsFields {
154
157
  number,
155
158
  number
156
159
  ];
157
- legacyMemory: ({
160
+ legacyMemory?: ({
158
161
  from: string;
159
162
  to: string;
160
163
  axis: 'x' | 'z' | 'zero';
@@ -1,4 +1,5 @@
1
1
  import * as v from 'valibot';
2
+ import { IndexFormatVersionSchema } from './index-format-version.ts';
2
3
 
3
4
  interface Measured { readonly path: string; readonly hash: string; readonly bytes: number }
4
5
  export interface OutputDownloadIndex {
@@ -18,9 +19,11 @@ export function readOutputDownloadIndex(input: unknown): OutputDownloadIndex {
18
19
  const bytes = v.pipe(v.number(), v.safeInteger(), v.minValue(0));
19
20
  const hash = v.pipe(v.string(), v.regex(/^[a-f0-9]{64}$/u));
20
21
  const measured = { path, hash, bytes };
21
- const index = v.parse(v.object({ format: v.literal('wildshard.shardfile'), formatVersion: v.literal(2),
22
+ const listed = v.pipe(v.array(v.object(measured)), v.maxLength(128));
23
+ // SHARD-COMPAT CP14: either envelope; format 0.1.0.2 drops the always-empty schemas list (FORMAT-PRUNE FP4).
24
+ const parsed = v.parse(v.object({ format: v.literal('wildshard.shardfile'), formatVersion: IndexFormatVersionSchema,
22
25
  sections: v.pipe(v.array(v.object({ ...measured, name: v.string() })), v.maxLength(256)),
23
- schemas: v.pipe(v.array(v.object(measured)), v.maxLength(128)),
26
+ schemas: v.exactOptional(listed),
24
27
  // The compiler and runtime share tier/variant selection. Dropping these
25
28
  // existing index facts here reserves bodies this device will never read.
26
29
  files: v.pipe(v.array(v.object({ path, hash, compressed: bytes, name: v.exactOptional(v.string()),
@@ -28,6 +31,7 @@ export function readOutputDownloadIndex(input: unknown): OutputDownloadIndex {
28
31
  runtime: v.unknown(),
29
32
  packs: v.exactOptional(v.pipe(v.array(v.object({ ...measured, entries: v.pipe(v.array(v.object({ hash, offset: bytes, bytes })), v.maxLength(8192)) })), v.maxLength(64))),
30
33
  }), input);
34
+ const index = { ...parsed, schemas: parsed.schemas ?? [] };
31
35
  const paths = ['shard.json', 'validation.json', ...index.sections.map(row => row.path), ...index.schemas.map(row => row.path), ...index.files.map(row => row.path)];
32
36
  if (new Set(paths).size !== paths.length) throw new Error('Duplicate shard file download path');
33
37
  return index;
@@ -2,6 +2,7 @@ import type { Shardfile } from './shardSchema.ts';
2
2
  import type { PlatformSectionName } from './sections.ts';
3
3
  import type { PlatformDataSections } from './platformDataSections.ts';
4
4
  import type { OutputIndex } from './outputIndex.ts';
5
+ import { shardfileFormatOf } from './version.ts';
5
6
 
6
7
  export interface SectionMapping { readonly name: PlatformSectionName; readonly fields: readonly (keyof Shardfile)[]; readonly row?: keyof Shardfile['rows']; readonly spawns?: true; }
7
8
  /** Root-key envelopes preserve optional-field absence and every existing host's values. */
@@ -105,7 +106,7 @@ export function outputSectionPayloads(source: Shardfile): ReadonlyMap<string, un
105
106
  export function assembleOutputTransport(index: OutputIndex, sections: ReadonlyMap<string, unknown>, checks?: { readonly bounds: (name: string, value: unknown) => void; readonly platform: (name: keyof PlatformDataSections, value: unknown) => void; readonly fields: (name: string, value: object) => Record<string, unknown> }): Record<string, unknown> {
106
107
  // J91: the server class is the product index's alone, never a field of the Shardfile a client admits.
107
108
  const {server:_server,audioWaiver:_audioWaiver,...admission}=index.admission;
108
- const result: Record<string, unknown> = {version:index.version,identity:index.identity,requires:index.requires,...admission,files:index.files.filter(file => file.commons !== true).map(({path: _path,name: _name,tier: _tier,variantOf: _variant,commons: _commons,jsonSchema: _schema,kind,...rest}) => Object.assign(rest,{kind:kind === 'tile' || kind === 'bin' ? 'binary' : kind})),runtime:index.runtime === null ? null : {kind:index.runtime.kind,cost:index.runtime.cost,binds:index.runtime.binds}};
109
+ const result: Record<string, unknown> = {version:shardfileFormatOf(index),identity:index.identity,requires:index.requires,...admission,files:index.files.filter(file => file.commons !== true).map(({path: _path,name: _name,tier: _tier,variantOf: _variant,commons: _commons,jsonSchema: _schema,kind,...rest}) => Object.assign(rest,{kind:kind === 'tile' || kind === 'bin' ? 'binary' : kind})),runtime:index.runtime === null ? null : {kind:index.runtime.kind,cost:index.runtime.cost,binds:index.runtime.binds}};
109
110
  if (sections.size !== index.sections.length || index.sections.some(entry => !sections.has(entry.name))) throw new Error('Missing or surplus output section');
110
111
  const rows: Record<string, unknown> = {};
111
112
  for (const entry of index.sections) {
@@ -15,8 +15,9 @@ import { ClientPlanRuntimeSchema } from './runtime.ts';
15
15
  import { RuntimeSpawnsSchema } from './runtimeSpawns.ts';
16
16
  import { RowsSchema } from './rows.ts';
17
17
  import { ShardHashSchema, ShardNaturalSchema, IdentitySchema, RequiresSchema, FilesSchema, type ShardIdentityInput, type ShardRequiresInput, type ShardReferencesInput, type ShardIdentity, type ShardRequires, type ShardReferences } from './shardSections.ts';
18
- import { SHARDFILE_VERSIONS } from './version.ts';
19
- import type { ShardfileVersion } from './version.ts';
18
+ import { LEGACY_LAYOUT } from './version.ts';
19
+ import { IndexFormatVersionSchema, LegacyIndexVersionSchema } from './index-format-version.ts';
20
+ import type { IndexFormatVersion, LegacyIndexVersion } from './version.ts';
20
21
  import { isJsonData, isJsonDataWithFileSchemas } from './json.ts';
21
22
  import { clientOwnershipRules } from './clientOwnership.ts';
22
23
  import { PLATFORM_DATA_SECTIONS } from './platformDataSections.ts';
@@ -27,17 +28,24 @@ const path = v.pipe(v.string(), v.maxLength(240), v.regex(/^(?:[a-zA-Z0-9_-][a-z
27
28
  const sectionName = v.pipe(v.string(), v.regex(/^[a-z][a-zA-Z0-9-]*\/[a-zA-Z][a-zA-Z0-9_-]*$/u));
28
29
  const measuredFile = { path, hash: ShardHashSchema, bytes: ShardNaturalSchema };
29
30
  const section = v.strictObject({ ...measuredFile, name: sectionName, schema: v.pipe(v.string(), v.maxLength(240)) });
31
+ /** Always empty; format 0.1.0.2 drops it (FORMAT-PRUNE FP4). */
32
+ const emptySchemas = v.exactOptional(v.pipe(v.array(v.strictObject(measuredFile)), v.maxLength(0)));
30
33
  const cookRow = v.exactOptional(v.strictObject({ ...measuredFile, path: v.literal('cook.json') }));
31
34
  const costs = v.omit(FilesSchema.pipe[0].item, ['kind']).entries;
32
35
  const fileSchema = v.strictObject({ ...costs, path, kind: v.picklist(['glb', 'ktx2', 'audio', 'json', 'wasm', 'tile', 'bin', 'image']), name: v.exactOptional(v.pipe(v.string(), v.maxLength(240))), tier: v.exactOptional(v.picklist(['phone', 'desktop'])), variantOf: v.exactOptional(v.pipe(v.string(), v.minLength(1), v.maxLength(240))), commons: v.exactOptional(v.literal(true)), jsonSchema: v.exactOptional(v.record(v.string(), v.unknown())) });
33
36
  /** `trust` is retired (OF1): new indexes omit it, old products still carry their value and nothing reads it. */
34
- const runtime = v.strictObject({ ...v.omit(ClientPlanRuntimeSchema.pipe[0], ['spawns']).entries, trust: v.exactOptional(v.unknown()), files: v.pipe(v.array(v.strictObject({ ...measuredFile, lines: ShardNaturalSchema })), v.maxLength(0)), lines: v.literal(0) });
37
+ /** `files` and `lines` are always empty: the 0.1.0.2 envelope drops them (FORMAT-PRUNE FP4), the legacy one still carries them. */
38
+ const runtimeFiles = v.exactOptional(v.pipe(v.array(v.strictObject({ ...measuredFile, lines: ShardNaturalSchema })), v.maxLength(0)));
39
+ const runtime = v.strictObject({ ...v.omit(ClientPlanRuntimeSchema.pipe[0], ['spawns']).entries, trust: v.exactOptional(v.unknown()), files: runtimeFiles, lines: v.exactOptional(v.literal(0)) });
35
40
  /** Format 2 inventories every emitted byte except its index and validation receipt. */
36
41
  export const OutputIndexSchema: v.GenericSchema<OutputIndexRowsInput, OutputIndexRows> & { readonly entries: { readonly [Key in keyof OutputIndexRows]-?: v.GenericSchema<OutputIndexRowsInput[Key], OutputIndexRows[Key]> } } = v.strictObject({
37
- format: v.literal('wildshard.shardfile'), formatVersion: v.literal(2), sdk: v.picklist(['0.2', '0.3']), version: v.picklist(SHARDFILE_VERSIONS),
42
+ format: v.literal('wildshard.shardfile'),
43
+ /** SHARD-COMPAT CP14 (FP25): the format version itself from 0.1.0.2; the legacy envelope carries the frozen layout marker
44
+ * `2` here and its version in `version`. `checkIndexEnvelope` holds each envelope to its own fields. */
45
+ formatVersion: IndexFormatVersionSchema, sdk: v.picklist(['0.2', '0.3']), version: LegacyIndexVersionSchema,
38
46
  identity: IdentitySchema, build: v.strictObject({ sourceHash: ShardHashSchema, validator: v.pipe(v.string(), v.minLength(1), v.maxLength(160)) }), requires: RequiresSchema,
39
47
  admission: v.strictObject({ budgets: ShardfileFieldSchemas.budgets, serverBudget: ShardfileFieldSchemas.serverBudget, authorCaps: ShardfileFieldSchemas.authorCaps, critical: ShardfileFieldSchemas.critical, library: ShardfileFieldSchemas.library, late: v.exactOptional(AdmissionLateSchema), server: v.exactOptional(AdmissionServerSchema), audioWaiver: v.exactOptional(AudioWaiverSchema) }),
40
- sections: v.pipe(v.array(section), v.maxLength(256)), schemas: v.pipe(v.array(v.strictObject(measuredFile)), v.maxLength(0)),
48
+ sections: v.pipe(v.array(section), v.maxLength(256)), schemas: emptySchemas,
41
49
  files: v.pipe(v.array(fileSchema), v.maxLength(8192)), runtime: v.nullable(runtime),
42
50
  ktx2Costs: v.exactOptional(v.pipe(v.record(ShardHashSchema,v.strictObject({rgba:ShardNaturalSchema,astc:ShardNaturalSchema,bc7:ShardNaturalSchema})),v.check(rows=>Object.keys(rows).length<=8192,'bounded texture cost table'))),
43
51
  /** iPhone downloads I5: content-hashed concatenations of the small sections, schemas and files, so a reader can fetch
@@ -63,8 +71,38 @@ export function parseOutputDescriptorIndex(input: unknown): OutputIndex | null {
63
71
  if (!isJsonDataWithFileSchemas(input)) throw new Error('Shardfile descriptor requires bounded plain JSON');
64
72
  return isOutputIndex(input) ? parseOutputIndexRows(input) : null;
65
73
  }
74
+ /** The fields only the legacy envelope (`formatVersion: 2`, formats 0.1 to 0.1.0.1) carries; 0.1.0.2 drops each
75
+ * (SHARD-COMPAT CP14; FORMAT-PRUNE FP3 `runtime.trust`, FP4 the always-empty four). */
76
+ // oxlint-disable-next-line typescript/prefer-readonly-parameter-types -- valibot output, only read
77
+ function legacyIndexFields(index: OutputIndex): readonly string[] {
78
+ return [
79
+ index.version === undefined ? undefined : 'version',
80
+ index.schemas === undefined ? undefined : 'schemas',
81
+ index.requires.capabilities === undefined ? undefined : 'requires.capabilities',
82
+ index.runtime?.files === undefined ? undefined : 'runtime.files',
83
+ index.runtime?.lines === undefined ? undefined : 'runtime.lines',
84
+ index.runtime === null || !Object.hasOwn(index.runtime, 'trust') ? undefined : 'runtime.trust',
85
+ ].filter((field): field is string => field !== undefined);
86
+ }
87
+ /** Hold each envelope to its own fields: the legacy one keeps every field its readers require, 0.1.0.2 carries none. */
88
+ // oxlint-disable-next-line typescript/prefer-readonly-parameter-types -- valibot output, only read
89
+ function checkIndexEnvelope(index: OutputIndex): void {
90
+ const carried = legacyIndexFields(index);
91
+ if (index.formatVersion !== LEGACY_LAYOUT) {
92
+ if (carried.length > 0) {
93
+ throw new Error(`Format ${index.formatVersion} drops ${carried.join(', ')} (shard.json)`);
94
+ }
95
+ return;
96
+ }
97
+ const needed = ['version', 'schemas', 'requires.capabilities', ...index.runtime === null ? [] : ['runtime.files', 'runtime.lines']];
98
+ const missing = needed.filter((field: string): boolean => !carried.includes(field));
99
+ if (missing.length > 0) {
100
+ throw new Error(`Legacy shard.json (formatVersion 2) needs ${missing.join(', ')}`);
101
+ }
102
+ }
66
103
  function parseOutputIndexRows(input: unknown): OutputIndex {
67
104
  const index = v.parse(OutputIndexSchema, input);
105
+ checkIndexEnvelope(index);
68
106
  if (index.sdk === '0.3' && index.cook === undefined) { throw new Error(`Missing cook preparation: run wildshard prepare <folder> --base <exact-preview-url> (${index.identity.slug})`); }
69
107
  if (index.sdk === '0.3' && index.cook !== undefined && index.cook.bytes > MAX_COOK_BYTES) { throw new Error('Cook preparation exceeds byte cap'); }
70
108
  const paths = new Set(['shard.json', 'validation.json']), names = new Set<string>();
@@ -76,7 +114,7 @@ function parseOutputIndexRows(input: unknown): OutputIndex {
76
114
  }
77
115
  }
78
116
  if (index.sections.reduce((total, entry) => total + entry.bytes, 0) > limits.sourceBytes) throw new Error('Output sections exceed the source byte cap');
79
- for (const entry of [...index.sections, ...index.schemas, ...index.files, ...index.runtime?.files ?? []]) {
117
+ for (const entry of [...index.sections, ...index.schemas ?? [], ...index.files, ...index.runtime?.files ?? []]) {
80
118
  if (entry.path.split('/').some(part => part === '.' || part === '..') || paths.has(entry.path)) throw new Error('Duplicate or escaping output path');
81
119
  paths.add(entry.path);
82
120
  }
@@ -108,7 +146,7 @@ function parseOutputIndexRows(input: unknown): OutputIndex {
108
146
  }
109
147
  if (!serverFilesExclusive(index.admission.server ?? [], index.files)) throw new Error('A server file is never also a client file');
110
148
  // I5: a pack lives beside the blobs, is listed once, and holds only listed members at their exact sizes, in order
111
- const members = new Map([...index.sections, ...index.schemas].map(entry => [entry.hash, entry.bytes] as const));
149
+ const members = new Map([...index.sections, ...index.schemas ?? []].map(entry => [entry.hash, entry.bytes] as const));
112
150
  for (const entry of index.files) members.set(entry.hash, entry.compressed);
113
151
  for (const pack of index.packs ?? []) {
114
152
  if (pack.path !== `blobs/pack/${pack.hash}.pack` || paths.has(pack.path)) throw new Error('Duplicate or mismatched pack path');
@@ -160,9 +198,9 @@ export function assembleOutputShardfile(input: unknown, sections: ReadonlyMap<st
160
198
  /** Exact admitted data, independent of validator implementation metadata. */
161
199
  interface OutputIndexRowsInputFields {
162
200
  format: "wildshard.shardfile";
163
- formatVersion: 2;
201
+ formatVersion: typeof LEGACY_LAYOUT | IndexFormatVersion;
164
202
  sdk: "0.2" | "0.3";
165
- version: ShardfileVersion;
203
+ version?: LegacyIndexVersion;
166
204
  identity: ShardIdentityInput;
167
205
  build: {
168
206
  sourceHash: string;
@@ -187,7 +225,7 @@ interface OutputIndexRowsInputFields {
187
225
  hash: string;
188
226
  bytes: number;
189
227
  }[];
190
- schemas: {
228
+ schemas?: {
191
229
  path: string;
192
230
  hash: string;
193
231
  bytes: number;
@@ -226,13 +264,13 @@ interface OutputIndexRowsInputFields {
226
264
  } | undefined;
227
265
  runtime: {
228
266
  trust?: unknown;
229
- files: {
267
+ files?: {
230
268
  lines: number;
231
269
  path: string;
232
270
  hash: string;
233
271
  bytes: number;
234
272
  }[];
235
- lines: 0;
273
+ lines?: 0;
236
274
  kind: "client-plan";
237
275
  cost: {
238
276
  imagesFirst?: {
@@ -258,9 +296,9 @@ interface OutputIndexRowsInputFields {
258
296
  export type OutputIndexRowsInput = { [Key in keyof OutputIndexRowsInputFields]: OutputIndexRowsInputFields[Key] };
259
297
  interface OutputIndexRowsFields {
260
298
  format: "wildshard.shardfile";
261
- formatVersion: 2;
299
+ formatVersion: typeof LEGACY_LAYOUT | IndexFormatVersion;
262
300
  sdk: "0.2" | "0.3";
263
- version: ShardfileVersion;
301
+ version?: LegacyIndexVersion;
264
302
  identity: ShardIdentity;
265
303
  build: {
266
304
  sourceHash: string;
@@ -285,7 +323,7 @@ interface OutputIndexRowsFields {
285
323
  hash: string;
286
324
  bytes: number;
287
325
  }[];
288
- schemas: {
326
+ schemas?: {
289
327
  path: string;
290
328
  hash: string;
291
329
  bytes: number;
@@ -324,13 +362,13 @@ interface OutputIndexRowsFields {
324
362
  } | undefined;
325
363
  runtime: {
326
364
  trust?: unknown;
327
- files: {
365
+ files?: {
328
366
  lines: number;
329
367
  path: string;
330
368
  hash: string;
331
369
  bytes: number;
332
370
  }[];
333
- lines: 0;
371
+ lines?: 0;
334
372
  kind: "client-plan";
335
373
  cost: {
336
374
  imagesFirst?: {
@@ -7,8 +7,8 @@ import * as v from 'valibot';
7
7
  import { isJsonData } from './json.ts';
8
8
  import { sketchReference } from './sketch.ts';
9
9
  import { JournalRowSchema, journalRowRules } from './compendiumRows.ts';
10
- import { CreatureAttackableSchema, CreatureMountSchema, creatureMountRules, CreatureTypeSchema, CreatureBodySchema, CreatureTemperamentSchema, CreatureSensesSchema, CreatureAbilitySchema, CreaturePresentationSchema } from './creature-layers.ts';
11
- import type { CreatureAbilityInput, CreatureLayers } from './creature-layers.ts';
10
+ import { ActorProjectionV2Schema, CreatureAttackableSchema, CreatureMountSchema, creatureMountRules, CreatureTypeSchema, CreatureBodySchema, CreatureTemperamentSchema, CreatureSensesSchema, CreatureAbilitySchema, CreaturePresentationSchema } from './creature-layers.ts';
11
+ import type { ActorProjectionV2Rows, CreatureAbilityInput, CreatureLayers } from './creature-layers.ts';
12
12
  import { creatureSizeRules } from './creature-sizes.ts';
13
13
  import { SKIN_CLIPS_RECIPE, SkinClipMapSchema } from './skins.ts';
14
14
  import type { SkinClipMap } from './skins.ts';
@@ -74,7 +74,9 @@ const species = v.strictObject({ id, kind: id, label: text, capExempt: v.exactOp
74
74
  type: v.exactOptional(CreatureTypeSchema), body: v.exactOptional(CreatureBodySchema),
75
75
  temperament: v.exactOptional(CreatureTemperamentSchema), senses: v.exactOptional(CreatureSensesSchema),
76
76
  abilities: v.exactOptional(abilities), presentation: v.exactOptional(CreaturePresentationSchema), mount: v.exactOptional(CreatureMountSchema),
77
- attackable: v.exactOptional(CreatureAttackableSchema) });
77
+ attackable: v.exactOptional(CreatureAttackableSchema),
78
+ // ONE-FORMAT OF30: a declared species may carry its view projection (Nalati's balbal guest), so no species programme holds it
79
+ projection: v.exactOptional(ActorProjectionV2Schema) });
78
80
  const parameter = v.union([finite, v.boolean(), text, v.pipe(v.array(finite), v.maxLength(16))]);
79
81
  const animationParameters = v.record(id, parameter);
80
82
  const lookAnimation = v.strictObject({
@@ -153,7 +155,7 @@ type ShardRows = { strikes: (StrikeRows)[]; weather: (({ id: string; states: ({
153
155
  type SpeciesRowInput = Omit<SpeciesRow, "abilities"> & { abilities?: CreatureAbilityInput[] };
154
156
 
155
157
  /** A species keeps its old fields, with optional explicit creature layers. */
156
- interface SpeciesRow extends CreatureLayers { capExempt?: boolean; harvest?: HarvestDrop[]; id: string; kind: string; label: string; aggressive: boolean; lockable: boolean; dims: { bodyY: number; bodyHalfLen: number; bodyRadius: number; headRadius: number; legLen: number; feet: ([number, number])[]; halfWidth: number; capsuleAxis?: 'y' | 'z'; }; flight?: { altitude: number; above?: 'ground' | 'world'; climbRate: number; diveRate: number; lockRange?: number; bank?: number; }; variants: ({ id: string; label: string; rarity: 'common' | 'uncommon' | 'rare' | 'legendary'; weight: number; scale: [number, number]; hp: number; mods: { speed: number; chargeDist: number; damageTaken: number; chargeDamage: number; relentless: boolean; }; })[]; }
158
+ interface SpeciesRow extends CreatureLayers { capExempt?: boolean; projection?: ActorProjectionV2Rows; harvest?: HarvestDrop[]; id: string; kind: string; label: string; aggressive: boolean; lockable: boolean; dims: { bodyY: number; bodyHalfLen: number; bodyRadius: number; headRadius: number; legLen: number; feet: ([number, number])[]; halfWidth: number; capsuleAxis?: 'y' | 'z'; }; flight?: { altitude: number; above?: 'ground' | 'world'; climbRate: number; diveRate: number; lockRange?: number; bank?: number; }; variants: ({ id: string; label: string; rarity: 'common' | 'uncommon' | 'rare' | 'legendary'; weight: number; scale: [number, number]; hp: number; mods: { speed: number; chargeDist: number; damageTaken: number; chargeDamage: number; relentless: boolean; }; })[]; }
157
159
 
158
160
  export { rowRules, RowsSchema, parseRows };
159
161
  export type { StrikeRowsInput, StrikeRows, ShardRowsInput, ShardRows, SpeciesRow };
@@ -40,7 +40,7 @@ const tileCount = (2 * CHUNK_HALF / WIRE_TILE_SIZES.l0) ** 2 + (2 * CHUNK_HALF /
40
40
  /** Stable authored shard identity and deterministic seed. */
41
41
  export const IdentitySchema: v.GenericSchema<ShardIdentityInput, ShardIdentity> = v.strictObject({ slug: name, name: v.pipe(v.string(), v.minLength(1), v.maxLength(limits.idCharacters)), author: v.pipe(v.string(), v.minLength(1), v.maxLength(limits.idCharacters)), revision: positive, seed: ShardNaturalSchema });
42
42
  /** Wire revision, capabilities and exact commons declarations. */
43
- export const RequiresSchema: v.GenericSchema<ShardRequiresInput, ShardRequires> = v.strictObject({ sdk: v.picklist(SHARDFILE_VERSIONS), capabilities: ShardNamesSchema, commons: v.pipe(v.array(ShardHashSchema), v.maxLength(limits.commons)), commonsWire: v.optional(v.record(ShardHashSchema, ShardNaturalSchema), {}), commonsCosts: v.optional(CommonsCostsSchema, {}) });
43
+ export const RequiresSchema: v.GenericSchema<ShardRequiresInput, ShardRequires> = v.strictObject({ sdk: v.picklist(SHARDFILE_VERSIONS), capabilities: v.exactOptional(ShardNamesSchema), commons: v.pipe(v.array(ShardHashSchema), v.maxLength(limits.commons)), commonsWire: v.optional(v.record(ShardHashSchema, ShardNaturalSchema), {}), commonsCosts: v.optional(CommonsCostsSchema, {}) });
44
44
  /** Authored compressed and resident ceilings. */
45
45
  export const BudgetsSchema: v.GenericSchema<ShardBudgetsInput, ShardBudgets> = v.strictObject({
46
46
  /** Reviewed whole-client floor retained when an opaque runtime becomes declared data. */
@@ -224,7 +224,8 @@ interface ShardIdentityFields {
224
224
  export type ShardIdentity = { [Key in keyof ShardIdentityFields]: ShardIdentityFields[Key] };
225
225
  interface ShardRequiresInputFields {
226
226
  sdk: ShardfileVersion;
227
- capabilities: ShardNamesInput;
227
+ /** Always empty, never read; format 0.1.0.2 drops it (FORMAT-PRUNE FP4). */
228
+ capabilities?: ShardNamesInput;
228
229
  commons: (ShardHashInput)[];
229
230
  commonsWire?: Record<string, ShardNaturalInput> | undefined;
230
231
  commonsCosts?: v.InferInput<typeof CommonsCostsSchema> | undefined;
@@ -232,7 +233,7 @@ interface ShardRequiresInputFields {
232
233
  export type ShardRequiresInput = { [Key in keyof ShardRequiresInputFields]: ShardRequiresInputFields[Key] };
233
234
  interface ShardRequiresFields {
234
235
  sdk: ShardfileVersion;
235
- capabilities: ShardNames;
236
+ capabilities?: ShardNames;
236
237
  commons: (ShardHash)[];
237
238
  commonsWire: Record<string, ShardNatural>;
238
239
  commonsCosts: v.InferOutput<typeof CommonsCostsSchema>;
@@ -15,7 +15,8 @@ interface Listed {
15
15
  }
16
16
  interface Members {
17
17
  readonly sections: readonly Listed[]
18
- readonly schemas: readonly Listed[]
18
+ /** Absent from format 0.1.0.2 on (FORMAT-PRUNE FP4). */
19
+ readonly schemas?: readonly Listed[] | undefined
19
20
  readonly files: readonly Listed[]
20
21
  }
21
22
  type Assets = ReadonlyMap<string, Uint8Array>
@@ -123,7 +124,7 @@ function packFromMembers(
123
124
  index: Members,
124
125
  read: ReadFile,
125
126
  ): Uint8Array {
126
- const rows = [...index.sections, ...index.schemas, ...index.files]
127
+ const rows = [...index.sections, ...(index.schemas ?? []), ...index.files]
127
128
  const paths = new Map(
128
129
  rows.map((row: Listed): [string, string] => [row.hash, row.path]),
129
130
  )
@@ -38,7 +38,7 @@ function memberPaths(
38
38
  index: OutputIndex,
39
39
  ): ReadonlyMap<string, string> {
40
40
  return new Map(
41
- [...index.sections, ...index.schemas, ...index.files].map(
41
+ [...index.sections, ...(index.schemas ?? []), ...index.files].map(
42
42
  (row: Readonly<{ hash: string; path: string }>): [string, string] => [
43
43
  row.hash,
44
44
  row.path,
@@ -3,7 +3,7 @@ import { assertMigrationCompatibility } from './migrations.ts';
3
3
  import { StateSchema } from './state.ts';
4
4
  import type { Shardfile } from './shardSchema.ts';
5
5
  import { isJsonDataWithFileSchemas } from './json.ts';
6
- import { SHARDFILE_VERSIONS } from './version.ts';
6
+ import { IndexFormatVersionSchema, LegacyIndexVersionSchema } from './index-format-version.ts';
7
7
  import { SHARDFILE_ADMISSION_LIMITS as limits } from './admissionLimits.ts';
8
8
 
9
9
  const identity = v.object({ slug: v.pipe(v.string(), v.regex(/^[a-z][a-z0-9.-]*$/u)),
@@ -16,11 +16,13 @@ export function parseStateLineage(input: unknown): StateLineage { return v.parse
16
16
  const path = v.pipe(v.string(), v.maxLength(240), v.regex(/^(?:[a-zA-Z0-9_-][a-zA-Z0-9_.-]*\/)*[a-zA-Z0-9_-][a-zA-Z0-9_.-]*$/u));
17
17
  const measured = { path, hash: v.pipe(v.string(), v.regex(/^[a-f0-9]{64}$/u)),
18
18
  bytes: v.pipe(v.number(), v.integer(), v.minValue(0), v.maxValue(Number.MAX_SAFE_INTEGER)) };
19
- const inventory = v.object({ format: v.literal('wildshard.shardfile'), formatVersion: v.literal(2), sdk: v.picklist(['0.2', '0.3']),
20
- version: v.picklist(SHARDFILE_VERSIONS), identity,
19
+ const lineageSchemas = v.exactOptional(v.pipe(v.array(v.strictObject(measured)), v.maxLength(128)));
20
+ // SHARD-COMPAT CP14: either envelope; 0.1.0.2 names its format in formatVersion and drops version and schemas.
21
+ const inventory = v.object({ format: v.literal('wildshard.shardfile'), formatVersion: IndexFormatVersionSchema, sdk: v.picklist(['0.2', '0.3']),
22
+ version: LegacyIndexVersionSchema, identity,
21
23
  sections: v.pipe(v.array(v.strictObject({ ...measured, name: v.pipe(v.string(), v.regex(/^[a-z][a-zA-Z0-9-]*\/[a-zA-Z][a-zA-Z0-9_-]*$/u)),
22
24
  schema: v.pipe(v.string(), v.maxLength(240)) })), v.maxLength(256)),
23
- schemas: v.pipe(v.array(v.strictObject(measured)), v.maxLength(128)) });
25
+ schemas: lineageSchemas });
24
26
  export interface OutputLineageIndex {
25
27
  readonly identity: { readonly slug: string; readonly revision: number };
26
28
  readonly sections: readonly { readonly path: string; readonly hash: string; readonly bytes: number; readonly name: string; readonly schema: string }[];
@@ -30,7 +32,8 @@ export interface OutputLineageIndex {
30
32
  * Obsolete host/asset declarations are never parsed or admitted by this reader. */
31
33
  export function parseOutputLineageIndex(input: unknown): OutputLineageIndex {
32
34
  if (!isJsonDataWithFileSchemas(input)) throw new Error('Shardfile descriptor requires bounded plain JSON');
33
- const index = v.parse(inventory, input), paths = new Set(['shard.json', 'validation.json']), names = new Set<string>();
35
+ const parsed = v.parse(inventory, input), paths = new Set(['shard.json', 'validation.json']), names = new Set<string>();
36
+ const index = { ...parsed, schemas: parsed.schemas ?? [] };
34
37
  if (index.sections.reduce((total, row) => total + row.bytes, 0) > limits.sourceBytes) throw new Error('Output sections exceed the source byte cap');
35
38
  for (const row of [...index.sections, ...index.schemas]) {
36
39
  if (row.path.split('/').some(part => part === '.' || part === '..') || paths.has(row.path)) throw new Error('Duplicate or escaping output path');
@@ -3,14 +3,30 @@
3
3
  const ZERO = 0
4
4
  const ONE = 1
5
5
 
6
- const SHARDFILE_VERSION = '0.1.0.1'
7
- /** Legacy 0.1 is the byte-preserving spelling of 0.1.0.0. */
8
- const SHARDFILE_VERSIONS: readonly [
6
+ const SHARDFILE_VERSION = '0.1.0.2'
7
+ /** Formats whose `shard.json` names its version in `version`, beside the frozen layout marker `formatVersion: 2`.
8
+ * Legacy 0.1 is the byte-preserving spelling of 0.1.0.0. */
9
+ const LEGACY_INDEX_VERSIONS: readonly ['0.1', '0.1.0.0', '0.1.0.1'] = [
9
10
  '0.1',
10
11
  '0.1.0.0',
11
- typeof SHARDFILE_VERSION,
12
- ] = ['0.1', '0.1.0.0', SHARDFILE_VERSION] as const
12
+ '0.1.0.1',
13
+ ] as const
14
+ /** Formats whose `shard.json` names its version in `formatVersion` (SHARD-COMPAT CP14, FORMAT-PRUNE FP25): the
15
+ * layout marker and `version` are gone, so a reader tells the two envelopes apart by the field's type. */
16
+ const INDEX_FORMAT_VERSIONS: readonly [typeof SHARDFILE_VERSION] = [
17
+ SHARDFILE_VERSION,
18
+ ] as const
19
+ const SHARDFILE_VERSIONS: readonly [
20
+ ...typeof LEGACY_INDEX_VERSIONS,
21
+ ...typeof INDEX_FORMAT_VERSIONS,
22
+ ] = [...LEGACY_INDEX_VERSIONS, ...INDEX_FORMAT_VERSIONS] as const
13
23
  type ShardfileVersion = (typeof SHARDFILE_VERSIONS)[number]
24
+ type LegacyIndexVersion = (typeof LEGACY_INDEX_VERSIONS)[number]
25
+ type IndexFormatVersion = (typeof INDEX_FORMAT_VERSIONS)[number]
26
+ /** The frozen layout marker the legacy envelope carries in `formatVersion`. */
27
+ const LEGACY_LAYOUT = 2
28
+ /** The first format that writes its version in `formatVersion`. */
29
+ const SHARDFILE_VERSION_INDEX_RENAME = '0.1.0.2'
14
30
  type ShardfileVersionParts = readonly [number, number, number, number]
15
31
 
16
32
  /** Read canonical bounded decimal components; the legacy two-part spelling has zero counters. */
@@ -67,9 +83,77 @@ function compatibleShardfileVersion(
67
83
  }
68
84
  }
69
85
 
86
+ /** The format version a `shard.json` declares: `formatVersion` when it is a version string (0.1.0.2 on), else the
87
+ * legacy `version` beside the layout marker `formatVersion: 2`. Throws when neither names a format. */
88
+ function shardfileFormatOf(index: unknown): ShardfileVersion {
89
+ const declared: unknown =
90
+ typeof index === 'object' && index !== null
91
+ ? Reflect.get(index, 'formatVersion')
92
+ : undefined
93
+ const legacy: unknown =
94
+ typeof index === 'object' && index !== null
95
+ ? Reflect.get(index, 'version')
96
+ : undefined
97
+ const found: unknown = declared === LEGACY_LAYOUT ? legacy : declared
98
+ const known = SHARDFILE_VERSIONS.find(
99
+ (version: string): boolean => version === found,
100
+ )
101
+ if (known === undefined) {
102
+ throw new Error('Shardfile index names no known format version')
103
+ }
104
+ return known
105
+ }
106
+
107
+ /** Whether a format version writes the 0.1.0.2 envelope (`formatVersion` as the version, no `version`). */
108
+ function writesIndexFormatVersion(version: string): boolean {
109
+ return (
110
+ compareShardfileVersions(version, SHARDFILE_VERSION_INDEX_RENAME) >= ZERO
111
+ )
112
+ }
113
+
114
+ /** A copy of a JSON object without `keys`; anything else as it is. */
115
+ function withoutKeys(value: unknown, keys: readonly string[]): unknown {
116
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) {
117
+ return value
118
+ }
119
+ return Object.fromEntries(
120
+ Object.entries(value).filter(
121
+ ([key]: readonly [string, unknown]): boolean => !keys.includes(key),
122
+ ),
123
+ )
124
+ }
125
+
126
+ /** SHARD-COMPAT CP14: writers build the legacy `shard.json` rows (`formatVersion: 2`, `version`, the always-empty lists)
127
+ * and pass them here. At a `version` of 0.1.0.2 or later this returns the envelope that version writes: `formatVersion`
128
+ * is the version, and `version`, `schemas`, `runtime.files`, `runtime.lines`, `runtime.trust` and
129
+ * `requires.capabilities` go. An older `version` comes back unchanged. */
130
+ function outputIndexEnvelope(
131
+ rows: Readonly<Record<string, unknown>>,
132
+ ): Record<string, unknown> {
133
+ const { version } = rows
134
+ if (typeof version !== 'string' || !writesIndexFormatVersion(version)) {
135
+ return { ...rows }
136
+ }
137
+ const { version: _version, schemas: _schemas, ...rest } = rows
138
+ return {
139
+ ...rest,
140
+ formatVersion: version,
141
+ requires: withoutKeys(rest['requires'], ['capabilities']),
142
+ runtime: withoutKeys(rest['runtime'], ['files', 'lines', 'trust']),
143
+ }
144
+ }
145
+
70
146
  export {
147
+ outputIndexEnvelope,
71
148
  SHARDFILE_VERSION,
72
149
  SHARDFILE_VERSIONS,
150
+ LEGACY_INDEX_VERSIONS,
151
+ INDEX_FORMAT_VERSIONS,
152
+ LEGACY_LAYOUT,
153
+ type LegacyIndexVersion,
154
+ type IndexFormatVersion,
155
+ shardfileFormatOf,
156
+ writesIndexFormatVersion,
73
157
  SHARDFILE_FLOOR,
74
158
  type ShardfileVersion,
75
159
  type ShardfileVersionParts,