@wildshard/shard-format 0.69.2 → 0.70.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/src/cli/main.ts CHANGED
@@ -1,9 +1,10 @@
1
1
  #!/usr/bin/env node
2
- import { readFile } from 'node:fs/promises'
3
2
  import { parseArgs } from 'node:util'
4
3
 
5
- import { corpusGate, readKnownFailures } from './corpus-gate.ts'
6
- import { corpusReport, runCorpus } from './corpus.ts'
4
+ import { corpusCommand } from './corpus-command.ts'
5
+ import { readLock } from './format-diff-lock.ts'
6
+ import { formatDiffReport } from './format-diff-report.ts'
7
+ import { formatDiff } from './format-diff.ts'
7
8
  import { packFolder } from './pack.ts'
8
9
  import { summary, validateShardfile } from './validate.ts'
9
10
  import { readVersion } from './version.ts'
@@ -13,12 +14,12 @@ const EXIT_USAGE = 1
13
14
  const EXIT_CRASH = 2
14
15
  const EXIT_INVALID = 3
15
16
  const NONE = 0
17
+ const JSON_INDENT = 1
16
18
 
17
19
  // Arguments start after [node, script] in process.argv.
18
20
  const FIRST_CLI_ARG = 2
19
21
  const DEFAULT_API = 'https://api.wildshard.io'
20
22
  const DEFAULT_CACHE = 'tmp/corpus'
21
- const KNOWN_FAILURES = 'corpus/known-failures.json'
22
23
 
