@wildshard/shard-format 0.69.2 → 0.71.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 (73) hide show
  1. package/package.json +21 -3
  2. package/src/cli/corpus-candidate.ts +228 -0
  3. package/src/cli/corpus-command.ts +67 -0
  4. package/src/cli/corpus-pins.ts +73 -0
  5. package/src/cli/corpus-report.ts +36 -0
  6. package/src/cli/corpus-tar.ts +28 -0
  7. package/src/cli/corpus-usage.ts +106 -0
  8. package/src/cli/corpus.ts +50 -68
  9. package/src/cli/format-diff-data.ts +89 -0
  10. package/src/cli/format-diff-lock.ts +122 -0
  11. package/src/cli/format-diff-normal.ts +300 -0
  12. package/src/cli/format-diff-paths.ts +103 -0
  13. package/src/cli/format-diff-range.ts +112 -0
  14. package/src/cli/format-diff-report.ts +30 -0
  15. package/src/cli/format-diff-rules.ts +232 -0
  16. package/src/cli/format-diff.ts +226 -0
  17. package/src/cli/main.ts +81 -32
  18. package/src/cli/pack.ts +20 -3
  19. package/src/cli/validate.ts +1 -1
  20. package/src/format/clientOwnership.ts +1 -1
  21. package/src/format/clientTrails.ts +121 -46
  22. package/src/format/cook-data.ts +22 -3
  23. package/src/format/cook-deprecations.ts +53 -0
  24. package/src/format/cook-preparation.ts +105 -70
  25. package/src/format/creature-rest-rig.ts +248 -0
  26. package/src/format/creature-skin-bounds.ts +146 -0
  27. package/src/format/deprecations.ts +30 -21
  28. package/src/format/edge-observations.ts +67 -0
  29. package/src/format/empty-shardfile.ts +4 -2
  30. package/src/format/entry-read-set.ts +147 -0
  31. package/src/format/format-migrate-rebuild.ts +4 -1
  32. package/src/format/format-migrate.ts +10 -5
  33. package/src/format/format-migration-envelope.ts +40 -0
  34. package/src/format/format-migration-prune.ts +42 -1
  35. package/src/format/format-migrations.ts +10 -1
  36. package/src/format/format-window.ts +71 -0
  37. package/src/format/immutable.ts +4 -1
  38. package/src/format/json-schema.ts +1468 -0
  39. package/src/format/lootEconomy.ts +4 -1
  40. package/src/format/mat4.ts +225 -0
  41. package/src/format/memory-armed.json +1 -9
  42. package/src/format/memory-armed.ts +46 -17
  43. package/src/format/memory-epoch.ts +10 -3
  44. package/src/format/memory-line.ts +17 -6
  45. package/src/format/outputFields.ts +3 -2
  46. package/src/format/outputIndex.ts +41 -6
  47. package/src/format/platformDataSections.ts +5 -0
  48. package/src/format/platformFileFamilies.ts +3 -3
  49. package/src/format/play-area.ts +95 -0
  50. package/src/format/policy-verdict.ts +12 -2
  51. package/src/format/preparation-checks.ts +100 -0
  52. package/src/format/preparation-spec.ts +45 -0
  53. package/src/format/registeredJson.ts +2 -2
  54. package/src/format/runtime-tier.ts +14 -7
  55. package/src/format/save-revision.ts +105 -0
  56. package/src/format/schema-source.ts +70 -0
  57. package/src/format/sections.ts +4 -1
  58. package/src/format/server-plan.ts +42 -0
  59. package/src/format/server-reads.ts +23 -0
  60. package/src/format/shardSchema.ts +9 -4
  61. package/src/format/shardSections.ts +17 -7
  62. package/src/format/shardfile-assets.ts +5 -5
  63. package/src/format/shardfile-stream-admit.ts +19 -10
  64. package/src/format/shardfile-stream-facts.ts +2 -1
  65. package/src/format/shardfile-stream.ts +2 -3
  66. package/src/format/shardfileValidation.ts +16 -9
  67. package/src/format/species-deprecations.ts +79 -0
  68. package/src/format/stateLineage.ts +15 -7
  69. package/src/format/tread-boxes.ts +65 -0
  70. package/src/format/vehicle-hulls.ts +124 -0
  71. package/src/format/version.ts +96 -10
  72. package/src/format/whole-inputs.ts +51 -0
  73. package/src/tools/runtime-hosts.json +4 -0
