@wildshard/dev 0.0.0 → 0.4.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 (139) hide show
  1. package/bin/wildshard.mjs +75 -0
  2. package/lint/host-callbacks.d.mts +6 -0
  3. package/lint/host-callbacks.mjs +123 -0
  4. package/lint/ratchet.json +3 -0
  5. package/package.json +95 -4
  6. package/scripts/audit-assets.d.mts +10 -0
  7. package/scripts/audit-assets.mjs +151 -0
  8. package/scripts/bake/coatFiles.d.mts +6 -0
  9. package/scripts/bake/coatFiles.mjs +37 -0
  10. package/scripts/bake/navmeshGround.ts +22 -0
  11. package/scripts/bake/near-placeholder.mjs +331 -0
  12. package/scripts/bake/viewmodelBytes.ts +26 -0
  13. package/scripts/bake/viewmodelPage.ts +11 -0
  14. package/scripts/bake-catalogue.mjs +44 -0
  15. package/scripts/bake-check.mjs +54 -0
  16. package/scripts/bake-chunk.mjs +124 -0
  17. package/scripts/bake-cloud-field.mjs +24 -0
  18. package/scripts/bake-coats.mjs +110 -0
  19. package/scripts/bake-data-maps.d.mts +24 -0
  20. package/scripts/bake-data-maps.mjs +78 -0
  21. package/scripts/bake-entry-programs.mjs +126 -0
  22. package/scripts/bake-geometry.mjs +106 -0
  23. package/scripts/bake-ktx2.mjs +477 -0
  24. package/scripts/bake-map-glb.mjs +127 -0
  25. package/scripts/bake-map-rest.d.mts +7 -0
  26. package/scripts/bake-map-rest.mjs +50 -0
  27. package/scripts/bake-maps.mjs +200 -0
  28. package/scripts/bake-navmesh.mjs +259 -0
  29. package/scripts/bake-packs.mjs +129 -0
  30. package/scripts/bake-pickups.mjs +102 -0
  31. package/scripts/bake-query-terrain.mjs +64 -0
  32. package/scripts/bake-textures.mjs +80 -0
  33. package/scripts/bake-viewmodel-sets.mjs +137 -0
  34. package/scripts/bake-voxel-ao.mjs +119 -0
  35. package/scripts/bake-water-ripples.mjs +25 -0
  36. package/scripts/browser-imports.d.mts +2 -0
  37. package/scripts/browser-imports.mjs +40 -0
  38. package/scripts/browser-machine-loader-proof.mjs +39 -0
  39. package/scripts/browser-machine-loader.d.mts +8 -0
  40. package/scripts/browser-machine-loader.mjs +87 -0
  41. package/scripts/browser-playwright.d.mts +10 -0
  42. package/scripts/browser-playwright.mjs +5 -0
  43. package/scripts/browser-test.d.mts +4 -0
  44. package/scripts/browser-test.mjs +18 -0
  45. package/scripts/build-sdk.mjs +95 -0
  46. package/scripts/build-shardfiles.d.mts +7 -0
  47. package/scripts/build-shardfiles.mjs +230 -0
  48. package/scripts/capture-hero.mjs +211 -0
  49. package/scripts/chromium-keychain.d.mts +1 -0
  50. package/scripts/chromium-keychain.mjs +7 -0
  51. package/scripts/entry-reads/crawl.ts +152 -0
  52. package/scripts/gen-host-catalogue.d.mts +14 -0
  53. package/scripts/gen-host-catalogue.mjs +108 -0
  54. package/scripts/gen-shards.d.mts +17 -0
  55. package/scripts/gen-shards.mjs +311 -0
  56. package/scripts/goldens/plot-inputs.d.mts +12 -0
  57. package/scripts/goldens/plot-inputs.mjs +46 -0
  58. package/scripts/gpu-texmem.mjs +98 -0
  59. package/scripts/ktx2-ab.mjs +111 -0
  60. package/scripts/map-bake-frames.d.mts +4 -0
  61. package/scripts/map-bake-frames.mjs +23 -0
  62. package/scripts/map-world.mjs +162 -0
  63. package/scripts/memory-product.mjs +62 -0
  64. package/scripts/music/export-midi.mjs +69 -0
  65. package/scripts/named-blob-output.d.mts +8 -0
  66. package/scripts/named-blob-output.mjs +48 -0
  67. package/scripts/practice/verify_unimate_skin.mjs +356 -0
  68. package/scripts/preparation-browser.mjs +25 -0
  69. package/scripts/preparation-seed.mjs +15 -0
  70. package/scripts/prepare-product.d.mts +14 -0
  71. package/scripts/prepare-product.mjs +133 -0
  72. package/scripts/prove-walk.mjs +83 -0
  73. package/scripts/push-tables.d.mts +1 -0
  74. package/scripts/push-tables.mjs +28 -0
  75. package/scripts/record-shard-mounts.mjs +133 -0
  76. package/scripts/section-inventory.ts +209 -0
  77. package/scripts/shard-build-pool.d.mts +4 -0
  78. package/scripts/shard-build-pool.mjs +53 -0
  79. package/scripts/shard-milestones.d.mts +15 -0
  80. package/scripts/shard-milestones.mjs +105 -0
  81. package/scripts/shard-progress.mjs +212 -0
  82. package/scripts/shardfile-cold-boot.mjs +79 -0
  83. package/scripts/shardfile-rolldown.d.mts +2 -0
  84. package/scripts/shardfile-rolldown.mjs +32 -0
  85. package/scripts/shardfile-vite.d.mts +4 -0
  86. package/scripts/shardfile-vite.mjs +20 -0
  87. package/scripts/site-facts.mjs +88 -0
  88. package/scripts/test-template-gate.mjs +44 -0
  89. package/scripts/tex-tiers.mjs +240 -0
  90. package/scripts/unused-assets.mjs +173 -0
  91. package/scripts/wildshard.d.mts +4 -0
  92. package/scripts/wildshard.mjs +146 -0
  93. package/scripts/witness-generation.d.mts +10 -0
  94. package/scripts/witness-generation.mjs +45 -0
  95. package/src/.oxlintrc.json +12 -0
  96. package/src/cli/bin.mjs +8 -0
  97. package/src/cli/content-command.ts +44 -0
  98. package/src/cli/content.ts +287 -0
  99. package/src/cli/grid/command.ts +48 -0
  100. package/src/cli/grid/grid.ts +155 -0
  101. package/src/cli/help.ts +262 -0
  102. package/src/cli/hero/adopt.ts +109 -0
  103. package/src/cli/install-home.ts +40 -0
  104. package/src/cli/main.ts +142 -0
  105. package/src/cli/version.ts +63 -0
  106. package/src/server/app.ts +19 -0
  107. package/src/server/serve.ts +49 -0
  108. package/src/sharddev/bake/json.mjs +84 -0
  109. package/src/sharddev/bake/mapRest.ts +57 -0
  110. package/src/sharddev/bake/nativeRaster.ts +106 -0
  111. package/src/sharddev/bake/source-loader.mjs +55 -0
  112. package/src/sharddev/bake/splatLayers.ts +29 -0
  113. package/src/sharddev/bootInventory.ts +132 -0
  114. package/src/sharddev/check.ts +125 -0
  115. package/src/sharddev/checkProject.ts +134 -0
  116. package/src/sharddev/cli.ts +207 -0
  117. package/src/sharddev/dev.ts +150 -0
  118. package/src/sharddev/devClient.ts +120 -0
  119. package/src/sharddev/devRoot.ts +6 -0
  120. package/src/sharddev/engineMusic.ts +23 -0
  121. package/src/sharddev/projectEntryProof.ts +32 -0
  122. package/src/sharddev/test/diskScriptScenario.ts +88 -0
  123. package/src/sharddev/test/scriptScenario.ts +254 -0
  124. package/src/sharddev/tsconfig.json +3 -0
  125. package/src/sharddev/watch/page.ts +288 -0
  126. package/src/sharddev/watch/pageEntry.ts +44 -0
  127. package/src/sharddev/watch/parity-baseline.json +22 -0
  128. package/src/sharddev/watch/parity.mjs +194 -0
  129. package/src/sharddev/watch/proof.mjs +199 -0
  130. package/src/sharddev/watch/socket.ts +57 -0
  131. package/src/sharddev/watch/watch.ts +382 -0
  132. package/src/shared/health.ts +10 -0
  133. package/src/tools/build-web.ts +59 -0
  134. package/src/web/app.tsx +53 -0
  135. package/src/web/index.html +12 -0
  136. package/src/web/main.tsx +10 -0
  137. package/tsconfig.author.json +25 -0
  138. package/tsconfig.json +47 -0
  139. package/README.md +0 -3