23
24
  const USAGE = `Usage: shard-format <command> [options]
24
25
 
@@ -30,10 +31,16 @@ Commands:
30
31
  Tar a folder into a shardfile: what its sections
31
32
  measure follows them, and format's validator must
32
33
  pass. Writes <slug>.tar by default
33
- corpus [--api <url>] [--cache <dir>]
34
+ corpus [--api <url>] [--cache <dir>] [--usage <file>]
34
35
  Validate every stored shard file the API keeps,
35
36
  as stored originals; list every failure. Exits 3
36
- when any fails
37
+ when any fails. --usage writes who uses each
38
+ deprecated path and chain step (FE13 reads it)
39
+ format-diff <a> <b> [--json]
40
+ Classify every change between two format locks
41
+ (a git ref or a folder holding src/format/lock):
42
+ additive, deprecation, breaking or review, with
43
+ rename? pairs and a suggested migration op
37
44
 
38
45
  Options:
39
46
  --version Print the version
@@ -48,6 +55,8 @@ interface CliArgs {
48
55
  readonly api: string
49
56
  readonly cache: string
50
57
  readonly version: boolean
58
+ readonly json: boolean
59
+ readonly usage: string | undefined
51
60
  }
52
61
 
53
62
  function parseCliArgs(argv: readonly string[]): CliArgs {
@@ -60,6 +69,8 @@ function parseCliArgs(argv: readonly string[]): CliArgs {
60
69
  api: { type: 'string', default: DEFAULT_API },
61
70
  cache: { type: 'string', default: DEFAULT_CACHE },
62
71
  version: { type: 'boolean', default: false },
72
+ json: { type: 'boolean', default: false },
73
+ usage: { type: 'string' },
63
74
  },
64
75
  })
65
76
  const [command, ...operands] = positionals
@@ -71,6 +82,8 @@ function parseCliArgs(argv: readonly string[]): CliArgs {
71
82
  api: values.api,
72
83
  cache: values.cache,
73
84
  version: values.version,
85
+ json: values.json,
86
+ usage: values.usage,
74
87
  }
75
88
  }
76
89
 
@@ -129,40 +142,46 @@ async function pack(args: CliArgs): Promise<number> {
129
142
  return await packReport(dir, args.out)
130
143
  }
131
144
 
132
- async function corpus(args: CliArgs): Promise<number> {
133
- if (args.operands.length > NONE) {
134
- process.stderr.write(`shard-format: corpus takes no operands\n\n${USAGE}`)
145
+ async function formatDiffCommand(args: CliArgs): Promise<number> {
146
+ const [before, after, ...extra] = args.operands
147
+ if (before === undefined || after === undefined || extra.length > NONE) {
148
+ process.stderr.write(
149
+ `shard-format: format-diff takes two locks\n\n${USAGE}`,
150
+ )
135
151
  return EXIT_USAGE
136
152
  }
137
- const rows = await runCorpus({
138
- api: args.api,
139
- cache: args.cache,
140
- validator: await readVersion(),
141
- })
142
- process.stdout.write(`${corpusReport(rows)}\n`)
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 => '[]',
153
+ const cwd = process.cwd()
154
+ const report = formatDiff(
155
+ await readLock(before, cwd),
156
+ await readLock(after, cwd),
146
157
  )
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
158
+ process.stdout.write(
159
+ `${args.json ? JSON.stringify(report, undefined, JSON_INDENT) : formatDiffReport(report)}\n`,
160
+ )
161
+ return EXIT_OK
162
+ }
163
+
164
+ const COMMANDS: Readonly<Record<string, (args: CliArgs) => Promise<number>>> = {
165
+ validate: async (args: CliArgs): Promise<number> =>
166
+ await validate(args.operands),
167
+ pack,
168
+ corpus: async (args: CliArgs): Promise<number> => {
169
+ if (args.operands.length > NONE) {
170
+ process.stderr.write(`shard-format: corpus takes no operands\n\n${USAGE}`)
171
+ return EXIT_USAGE
172
+ }
173
+ return await corpusCommand(args)
174
+ },
175
+ 'format-diff': formatDiffCommand,
152
176
  }
153
177
 
154
178
  async function runCommand(args: CliArgs): Promise<number> {
155
179
  if (args.command === undefined) {
156
180
  return printUsage(EXIT_USAGE)
157
181
  }
158
- if (args.command === 'validate') {
159
- return await validate(args.operands)
160
- }
161
- if (args.command === 'pack') {
162
- return await pack(args)
163
- }
164
- if (args.command === 'corpus') {
165
- return await corpus(args)
182
+ const command = COMMANDS[args.command]
183
+ if (command !== undefined) {
184
+ return await command(args)
166
185
  }
167
186
  process.stderr.write(
168
187
  `shard-format: unknown command ${args.command}\n\n${USAGE}`,
@@ -13,9 +13,15 @@ import {
13
13
  string,
14
14
  } from 'valibot'
15
15
 
16
- import { CookPreparationSchema } from './cook-preparation.ts'
16
+ import {
17
+ CookPreparationSchema,
18
+ CookSpecPreparationSchema,
19
+ } from './cook-preparation.ts'
17
20
 
18
- import type { CookPreparation } from './cook-preparation.ts'
21
+ import type {
22
+ CookPreparation,
23
+ CookSpecPreparation,
24
+ } from './cook-preparation.ts'
19
25
  import type { GenericSchema } from 'valibot'
20
26
 
21
27
  // C0 (J137, D5): what makes a shardfile stand alone, in one file beside
@@ -104,6 +110,11 @@ const PreparedCookDataSchema = strictObject({
104
110
  ...CookPreparationSchema.entries,
105
111
  mounts: mountRows,
106
112
  })
113
+ /** SHARD-COMPAT PR4: preparation spec 4, which names no engine. */
114
+ const SpecCookDataSchema = strictObject({
115
+ ...CookSpecPreparationSchema.entries,
116
+ mounts: mountRows,
117
+ })
107
118
  const PREVIOUS_COOK_VERSION = 2
108
119
  const PreviousCookDataSchema = strictObject({
109
120
  version: literal(PREVIOUS_COOK_VERSION),
@@ -123,11 +134,19 @@ interface PreviousCookData extends Omit<
123
134
  interface PreparedCookData extends CookPreparation {
124
135
  readonly mounts: readonly CookMount[]
125
136
  }
126
- type CookData = LegacyCookData | PreviousCookData | PreparedCookData
137
+ interface SpecCookData extends CookSpecPreparation {
138
+ readonly mounts: readonly CookMount[]
139
+ }
140
+ type CookData =
141
+ | LegacyCookData
142
+ | PreviousCookData
143
+ | PreparedCookData
144
+ | SpecCookData
127
145
  const CookDataSchema: GenericSchema<unknown, CookData> = variant('version', [
128
146
  LegacyCookDataSchema,
129
147
  PreviousCookDataSchema,
130
148
  PreparedCookDataSchema,
149
+ SpecCookDataSchema,
131
150
  ])
132
151
 
133
152
  /** Where a mount's bytes sit in a product. */
@@ -14,8 +14,19 @@ import {
14
14
  strictObject,
15
15
  string,
16
16
  tuple,
17
+ union,
17
18
  } from 'valibot'
18
19
 
20
+ import {
21
+ failureOf,
22
+ fenceValid,
23
+ preparationMarked,
24
+ programMountValid,
25
+ } from './preparation-checks.ts'
26
+ import {
27
+ LEGACY_PREPARATION_SPEC,
28
+ PREPARATION_SPEC,
29
+ } from './preparation-spec.ts'
19
30
  import { validationSourceBytes } from './validationReceipt.ts'
20
31
 
21
32
  import type { OutputIndex } from './outputIndex.ts'
@@ -30,8 +41,10 @@ const MAX_BUILD = 160
30
41
  const MAX_FENCE = 8192
31
42
  const ZERO = 0
32
43
  const ONE = 1
33
- const VERSION = 3
44
+ const VERSION: typeof LEGACY_PREPARATION_SPEC = LEGACY_PREPARATION_SPEC
34
45
  const PROGRAM_VERSION = 2
46
+ /** Programs at spec 4: the same GLSL rows with no engine `build`. */
47
+ const SPEC_PROGRAM_VERSION = 3
35
48
  const MAX_COOK_BYTES = 8_388_608
36
49
 
37
50
  /** Actual linked GLSL pairs, not decision programs. The recorder owns provenance. */
@@ -42,6 +55,14 @@ interface EntryPrograms {
42
55
  readonly shaders: readonly (readonly number[])[]
43
56
  readonly programs: readonly (readonly [number, number])[]
44
57
  }
58
+ /** Spec 4's programs: a warm-up hint any engine may use or ignore; no engine build is named. */
59
+ interface SpecPrograms {
60
+ readonly version: typeof SPEC_PROGRAM_VERSION
61
+ readonly lines: readonly string[]
62
+ readonly shaders: readonly (readonly number[])[]
63
+ readonly programs: readonly (readonly [number, number])[]
64
+ }
65
+ type AnyPrograms = EntryPrograms | SpecPrograms
45
66
  interface CookPreparation {
46
67
  readonly version: typeof VERSION
47
68
  readonly inputHash: string
@@ -50,6 +71,14 @@ interface CookPreparation {
50
71
  readonly fence: readonly string[]
51
72
  readonly programs: EntryPrograms
52
73
  }
74
+ /** Preparation spec 4 (PR4): spec 3 without the renderer fingerprint; programs without the engine build. */
75
+ interface CookSpecPreparation {
76
+ readonly version: typeof PREPARATION_SPEC
77
+ readonly inputHash: string
78
+ readonly packs: 'fence' | 'whole'
79
+ readonly fence: readonly string[]
80
+ readonly programs: SpecPrograms
81
+ }
53
82
  const natural = pipe(number(), safeInteger(), minValue(ZERO))
54
83
  const shader = pipe(array(natural), maxLength(MAX_LINES))
55
84
  const program = tuple([natural, natural])
@@ -59,14 +88,14 @@ const lines = pipe(array(line), maxLength(MAX_LINES))
59
88
  const shaders = pipe(array(shader), maxLength(MAX_SHADERS))
60
89
  const build = pipe(string(), minLength(ONE), maxLength(MAX_BUILD))
61
90
 
62
- function programSourceValid(row: EntryPrograms): boolean {
91
+ function programSourceValid(row: AnyPrograms): boolean {
63
92
  let size = ZERO
64
93
  for (const text of row.lines) {
65
94
  size += text.length
66
95
  }
67
96
  return size <= MAX_TEXT
68
97
  }
69
- function programLinesValid(row: EntryPrograms): boolean {
98
+ function programLinesValid(row: AnyPrograms): boolean {
70
99
  for (const source of row.shaders) {
71
100
  for (const index of source) {
72
101
  if (index >= row.lines.length) {
@@ -76,7 +105,7 @@ function programLinesValid(row: EntryPrograms): boolean {
76
105
  }
77
106
  return true
78
107
  }
79
- function programPairsValid(row: EntryPrograms): boolean {
108
+ function programPairsValid(row: AnyPrograms): boolean {
80
109
  const seen = new Set<string>()
81
110
  for (const pair of row.programs) {
82
111
  if (
@@ -97,12 +126,41 @@ const programRows: GenericSchema<unknown, EntryPrograms> = strictObject({
97
126
  shaders,
98
127
  programs,
99
128
  })
100
- const EntryProgramsSchema: GenericSchema<unknown, EntryPrograms> = pipe(
101
- programRows,
102
- check(programSourceValid, 'Program source exceeds cap'),
103
- check(programLinesValid, 'Program line index is out of range'),
104
- check(programPairsValid, 'Invalid or duplicate program pair'),
105
- )
129
+ const specProgramRows: GenericSchema<unknown, SpecPrograms> = strictObject({
130
+ version: literal(SPEC_PROGRAM_VERSION),
131
+ lines,
132
+ shaders,
133
+ programs,
134
+ })
135
+ function programChecks<Row extends AnyPrograms>(
136
+ // oxlint-disable-next-line typescript/prefer-readonly-parameter-types -- a valibot schema, only piped
137
+ rows: GenericSchema<unknown, Row>,
138
+ ): GenericSchema<unknown, Row> {
139
+ return pipe(
140
+ rows,
141
+ check(
142
+ (row: Row): boolean => programSourceValid(row),
143
+ 'Program source exceeds cap',
144
+ ),
145
+ check(
146
+ (row: Row): boolean => programLinesValid(row),
147
+ 'Program line index is out of range',
148
+ ),
149
+ check(
150
+ (row: Row): boolean => programPairsValid(row),
151
+ 'Invalid or duplicate program pair',
152
+ ),
153
+ )
154
+ }
155
+ const EntryProgramsSchema: GenericSchema<unknown, EntryPrograms> =
156
+ programChecks(programRows)
157
+ const SpecProgramsSchema: GenericSchema<unknown, SpecPrograms> =
158
+ programChecks(specProgramRows)
159
+ /** The programs mount at either spec, by its `version`. */
160
+ const AnyProgramsSchema: GenericSchema<unknown, AnyPrograms> = union([
161
+ EntryProgramsSchema,
162
+ SpecProgramsSchema,
163
+ ])
106
164
  const hash = pipe(string(), regex(HASH))
107
165
  const fenceRows: GenericSchema<unknown, readonly string[]> = pipe(
108
166
  array(hash),
@@ -127,6 +185,20 @@ const CookPreparationSchema: GenericSchema<unknown, CookPreparation> & {
127
185
  fence,
128
186
  programs: EntryProgramsSchema,
129
187
  })
188
+ const CookSpecPreparationSchema: GenericSchema<unknown, CookSpecPreparation> & {
189
+ readonly entries: {
190
+ readonly [Key in keyof CookSpecPreparation]: GenericSchema<
191
+ unknown,
192
+ CookSpecPreparation[Key]
193
+ >
194
+ }
195
+ } = strictObject({
196
+ version: literal(PREPARATION_SPEC),
197
+ inputHash: hash,
198
+ packs: picklist(['fence', 'whole']),
199
+ fence,
200
+ programs: SpecProgramsSchema,
201
+ })
130
202
  /** Omit only the pointer to preparation itself; all other transport/host inputs remain bound. */
131
203
  type Frozen<Value> = Value extends object
132
204
  ? { readonly [Key in keyof Value]: Frozen<Value[Key]> }
@@ -148,57 +220,6 @@ function cookPreparationBytes(
148
220
  ...(renderer === undefined ? {} : { renderer }),
149
221
  })
150
222
  }
151
- /** Shared by admission and the cook. Legacy sdk 0.2 is an explicit migration boundary. */
152
- function fenceValid(
153
- index: Frozen<OutputIndex>,
154
- lists: Readonly<{
155
- fence: readonly string[]
156
- mounts: readonly Readonly<{ hash: string }>[]
157
- }>,
158
- fix: string,
159
- ): void {
160
- const known = new Set<string>()
161
- for (const file of index.files) {
162
- known.add(file.hash)
163
- }
164
- for (const mount of lists.mounts) {
165
- known.add(mount.hash)
166
- }
167
- for (const row of lists.fence) {
168
- if (!known.has(row) && !index.requires.commons.includes(row)) {
169
- throw new Error(`stale fence preparation: run ${fix}`)
170
- }
171
- }
172
- }
173
- function programMountValid(
174
- index: Frozen<OutputIndex>,
175
- cook: {
176
- readonly programs?: EntryPrograms
177
- readonly mounts: readonly Readonly<{ url: string; hash: string }>[]
178
- },
179
- digest: (bytes: Readonly<Uint8Array>) => string,
180
- ): void {
181
- const url = `/programs/${index.identity.slug}.json`
182
- const mount = cook.mounts.find(
183
- (row: Readonly<{ url: string; hash: string }>): boolean => row.url === url,
184
- )
185
- if (
186
- cook.programs === undefined ||
187
- mount?.hash !== digest(validationSourceBytes(cook.programs))
188
- ) {
189
- throw new Error(
190
- `stale GLSL program mount: run wildshard prepare <folder> --base <exact-preview-url> (${index.identity.slug})`,
191
- )
192
- }
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
- }
202
223
  function requireCookPreparation(
203
224
  index: Frozen<OutputIndex>,
204
225
  cook:
@@ -213,19 +234,16 @@ function requireCookPreparation(
213
234
  inputHash?: string
214
235
  renderer?: string
215
236
  fence?: readonly string[]
216
- programs?: EntryPrograms
237
+ programs?: AnyPrograms
217
238
  packs?: 'fence' | 'whole'
218
239
  }>
219
240
  | undefined,
220
241
  digest: (bytes: Readonly<Uint8Array>) => string,
221
242
  ): void {
222
243
  const fix = `wildshard prepare <folder> --base <exact-preview-url> (${index.identity.slug})`
223
- if (index.sdk === '0.2' && cook?.version !== VERSION) {
244
+ if (!preparationMarked(index, cook?.version, fix) || cook === undefined) {
224
245
  return
225
246
  }
226
- if (cook?.version !== VERSION) {
227
- throw new Error(`Missing cook preparation: run ${fix}`)
228
- }
229
247
  // SHARD-COMPAT PR5 (J487): every failing prepared part is named, not the first.
230
248
  const failures = [
231
249
  cook.inputHash ===
@@ -243,15 +261,31 @@ function requireCookPreparation(
243
261
  throw new Error(failures.join('; '))
244
262
  }
245
263
  }
246
- function readEntryPrograms(input: unknown): EntryPrograms {
247
- return parse(EntryProgramsSchema, input)
264
+ /** Whether a `cook.json` is prepared, at any spec this package reads (PR4). */
265
+ function isPreparedCook(
266
+ cook: Readonly<{ version: number }> | undefined,
267
+ ): boolean {
268
+ return preparationMarked({ sdk: '0.2' }, cook?.version, '')
269
+ }
270
+ function readEntryPrograms(input: unknown): AnyPrograms {
271
+ return parse(AnyProgramsSchema, input)
272
+ }
273
+ export type {
274
+ AnyPrograms,
275
+ EntryPrograms,
276
+ SpecPrograms,
277
+ CookPreparation,
278
+ CookSpecPreparation,
248
279
  }
249
- export type { EntryPrograms, CookPreparation }
250
280
  export {
251
281
  CookPreparationSchema,
282
+ CookSpecPreparationSchema,
252
283
  EntryProgramsSchema,
284
+ SpecProgramsSchema,
285
+ AnyProgramsSchema,
253
286
  cookPreparationBytes,
254
287
  requireCookPreparation,
255
288
  readEntryPrograms,
289
+ isPreparedCook,
256
290
  MAX_COOK_BYTES,
257
291
  }
@@ -36,6 +36,8 @@ const CURRENT = '0.1.0.1'
36
36
  /** Format 0.1.0.2's envelope (SHARD-COMPAT CP14, FORMAT-PRUNE FP4 and FP25). */
37
37
  const ENVELOPE = '0.1.0.2'
38
38
  const LEGACY_LAYOUT = 2
39
+ /** Format 0.1.0.3: `preparation` replaces the `sdk` marker (SHARD-COMPAT PR4). */
40
+ const PREPARATION_MARKER = '0.1.0.3'
39
41
  /** FORMAT-PRUNE FP4: always empty, never read. */
40
42
  const EMPTY_INDEX_FIELDS: readonly (readonly [string, string | undefined])[] = [
41
43
  ['schemas', undefined],
@@ -105,6 +107,16 @@ const RULES: readonly DeprecationRule[] = [
105
107
  : field(field(shard.index, outer), inner) !== undefined,
106
108
  ),
107
109
  },
110
+ {
111
+ id: 'shard.sdk-marker',
112
+ path: "shard.json sdk ('0.2' built, '0.3' prepared), the preparation marker (SHARD-COMPAT PR4, FORMAT-PRUNE FP5)",
113
+ since: PREPARATION_MARKER,
114
+ replacement:
115
+ 'preparation: the preparation spec version (cook.json version), absent on an unprepared file',
116
+ migration: 'pr4-preparation-marker',
117
+ uses: (shard: Readonly<DeprecationInput>): boolean =>
118
+ field(shard.index, 'sdk') !== undefined,
119
+ },
108
120
  {
109
121
  id: 'requires.sdk',
110
122
  path: 'shard.json requires.sdk (SHARD-COMPAT CP8): a copy of the format version',
@@ -5,7 +5,7 @@
5
5
  * It is deterministic (canonical JSON, no clock, network or randomness), always starts from the original, and twice
6
6
  * equals once. */
7
7
  import { readCookData } from './cook-data.ts'
8
- import { requireCookPreparation } from './cook-preparation.ts'
8
+ import { isPreparedCook, requireCookPreparation } from './cook-preparation.ts'
9
9
  import {
10
10
  INDEX,
11
11
  RECEIPT,
@@ -77,7 +77,6 @@ interface Admitted {
77
77
  }
78
78
 
79
79
  const RUNNER = 1
80
- const PREPARED = 3
81
80
  const NONE = 0
82
81
 
83
82
  function chainId(migrations: readonly FormatMigration[], hash: Hash): string {
@@ -210,7 +209,7 @@ function writeCopy(
210
209
  const copy = { index, out, hash: plan.hash }
211
210
  rebuildInventory(copy, shard, {
212
211
  mountText,
213
- reseal: cook?.version === PREPARED && !rendersAgain(plan.steps),
212
+ reseal: isPreparedCook(cook) && !rendersAgain(plan.steps),
214
213
  })
215
214
  copy.out.set(INDEX, validationSourceBytes(index))
216
215
  return copy.out
@@ -220,7 +219,7 @@ function preparationOf(
220
219
  cook: Readonly<CookData> | undefined,
221
220
  steps: readonly FormatMigration[],
222
221
  ): MigratedShardfile['preparation'] {
223
- if (cook?.version !== PREPARED) {
222
+ if (!isPreparedCook(cook)) {
224
223
  return 'none'
225
224
  }
226
225
  return rendersAgain(steps) ? 'stale' : 'author'
@@ -3,6 +3,7 @@
3
3
  * version into `formatVersion` from 0.1.0.2 on (`writeShardfileFormat`), replacing the frozen layout marker `2`; these
4
4
  * steps drop the fields the new envelope no longer carries. Every dropped field held nothing: `version` repeats the
5
5
  * format version, and the other four are always empty with no reader. */
6
+ import { LEGACY_PREPARATION_SPEC, PREPARED_SDK } from './preparation-spec.ts'
6
7
  import { LEGACY_LAYOUT, writesIndexFormatVersion } from './version.ts'
7
8
 
8
9
  import type { FormatMigration, MigratingShard } from './format-migrations.ts'
@@ -10,6 +11,7 @@ import type { FormatMigration, MigratingShard } from './format-migrations.ts'
10
11
  type JsonRecord = Record<string, unknown>
11
12
 
12
13
  const ENVELOPE = '0.1.0.2'
14
+ const PREPARATION_MARKER = '0.1.0.3'
13
15
 
14
16
  function isRecord(value: unknown): value is JsonRecord {
15
17
  return typeof value === 'object' && value !== null && !Array.isArray(value)
@@ -44,6 +46,24 @@ const dropEmptyIndexFields: FormatMigration = {
44
46
  },
45
47
  }
46
48
 
49
+ /** SHARD-COMPAT PR4 (J487, FORMAT-PRUNE FP5 folded in): the `sdk` marker becomes `preparation`, the spec version the
50
+ * file was prepared to. `'0.3'` (prepared) is spec 3, the only spec that marker ever meant; `'0.2'` (built, not
51
+ * prepared) leaves no field. Data only: the copy's `cook.json` stays spec 3 and its input hash is re-sealed over the
52
+ * new index. */
53
+ const preparationMarker: FormatMigration = {
54
+ id: 'pr4-preparation-marker',
55
+ to: PREPARATION_MARKER,
56
+ touches: 'data',
57
+ affects: [],
58
+ apply: (shard: MigratingShard): void => {
59
+ const { index } = shard
60
+ if (index['sdk'] === PREPARED_SDK) {
61
+ index['preparation'] = LEGACY_PREPARATION_SPEC
62
+ }
63
+ Reflect.deleteProperty(index, 'sdk')
64
+ },
65
+ }
66
+
47
67
  /** The format version a `shard.json` declares, as written, or `undefined`: `formatVersion` from 0.1.0.2, else the
48
68
  * legacy `version` beside the layout marker. */
49
69
  function declaredShardfileFormat(index: Readonly<JsonRecord>): unknown {
@@ -68,5 +88,6 @@ export {
68
88
  declaredShardfileFormat,
69
89
  dropEmptyIndexFields,
70
90
  formatVersionField,
91
+ preparationMarker,
71
92
  writeShardfileFormat,
72
93
  }
@@ -5,6 +5,7 @@
5
5
  import {
6
6
  dropEmptyIndexFields,
7
7
  formatVersionField,
8
+ preparationMarker,
8
9
  } from './format-migration-envelope.ts'
9
10
  import { journalGlyphImages } from './format-migration-journal.ts'
10
11
  import { dropRuntimeTrust, shardfilePointer } from './format-migration-prune.ts'
@@ -71,6 +72,7 @@ const FORMAT_MIGRATIONS: readonly FormatMigration[] = [
71
72
  dropRuntimeTrust,
72
73
  formatVersionField,
73
74
  dropEmptyIndexFields,
75
+ preparationMarker,
74
76
  ]
75
77
 
76
78
  /** Whether a file at `version` still needs a step that writes `to`. The legacy two-part spelling sits just below its
@@ -1,5 +1,6 @@
1
1
  import { platformFileFamily } from './platformFileFamilies.ts';
2
2
  import { MAX_COOK_BYTES } from './cook-preparation.ts';
3
+ import { PREPARATION_SPECS, preparationSpecOf } from './preparation-spec.ts';
3
4
  import type { Ktx2DeviceCosts } from './ktx2Cost.ts';
4
5
  import { AdmissionLateSchema, lateLibraryRootsValid, type AdmissionLate } from './admissionLate.ts';
5
6
  import { AdmissionServerSchema, serverFilesExclusive, type AdmissionServer } from './admissionServer.ts';
@@ -15,9 +16,10 @@ import { ClientPlanRuntimeSchema } from './runtime.ts';
15
16
  import { RuntimeSpawnsSchema } from './runtimeSpawns.ts';
16
17
  import { RowsSchema } from './rows.ts';
17
18
  import { ShardHashSchema, ShardNaturalSchema, IdentitySchema, RequiresSchema, FilesSchema, type ShardIdentityInput, type ShardRequiresInput, type ShardReferencesInput, type ShardIdentity, type ShardRequires, type ShardReferences } from './shardSections.ts';
18
- import { LEGACY_LAYOUT } from './version.ts';
19
+ import { LEGACY_LAYOUT, writesPreparationMarker } from './version.ts';
19
20
  import { IndexFormatVersionSchema, LegacyIndexVersionSchema } from './index-format-version.ts';
20
21
  import type { IndexFormatVersion, LegacyIndexVersion } from './version.ts';
22
+ import type { PreparationSpec } from './preparation-spec.ts';
21
23
  import { isJsonData, isJsonDataWithFileSchemas } from './json.ts';
22
24
  import { clientOwnershipRules } from './clientOwnership.ts';
23
25
  import { PLATFORM_DATA_SECTIONS } from './platformDataSections.ts';
@@ -42,7 +44,12 @@ export const OutputIndexSchema: v.GenericSchema<OutputIndexRowsInput, OutputInde
42
44
  format: v.literal('wildshard.shardfile'),
43
45
  /** SHARD-COMPAT CP14 (FP25): the format version itself from 0.1.0.2; the legacy envelope carries the frozen layout marker
44
46
  * `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,