package/src/cli/corpus.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { createWriteStream } from 'node:fs'
2
- import { mkdir, open, readFile, rm, writeFile } from 'node:fs/promises'
2
+ import { mkdir, readFile, rm, writeFile } from 'node:fs/promises'
3
3
  import path from 'node:path'
4
4
  import { Readable } from 'node:stream'
5
5
  import { pipeline } from 'node:stream/promises'
@@ -16,8 +16,13 @@ import {
16
16
  string,
17
17
  } from 'valibot'
18
18
 
19
- import { deprecationLines, storedDeprecations } from './corpus-deprecations.ts'
19
+ import { candidateField, onlyNamed } from './corpus-candidate.ts'
20
+ import { storedDeprecations } from './corpus-deprecations.ts'
21
+ import { withPins } from './corpus-pins.ts'
22
+ import { firstBytes, isPlainTar } from './corpus-tar.ts'
20
23
 
24
+ import type { Candidate } from './corpus-candidate.ts'
25
+ import type { Pin } from './corpus-pins.ts'
21
26
  import type { InferOutput } from 'valibot'
22
27
 
23
28
  // `shard-format corpus` (meta SHARD-COMPAT FE3, J486 Q47 Q52): run this
@@ -61,12 +66,17 @@ interface CorpusRow {
61
66
  readonly reason: string | undefined
62
67
  readonly cached: boolean
63
68
  readonly deprecations: readonly string[]
69
+ /** FE13: engine pins this original. */
70
+ readonly pinned?: true
71
+ /** FE3b: the candidate's verdict, when one runs. */
72
+ readonly candidate?: string
64
73
  }
65
74
 
66
75
  type Judgement = Readonly<{
67
76
  verdict: 'valid' | 'fails'
68
77
  reason?: string
69
78
  deprecations?: readonly string[]
79
+ candidate?: string
70
80
  transient: boolean
71
81
  }>
72
82
 
@@ -75,12 +85,15 @@ interface CorpusOptions {
75
85
  readonly cache: string
76
86
  readonly validator: string
77
87
  readonly fetch?: typeof fetch
88
+ /** FE13: engine's shard-file pins, judged with the kept originals. */
89
+ readonly pins?: readonly Pin[]
90
+ /** FE3b: a candidate chain and validator judged beside the current one; every original is fetched again. */
91
+ readonly candidate?: Candidate
92
+ /** Only these shards' originals (`slug`, or one revision as `slug@r5`): a candidate run over the shards it targets. */
93
+ readonly only?: readonly string[]
78
94
  }
79
95
 
80
96
  const NONE = 0
81
- const TAR_MAGIC_AT = 257
82
- const TAR_MAGIC = 'ustar'
83
- const PEEK_BYTES = 512
84
97
  const FETCH_TIMEOUT_MS = 900_000
85
98
  /** One original is at most a few hundred MB; a download that takes longer has stalled. */
86
99
  const DOWNLOAD_TIMEOUT_MS = 180_000
@@ -88,8 +101,6 @@ const DOWNLOAD_TRIES = 3
88
101
  const FIRST_TRY = 1
89
102
  const OK_LOW = 200
90
103
  const OK_HIGH = 300
91
- const SHORT_HASH = 12
92
- const VERDICT_WIDTH = 5
93
104
  const FIRST = 0
94
105
 
