@wildshard/shard-format 0.67.0 → 0.68.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/package.json +7 -19
  2. package/src/cli/corpus-deprecations.ts +41 -0
  3. package/src/cli/corpus.ts +300 -0
  4. package/src/cli/main.ts +32 -0
  5. package/src/format/cook-preparation.ts +22 -6
  6. package/src/format/deprecations.ts +132 -0
  7. package/src/format/empty-shardfile.json +56 -0
  8. package/src/format/empty-shardfile.ts +43 -0
  9. package/src/format/format-migrate-inventory.ts +142 -0
  10. package/src/format/format-migrate-rebuild.ts +269 -0
  11. package/src/format/format-migrate.ts +290 -0
  12. package/src/format/format-migration-journal.ts +129 -0
  13. package/src/format/format-migration-ops.ts +230 -0
  14. package/src/format/format-migration-prune.ts +106 -0
  15. package/src/format/format-migrations.ts +124 -0
  16. package/src/format/issue-codes.ts +3 -1
  17. package/src/format/journal-glyphs.json +12 -0
  18. package/src/format/memory-armed.json +1 -39
  19. package/src/format/memory-armed.ts +41 -8
  20. package/src/format/memory-epoch.ts +2 -2
  21. package/src/format/memory-line.ts +4 -3
  22. package/src/format/memoryAdmission.ts +1 -1
  23. package/src/format/policy-verdict.ts +95 -0
  24. package/src/format/runtime-tier.ts +3 -3
  25. package/src/format/shardSections.ts +11 -1
  26. package/src/format/shardfile-assets.ts +12 -8
  27. package/src/format/shardfile-stream-admit.ts +41 -16
  28. package/src/format/shardfile-stream-rows.ts +3 -1
  29. package/src/format/shardfile-stream.ts +12 -9
  30. package/src/format/shardfileValidation.ts +30 -18
  31. package/src/format/stateLineage.ts +1 -1
  32. package/src/format/version.ts +11 -13
  33. package/src/format/baked-terrain.golden.json +0 -2760
  34. package/src/format/colliders.golden.json +0 -1619
  35. package/src/format/forest-placement.golden.json +0 -4588
  36. package/src/format/geometry-layout.golden.json +0 -180
  37. package/src/format/interact-table.golden.json +0 -340
  38. package/src/format/item-catalogue.golden.json +0 -2310
  39. package/src/format/memory-ratchet.ts +0 -107
  40. package/src/format/small-laws.golden.json +0 -57
  41. package/src/format/terrain-field.golden.json +0 -3998
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wildshard/shard-format",
3
- "version": "0.67.0",
3
+ "version": "0.68.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": {
@@ -21,15 +21,9 @@
21
21
  "!src/format/*.golden-specs.ts",
22
22
  "src/format/memoryGates.json",
23
23
  "src/format/memory-armed.json",
24
+ "src/format/empty-shardfile.json",
25
+ "src/format/journal-glyphs.json",
24
26
  "src/format/seeded-rng.golden.json",
25
- "src/format/terrain-field.golden.json",
26
- "src/format/baked-terrain.golden.json",
27
- "src/format/forest-placement.golden.json",
28
- "src/format/geometry-layout.golden.json",
29
- "src/format/colliders.golden.json",
30
- "src/format/small-laws.golden.json",
31
- "src/format/interact-table.golden.json",
32
- "src/format/item-catalogue.golden.json",
33
27
  "src/tools/runtime-hosts.json",
34
28
  "packages/wire/src/net-command.ts",
35
29
  "src/cli/*.ts",
@@ -124,7 +118,6 @@
124
118
  "./director": "./src/format/director.ts",
125
119
  "./detail-layer": "./src/format/detail-layer.ts",
126
120
  "./pbr-emissive": "./src/format/pbr-emissive.ts",
127
- "./pbr-fur": "./src/format/pbr-fur.ts",
128
121
  "./fur-strands": "./src/format/fur-strands.ts",
129
122
  "./scene-render": "./src/format/scene-render.ts",
130
123
  "./look-level": "./src/format/look-level.ts",
@@ -349,10 +342,12 @@
349
342
  "./scripts": "./src/format/scripts.ts",
350
343
  "./sections": "./src/format/sections.ts",
351
344
  "./shardSchema": "./src/format/shardSchema.ts",
345
+ "./emptyShardfile": "./src/format/empty-shardfile.ts",
346
+ "./migrate": "./src/format/format-migrate.ts",
347
+ "./migrations": "./src/format/format-migrations.ts",
352
348
  "./shardSections": "./src/format/shardSections.ts",
353
349
  "./sketch": "./src/format/sketch.ts",
354
350
  "./skinAssets": "./src/format/skinAssets.ts",
355
- "./skinTextures": "./src/format/skin-textures.ts",
356
351
  "./skinData": "./src/format/skinData.ts",
357
352
  "./skinLayers": "./src/format/skinLayers.ts",
358
353
  "./skins": "./src/format/skins.ts",
@@ -435,24 +430,16 @@
435
430
  "./seeded-rng.golden.json": "./src/format/seeded-rng.golden.json",
436
431
  "./noise": "./src/format/noise.ts",
437
432
  "./terrainField": "./src/format/terrain-field.ts",
438
- "./terrain-field.golden.json": "./src/format/terrain-field.golden.json",
439
433
  "./forestPlacement": "./src/format/forest-placement.ts",
440
434
  "./grassField": "./src/format/grass-field.ts",
441
- "./forest-placement.golden.json": "./src/format/forest-placement.golden.json",
442
435
  "./nativeGeometryChannels": "./src/format/native-geometry-channels.ts",
443
436
  "./wholePartition": "./src/format/whole-partition.ts",
444
- "./geometry-layout.golden.json": "./src/format/geometry-layout.golden.json",
445
437
  "./colliders": "./src/format/colliders.ts",
446
- "./colliders.golden.json": "./src/format/colliders.golden.json",
447
438
  "./headlessSections": "./src/format/headless-sections.ts",
448
439
  "./roadLight": "./src/format/road-light.ts",
449
440
  "./moverPose": "./src/format/mover-pose.ts",
450
- "./small-laws.golden.json": "./src/format/small-laws.golden.json",
451
441
  "./interactTable": "./src/format/interact-table.ts",
452
- "./interact-table.golden.json": "./src/format/interact-table.golden.json",
453
442
  "./itemCatalogue": "./src/format/item-catalogue.ts",
454
- "./item-catalogue.golden.json": "./src/format/item-catalogue.golden.json",
455
- "./baked-terrain.golden.json": "./src/format/baked-terrain.golden.json",
456
443
  "./rigLooks": "./src/format/rig-looks.ts"
457
444
  },