@@ -0,0 +1,356 @@
1
+ /** E336: evaluate the original skins against every baked UniMate frame without rendering.
2
+ * Usage: node scripts/practice/verify_unimate_skin.mjs [motion.glb] [report.json]
3
+ * Textures are replaced only in memory; real geometry, bind matrices and weights are loaded.
4
+ */
5
+ import { existsSync, readFileSync, writeFileSync } from 'node:fs';
6
+ import { createHash } from 'node:crypto';
7
+ import { execFileSync } from 'node:child_process';
8
+ import { registerHooks, stripTypeScriptTypes } from 'node:module';
9
+ import { fileURLToPath } from 'node:url';
10
+ import * as THREE from 'three';
11
+ import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js';
12
+ import { MeshoptDecoder } from 'meshoptimizer';
13
+ import { NodeIO } from '@gltf-transform/core';
14
+ import { ALL_EXTENSIONS } from '@gltf-transform/extensions';
15
+
16
+ const [motionPath = 'public/assets/practice/dummies/unimate-motion.glb',
17
+ reportPath = 'docs/audits/dummy-unimate-skin.json'] = process.argv.slice(2);
18
+ const previousReport = existsSync(reportPath) ? JSON.parse(readFileSync(reportPath, 'utf8')) : null;
19
+ const originalRevision = previousReport?.originalRevision ?? execFileSync('git', ['rev-parse', 'HEAD'], { encoding: 'utf8' }).trim();
20
+ const minRestTriangleArea = 1e-8;
21
+ // E388: no invented tolerance. A weight sum can only be off by its storage's rounding, half a quantum per weight (glTF
22
+ // stores WEIGHTS_0 as float32 or as normalized unsigned byte / short): for float32 4 × 2⁻²⁴ ≈ 2.4e-7, img2-character G4's 2e-7.
23
+ const weightSumTolerance = (array, normalized) => 4 * (normalized && !(array instanceof Float32Array) ? 0.5 / (2 ** (8 * array.BYTES_PER_ELEMENT) - 1) : 2 ** -24);
24
+ // The skin's deformation and the clips' joint speed are held to what the figure's shipped reactions already do: the
25
+ // existing hit springs alone, measured in this run on the same figure (springBaseline). The first take (stretch 3.7–5.1×,
26
+ // area down to 0.3 %) fails that bar; the approved bake passes it.
27
+ const firstTake = previousReport?.beforeSkinRepair ?? (previousReport?.variants?.every((v) => v.unchangedFromHEAD)
28
+ ? previousReport.variants.map((v) => ({ variant: v.variant, sourceSHA256: v.sha256, skins: v.skins,
29
+ clips: v.clips.map((c) => ({ name: c.name, maxEdgeStretch: c.maxEdgeStretch,
30
+ minTriangleAreaRatio: c.minTriangleAreaRatio, collapsedTriangleSamples: c.collapsedTriangleSamples,
31
+ worstStretch: c.worstStretch, worstCollapse: c.worstCollapse })), springComparison: v.springComparison })) : null);
32
+ // Exercise the same TypeScript springs and sampler as the arena, without copying their formulas.
33
+ registerHooks({
34
+ resolve(specifier, context, next) {
35
+ try { return next(specifier, context); }
36
+ catch (error) {
37
+ if (specifier.startsWith('.') && context.parentURL) return next(`${specifier}.ts`, context);
38
+ throw error;
39
+ }
40
+ },
41
+ load(url, context, next) {
42
+ if (url.endsWith('.ts')) return { format: 'module', shortCircuit: true,
43
+ source: stripTypeScriptTypes(readFileSync(fileURLToPath(url), 'utf8'), { mode: 'transform' }) };
44
+ return next(url, context);
45
+ },
46
+ });
47
+ const { DummyMotion, DummyPose } = await import('@wildshard/engine/practice/DummyMotion');
48
+ const { DummyClips } = await import('@wildshard/engine/practice/DummyClips');
49
+ const { DUMMY_BONE_NAMES } = await import('@wildshard/engine/practice/TrainingDummy');
50
+ const loader = new GLTFLoader().setMeshoptDecoder(MeshoptDecoder);
51
+ await MeshoptDecoder.ready;
52
+ const rawIO = new NodeIO().registerExtensions(ALL_EXTENSIONS).registerDependencies({ 'meshopt.decoder': MeshoptDecoder });
53
+ loader.register((parser) => {
54
+ parser.loadTextureImage = () => Promise.resolve(new THREE.DataTexture(new Uint8Array([255, 255, 255, 255]), 1, 1));
55
+ return { name: 'HEADLESS_TEXTURE_SUBSTITUTE' };
56
+ });
57
+ const load = (path) => {
58
+ const data = readFileSync(path);
59
+ return loader.parseAsync(data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength), '');
60
+ };
61
+ const sha = (path) => createHash('sha256').update(readFileSync(path)).digest('hex');
62
+ const fixedNames = new Set(['Root', 'LeftThigh', 'LeftShin', 'RightThigh', 'RightShin']);
63
+ const motions = await load(motionPath), rows = [];
64
+ const failures = [];
65
+ if (motions.animations.length !== 18) failures.push('Motion library must contain 18 clips');
66
+ const round = (value) => Number(value.toFixed(9));
67
+ const a = new THREE.Vector3(), b = new THREE.Vector3(), c = new THREE.Vector3();
68
+ const e1 = new THREE.Vector3(), e2 = new THREE.Vector3();
69
+ function positions(mesh) {
70
+ const out = new Float64Array(mesh.geometry.attributes.position.count * 3);
71
+ for (let i = 0; i < out.length / 3; i++) mesh.getVertexPosition(i, a).toArray(out, i * 3);
72
+ return out;
73
+ }
74
+ function triangleMeasure(values, triangle) {
75
+ a.fromArray(values, triangle[0] * 3); b.fromArray(values, triangle[1] * 3); c.fromArray(values, triangle[2] * 3);
76
+ const edges = [a.distanceTo(b), b.distanceTo(c), c.distanceTo(a)];
77
+ const area = e1.subVectors(b, a).cross(e2.subVectors(c, a)).length() * 0.5;
78
+ return { edges, area };
79
+ }
80
+ for (const [variant, filename] of [['wood', 'wood-wood'], ['straw-cloth', 'straw-cloth'], ['wood-steel', 'wood-steel']]) {
81
+ const source = `public/assets/practice/dummies/${filename}.glb`;
82
+ const gltf = await load(source), scene = gltf.scene;
83
+ scene.updateMatrixWorld(true);
84
+ const meshes = [];
85
+ scene.traverse((object) => { if (object.isSkinnedMesh) meshes.push(object); });
86
+ const clips = motions.animations.filter((clip) => clip.name.startsWith(`${variant}:`));
87
+ const row = { variant, source, sha256: sha(source), unchangedFromHEAD: false, skins: [], clips: [] };
88
+ const rawDocument = await rawIO.read(source);
89
+ row.rawSkinAttributes = [];
90
+ for (const node of rawDocument.getRoot().listNodes()) {
91
+ const skin = node.getSkin(), mesh = node.getMesh();
92
+ if (!skin || !mesh) continue;
93
+ for (const primitive of mesh.listPrimitives()) {
94
+ const weights = primitive.getAttribute('WEIGHTS_0'), indices = primitive.getAttribute('JOINTS_0');
95
+ if (!weights || !indices) throw new Error('Source skin attributes missing');
96
+ const weight = [], index = [];
97
+ let maxWeightSumError = 0, invalidWeights = 0, invalidIndices = 0;
98
+ for (let v = 0; v < weights.getCount(); v++) {
99
+ weights.getElement(v, weight); indices.getElement(v, index);
100
+ maxWeightSumError = Math.max(maxWeightSumError, Math.abs(weight.reduce((sum, w) => sum + w, 0) - 1));
101
+ for (let j = 0; j < 4; j++) {
102
+ if (!Number.isFinite(weight[j]) || weight[j] < 0) invalidWeights++;
103
+ if (weight[j] > 0 && (!Number.isInteger(index[j]) || index[j] < 0 || index[j] >= skin.listJoints().length)) invalidIndices++;
104
+ }
105
+ }
106
+ const tolerance = weightSumTolerance(weights.getArray(), weights.getNormalized());
107
+ row.rawSkinAttributes.push({ maxWeightSumError, tolerance, invalidWeights, invalidIndices });
108
+ if (maxWeightSumError > tolerance || invalidWeights || invalidIndices) failures.push(`${variant}: invalid raw source skin attributes`);
109
+ }
110
+ }
111
+ try {
112
+ const committed = execFileSync('git', ['show', `${originalRevision}:${source}`], { maxBuffer: 8 * 1024 * 1024 });
113
+ row.unchangedFromHEAD = createHash('sha256').update(committed).digest('hex') === row.sha256;
114
+ const original = await loader.parseAsync(committed.buffer.slice(committed.byteOffset, committed.byteOffset + committed.byteLength), '');
115
+ const oldMeshes = []; original.scene.traverse((object) => { if (object.isSkinnedMesh) oldMeshes.push(object); });
116
+ let maxPositionDelta = 0, maxBindMatrixDelta = 0, maxJointRestMatrixDelta = 0, sameIndices = true, sameOrientedTriangles = true, sameJointOrder = true;
117
+ if (oldMeshes.length !== meshes.length) throw new Error('Skin count changed');
118
+ for (let m = 0; m < meshes.length; m++) {
119
+ const old = oldMeshes[m], current = meshes[m];
120
+ const p = current.geometry.attributes.position, op = old.geometry.attributes.position;
121
+ if (p.count !== op.count) throw new Error('Vertex count changed');
122
+ for (let v = 0; v < p.count; v++) for (let axis = 0; axis < 3; axis++) maxPositionDelta = Math.max(maxPositionDelta, Math.abs(p.getComponent(v, axis) - op.getComponent(v, axis)));
123
+ const ix = current.geometry.index, oix = old.geometry.index;
124
+ sameIndices &&= ix?.count === oix?.count;
125
+ if (ix && oix) for (let v = 0; v < ix.count; v++) sameIndices &&= ix.getX(v) === oix.getX(v);
126
+ const canonical = (index, v) => {
127
+ const first = index.getX(v), second = index.getX(v + 1), third = index.getX(v + 2);
128
+ return [`${first},${second},${third}`, `${second},${third},${first}`, `${third},${first},${second}`].sort()[0];
129
+ };
130
+ sameOrientedTriangles &&= ix?.count === oix?.count;
131
+ if (ix && oix) for (let v = 0; v < ix.count; v += 3) sameOrientedTriangles &&= canonical(ix, v) === canonical(oix, v);
132
+ sameJointOrder &&= current.skeleton.bones.map((joint) => joint.name).join('|') === old.skeleton.bones.map((joint) => joint.name).join('|');
133
+ for (let j = 0; j < current.skeleton.bones.length; j++) {
134
+ const bone = current.skeleton.bones[j], ob = old.skeleton.bones[j]; bone.updateMatrix(); ob.updateMatrix();
135
+ for (let k = 0; k < 16; k++) {
136
+ maxJointRestMatrixDelta = Math.max(maxJointRestMatrixDelta, Math.abs(bone.matrix.elements[k] - ob.matrix.elements[k]));
137
+ maxBindMatrixDelta = Math.max(maxBindMatrixDelta, Math.abs(current.skeleton.boneInverses[j].elements[k] - old.skeleton.boneInverses[j].elements[k]));
138
+ }
139
+ }
140
+ }
141
+ row.originalGeometryParity = { maxPositionDelta, maxBindMatrixDelta, maxJointRestMatrixDelta, sameIndices, sameOrientedTriangles, sameJointOrder };
142
+ if (maxPositionDelta > 1e-7 || maxBindMatrixDelta > 1e-7 || maxJointRestMatrixDelta > 1e-7 || !sameOrientedTriangles || !sameJointOrder) failures.push(`${variant}: geometry/topology/bind changed from original HEAD`);
143
+ } catch { /* Standalone exports can lack git metadata; false is explicit. */ }
144
+ if (!row.originalGeometryParity) failures.push(`${variant}: original HEAD geometry could not be checked`);
145
+ const restBones = new Map();
146
+ for (const mesh of meshes) for (const bone of mesh.skeleton.bones) restBones.set(bone, bone.quaternion.clone());
147
+ const bind = meshes.map((mesh) => positions(mesh));
148
+ const triangles = meshes.map((mesh) => {
149
+ const count = mesh.geometry.index?.count ?? mesh.geometry.attributes.position.count;
150
+ return Array.from({ length: count / 3 }, (_, i) => [0, 1, 2].map((k) => mesh.geometry.index?.getX(i * 3 + k) ?? i * 3 + k));
151
+ });
152
+ const baseline = triangles.map((list, m) => list.map((triangle) => triangleMeasure(bind[m], triangle)));
153
+ for (const [m, mesh] of meshes.entries()) {
154
+ const p = mesh.geometry.attributes.position, w = mesh.geometry.attributes.skinWeight, ix = mesh.geometry.attributes.skinIndex;
155
+ let bindError = 0, weightError = 0, invalidWeights = 0, invalidIndices = 0;
156
+ for (let v = 0; v < p.count; v++) {
157
+ a.fromBufferAttribute(p, v); b.fromArray(bind[m], v * 3); bindError = Math.max(bindError, a.distanceTo(b));
158
+ let sum = 0;
159
+ for (let j = 0; j < 4; j++) {
160
+ const weight = w.getComponent(v, j), index = ix.getComponent(v, j); sum += weight;
161
+ if (!Number.isFinite(weight) || weight < 0) invalidWeights++;
162
+ if (weight > 0 && (!Number.isInteger(index) || index < 0 || index >= mesh.skeleton.bones.length)) invalidIndices++;
163
+ }
164
+ weightError = Math.max(weightError, Math.abs(sum - 1));
165
+ }
166
+ row.skins.push({ mesh: mesh.name, vertices: p.count, triangles: triangles[m].length,
167
+ jointOrder: mesh.skeleton.bones.map((bone) => bone.name), maxBindPositionError: round(bindError),
168
+ maxWeightSumError: round(weightError), invalidWeights, invalidIndices,
169
+ existingDegenerateTriangles: baseline[m].filter((t) => t.area < 1e-10).length,
170
+ existingNumericalSliverTriangles: baseline[m].filter((t) => t.area >= 1e-10 && t.area < minRestTriangleArea).length });
171
+ if (bindError > 1e-4 || weightError > weightSumTolerance(w.array, w.normalized) || invalidWeights || invalidIndices) failures.push(`${variant}: invalid bind or weights`);
172
+ }
173
+ const deformations = [];
174
+ for (const clip of clips) {
175
+ for (const [bone, rest] of restBones) bone.quaternion.copy(rest);
176
+ const mixer = new THREE.AnimationMixer(scene), action = mixer.clipAction(clip);
177
+ action.setLoop(THREE.LoopOnce, 1); action.clampWhenFinished = true; action.play();
178
+ let maxQuaternionError = 0, missingBindings = 0, forbiddenTracks = 0, finiteKeyframes = true,
179
+ maxKeyframeRotationStep = 0, maxKeyframeAngularSpeed = 0;
180
+ for (const track of clip.tracks) {
181
+ const name = track.name.replace(/\.quaternion$/, '');
182
+ if (!scene.getObjectByName(name)) missingBindings++;
183
+ if (!track.name.endsWith('.quaternion') || fixedNames.has(name)) forbiddenTracks++;
184
+ for (let i = 0; i < track.values.length; i += 4) {
185
+ const q = new THREE.Quaternion().fromArray(track.values, i);
186
+ finiteKeyframes &&= Number.isFinite(q.x) && Number.isFinite(q.y) && Number.isFinite(q.z) && Number.isFinite(q.w);
187
+ maxQuaternionError = Math.max(maxQuaternionError, Math.abs(q.length() - 1));
188
+ if (i >= 4) {
189
+ const angle = q.clone().normalize().angleTo(new THREE.Quaternion().fromArray(track.values, i - 4).normalize());
190
+ const dt = track.times[i / 4] - track.times[i / 4 - 1];
191
+ maxKeyframeRotationStep = Math.max(maxKeyframeRotationStep, angle);
192
+ maxKeyframeAngularSpeed = Math.max(maxKeyframeAngularSpeed, angle / dt);
193
+ }
194
+ }
195
+ }
196
+ let finite = true, maxEdgeStretch = 1, minAreaRatio = 1;
197
+ let maxFixedJointRotation = 0, seamPositionError = 0, maxDisplacement = 0, maxBaseDisplacement = 0;
198
+ let worstStretch, worstCollapse;
199
+ let firstPositions;
200
+ for (let frame = 0; frame <= 60; frame++) {
201
+ mixer.setTime(clip.duration * frame / 60);
202
+ scene.updateMatrixWorld(true);
203
+ for (const [bone, rest] of restBones) if (fixedNames.has(bone.name)) maxFixedJointRotation = Math.max(maxFixedJointRotation, bone.quaternion.clone().normalize().angleTo(rest.clone().normalize()));
204
+ const current = meshes.map((mesh) => positions(mesh));
205
+ if (frame === 0) firstPositions = current;
206
+ for (let m = 0; m < meshes.length; m++) {
207
+ const values = current[m];
208
+ for (let v = 0; v < values.length; v += 3) {
209
+ a.fromArray(values, v); b.fromArray(bind[m], v);
210
+ finite &&= Number.isFinite(a.x) && Number.isFinite(a.y) && Number.isFinite(a.z);
211
+ maxDisplacement = Math.max(maxDisplacement, a.distanceTo(b));
212
+ if (b.y < 0.2) maxBaseDisplacement = Math.max(maxBaseDisplacement, a.distanceTo(b));
213
+ if (frame === 60) { b.fromArray(firstPositions[m], v); seamPositionError = Math.max(seamPositionError, a.distanceTo(b)); }
214
+ }
215
+ for (let t = 0; t < triangles[m].length; t++) {
216
+ const base = baseline[m][t];
217
+ if (base.area < minRestTriangleArea) continue;
218
+ const sample = triangleMeasure(values, triangles[m][t]);
219
+ const ratio = sample.area / base.area;
220
+ const detail = () => ({ mesh: meshes[m].name, frame, indices: triangles[m][t], restArea: base.area,
221
+ vertices: triangles[m][t].map((v) => ({ position: Array.from(bind[m].slice(v * 3, v * 3 + 3)),
222
+ weights: [0, 1, 2, 3].map((j) => ({ bone: meshes[m].skeleton.bones[meshes[m].geometry.attributes.skinIndex.getComponent(v, j)]?.name,
223
+ weight: meshes[m].geometry.attributes.skinWeight.getComponent(v, j) })).filter((w) => w.weight > 0) })) });
224
+ if (ratio < minAreaRatio) worstCollapse = detail();
225
+ minAreaRatio = Math.min(minAreaRatio, ratio);
226
+ for (let e = 0; e < 3; e++) if (base.edges[e] > 1e-7) {
227
+ const stretch = sample.edges[e] / base.edges[e];
228
+ if (stretch > maxEdgeStretch) worstStretch = { ...detail(), edge: e, restEdgeLength: base.edges[e] };
229
+ maxEdgeStretch = Math.max(maxEdgeStretch, stretch);
230
+ }
231
+ }
232
+ }
233
+ }
234
+ // An arena yaw and uniform game scale must transform skinned positions rigidly.
235
+ mixer.setTime(clip.duration * 0.5); scene.updateMatrixWorld(true);
236
+ const beforeYaw = meshes.map((mesh) => positions(mesh));
237
+ scene.rotation.y = Math.PI / 2; scene.scale.setScalar(1.8 / 2.65); scene.updateMatrixWorld(true);
238
+ let yawLocalError = 0;
239
+ for (let m = 0; m < meshes.length; m++) {
240
+ const afterYaw = positions(meshes[m]);
241
+ for (let i = 0; i < afterYaw.length; i++) yawLocalError = Math.max(yawLocalError, Math.abs(afterYaw[i] - beforeYaw[m][i]));
242
+ }
243
+ scene.rotation.y = 0; scene.scale.setScalar(1); scene.updateMatrixWorld(true);
244
+ mixer.stopAllAction(); mixer.uncacheRoot(scene);
245
+ const measured = { name: clip.name, durationSeconds: clip.duration, samples: 61, tracks: clip.tracks.length,
246
+ finite, finiteKeyframes, missingBindings, forbiddenTracks, maxQuaternionLengthError: round(maxQuaternionError),
247
+ maxKeyframeRotationStepDegrees: round(maxKeyframeRotationStep * 180 / Math.PI),
248
+ maxKeyframeAngularSpeedDegreesPerSecond: round(maxKeyframeAngularSpeed * 180 / Math.PI),
249
+ maxFixedJointRotationRadians: round(maxFixedJointRotation), seamPositionError: round(seamPositionError),
250
+ maxVertexDisplacement: round(maxDisplacement), maxBaseDisplacement: round(maxBaseDisplacement), maxEdgeStretch: round(maxEdgeStretch),
251
+ minTriangleAreaRatio: round(minAreaRatio),
252
+ maxYawScaleLocalPositionError: round(yawLocalError), worstStretch, worstCollapse };
253
+ row.clips.push(measured);
254
+ deformations.push({ name: clip.name, maxEdgeStretch, minAreaRatio, speed: maxKeyframeAngularSpeed * 180 / Math.PI });
255
+ if (!finite || !finiteKeyframes || missingBindings || forbiddenTracks || maxQuaternionError > 1e-5 || maxFixedJointRotation > 1e-5 ||
256
+ seamPositionError > 1e-4 || maxBaseDisplacement > 1e-4 || yawLocalError > 1e-5) failures.push(`${clip.name}: numerical gate failed`);
257
+ console.log(variant, clip.name, `stretch ${maxEdgeStretch.toFixed(4)}, minimum area ${minAreaRatio.toFixed(4)}, displacement ${maxDisplacement.toFixed(4)}`);
258
+ }
259
+ row.springComparison = [];
260
+ const joints = Object.fromEntries(Object.entries(DUMMY_BONE_NAMES).map(([logical, name]) => [logical, scene.getObjectByName(name)]));
261
+ const mass = variant === 'straw-cloth' ? 0.8 : variant === 'wood-steel' ? 1.3 : 1;
262
+ const gain = 0.2;
263
+ for (const scenario of [
264
+ { name: 'light-sword', amount: 12, py: 1.2, headshot: false, stagger: 0, clip: 'body-hit' },
265
+ { name: 'charged-sword', amount: 24, py: 1.2, headshot: false, stagger: 1, clip: 'heavy-hit' },
266
+ { name: 'body-bolt', amount: 38, py: 1.05, headshot: false, stagger: null, clip: 'body-hit' },
267
+ { name: 'head-bolt', amount: 83, py: 1.58, headshot: true, stagger: null, clip: 'head-hit' },
268
+ ]) {
269
+ const result = { scenario: scenario.name, mass, samples: 61 };
270
+ for (const combined of [false, true]) {
271
+ for (const [bone, rest] of restBones) bone.quaternion.copy(rest);
272
+ scene.updateMatrixWorld(true);
273
+ const pose = new DummyPose(scene, joints), motion = new DummyMotion(1);
274
+ motion.leftSign = DummyPose.leftSign(scene, joints);
275
+ const controller = combined ? new DummyClips(scene, clips, variant) : null;
276
+ for (let frame = 0; frame < 120; frame++) {
277
+ motion.update(1 / 60); controller?.update(1 / 60); pose.apply(motion, combined, combined ? gain : 1);
278
+ }
279
+ const weight = Math.min(3, Math.max(0.3, scenario.amount / 25)) / mass;
280
+ motion.hit({ px: 0.05, py: scenario.py, pz: 0.3, dx: 0.3, dz: -0.95, weight, headshot: scenario.headshot });
281
+ if (scenario.stagger !== null) motion.shove(scenario.py, 0.5, -0.85, scenario.stagger, mass);
282
+ controller?.hit(scenario.headshot ? 'head-hit' : 'body-hit', scenario.amount / 25, mass);
283
+ if (scenario.stagger !== null && scenario.stagger >= 0.7) controller?.hit('heavy-hit', 1 + scenario.stagger, mass);
284
+ let maxEdgeStretch = 1, minAreaRatio = 1, finite = true, worstStretch, worstCollapse, maxBaseDisplacement = 0, maxJointSpeed = 0;
285
+ const previousPose = new Map();
286
+ for (let frame = 0; frame <= 120; frame++) {
287
+ if (frame > 0) motion.update(1 / 60);
288
+ controller?.update(frame > 0 ? 1 / 60 : 0);
289
+ pose.apply(motion, combined, combined ? gain : 1);
290
+ for (const bone of restBones.keys()) {
291
+ const before = previousPose.get(bone);
292
+ if (before) maxJointSpeed = Math.max(maxJointSpeed, before.angleTo(bone.quaternion) * 60);
293
+ previousPose.set(bone, bone.quaternion.clone());
294
+ }
295
+ if (frame % 2 !== 0) continue;
296
+ scene.updateMatrixWorld(true);
297
+ for (let m = 0; m < meshes.length; m++) {
298
+ const values = positions(meshes[m]);
299
+ finite &&= values.every(Number.isFinite);
300
+ for (let v = 0; v < values.length; v += 3) if (bind[m][v + 1] < 0.2) {
301
+ a.fromArray(values, v); b.fromArray(bind[m], v);
302
+ maxBaseDisplacement = Math.max(maxBaseDisplacement, a.distanceTo(b));
303
+ }
304
+ for (let t = 0; t < triangles[m].length; t++) {
305
+ const base = baseline[m][t];
306
+ if (base.area < minRestTriangleArea) continue;
307
+ const sample = triangleMeasure(values, triangles[m][t]), ratio = sample.area / base.area;
308
+ const detail = () => ({ frame, indices: triangles[m][t], restArea: base.area,
309
+ vertices: triangles[m][t].map((v) => ({ position: Array.from(bind[m].slice(v * 3, v * 3 + 3)),
310
+ weights: [0, 1, 2, 3].map((j) => ({ bone: meshes[m].skeleton.bones[meshes[m].geometry.attributes.skinIndex.getComponent(v, j)]?.name,
311
+ weight: meshes[m].geometry.attributes.skinWeight.getComponent(v, j) })).filter((w) => w.weight > 0) })) });
312
+ if (ratio < minAreaRatio) worstCollapse = detail();
313
+ minAreaRatio = Math.min(minAreaRatio, ratio);
314
+ for (let e = 0; e < 3; e++) if (base.edges[e] > 1e-7) {
315
+ const stretch = sample.edges[e] / base.edges[e];
316
+ if (stretch > maxEdgeStretch) worstStretch = { ...detail(), edge: e, restEdgeLength: base.edges[e] };
317
+ maxEdgeStretch = Math.max(maxEdgeStretch, stretch);
318
+ }
319
+ }
320
+ }
321
+ }
322
+ result[combined ? 'clipsPlusSprings' : 'existingSpringsOnly'] = { finite,
323
+ gain: combined ? gain : 1, maxEdgeStretch: round(maxEdgeStretch), minTriangleAreaRatio: round(minAreaRatio),
324
+ maxJointSpeedDegreesPerSecond: round(maxJointSpeed * 180 / Math.PI), maxBaseDisplacement: round(maxBaseDisplacement),
325
+ worstStretch, worstCollapse };
326
+ if (combined && (!finite || maxBaseDisplacement > 1e-4)) failures.push(`${variant}:${scenario.name}: combined runtime skin gate failed`);
327
+ if (combined) deformations.push({ name: `${variant}:${scenario.name} clips + springs`, maxEdgeStretch, minAreaRatio, speed: maxJointSpeed * 180 / Math.PI });
328
+ }
329
+ row.springComparison.push(result);
330
+ console.log(variant, scenario.name, `existing ${result.existingSpringsOnly.maxEdgeStretch}x / combined ${result.clipsPlusSprings.maxEdgeStretch}x`);
331
+ }
332
+ const shipped = row.springComparison.map((r) => r.existingSpringsOnly);
333
+ row.springBaseline = { maxEdgeStretch: Math.max(...shipped.map((r) => r.maxEdgeStretch)),
334
+ minTriangleAreaRatio: Math.min(...shipped.map((r) => r.minTriangleAreaRatio)),
335
+ maxJointSpeedDegreesPerSecond: Math.max(...shipped.map((r) => r.maxJointSpeedDegreesPerSecond)) };
336
+ for (const d of deformations) {
337
+ if (round(d.maxEdgeStretch) > row.springBaseline.maxEdgeStretch || round(d.minAreaRatio) < row.springBaseline.minTriangleAreaRatio) failures.push(`${d.name}: deforms the skin more than the shipped springs (stretch ${round(d.maxEdgeStretch)} vs ${row.springBaseline.maxEdgeStretch}, area ${round(d.minAreaRatio)} vs ${row.springBaseline.minTriangleAreaRatio})`);
338
+ if (round(d.speed) > row.springBaseline.maxJointSpeedDegreesPerSecond) failures.push(`${d.name}: turns a joint faster than the shipped springs (${round(d.speed)} vs ${row.springBaseline.maxJointSpeedDegreesPerSecond} °/s)`);
339
+ }
340
+ if (sha(source) !== row.sha256) failures.push(`${variant}: source GLB changed during verification`);
341
+ rows.push(row);
342
+ }
343
+ const report = { schema: 1, originalRevision, motionPath, motionSHA256: sha(motionPath),
344
+ method: 'Three.js GLTFLoader with original Meshopt geometry and bind matrices; all vertices and all nondegenerate triangles, 61 samples per clip. Texture pixels substituted in memory only. Clips evaluated through AnimationMixer by bone name. Separate springComparison uses the actual DummyMotion, DummyPose and DummyClips TypeScript classes on four weapon hits at the arena material masses; existing springs alone and the new clips plus springs are sampled over two seconds at 30 Hz.',
345
+ runtimeSourceSHA256: { dummyMotion: sha('src/client/engine/practice/DummyMotion.ts'), dummyClips: sha('src/client/engine/practice/DummyClips.ts') },
346
+ units: 'original GLB model units, before TrainingDummyAssets game scaling',
347
+ limits: { maxBindPositionError: 0.0001, maxWeightSumError: 'half a storage quantum per weight, × 4 (float32: 4 × 2^-24)',
348
+ deformationAndJointSpeed: 'no worse than the variant\'s shipped springs alone, measured in this run (springBaseline): max edge stretch, min triangle area ratio, max joint speed',
349
+ minRestTriangleArea, excludedSliverReason: 'Area below 1e-8 model units squared is already a numerical sliver in the original bind. These are counted separately; the same cutoff is used by the existing Blender dummy rig gate.',
350
+ maxSeamPositionError: 0.0001, maxQuaternionLengthError: 0.00001, maxFixedJointRotationRadians: 0.00001,
351
+ maxYawScaleLocalPositionError: 0.00001 },
352
+ historyNote: 'beforeSkinRepair records the first complete trial with original weights, earlier clip caps, and full spring gain. Comparing it with this report measures the whole remaster; it does not isolate the effect of weight repair alone.',
353
+ beforeSkinRepair: firstTake, variants: rows, passed: failures.length === 0, failures };
354
+ writeFileSync(reportPath, `${JSON.stringify(report, null, 2)}\n`);
355
+ console.log(`Report ${reportPath}: ${report.passed ? 'PASS' : 'FAIL'}`);
356
+ if (!report.passed) process.exitCode = 1;
@@ -0,0 +1,25 @@
1
+ // MU3/F30: test the installed phone browser before fetching a large client.
2
+ // WebKit uses its own defaults: Chromium's Metal/keychain flags do not apply.
3
+ import {webkit} from "./browser-playwright.mjs";
4
+ import {createRequire} from 'node:module';
5
+
6
+ const require=createRequire(import.meta.url);
7
+ const version=require('playwright/package.json').version;
8
+ export const PREPARATION_LAUNCH_TIMEOUT=20000;
9
+
10
+ /** A bounded, headless WebKit launch. Playwright owns timeout/process cleanup. */
11
+ export async function launchPreparationBrowser(){
12
+ try{return await webkit.launch({headless:true,timeout:PREPARATION_LAUNCH_TIMEOUT});}
13
+ catch(error){
14
+ const detail=String(error instanceof Error?error.message:error).split('\n').find(line=>line.trim()!=='')?.trim();
15
+ const reason=error instanceof Error&&error.name==='TimeoutError'?`did not start within ${PREPARATION_LAUNCH_TIMEOUT/1000} seconds (up to 30 seconds more for process cleanup)`:`could not start: ${detail??'unknown launch failure'}`;
16
+ throw new Error(`Phone WebKit ${reason} (Playwright ${version}). Run npx playwright@${version} install webkit, then retry. If it still fails, run prepare on another macOS/Linux machine with working WebKit; --base also needs local WebKit. Candidate left as a draft.`,{cause:error});
17
+ }
18
+ }
19
+
20
+ /** Pay first-launch cost and report the actual browser before any client download. */
21
+ export async function checkPreparationBrowser(){
22
+ const at=Date.now(),browser=await launchPreparationBrowser();
23
+ try{console.error(`wildshard prepare: headless WebKit ${browser.version()} ready (${Date.now()-at} ms; Playwright ${version})`);}
24
+ finally{await browser.close();}
25
+ }
@@ -0,0 +1,15 @@
1
+ // The save a fresh `wildshard prepare` context starts from (SENTRY-TRIAGE S12): the phone tier, quiet, and a device that has
2
+ // played and answered the Name prompt, so PLAY goes straight to SHARD SELECT on engine main (firstPlay.ts, MP2.4).
3
+ import { NAME_ASKED } from '@wildshard/engine/scripts/debug-settings.mjs';
4
+
5
+ /** localStorage rows by key, for the served save epoch. @param {number} epoch @returns {Record<string, string>} */
6
+ export function preparationSaveSeed(epoch) {
7
+ const prefix = `wildshard.save.v2${epoch === 0 ? '' : `@${epoch}`}.`, row = (/** @type {unknown} */ data) => ({ v: 1, data });
8
+ return {
9
+ [`${prefix}global`]: JSON.stringify({ keys: { settings: row({ tier: 'phone', volume: 0, time: 'midday', weather: 'clear' }), gfx: row({ dpr: '2', aa: 'auto' }) } }),
10
+ [`${prefix}${NAME_ASKED.scope}`]: JSON.stringify({ keys: {
11
+ devMode: row(true), firstPlayDone: row(true), [NAME_ASKED.key]: row(NAME_ASKED.data),
12
+ 'debug.global.holdLoading': row('off'), 'debug.earlyPrograms': row('off'),
13
+ } }),
14
+ };
15
+ }
@@ -0,0 +1,14 @@
1
+ /** J198: what `wildshard prepare` records in phone WebKit; tests pass a fixture recording. */
2
+ export interface PreparationRecording {
3
+ readonly headerHash: string;
4
+ readonly renderer: string;
5
+ readonly reads: readonly string[];
6
+ readonly hashes?: readonly string[];
7
+ readonly programs: unknown;
8
+ }
9
+ /** Finish preparing the exact candidate in `dir` from a recording: sdk 0.3 with a version 3 cook, validated. */
10
+ export function finishPreparation(dir: string, recording: PreparationRecording, originalHeader: Uint8Array): Promise<{ slug: string; fence: number; programs: number; renderer: string; document: string }>;
11
+ /** Record the candidate served at `base` in phone WebKit, then finish its preparation. */
12
+ export function prepareProduct(dir: string, base: string): Promise<{ slug: string; fence: number; programs: number; renderer: string; document: string }>;
13
+ /** The producer's dependency fence plus the recording's cold reads. */
14
+ export function preparationFence(index: unknown, sections: ReadonlyMap<string, unknown>, recording: PreparationRecording, mounts: readonly unknown[]): string[];
@@ -0,0 +1,133 @@
1
+ #!/usr/bin/env node
2
+ // J198: prepare an already built candidate using actual phone WebKit links.
3
+ // Draft sdk 0.2 output is not relabelled until this exact product enters.
4
+ import {createHash} from 'node:crypto';
5
+ import {spawn} from 'node:child_process';
6
+ import {readFileSync,writeFileSync,mkdirSync,mkdtempSync,rmSync,readdirSync,statSync,lstatSync} from 'node:fs';
7
+ import {join,resolve,dirname} from 'node:path';
8
+ import {fileURLToPath} from 'node:url';
9
+ import '@wildshard/format/formatHook';
10
+ import {readCookData,cookMountPath} from '@wildshard/format/cookData';
11
+ import {cookPreparationBytes,readEntryPrograms,requireCookPreparation} from '@wildshard/format/cookPreparation';
12
+ import {parseOutputIndex,assembleOutputShardfile} from '@wildshard/format/outputIndex';
13
+ import {controlFileHashes,playLibrarySteps} from '@wildshard/format/admissionControl';
14
+ import {entryFileSteps} from '@wildshard/format/tierSelection';
15
+ import {validationSourceBytes} from '@wildshard/format/validationReceipt';
16
+ import {prepareAssetDecoders} from '@wildshard/format/shardfileAssets';
17
+ import {validateShardfileFolder as validateShardfileProduct} from '@wildshard/format/shardfileValidation';
18
+ import {checkPreparationBrowser} from './preparation-browser.mjs';
19
+
20
+ const hash=bytes=>createHash('sha256').update(bytes).digest('hex');
21
+ const json=(dir,name)=>JSON.parse(readFileSync(join(dir,name),'utf8'));
22
+ const bytesOf=value=>validationSourceBytes(value);
23
+ const drain=steps=>{for(;;){const row=steps.next();if(row.done)return row.value;}};
24
+
25
+ function productPaths(dir){
26
+ if(lstatSync(dir).isSymbolicLink())throw new Error('The shard file folder to prepare must be a regular directory');
27
+ const entries=readdirSync(dir,{recursive:true,withFileTypes:true});
28
+ if(entries.some(row=>!row.isDirectory()&&!row.isFile()))throw new Error('The shard file folder to prepare must hold regular files, not symlinks');
29
+ return entries.filter(row=>row.isFile()).map(row=>join(row.parentPath,row.name).slice(dir.length+1).split('\\').join('/'));
30
+ }
31
+ async function validateFinished(dir,index){
32
+ const paths=productPaths(dir);
33
+ await prepareAssetDecoders();
34
+ validateShardfileProduct({paths:()=>paths,read:(path,cap)=>{
35
+ const file=join(dir,path);if(statSync(file).size>cap)throw new Error(`Preparation read exceeds byte cap: ${path}`);
36
+ return readFileSync(file);
37
+ }},{hash});
38
+ // This is the same admitted source and validator revision; only the index
39
+ // transport digest changed. Never invent a new cost or revision receipt.
40
+ const receipt=json(dir,'validation.json');
41
+ if(receipt.indexHash!==undefined){
42
+ receipt.indexHash=hash(bytesOf(index));
43
+ writeFileSync(join(dir,'validation.json'),bytesOf(receipt));
44
+ }
45
+ }
46
+
47
+ /** The producer's computed conservative dependency fence plus actual cold reads. */
48
+ export function preparationFence(index,sections,recording,mounts){
49
+ const source=assembleOutputShardfile(index,sections),descriptor={index,sections};
50
+ const cold=drain(playLibrarySteps(source,descriptor));
51
+ const required=controlFileHashes({...source,library:source.library.filter(row=>!cold.has(row))});
52
+ const excluded=drain(entryFileSteps(source,'phone',descriptor));
53
+ const known=new Set([...index.files.map(row=>row.hash),...mounts.map(row=>row.hash),...index.requires.commons]);
54
+ return [...new Set([...required,...(recording.hashes??[]).filter(row=>known.has(row)),...index.files.filter(row=>recording.reads.some(url=>url.endsWith(`/${row.path}`))).map(row=>row.hash),...mounts.filter(row=>recording.reads.some(url=>url.endsWith(row.url))).map(row=>row.hash)])].filter(row=>!excluded.has(row)).sort();
55
+ }
56
+
57
+ /** Only the measured recorder envelope can finish the exact candidate. */
58
+ export async function finishPreparation(dir,recording,originalHeader){
59
+ dir=resolve(dir);
60
+ productPaths(dir); // Refuse linked output paths before any file is written.
61
+ const header=readFileSync(join(dir,'shard.json'));
62
+ if(hash(header)!==hash(originalHeader)||recording.headerHash!==hash(header))throw new Error('Candidate changed during preparation; rerun wildshard prepare');
63
+ const held=parseOutputIndex(JSON.parse(header)),programs=readEntryPrograms(recording.programs),renderer=recording.renderer;
64
+ if(typeof renderer!=='string'||!/^[a-f0-9]{64}$/u.test(renderer))throw new Error('Recording has no engine renderer revision; use a D5 preparation preview');
65
+ const sections=new Map(held.sections.map(row=>[row.name,json(dir,row.path)]));
66
+ const old=held.cook===undefined?{mounts:[]}:readCookData(json(dir,'cook.json'));
67
+ const url=`/programs/${held.identity.slug}.json`,path=cookMountPath(url),programBytes=bytesOf(programs);
68
+ const mounts=[...old.mounts.filter(row=>row.url!==url),{url,path,hash:hash(programBytes),bytes:programBytes.length}].sort((a,b)=>a.url.localeCompare(b.url));
69
+ const index={...held,sdk:'0.3'},fence=preparationFence(index,sections,recording,mounts);
70
+ // A full phone set contains every admitted non-desktop file. Only a strict
71
+ // measured subset needs the existing fence policy; desktop stays whole.
72
+ const all=index.files.filter(row=>row.tier!=='desktop'),selected=new Set(fence);
73
+ const packs=all.some(row=>!selected.has(row.hash))?'fence':'whole';
74
+ const cook={version:3,mounts,packs,fence,programs,renderer,inputHash:hash(cookPreparationBytes(index,mounts,renderer))};
75
+ const bytes=bytesOf(cook),next={...index,cook:{path:'cook.json',hash:hash(bytes),bytes:bytes.length}};
76
+ requireCookPreparation(parseOutputIndex(next),readCookData(cook),hash);
77
+ mkdirSync(dirname(join(dir,path)),{recursive:true});writeFileSync(join(dir,path),programBytes);
78
+ writeFileSync(join(dir,'cook.json'),bytes);writeFileSync(join(dir,'shard.json'),bytesOf(next));
79
+ await validateFinished(dir,next);
80
+ return {slug:index.identity.slug,fence:fence.length,programs:programs.programs.length,renderer,document:programs.build};
81
+ }
82
+
83
+ /** SA43: with no --base, serve engine's preparation client (fetched at this package's engine pin) around the candidate. */
84
+ async function ownPreview(dir){
85
+ const {preparationClient}=await import('../src/sharddev/devClient.ts');
86
+ const {clientPage}=await import('@wildshard/sdk/internal/clientPage');
87
+ const {preparationPreview}=await import('@wildshard/sdk/scripts/preparation-preview.mjs');
88
+ return preparationPreview(await preparationClient(),dir,{clientPage});
89
+ }
90
+
91
+ export async function prepareProduct(dir,base,inline=false){
92
+ if(!inline)await checkPreparationBrowser();
93
+ if(base===undefined){
94
+ const preview=await ownPreview(dir);
95
+ console.error(`wildshard prepare: serving engine's preparation client at ${preview.url}`);
96
+ try{return await prepareProduct(dir,preview.url,true);}finally{await preview.close();}
97
+ }
98
+ const header=readFileSync(join(dir,'shard.json')),index=parseOutputIndex(JSON.parse(header));
99
+ // SA17: the recording lands under the project's own tmp/ (git-ignored by `new`), never the system temp dir.
100
+ const parent=join(process.cwd(),'tmp');mkdirSync(parent,{recursive:true});
101
+ const scratch=mkdtempSync(join(parent,'wildshard-prepare-'));
102
+ try{
103
+ const out=join(scratch,'recording.json');
104
+ const script=fileURLToPath(new URL('./bake-entry-programs.mjs',import.meta.url));
105
+ // Like the existing recorder, the operator runs this command through the
106
+ // engine browser-lane wrapper. Do not acquire a second nested browser slot.
107
+ // Not spawnSync: with no --base this process serves the preview the recorder reads (SA43).
108
+ const run=await new Promise(done=>{
109
+ const child=spawn(process.execPath,[script,'--base',base,'--out',out,'--header',hash(header),'--title',index.identity.name,...(inline?['--inline']:[]),index.identity.slug],{stdio:['inherit','inherit','pipe'],timeout:300000});
110
+ let stderr='';
111
+ const debug=process.env.WILDSHARD_PREPARATION_DEBUG==='1'||process.env.DEBUG?.includes('pw:');
112
+ child.stderr.on('data',bytes=>{stderr=(stderr+String(bytes)).slice(-16384);if(debug)process.stderr.write(bytes);});
113
+ child.once('error',error=>{done({error,status:null,stderr});});
114
+ child.once('close',(status,signal)=>{done({error:undefined,status,stderr,timedOut:child.killed&&signal==='SIGTERM'});});
115
+ });
116
+ if(run.error!==undefined||run.status!==0){
117
+ const detail=run.timedOut?'Recorder exceeded its 300 second limit':run.error?.message??run.stderr.split('\n').reverse().find(line=>/^[A-Za-z]*Error(?: \[[^\]]+\])?: /u.test(line))??`Recorder exited ${run.status??'without a status'}; rerun with WILDSHARD_PREPARATION_DEBUG=1 for details`;
118
+ throw new Error(detail?.includes('Candidate left as a draft.')?detail:`Phone WebKit preparation did not pass${detail===undefined?'':`: ${detail}`}; candidate left as a draft`);
119
+ }
120
+ return await finishPreparation(dir,json(scratch,'recording.json'),header);
121
+ }finally{rmSync(scratch,{recursive:true,force:true});}
122
+ }
123
+
124
+ if(process.argv[1]!==undefined&&resolve(process.argv[1])===fileURLToPath(import.meta.url)){
125
+ const [dir,flag,base]=process.argv.slice(2);
126
+ if(dir===undefined||(flag!==undefined&&(flag!=='--base'||base===undefined)))throw new Error('usage: wildshard prepare <folder> [--base <exact-preview-url>]');
127
+ try{console.log(JSON.stringify(await prepareProduct(resolve(dir),base)));}
128
+ catch(error){
129
+ if(process.env.WILDSHARD_PREPARATION_DEBUG==='1')console.error(error);
130
+ else console.error(`wildshard prepare: ${error instanceof Error?error.message:String(error)}`);
131
+ process.exitCode=1;
132
+ }
133
+ }
@@ -0,0 +1,83 @@
1
+ #!/usr/bin/env node
2
+ // `wildshard prove <source> <walk.mjs> --base <dev url>`: play a walk proof (meta NEW-SHARD-E2E F27). A walk proof is a
3
+ // small script whose default export gets the walk helpers (src/sharddev/walkProof.ts) and plays the shard on a served page
4
+ // by real inputs: walk to an NPC, E to talk, a digit to answer, a click to swing; then it asserts what the server says
5
+ // (flags, quest steps). A tape (`prove <source> proof.json`) plays the headless simulation; a walk plays the page.
6
+ //
7
+ // Serve the shard first with `wildshard dev .` and pass the URL it prints. Headless Chromium on the real GPU (Metal), muted,
8
+ // 60 fps, never a visible window. Prints the steps and the server's final flags and quests as JSON; exit 1 on a refusal.
9
+ import { existsSync } from 'node:fs';
10
+ import { resolve } from 'node:path';
11
+ import { pathToFileURL } from 'node:url';
12
+ import { findShardSource } from '@wildshard/upload/sharddev/shardSource.ts';
13
+ import { walkProof, WalkProofError } from '@wildshard/sdk/internal/walkProof';
14
+
15
+ const USAGE = 'usage: wildshard prove <source> <walk.mjs> --base <url> (serve the shard first: `wildshard dev .` prints its URL)';
16
+
17
+ /** The served root, so the URL `wildshard dev` prints (`…/?skipintro`) works as `--base`. */
18
+ function servedRoot(base) {
19
+ const url = new URL(base); url.search = ''; url.hash = '';
20
+ return url.href.replace(/\/+$/u, '');
21
+ }
22
+ /** True when `base` is a `wildshard dev` server: it answers its reload poll. */
23
+ async function isDevServer(base) {
24
+ try {
25
+ const response = await fetch(`${base}/__wildshard_dev_revision`, { cache: 'no-store' });
26
+ return response.ok && typeof (await response.json()).revision === 'number';
27
+ } catch { return false; }
28
+ }
29
+
30
+ /** Play `walk` against the shard served at `base`; returns the report (verdict pass or fail, never throws for the walk). */
31
+ export async function proveWalk(source, walk, given, { log = console.info } = {}) {
32
+ const shard = findShardSource(source), script = resolve(walk), base = servedRoot(given);
33
+ if (!existsSync(script)) throw new WalkProofError(`${walk}: no such walk script`);
34
+ const { default: play } = await import(pathToFileURL(script).href);
35
+ if (typeof play !== 'function') throw new WalkProofError(`${walk}: export default async function ({ talk, choose, expectFlags, ... }) { ... }`);
36
+ if (!(await isDevServer(base))) throw new WalkProofError(`${given} is not a \`wildshard dev\` page (no /__wildshard_dev_revision); run \`wildshard dev ${source}\` and pass the URL it prints`);
37
+ const [{ chromium }, { NAME_ASKED, saveFixture }, { KEYCHAIN_ARGS }] = await Promise.all([
38
+ import("./browser-playwright.mjs"), import('@wildshard/engine/scripts/debug-settings.mjs'), import('./chromium-keychain.mjs')]);
39
+ const started = Date.now(), errors = [];
40
+ const browser = await chromium.launch({ headless: true, args: [...KEYCHAIN_ARGS, '--mute-audio', '--use-angle=metal', '--ignore-gpu-blocklist'] });
41
+ let report;
42
+ try {
43
+ const context = await browser.newContext({ viewport: { width: 800, height: 600 } });
44
+ await saveFixture(context, NAME_ASKED);
45
+ // the game at 60 fps, as a player's phone would run it
46
+ await context.addInitScript(() => {
47
+ const frame = window.requestAnimationFrame.bind(window); let last = 0;
48
+ window.requestAnimationFrame = callback => frame(function tick(at) { if (at - last < 1000 / 60 - 1) return frame(tick); last = at; return callback(at); });
49
+ });
50
+ const page = await context.newPage();
51
+ page.on('pageerror', error => errors.push(error.message.slice(0, 300)));
52
+ log(`prove: entering ${base} (wildshard dev) for ${shard}`);
53
+ await page.goto(`${base}/?skipintro&mute=1&nolock=1&perf=0`, { waitUntil: 'load' });
54
+ await page.waitForFunction(() => Boolean(window.__wildshard?.world?.hud?.entered && window.__workerClient) && document.querySelector('.ws-load') === null,
55
+ undefined, { timeout: 240000, polling: 500 });
56
+ if (await page.evaluate(() => window.__wildshard.world.hud.paused)) await page.keyboard.press('Escape');
57
+ const proof = walkProof(page);
58
+ let failure = null;
59
+ try { await play({ ...proof, page }); } catch (error) { failure = error instanceof Error ? error.message : String(error); }
60
+ if (failure === null && errors.length > 0) failure = `page errors: ${errors.slice(0, 3).join(' | ')}`;
61
+ const end = await proof.state().catch(() => null);
62
+ report = { verdict: failure === null ? 'pass' : 'fail', ...(failure === null ? {} : { refusal: failure }), walk: script, base,
63
+ seconds: Number(((Date.now() - started) / 1000).toFixed(1)), steps: proof.steps, flags: end?.flags ?? null, quests: end?.quests ?? null, errors };
64
+ await context.close();
65
+ } finally { await browser.close(); }
66
+ return report;
67
+ }
68
+
69
+ if (process.argv[1] !== undefined && resolve(process.argv[1]) === resolve(import.meta.filename)) {
70
+ const [source, walk, flag, base] = process.argv.slice(2);
71
+ if (source === undefined || walk === undefined || flag !== '--base' || base === undefined) { console.error(USAGE); process.exit(2); }
72
+ try {
73
+ const report = await proveWalk(source, walk, base, { log: line => console.error(line) });
74
+ console.info(JSON.stringify(report, null, 2));
75
+ if (report.verdict !== 'pass') {
76
+ console.error(`${report.refusal}\n [proof-failed] fix: Walk the quest in \`wildshard dev\`, then fix the data or the walk step that did not happen. (GUIDE.md#walk-proofs)`);
77
+ process.exitCode = 1;
78
+ }
79
+ } catch (error) {
80
+ console.error(error instanceof WalkProofError ? `${error.message}\n [proof-failed] ${USAGE}` : error);
81
+ process.exitCode = 1;
82
+ }
83
+ }
@@ -0,0 +1 @@
1
+ export function pushTables(root:string):void;