95
106
  function shortReason(error: unknown): string {
@@ -101,14 +112,6 @@ function shortReason(error: unknown): string {
101
112
  return `${code}${text}`.split('\n')[FIRST] ?? text
102
113
  }
103
114
 
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
115
  /** Downloads one original to `file`: the validator reads it twice, so it is fetched once and read from disk. */
113
116
  async function download(
114
117
  options: Readonly<CorpusOptions>,
@@ -129,18 +132,6 @@ async function download(
129
132
  await pipeline(Readable.fromWeb(response.body), createWriteStream(file))
130
133
  }
131
134
 
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
135
  /** A download, tried again when it stalls or drops; the last error is thrown. */
145
136
  async function downloadWithRetries(
146
137
  options: Readonly<CorpusOptions>,
@@ -181,8 +172,12 @@ async function judge(
181
172
  }
182
173
  }
183
174
  const plain = isPlainTar(await firstBytes(file))
184
- const stored = await storedDeprecations(file, plain)
185
- return { verdict: 'valid', ...stored, transient: false }
175
+ return {
176
+ verdict: 'valid',
177
+ ...(await storedDeprecations(file, plain)),
178
+ ...(await candidateField(options.candidate, file, plain)),
179
+ transient: false,
180
+ }
186
181
  } catch (error: unknown) {
187
182
  return { verdict: 'fails', reason: shortReason(error), transient: false }
188
183
  } finally {
@@ -199,10 +194,12 @@ async function cachedVerdict(
199
194
  await readFile(path.join(options.cache, `${hash}.json`), 'utf8'),
200
195
  )
201
196
  const cached = parse(CachedSchema, raw)
197
+ // FE3b: a candidate run judges every original again.
202
198
  // A valid verdict cached before FE7 has no deprecation list: judge it again.
203
199
  const stale =
204
200
  cached.verdict === 'valid' && cached.deprecations === undefined
205
- return cached.validator === options.validator && !stale ? cached : undefined
201
+ const fresh = cached.validator === options.validator && !stale
202
+ return fresh && options.candidate === undefined ? cached : undefined
206
203
  } catch {
207
204
  return undefined
208
205
  }
@@ -246,55 +243,40 @@ async function row(
246
243
  }
247
244
  }
248
245
 