458
445
  "engines": {
@@ -469,6 +456,7 @@
469
456
  "format:check": "npr oxfmt -c kit/.oxfmtrc.json --check kit src '!src/format/**' '!src/test/fixtures/**'",
470
457
  "test": "node --test 'src/!(format|ci)/**/*.test.ts'",
471
458
  "test:ci": "node --test 'src/ci/**/*.test.ts'",
459
+ "test:chain": "node --test 'src/tools/*.chain.ts'",
472
460
  "test:format": "vitest run src/format --testTimeout=30000 --maxWorkers=2",
473
461
  "check:asks": "node kit/scripts/asks.mjs check",
474
462
  "check:agents": "node .githooks/agents-md.mjs lint",
@@ -0,0 +1,41 @@
1
+ /** The corpus's deprecation count (SHARD-COMPAT FE7): how many kept originals use each deprecated path, and which. */
2
+ import { createReadStream } from 'node:fs'
3
+
4
+ import { nodeStreamPorts } from '../format/shardfile-stream-node.ts'
5
+ import { validateShardfileStream } from '../format/shardfile-stream.ts'
6
+
7
+ import type { CorpusRow } from './corpus.ts'
8
+
9
+ /** Validate one stored original (brotli unless `plain`) as the API stored it; the deprecated paths it uses. Throws on a
10
+ * refusal. */
11
+ async function storedDeprecations(
12
+ file: string,
13
+ 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
20
+ }
21
+
22
+ /** FE7: one line per deprecated path a kept original uses, with how many and which. */
23
+ function deprecationLines(
24
+ rows: readonly Pick<CorpusRow, 'slug' | 'revision' | 'deprecations'>[],
25
+ ): string[] {
26
+ const users = new Map<string, string[]>()
27
+ for (const found of rows) {
28
+ for (const id of found.deprecations) {
29
+ users.set(id, [
30
+ ...(users.get(id) ?? []),
31
+ `${found.slug} r${String(found.revision)}`,
32
+ ])
33
+ }
34
+ }
35
+ return [...users].map(
36
+ ([id, names]: readonly [string, readonly string[]]): string =>
37
+ `deprecated ${id}: ${String(names.length)} kept originals (${names.join(', ')})`,
38
+ )
39
+ }
40
+
41
+ export { deprecationLines, storedDeprecations }
@@ -0,0 +1,300 @@
1
+ import { createWriteStream } from 'node:fs'
2
+ import { mkdir, open, readFile, rm, writeFile } from 'node:fs/promises'
3
+ import path from 'node:path'
4
+ import { Readable } from 'node:stream'
5
+ import { pipeline } from 'node:stream/promises'
6
+
7
+ import {
8
+ array,
9
+ number,
10
+ object,
11
+ optional,
12
+ parse,
13
+ pipe,
14
+ regex,
15
+ safeInteger,
16
+ string,
17
+ } from 'valibot'
18
+
19
+ import { deprecationLines, storedDeprecations } from './corpus-deprecations.ts'
20
+
21
+ import type { InferOutput } from 'valibot'
22
+
23
+ // `shard-format corpus` (meta SHARD-COMPAT FE3, J486 Q47 Q52): run this
24
+ // validator over every stored shard file the API keeps, as a stored
25
+ // original (`judged: 'stored'`: readability, not memory policy), and list
26
+ // every failure by shard, revision and reason. It reads the API's public
27
+ // list (`GET /api/shardfiles`: originals prune has not marked) and each
28
+ // original by hash (`GET /api/shardfiles/<hash>`), so it needs no token.
29
+ // The stream validator keeps only the index and JSON members and hashes
30
+ // blobs as they pass, so memory stays bounded; a verdict is cached by
31
+ // original hash and validator version, so a warm run fetches only new
32
+ // uploads. The migration chain (CP1) joins here when it exists.
33
+
34
+ const NamedSchema = object({ shard: string(), revision: number() })
35
+ const RecordSchema = object({
36
+ hash: pipe(string(), regex(/^[a-f0-9]{64}$/u)),
37
+ storedBytes: pipe(number(), safeInteger()),
38
+ revisions: array(NamedSchema),
39
+ })
40
+ const ListSchema = object({ shardfiles: array(RecordSchema) })
41
+ const IDS = array(string())
42
+ const CachedSchema = object({
43
+ validator: string(),
44
+ verdict: string(),
45
+ reason: optional(string()),
46
+ deprecations: optional(IDS),
47
+ })
48
+
49
+ type StoredRecord = Readonly<{
50
+ hash: string
51
+ storedBytes: number
52
+ revisions: readonly Readonly<InferOutput<typeof NamedSchema>>[]
53
+ }>
54
+
55
+ interface CorpusRow {
56
+ readonly slug: string
57
+ readonly revision: number
58
+ readonly hash: string
59
+ readonly storedBytes: number
60
+ readonly verdict: 'valid' | 'fails'
61
+ readonly reason: string | undefined
62
+ readonly cached: boolean
63
+ readonly deprecations: readonly string[]
64
+ }
65
+
66
+ type Judgement = Readonly<{
67
+ verdict: 'valid' | 'fails'
68
+ reason?: string
69
+ deprecations?: readonly string[]
70
+ transient: boolean
71
+ }>
72
+
73
+ interface CorpusOptions {
74
+ readonly api: string
75
+ readonly cache: string
76
+ readonly validator: string
77
+ readonly fetch?: typeof fetch
78
+ }
79
+
80
+ const NONE = 0
81
+ const TAR_MAGIC_AT = 257
82
+ const TAR_MAGIC = 'ustar'
83
+ const PEEK_BYTES = 512
84
+ const FETCH_TIMEOUT_MS = 900_000
85
+ /** One original is at most a few hundred MB; a download that takes longer has stalled. */
86
+ const DOWNLOAD_TIMEOUT_MS = 180_000
87
+ const DOWNLOAD_TRIES = 3
88
+ const FIRST_TRY = 1
89
+ const OK_LOW = 200
90
+ const OK_HIGH = 300
91
+ const SHORT_HASH = 12
92
+ const VERDICT_WIDTH = 5
93
+ const FIRST = 0
94
+
95
+ function shortReason(error: unknown): string {
96
+ const text = error instanceof Error ? error.message : String(error)
97
+ const code =
98
+ typeof error === 'object' && error !== null && 'code' in error
99
+ ? `${String(error.code)}: `
100
+ : ''
101
+ return `${code}${text}`.split('\n')[FIRST] ?? text
102
+ }
103
+
104
+ /** Whether the first bytes are a plain tarball (`ustar` at 257) rather than Brotli. */
105
+ function isPlainTar(head: Readonly<Uint8Array>): boolean {
106
+ const magic = new TextDecoder().decode(
107
+ head.subarray(TAR_MAGIC_AT, TAR_MAGIC_AT + TAR_MAGIC.length),
108
+ )
109
+ return magic === TAR_MAGIC
110
+ }
111
+
112
+ /** Downloads one original to `file`: the validator reads it twice, so it is fetched once and read from disk. */
113
+ async function download(
114
+ options: Readonly<CorpusOptions>,
115
+ hash: string,
116
+ file: string,
117
+ ): Promise<void> {
118
+ const url = new URL(`/api/shardfiles/${hash}`, options.api)
119
+ const response = await (options.fetch ?? fetch)(url, {
120
+ headers: { 'accept-encoding': 'br' },
121
+ signal: AbortSignal.timeout(DOWNLOAD_TIMEOUT_MS),
122
+ })
123
+ if (response.status < OK_LOW || response.status >= OK_HIGH) {
124
+ throw new Error(`download ${hash}: HTTP ${String(response.status)}`)
125
+ }
126
+ if (response.body === null) {
127
+ throw new Error(`download ${hash}: no body`)
128
+ }
129
+ await pipeline(Readable.fromWeb(response.body), createWriteStream(file))
130
+ }
131
+
132
+ async function firstBytes(file: string): Promise<Uint8Array> {
133
+ const handle = await open(file)
134
+ try {
135
+ const bytes = new Uint8Array(PEEK_BYTES)
136
+ await handle.read(bytes, NONE, PEEK_BYTES, NONE)
137
+ return bytes
138
+ } finally {
139
+ await handle.close()
140
+ }
141
+ }
142
+
143
+ /** One original through the stream validator, as a stored file. */
144
+ /** A download, tried again when it stalls or drops; the last error is thrown. */
145
+ async function downloadWithRetries(
146
+ options: Readonly<CorpusOptions>,
147
+ hash: string,
148
+ file: string,
149
+ ): Promise<void> {
150
+ let last: unknown = undefined
151
+ for (
152
+ let attempt = FIRST_TRY;
153
+ attempt <= DOWNLOAD_TRIES;
154
+ attempt += FIRST_TRY
155
+ ) {
156
+ try {
157
+ // oxlint-disable-next-line eslint/no-await-in-loop -- a retry waits for the try before it
158
+ await download(options, hash, file)
159
+ return
160
+ } catch (error: unknown) {
161
+ last = error
162
+ }
163
+ }
164
+ throw last
165
+ }
166
+
167
+ /** One original through the stream validator, as a stored file. A download that never completes is not a verdict. */
168
+ async function judge(
169
+ options: Readonly<CorpusOptions>,
170
+ hash: string,
171
+ ): Promise<Judgement> {
172
+ const file = path.join(options.cache, `${hash}.download`)
173
+ try {
174
+ try {
175
+ await downloadWithRetries(options, hash, file)
176
+ } catch (error: unknown) {
177
+ return {
178
+ verdict: 'fails',
179
+ reason: `download: ${shortReason(error)}`,
180
+ transient: true,
181
+ }
182
+ }
183
+ const plain = isPlainTar(await firstBytes(file))
184
+ const deprecations = await storedDeprecations(file, plain)
185
+ return { verdict: 'valid', deprecations, transient: false }
186
+ } catch (error: unknown) {
187
+ return { verdict: 'fails', reason: shortReason(error), transient: false }
188
+ } finally {
189
+ await rm(file, { force: true })
190
+ }
191
+ }
192
+
193
+ async function cachedVerdict(
194
+ options: Readonly<CorpusOptions>,
195
+ hash: string,
196
+ ): Promise<InferOutput<typeof CachedSchema> | undefined> {
197
+ try {
198
+ const raw: unknown = JSON.parse(
199
+ await readFile(path.join(options.cache, `${hash}.json`), 'utf8'),
200
+ )
201
+ const cached = parse(CachedSchema, raw)
202
+ // A valid verdict cached before FE7 has no deprecation list: judge it again.
203
+ const stale =
204
+ cached.verdict === 'valid' && cached.deprecations === undefined
205
+ return cached.validator === options.validator && !stale ? cached : undefined
206
+ } catch {
207
+ return undefined
208
+ }
209
+ }
210
+
211
+ async function row(
212
+ options: Readonly<CorpusOptions>,
213
+ stored: StoredRecord,
214
+ ): Promise<CorpusRow> {
215
+ const named = stored.revisions[FIRST]
216
+ const base = {
217
+ slug: named?.shard ?? '?',
218
+ revision: named?.revision ?? NONE,
219
+ hash: stored.hash,
220
+ storedBytes: stored.storedBytes,
221
+ }
222
+ const cached = await cachedVerdict(options, stored.hash)
223
+ if (cached !== undefined) {
224
+ return {
225
+ ...base,
226
+ verdict: cached.verdict === 'valid' ? 'valid' : 'fails',
227
+ reason: cached.reason,
228
+ cached: true,
229
+ deprecations: cached.deprecations ?? [],
230
+ }
231
+ }
232
+ await mkdir(options.cache, { recursive: true })
233
+ const { transient, ...judged } = await judge(options, stored.hash)
234
+ if (!transient) {
235
+ await writeFile(
236
+ path.join(options.cache, `${stored.hash}.json`),
237
+ `${JSON.stringify({ validator: options.validator, ...judged })}\n`,
238
+ )
239
+ }
240
+ return {
241
+ ...base,
242
+ ...judged,
243
+ reason: judged.reason,
244
+ cached: false,
245
+ deprecations: judged.deprecations ?? [],
246
+ }
247
+ }
248
+
249
+ /** Every kept original's verdict, in the API's upload order. */
250
+ async function runCorpus(
251
+ options: Readonly<CorpusOptions>,
252
+ ): Promise<CorpusRow[]> {
253
+ const listed = await (options.fetch ?? fetch)(
254
+ new URL('/api/shardfiles', options.api),
255
+ {
256
+ signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
257
+ },
258
+ )
259
+ if (listed.status < OK_LOW || listed.status >= OK_HIGH) {
260
+ throw new Error(`list: HTTP ${String(listed.status)}`)
261
+ }
262
+ const { shardfiles } = parse(ListSchema, await listed.json())
263
+ const rows: CorpusRow[] = []
264
+ for (const stored of shardfiles) {
265
+ // oxlint-disable-next-line eslint/no-await-in-loop -- one original at a time keeps memory bounded
266
+ rows.push(await row(options, stored))
267
+ }
268
+ return rows
269
+ }
270
+
271
+ function corpusReport(rows: readonly CorpusRow[]): string {
272
+ const lines = rows.map(
273
+ (found: Readonly<CorpusRow>): string =>
274
+ `${found.verdict.padEnd(VERDICT_WIDTH)} ${found.slug} r${String(found.revision)} ${found.hash.slice(FIRST, SHORT_HASH)}${found.reason === undefined ? '' : ` ${found.reason}`}`,
275
+ )
276
+ const failed = rows.filter(
277
+ (found: Readonly<CorpusRow>): boolean => found.verdict === 'fails',
278
+ ).length
279
+ const fetched = rows.filter(
280
+ (found: Readonly<CorpusRow>): boolean => !found.cached,
281
+ )
282
+ const bytes = fetched.reduce(
283
+ (sum: number, found: Readonly<CorpusRow>): number =>
284
+ sum + found.storedBytes,
285
+ NONE,
286
+ )
287
+ lines.push(
288
+ `corpus: ${String(rows.length)} kept originals, ${String(rows.length - failed)} valid, ${String(failed)} fail; fetched ${String(fetched.length)} (${String(bytes)} stored bytes), ${String(rows.length - fetched.length)} from cache`,
289
+ ...deprecationLines(rows),
290
+ )
291
+ return lines.join('\n')
292
+ }
293
+
294
+ export {
295
+ type CorpusOptions,
296
+ type CorpusRow,
297
+ corpusReport,
298
+ isPlainTar,
299
+ runCorpus,
300
+ }
package/src/cli/main.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import { parseArgs } from 'node:util'
3
3
 
4
+ import { corpusReport, runCorpus } from './corpus.ts'
4
5
  import { packFolder } from './pack.ts'
5
6
  import { summary, validateShardfile } from './validate.ts'
6
7
  import { readVersion } from './version.ts'
@@ -13,6 +14,8 @@ const NONE = 0
13
14
 
14
15
  // Arguments start after [node, script] in process.argv.
15
16
  const FIRST_CLI_ARG = 2
17
+ const DEFAULT_API = 'https://api.wildshard.io'
18
+ const DEFAULT_CACHE = 'tmp/corpus'
16
19
 
17
20
  const USAGE = `Usage: shard-format <command> [options]
18
21
 
@@ -24,6 +27,10 @@ Commands:
24
27
  Tar a folder into a shardfile: what its sections
25
28
  measure follows them, and format's validator must
26
29
  pass. Writes <slug>.tar by default
30
+ corpus [--api <url>] [--cache <dir>]
31
+ Validate every stored shard file the API keeps,
32
+ as stored originals; list every failure. Exits 3
33
+ when any fails
27
34
 
28
35
  Options:
29
36
  --version Print the version
@@ -35,6 +42,8 @@ interface CliArgs {
35
42
  readonly operands: readonly string[]
36
43
  readonly help: boolean
37
44
  readonly out: string | undefined
45
+ readonly api: string
46
+ readonly cache: string
38
47
  readonly version: boolean
39
48
  }
40
49
 
@@ -45,6 +54,8 @@ function parseCliArgs(argv: readonly string[]): CliArgs {
45
54
  options: {
46
55
  help: { type: 'boolean', default: false },
47
56
  out: { type: 'string' },
57
+ api: { type: 'string', default: DEFAULT_API },
58
+ cache: { type: 'string', default: DEFAULT_CACHE },
48
59
  version: { type: 'boolean', default: false },
49
60
  },
50
61
  })
@@ -54,6 +65,8 @@ function parseCliArgs(argv: readonly string[]): CliArgs {
54
65
  operands,
55
66
  help: values.help,
56
67
  out: values.out,
68
+ api: values.api,
69
+ cache: values.cache,
57
70
  version: values.version,
58
71
  }
59
72
  }
@@ -113,6 +126,22 @@ async function pack(args: CliArgs): Promise<number> {
113
126
  return await packReport(dir, args.out)
114
127
  }
115
128
 
129
+ async function corpus(args: CliArgs): Promise<number> {
130
+ if (args.operands.length > NONE) {
131
+ process.stderr.write(`shard-format: corpus takes no operands\n\n${USAGE}`)
132
+ return EXIT_USAGE
133
+ }
134
+ const rows = await runCorpus({
135
+ api: args.api,
136
+ cache: args.cache,
137
+ validator: await readVersion(),
138
+ })
139
+ process.stdout.write(`${corpusReport(rows)}\n`)
140
+ return rows.some((found): boolean => found.verdict === 'fails')
141
+ ? EXIT_INVALID
142
+ : EXIT_OK
143
+ }
144
+
116
145
  async function runCommand(args: CliArgs): Promise<number> {
117
146
  if (args.command === undefined) {
118
147
  return printUsage(EXIT_USAGE)
@@ -123,6 +152,9 @@ async function runCommand(args: CliArgs): Promise<number> {
123
152
  if (args.command === 'pack') {
124
153
  return await pack(args)
125
154
  }
155
+ if (args.command === 'corpus') {
156
+ return await corpus(args)
157
+ }
126
158
  process.stderr.write(
127
159
  `shard-format: unknown command ${args.command}\n\n${USAGE}`,
128
160
  )
@@ -191,6 +191,14 @@ function programMountValid(
191
191
  )
192
192
  }
193
193
  }
194
+ function failureOf(run: () => void): string | undefined {
195
+ try {
196
+ run()
197
+ return undefined
198
+ } catch (error: unknown) {
199
+ return error instanceof Error ? error.message : String(error)
200
+ }
201
+ }
194
202
  function requireCookPreparation(
195
203
  index: Frozen<OutputIndex>,
196
204
  cook:
@@ -218,14 +226,22 @@ function requireCookPreparation(
218
226
  if (cook?.version !== VERSION) {
219
227
  throw new Error(`Missing cook preparation: run ${fix}`)
220
228
  }
221
- if (
222
- cook.inputHash !==
229
+ // SHARD-COMPAT PR5 (J487): every failing prepared part is named, not the first.
230
+ const failures = [
231
+ cook.inputHash ===
223
232
  digest(cookPreparationBytes(index, cook.mounts, cook.renderer))
224
- ) {
225
- throw new Error(`stale cook preparation: run ${fix}`)
233
+ ? undefined
234
+ : `stale cook preparation: run ${fix}`,
235
+ failureOf((): void => {
236
+ fenceValid(index, { fence: cook.fence ?? [], mounts: cook.mounts }, fix)
237
+ }),
238
+ failureOf((): void => {
239
+ programMountValid(index, cook, digest)
240
+ }),
241
+ ].filter((row: string | undefined): row is string => row !== undefined)
242
+ if (failures.length > ZERO) {
243
+ throw new Error(failures.join('; '))
226
244
  }
227
- fenceValid(index, { fence: cook.fence ?? [], mounts: cook.mounts }, fix)
228
- programMountValid(index, cook, digest)
229
245
  }
230
246
  function readEntryPrograms(input: unknown): EntryPrograms {
231
247
  return parse(EntryProgramsSchema, input)
@@ -0,0 +1,132 @@
1
+ // oxlint-disable typescript/prefer-readonly-parameter-types -- the index is valibot output, only read
2
+ /** The deprecation counter (SHARD-COMPAT FE7, J486). A deprecated path still validates; it carries the version that
3
+ * deprecated it and its replacement, both validators warn when a shard file uses it, and the corpus counts the kept
4
+ * files using each (`shard-format corpus`). A path with a migration is mended by the chain; one without waits for its
5
+ * users to reach zero before it is deleted. */
6
+ import type { OutputIndex } from './outputIndex.ts'
7
+
8
+ /** One deprecated path. */
9
+ interface Deprecation {
10
+ /** Stable id the warnings and the corpus count use. */
11
+ readonly id: string
12
+ /** Where it sits in a shard file, in words. */
13
+ readonly path: string
14
+ /** The format version that deprecated it. */
15
+ readonly since: string
16
+ /** What to write instead. */
17
+ readonly replacement: string
18
+ /** The chain step that mends it, or `undefined` when nothing can (`format-migrations.ts`). */
19
+ readonly migration: string | undefined
20
+ }
21
+
22
+ /** What a deprecation test reads: the index and each section by name. */
23
+ interface DeprecationInput {
24
+ readonly index: Readonly<OutputIndex> | Readonly<Record<string, unknown>>
25
+ readonly sections: ReadonlyMap<string, unknown>
26
+ }
27
+
28
+ interface DeprecationRule extends Deprecation {
29
+ readonly uses: (shard: Readonly<DeprecationInput>) => boolean
30
+ }
31
+
32
+ const LEGACY_SPELLING = '0.1'
33
+
34
+ function field(value: unknown, key: string): unknown {
35
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
36
+ ? Reflect.get(value, key)
37
+ : undefined
38
+ }
39
+
40
+ const RULES: readonly DeprecationRule[] = [
41
+ {
42
+ id: 'version.two-part',
43
+ path: 'shard.json version and requires.sdk spelled "0.1"',
44
+ since: '0.1.0.0',
45
+ replacement: 'the four-part "0.1.0.0"',
46
+ migration: 'fp6-four-part-version',
47
+ uses: (shard: Readonly<DeprecationInput>): boolean =>
48
+ field(shard.index, 'version') === LEGACY_SPELLING,
49
+ },
50
+ {
51
+ id: 'manifest.gridShardfile',
52
+ path: 'sections/ui/level manifest.gridShardfile (and the discovery mount)',
53
+ since: '0.1.0.1',
54
+ replacement: 'manifest.shardfile',
55
+ migration: 'fp8-shardfile-pointer',
56
+ uses: (shard: Readonly<DeprecationInput>): boolean =>
57
+ field(
58
+ field(shard.sections.get('ui/level'), 'manifest'),
59
+ 'gridShardfile',
60
+ ) !== undefined,
61
+ },
62
+ {
63
+ id: 'runtime.trust',
64
+ path: 'shard.json runtime.trust',
65
+ since: '0.1.0.1',
66
+ replacement: 'nothing: no reader reads it',
67
+ migration: 'fp3-drop-runtime-trust',
68
+ uses: (shard: Readonly<DeprecationInput>): boolean =>
69
+ field(field(shard.index, 'runtime'), 'trust') !== undefined,
70
+ },
71
+ ]
72
+
73
+ /** Every deprecated path, without its test. */
74
+ const DEPRECATIONS: readonly Deprecation[] = RULES.map(
75
+ ({ uses: _uses, ...row }: Readonly<DeprecationRule>): Deprecation => row,
76
+ )
77
+
78
+ /** The deprecations a shard file uses, in registry order. */
79
+ function deprecationsUsed(
80
+ shard: Readonly<DeprecationInput>,
81
+ ): readonly Deprecation[] {
82
+ return RULES.filter((rule: Readonly<DeprecationRule>): boolean =>
83
+ rule.uses(shard),
84
+ ).map(
85
+ ({ uses: _uses, ...row }: Readonly<DeprecationRule>): Deprecation => row,
86
+ )
87
+ }
88
+
89
+ /** What a validator returns about warnings: its own, then one per deprecated path the file uses, and their ids. */
90
+ interface DeprecationReport {
91
+ /** Admitted with a warning: grandfathered script side lines (`SCRIPT_SIDE_GRANDFATHER`, SERVER-PARITY SS11) and each
92
+ * deprecated path the file uses (FE7). */
93
+ readonly warnings: readonly string[]
94
+ /** FE7: the ids of the deprecated paths the file uses. */
95
+ readonly deprecations: readonly string[]
96
+ }
97
+
98
+ /** The warning a validator gives for one used deprecation. */
99
+ function deprecationWarning(row: Readonly<Deprecation>): string {
100
+ const mend =
101
+ row.migration === undefined
102
+ ? 'no migration: it is deleted once no kept file uses it'
103
+ : `the chain mends it (${row.migration})`
104
+ return `deprecated since ${row.since} (${row.id}): ${row.path}; use ${row.replacement}; ${mend}`
105
+ }
106
+
107
+ /** A validator's warnings with the file's deprecations added (FE7). */
108
+ function deprecationReport(
109
+ shard: Readonly<DeprecationInput>,
110
+ warnings: readonly string[],
111
+ ): DeprecationReport {
112
+ const used = deprecationsUsed(shard)
113
+ return {
114
+ warnings: [
115
+ ...warnings,
116
+ ...used.map((row: Readonly<Deprecation>): string =>
117
+ deprecationWarning(row),
118
+ ),
119
+ ],
120
+ deprecations: used.map((row: Readonly<Deprecation>): string => row.id),
121
+ }
122
+ }
123
+
124
+ export {
125
+ DEPRECATIONS,
126
+ type DeprecationReport,
127
+ deprecationReport,
128
+ type Deprecation,
129
+ type DeprecationInput,
130
+ deprecationWarning,
131
+ deprecationsUsed,
132
+ }