47
+ formatVersion: IndexFormatVersionSchema, version: LegacyIndexVersionSchema,
48
+ /** The legacy preparation marker (`'0.2'` built, `'0.3'` prepared) up to format 0.1.0.2; 0.1.0.3 drops it (PR4). */
49
+ sdk: v.exactOptional(v.picklist(['0.2', '0.3'])),
50
+ /** SHARD-COMPAT PR4 (J487): from format 0.1.0.3, the preparation spec version a prepared file was made to, owned by
51
+ * this package (`cook.json`'s `version`); absent on an unprepared file. It names no engine release. */
52
+ preparation: v.exactOptional(v.picklist(PREPARATION_SPECS)),
46
53
  identity: IdentitySchema, build: v.strictObject({ sourceHash: ShardHashSchema, validator: v.pipe(v.string(), v.minLength(1), v.maxLength(160)) }), requires: RequiresSchema,
47
54
  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) }),
48
55
  sections: v.pipe(v.array(section), v.maxLength(256)), schemas: emptySchemas,
@@ -83,9 +90,21 @@ function legacyIndexFields(index: OutputIndex): readonly string[] {
83
90
  index.runtime === null || !Object.hasOwn(index.runtime, 'trust') ? undefined : 'runtime.trust',
84
91
  ].filter((field): field is string => field !== undefined);