249
- /** Every kept original's verdict, in the API's upload order. */
250
- async function runCorpus(
246
+ /** The API's public list of kept originals. */
247
+ async function listKept(
251
248
  options: Readonly<CorpusOptions>,
252
- ): Promise<CorpusRow[]> {
249
+ ): Promise<readonly StoredRecord[]> {
253
250
  const listed = await (options.fetch ?? fetch)(
254
251
  new URL('/api/shardfiles', options.api),
255
- {
256
- signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
257
- },
252
+ { signal: AbortSignal.timeout(FETCH_TIMEOUT_MS) },
258
253
  )
259
254
  if (listed.status < OK_LOW || listed.status >= OK_HIGH) {
260
255
  throw new Error(`list: HTTP ${String(listed.status)}`)
261
256
  }
262
- const { shardfiles } = parse(ListSchema, await listed.json())
257
+ return parse(ListSchema, await listed.json()).shardfiles
258
+ }
259
+
260
+ /** Every kept original's verdict, in the API's upload order, then engine's pins the list leaves out (FE13). */
261
+ async function runCorpus(
262
+ options: Readonly<CorpusOptions>,
263
+ ): Promise<CorpusRow[]> {
264
+ const kept = await listKept(options)
265
+ const shardfiles = kept.filter((stored: StoredRecord): boolean =>
266
+ onlyNamed(options.only, stored.revisions),
267
+ )
268
+ const pins = options.pins ?? []
269
+ const pinned = new Set(pins.map((pin: Readonly<Pin>): string => pin.hash))
263
270
  const rows: CorpusRow[] = []
264
- for (const stored of shardfiles) {
271
+ for (const stored of withPins(shardfiles, pins)) {
265
272
  // oxlint-disable-next-line eslint/no-await-in-loop -- one original at a time keeps memory bounded
266
- rows.push(await row(options, stored))
273
+ const found = await row(options, stored)
274
+ rows.push(pinned.has(stored.hash) ? { ...found, pinned: true } : found)
267
275
  }
268
276
  return rows
269
277
  }
270
278
 
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
- }
279
+ export { type CorpusOptions, type CorpusRow, type StoredRecord, runCorpus }
293
280
 
294
- export {
295
- type CorpusOptions,
296
- type CorpusRow,
297
- corpusReport,
298
- isPlainTar,
299
- runCorpus,
300
- }
281
+ export { corpusReport } from './corpus-report.ts'
282
+ export { isPlainTar } from './corpus-tar.ts'
@@ -0,0 +1,89 @@
1
+ import type { Json } from './format-diff-lock.ts'
2
+ import type { DataRow } from './format-diff-normal.ts'
3
+
4
+ // SHARD-COMPAT FE2: the findings type, and how a plain data row (an option
5
+ // list, a limit constant, a table) is classified. Schema rows:
6
+ // format-diff-rules.ts.
7
+
8
+ type ChangeKind = 'additive' | 'breaking' | 'deprecation' | 'review'
9
+ type MigrationOp =
10
+ | 'drop'
11
+ | 'fill'
12
+ | 'map'
13
+ | 'moveSection'
14
+ | 'rename'
15
+ | 'renameKind'
16
+
17
+ interface Finding {
18
+ readonly kind: ChangeKind
19
+ readonly what: string
20
+ readonly op?: MigrationOp
21
+ }
22
+
23
+ interface Change extends Finding {
24
+ readonly path: string
25
+ readonly rename?: { readonly from: string; readonly to: string }
26
+ }
27
+
28
+ const RAISE_NAME = /(?:max|limit|cap|budget|ceiling)[^.#]*$/iu
29
+ const FLOOR_NAME = /(?:min|floor)[^.#]*$/iu
30
+ const NONE = 0
31
+ const NEXT = 1
32
+
33
+ function finding(kind: ChangeKind, what: string, op?: MigrationOp): Finding {
34
+ return op === undefined ? { kind, what } : { kind, what, op }
35
+ }
36
+
37
+ /** A limit's move: up widens a ceiling, down widens a floor. */
38
+ function directed(widens: boolean, what: string): Finding {
39
+ return finding(widens ? 'additive' : 'breaking', what)
40
+ }
41
+
42
+ /** Members added only widen; any removed is a break (an old file may hold it). */
43
+ function setFinding(
44
+ what: string,
45
+ before: readonly Json[],
46
+ after: readonly Json[],
47
+ ): Finding {
48
+ const was = new Set(before.map((item: Json): string => JSON.stringify(item)))
49
+ const now = new Set(after.map((item: Json): string => JSON.stringify(item)))
50
+ const gone = [...was].filter((item: string): boolean => !now.has(item))
51
+ const added = [...now].filter((item: string): boolean => !was.has(item))
52
+ if (gone.length > NONE) {
53
+ return finding('breaking', `${what} removes ${gone.join(', ')}`, 'map')
54
+ }
55
+ return added.length > NONE
56
+ ? finding('additive', `${what} adds ${added.join(', ')}`)
57
+ : finding('review', `${what} reordered`)
58
+ }
59
+
60
+ /** A number constant by its name: a ceiling, a floor, or for review. */
61
+ function numberFinding(name: string, before: number, after: number): Finding {
62
+ const moved = `${name} ${String(before)} -> ${String(after)}`
63
+ if (RAISE_NAME.test(name)) {
64
+ return directed(after > before, moved)
65
+ }
66
+ if (FLOOR_NAME.test(name)) {
67
+ return directed(after < before, moved)
68
+ }
69
+ return finding('review', moved)
70
+ }
71
+
72
+ /** A plain data row: option lists by membership, named limits by direction, the rest for review. */
73
+ function dataFinding(path: string, before: DataRow, after: DataRow): Finding {
74
+ const name = path.slice(path.lastIndexOf('#') + NEXT)
75
+ if (Array.isArray(before.value) && Array.isArray(after.value)) {
76
+ return setFinding(
77
+ path.endsWith('|') ? 'options' : 'list',
78
+ before.value,
79
+ after.value,
80
+ )
81
+ }
82
+ if (typeof before.value === 'number' && typeof after.value === 'number') {
83
+ return numberFinding(name, before.value, after.value)
84
+ }
85
+ return finding('review', `${name} value changed`)
86
+ }
87
+
88
+ export { dataFinding, directed, finding, setFinding }
89
+ export type { Change, ChangeKind, Finding, MigrationOp }
@@ -0,0 +1,122 @@
1
+ import { execFile } from 'node:child_process'
2
+ import { mkdir, readdir, readFile, rm, stat } from 'node:fs/promises'
3
+ import path from 'node:path'
4
+ import { promisify } from 'node:util'
5
+
6
+ // SHARD-COMPAT FE2: read a format lock (FE1) from a folder or a git ref.
7
+ // A lock is `src/format/lock/`: `index.json` (chain id, exclusions) and one
8
+ // `<subpath>.json` of rows per package subpath.
9
+
10
+ type Json =
11
+ | boolean
12
+ | number
13
+ | string
14
+ | null
15
+ | readonly Json[]
16
+ | { readonly [key: string]: Json }
17
+
18
+ interface LockData {
19
+ readonly chainId: string
20
+ readonly rows: Readonly<Record<string, Json>>
21
+ readonly excluded: Readonly<Record<string, string>>
22
+ }
23
+
24
+ // eslint-disable-next-line typescript/strict-void-return -- Node execFile returns a child while its callback supplies the result.
25
+ const run = promisify(execFile)
26
+ const LOCK_FOLDER = 'src/format/lock'
27
+ const INDEX = 'index.json'
28
+ const MAX_OUTPUT = 268_435_456
29
+ const SAFE_REF = /[^A-Za-z0-9._-]/gu
30
+
31
+ function isRecord(value: unknown): value is Readonly<Record<string, unknown>> {
32
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
33
+ }
34
+
35
+ function assemble(
36
+ names: readonly string[],
37
+ parsed: readonly unknown[],
38
+ root: string,
39
+ ): LockData {
40
+ const index = parsed[names.indexOf(INDEX)]
41
+ if (!isRecord(index) || typeof index['chainId'] !== 'string') {
42
+ throw new Error(`${root}: no format lock (no ${INDEX} with a chainId)`)
43
+ }
44
+ const rows: Record<string, Json> = {}
45
+ for (const [at, body] of parsed.entries()) {
46
+ if (names[at] !== INDEX && isRecord(body)) {
47
+ Object.assign(rows, body)
48
+ }
49
+ }
50
+ const excluded = isRecord(index['excluded']) ? index['excluded'] : {}
51
+ return {
52
+ chainId: index['chainId'],
53
+ rows,
54
+ excluded: Object.fromEntries(
55
+ Object.entries(excluded).map(
56
+ ([key, why]: readonly [string, unknown]): readonly [string, string] => [
57
+ key,
58
+ String(why),
59
+ ],
60
+ ),
61
+ ),
62
+ }
63
+ }
64
+
65
+ /** The lock in one folder (the lock folder itself, or a checkout holding src/format/lock). */
66
+ async function readLockFolder(folder: string): Promise<LockData> {
67
+ const inner = path.join(folder, LOCK_FOLDER)
68
+ const found = await stat(inner).catch((): undefined => undefined)
69
+ const root = found?.isDirectory() === true ? inner : folder
70
+ const listed = await readdir(root)
71
+ const names = listed.filter((name: string): boolean => name.endsWith('.json'))
72
+ const parsed = await Promise.all(
73
+ names.map(async (name: string): Promise<unknown> => {
74
+ const body = await readFile(path.join(root, name), 'utf8')
75
+ return JSON.parse(body)
76
+ }),
77
+ )
78
+ return assemble(names, parsed, root)
79
+ }
80
+
81
+ /** The lock at a git ref, extracted under ./tmp/format-diff/<ref>. */
82
+ async function readLockRef(ref: string, cwd: string): Promise<LockData> {
83
+ const out = path.join(cwd, 'tmp/format-diff', ref.replaceAll(SAFE_REF, '_'))
84
+ await rm(out, { recursive: true, force: true })
85
+ await mkdir(out, { recursive: true })
86
+ const { stdout } = await run(
87
+ 'git',
88
+ ['ls-tree', '-r', '--name-only', ref, '--', `${LOCK_FOLDER}/`],
89
+ { cwd, encoding: 'utf8', maxBuffer: MAX_OUTPUT },
90
+ )
91
+ if (stdout.trim() === '') {
92
+ throw new Error(
93
+ `${ref} has no format lock (FE1 landed after 0.69.2): build one with \`pnpm lock:write\` in a checkout of it and pass that folder`,
94
+ )
95
+ }
96
+ await run(
97
+ 'sh',
98
+ [
99
+ '-c',
100
+ 'git archive "$1" "$2" | tar -x -C "$3"',
101
+ 'sh',
102
+ ref,
103
+ LOCK_FOLDER,
104
+ out,
105
+ ],
106
+ { cwd, maxBuffer: MAX_OUTPUT },
107
+ )
108
+ return await readLockFolder(out)
109
+ }
110
+
111
+ /** A lock from a folder when one exists at that path, else from a git ref in cwd. */
112
+ async function readLock(where: string, cwd: string): Promise<LockData> {
113
+ const found = await stat(path.resolve(cwd, where)).catch(
114
+ (): undefined => undefined,
115
+ )
116
+ return found?.isDirectory() === true
117
+ ? await readLockFolder(path.resolve(cwd, where))
118
+ : await readLockRef(where, cwd)
119
+ }
120
+
121
+ export { isRecord, readLock, readLockFolder }
122
+ export type { Json, LockData }