85
92
  }
93
+ /** PR4: 0.1.0.3 on records `preparation` and drops `sdk`; below it `sdk` is required and `preparation` unknown. */
94
+ // oxlint-disable-next-line typescript/prefer-readonly-parameter-types -- valibot output, only read
95
+ function checkPreparationMarker(index: OutputIndex): void {
96
+ const version = index.formatVersion === LEGACY_LAYOUT ? undefined : index.formatVersion;
97
+ if (version !== undefined && writesPreparationMarker(version)) {
98
+ if (index.sdk !== undefined) { throw new Error(`Format ${version} drops sdk; it records preparation (shard.json)`); }
99
+ return;
100
+ }
101
+ if (index.sdk === undefined) { throw new Error(`Format ${version ?? index.version ?? 'legacy'} needs sdk (shard.json)`); }
102
+ if (index.preparation !== undefined) { throw new Error(`Format ${version ?? index.version ?? 'legacy'} has no preparation field; it records sdk (shard.json)`); }
103
+ }
86
104
  /** Hold each envelope to its own fields: the legacy one keeps every field its readers require, 0.1.0.2 carries none. */
87
105
  // oxlint-disable-next-line typescript/prefer-readonly-parameter-types -- valibot output, only read
88
106
  function checkIndexEnvelope(index: OutputIndex): void {
107
+ checkPreparationMarker(index);
89
108
  const carried = legacyIndexFields(index);
90
109
  if (index.formatVersion !== LEGACY_LAYOUT) {
91
110
  if (carried.length > 0) {
@@ -102,8 +121,9 @@ function checkIndexEnvelope(index: OutputIndex): void {
102
121
  function parseOutputIndexRows(input: unknown): OutputIndex {
103
122
  const index = v.parse(OutputIndexSchema, input);
104
123
  checkIndexEnvelope(index);
105
- 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})`); }
106
- if (index.sdk === '0.3' && index.cook !== undefined && index.cook.bytes > MAX_COOK_BYTES) { throw new Error('Cook preparation exceeds byte cap'); }
124
+ const prepared = preparationSpecOf(index) !== undefined;
125
+ if (prepared && index.cook === undefined) { throw new Error(`Missing cook preparation: run wildshard prepare <folder> --base <exact-preview-url> (${index.identity.slug})`); }
126
+ if (prepared && index.cook !== undefined && index.cook.bytes > MAX_COOK_BYTES) { throw new Error('Cook preparation exceeds byte cap'); }
107
127
  const paths = new Set(['shard.json', 'validation.json']), names = new Set<string>();
108
128
  if (index.ktx2Costs !== undefined) {
109
129
  const textures = new Map(index.files.filter(row=>row.kind==='ktx2' && row.commons!==true).map(row=>[row.hash,row]));
@@ -198,7 +218,8 @@ export function assembleOutputShardfile(input: unknown, sections: ReadonlyMap<st
198
218
  interface OutputIndexRowsInputFields {
199
219
  format: "wildshard.shardfile";
200
220
  formatVersion: typeof LEGACY_LAYOUT | IndexFormatVersion;
201
- sdk: "0.2" | "0.3";
221
+ sdk?: "0.2" | "0.3";
222
+ preparation?: PreparationSpec;
202
223
  version?: LegacyIndexVersion;
203
224
  identity: ShardIdentityInput;
204
225
  build: {
@@ -296,7 +317,8 @@ export type OutputIndexRowsInput = { [Key in keyof OutputIndexRowsInputFields]:
296
317
  interface OutputIndexRowsFields {
297
318
  format: "wildshard.shardfile";
298
319
  formatVersion: typeof LEGACY_LAYOUT | IndexFormatVersion;
299
- sdk: "0.2" | "0.3";
320
+ sdk?: "0.2" | "0.3";
321
+ preparation?: PreparationSpec;
300
322
  version?: LegacyIndexVersion;
301
323
  identity: ShardIdentity;
302
324
  build: {