@wildshard/sdk 0.0.1 → 0.2.4

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 (688) hide show
  1. package/GUIDE.md +895 -0
  2. package/README.md +13 -5
  3. package/bin/wildshard.mjs +38 -0
  4. package/lint/declaration-config.d.mts +2 -0
  5. package/lint/declaration-config.mjs +19 -0
  6. package/lint/engine-plugin.d.mts +2 -0
  7. package/lint/engine-plugin.mjs +40 -0
  8. package/lint/host-callbacks.d.mts +6 -0
  9. package/lint/host-callbacks.mjs +123 -0
  10. package/lint/host-files.d.mts +1 -0
  11. package/lint/host-files.mjs +7 -0
  12. package/lint/layer-exports.d.mts +2 -0
  13. package/lint/layer-exports.mjs +21 -0
  14. package/lint/legacy-line-basis.json +995 -0
  15. package/lint/nine-tiling-baseline.json +35 -0
  16. package/lint/ratchet.json +11 -0
  17. package/lint/runtime-files.d.mts +12 -0
  18. package/lint/runtime-files.json +16 -0
  19. package/lint/runtime-files.mjs +69 -0
  20. package/lint/runtime-performance.d.mts +6 -0
  21. package/lint/runtime-performance.mjs +184 -0
  22. package/lint/sdk-plugin.d.mts +4 -0
  23. package/lint/sdk-plugin.mjs +134 -0
  24. package/lint/shardfile-boundaries.d.mts +10 -0
  25. package/lint/shardfile-boundaries.mjs +122 -0
  26. package/lint/tile-bake-debt.json +556 -0
  27. package/package.json +365 -3
  28. package/scripts/agent-parity.mjs +1524 -0
  29. package/scripts/agent-sync.mjs +518 -0
  30. package/scripts/apfs-clone.mjs +67 -0
  31. package/scripts/assert-store-layout.mjs +23 -0
  32. package/scripts/astc6-phone-cap.d.mts +3 -0
  33. package/scripts/astc6-phone-cap.mjs +137 -0
  34. package/scripts/audit-assets.d.mts +10 -0
  35. package/scripts/audit-assets.mjs +151 -0
  36. package/scripts/bake/coatFiles.d.mts +6 -0
  37. package/scripts/bake/coatFiles.mjs +37 -0
  38. package/scripts/bake/environment.d.mts +2 -0
  39. package/scripts/bake/environment.mjs +58 -0
  40. package/scripts/bake/far-proxies.mjs +45 -0
  41. package/scripts/bake/keyed-sky.d.mts +4 -0
  42. package/scripts/bake/keyed-sky.mjs +34 -0
  43. package/scripts/bake/movers.mjs +56 -0
  44. package/scripts/bake/nativeWorld.d.mts +6 -0
  45. package/scripts/bake/nativeWorld.mjs +43 -0
  46. package/scripts/bake/navmeshGround.ts +22 -0
  47. package/scripts/bake/near-placeholder.mjs +331 -0
  48. package/scripts/bake/placeholderShards.mjs +41 -0
  49. package/scripts/bake/skins.mjs +15 -0
  50. package/scripts/bake/template-skins.mjs +33 -0
  51. package/scripts/bake/viewmodelBytes.ts +26 -0
  52. package/scripts/bake/viewmodelPage.ts +11 -0
  53. package/scripts/bake/worldHost.d.mts +35 -0
  54. package/scripts/bake/worldHost.mjs +110 -0
  55. package/scripts/bake-astc6.cache.json +80 -0
  56. package/scripts/bake-astc6.far-reach.cache.json +23 -0
  57. package/scripts/bake-astc6.list.json +111 -0
  58. package/scripts/bake-astc6.mjs +279 -0
  59. package/scripts/bake-astc6.nalati-grasslands.cache.json +42 -0
  60. package/scripts/bake-catalogue.mjs +44 -0
  61. package/scripts/bake-check.mjs +54 -0
  62. package/scripts/bake-chunk.mjs +124 -0
  63. package/scripts/bake-cloud-field.mjs +24 -0
  64. package/scripts/bake-coats.mjs +110 -0
  65. package/scripts/bake-data-maps.d.mts +24 -0
  66. package/scripts/bake-data-maps.mjs +72 -0
  67. package/scripts/bake-entry-programs.mjs +117 -0
  68. package/scripts/bake-geometry.mjs +106 -0
  69. package/scripts/bake-hybrid-tiles.mjs +28 -0
  70. package/scripts/bake-ktx2.cache.json +276 -0
  71. package/scripts/bake-ktx2.list.json +365 -0
  72. package/scripts/bake-ktx2.mjs +477 -0
  73. package/scripts/bake-map-glb.mjs +127 -0
  74. package/scripts/bake-map-rest.d.mts +7 -0
  75. package/scripts/bake-map-rest.mjs +50 -0
  76. package/scripts/bake-maps.mjs +200 -0
  77. package/scripts/bake-navmesh.mjs +259 -0
  78. package/scripts/bake-packs.mjs +129 -0
  79. package/scripts/bake-pickups.mjs +102 -0
  80. package/scripts/bake-query-terrain.mjs +64 -0
  81. package/scripts/bake-recurve-pool.mjs +16 -0
  82. package/scripts/bake-section-schemas.d.mts +3 -0
  83. package/scripts/bake-template-shardfile.mjs +32 -0
  84. package/scripts/bake-textures.mjs +80 -0
  85. package/scripts/bake-viewmodel-sets.json +45 -0
  86. package/scripts/bake-viewmodel-sets.mjs +137 -0
  87. package/scripts/bake-voxel-ao.mjs +119 -0
  88. package/scripts/bake-water-ripples.mjs +25 -0
  89. package/scripts/blender/README.md +129 -0
  90. package/scripts/blender/build.sh +166 -0
  91. package/scripts/blender/lib/export-scene.mjs +129 -0
  92. package/scripts/blender/lib/glb-digest.mjs +188 -0
  93. package/scripts/blender/lib/glb.py +68 -0
  94. package/scripts/blender/lib/save_blend.py +17 -0
  95. package/scripts/blender/lib/world_fixture.py +55 -0
  96. package/scripts/blender/targets.json +591 -0
  97. package/scripts/build-sdk.mjs +95 -0
  98. package/scripts/build-shardfiles.d.mts +7 -0
  99. package/scripts/build-shardfiles.mjs +206 -0
  100. package/scripts/capture-hero.mjs +137 -0
  101. package/scripts/check-lift-review.mjs +23 -0
  102. package/scripts/chromium-keychain-check.mjs +139 -0
  103. package/scripts/chromium-keychain.d.mts +1 -0
  104. package/scripts/chromium-keychain.mjs +5 -0
  105. package/scripts/compile-script.d.mts +3 -0
  106. package/scripts/compile-script.mjs +8 -0
  107. package/scripts/creature-color.mjs +255 -0
  108. package/scripts/decide/calibrate.py +127 -0
  109. package/scripts/decide/calibration/2026-10-03/labels-s1.tsv +281 -0
  110. package/scripts/decide/calibration/2026-10-03/labels-s2.tsv +97 -0
  111. package/scripts/decide/calibration/2026-10-03/labels-s3.tsv +48 -0
  112. package/scripts/decide/calibration/2026-10-03/labels-s3b.tsv +26 -0
  113. package/scripts/decide/calibration/2026-10-03/res-capture-status-v1.jsonl +376 -0
  114. package/scripts/decide/calibration/2026-10-03/res-text-garbled-strings.jsonl +48 -0
  115. package/scripts/decide/calibration/2026-10-03/res-text-garbled-v1.jsonl +73 -0
  116. package/scripts/decide/decide.py +262 -0
  117. package/scripts/decide/decide.sh +50 -0
  118. package/scripts/decide/layer-purity-pilot.mjs +41 -0
  119. package/scripts/decide/sets/capture-status.json +46 -0
  120. package/scripts/decide/sets/layer-purity.json +28 -0
  121. package/scripts/decide/sets/text-garbled.json +17 -0
  122. package/scripts/decide/test_decide.py +37 -0
  123. package/scripts/docs.mjs +15 -0
  124. package/scripts/entry-reads/crawl.ts +152 -0
  125. package/scripts/entry-reads/tsconfig.json +25 -0
  126. package/scripts/gen-format-schema.d.mts +2 -0
  127. package/scripts/gen-format-schema.mjs +21 -0
  128. package/scripts/gen-host-catalogue.d.mts +14 -0
  129. package/scripts/gen-host-catalogue.mjs +108 -0
  130. package/scripts/gen-shard-layout-doc.d.mts +4 -0
  131. package/scripts/gen-shard-layout-doc.mjs +55 -0
  132. package/scripts/gen-shards.d.mts +17 -0
  133. package/scripts/gen-shards.mjs +311 -0
  134. package/scripts/goldens/capture-inputs.d.mts +4 -0
  135. package/scripts/goldens/capture-inputs.mjs +34 -0
  136. package/scripts/goldens/colour_shift.py +27 -0
  137. package/scripts/goldens/native-residency.d.mts +10 -0
  138. package/scripts/goldens/native-residency.mjs +104 -0
  139. package/scripts/goldens/plot-inputs.d.mts +12 -0
  140. package/scripts/goldens/plot-inputs.mjs +46 -0
  141. package/scripts/gpu-texmem.mjs +98 -0
  142. package/scripts/horizon-matte/config.py +24 -0
  143. package/scripts/horizon-matte/encode.py +91 -0
  144. package/scripts/horizon-matte/key.py +141 -0
  145. package/scripts/horizon-matte/mkjobs.py +33 -0
  146. package/scripts/horizon-matte/mkjobs_day2.py +11 -0
  147. package/scripts/horizon-matte/overlap.py +80 -0
  148. package/scripts/horizon-matte/run_codex.py +57 -0
  149. package/scripts/horizon-matte/stitch.py +133 -0
  150. package/scripts/img2mesh/CC0.md +105 -0
  151. package/scripts/img2mesh/README.md +209 -0
  152. package/scripts/img2mesh/ab_board.py +102 -0
  153. package/scripts/img2mesh/birds/birds.json +255 -0
  154. package/scripts/img2mesh/birds/birds_atlas.py +150 -0
  155. package/scripts/img2mesh/birds/birds_fix_preview.mjs +103 -0
  156. package/scripts/img2mesh/birds/birds_fix_render.py +75 -0
  157. package/scripts/img2mesh/birds/birds_pack.py +110 -0
  158. package/scripts/img2mesh/birds/birds_phone_b.py +112 -0
  159. package/scripts/img2mesh/birds/birds_post.py +550 -0
  160. package/scripts/img2mesh/birds/birds_render.py +125 -0
  161. package/scripts/img2mesh/birds/birds_sheet.py +33 -0
  162. package/scripts/img2mesh/birds/birds_view.py +60 -0
  163. package/scripts/img2mesh/board.py +100 -0
  164. package/scripts/img2mesh/build_cc0.sh +52 -0
  165. package/scripts/img2mesh/build_driftwood.sh +12 -0
  166. package/scripts/img2mesh/build_faces.sh +53 -0
  167. package/scripts/img2mesh/build_props.py +81 -0
  168. package/scripts/img2mesh/cc0_export.py +186 -0
  169. package/scripts/img2mesh/driftwood_post.py +571 -0
  170. package/scripts/img2mesh/e304_faces.sh +67 -0
  171. package/scripts/img2mesh/face_remaster.py +911 -0
  172. package/scripts/img2mesh/face_views.py +95 -0
  173. package/scripts/img2mesh/faces-e304.json +9 -0
  174. package/scripts/img2mesh/faces.json +30 -0
  175. package/scripts/img2mesh/head_cut.py +100 -0
  176. package/scripts/img2mesh/hi3d_paint.py +94 -0
  177. package/scripts/img2mesh/hi3d_refine.py +161 -0
  178. package/scripts/img2mesh/hunyuan_cpu_rasterizer.sh +42 -0
  179. package/scripts/img2mesh/pine_hollow_phone.sh +13 -0
  180. package/scripts/img2mesh/props/coral-arch.json +32 -0
  181. package/scripts/img2mesh/props/ember-furnace.json +30 -0
  182. package/scripts/img2mesh/props/night-market-gate.json +10 -0
  183. package/scripts/img2mesh/render_still.py +86 -0
  184. package/scripts/img2mesh/rig_strip.mjs +46 -0
  185. package/scripts/img2mesh/rig_transfer.mjs +104 -0
  186. package/scripts/img2mesh/split_sheet.py +48 -0
  187. package/scripts/img2mesh/trellis_batch.py +110 -0
  188. package/scripts/img2mesh/versus_board.py +114 -0
  189. package/scripts/import-bundle.d.mts +2 -0
  190. package/scripts/import-bundle.mjs +20 -0
  191. package/scripts/ktx2-ab-board.py +133 -0
  192. package/scripts/ktx2-ab.mjs +111 -0
  193. package/scripts/ktx2-settings.mjs +18 -0
  194. package/scripts/land.d.mts +14 -0
  195. package/scripts/land.mjs +809 -0
  196. package/scripts/lint-dispatch.mjs +14 -0
  197. package/scripts/map-bake-frames.d.mts +4 -0
  198. package/scripts/map-bake-frames.mjs +23 -0
  199. package/scripts/map-geometry.d.mts +9 -0
  200. package/scripts/map-geometry.mjs +29 -0
  201. package/scripts/map-world.mjs +162 -0
  202. package/scripts/mockup-local.sh +46 -0
  203. package/scripts/music/export-midi.mjs +68 -0
  204. package/scripts/music/gen/analyze.py +308 -0
  205. package/scripts/music/gen/audio_jobs.py +46 -0
  206. package/scripts/music/gen/briefs.json +51 -0
  207. package/scripts/music/gen/build_page.py +334 -0
  208. package/scripts/music/gen/folk.json +3187 -0
  209. package/scripts/music/gen/gen_ace_step.py +156 -0
  210. package/scripts/music/gen/gen_heartmula.py +187 -0
  211. package/scripts/music/gen/gen_minimax.py +143 -0
  212. package/scripts/music/gen/gen_sao.py +122 -0
  213. package/scripts/music/gen/gen_sao_small.py +104 -0
  214. package/scripts/music/gen/gen_sfx.py +98 -0
  215. package/scripts/music/gen/gen_sfx_ezaudio.py +112 -0
  216. package/scripts/music/gen/gen_sfx_moss.py +112 -0
  217. package/scripts/music/gen/models.json +61 -0
  218. package/scripts/music/gen/nalati-jobs.json +104 -0
  219. package/scripts/music/gen/nalati-score-build.json +119 -0
  220. package/scripts/music/gen/nalati-score.json +3448 -0
  221. package/scripts/music/gen/ob7-fit-decisions.json +38 -0
  222. package/scripts/music/gen/ob7-score-jobs.json +152 -0
  223. package/scripts/music/gen/ob7-sfx-jobs.json +897 -0
  224. package/scripts/music/gen/ob7_build.py +469 -0
  225. package/scripts/music/gen/ob7_generate.py +67 -0
  226. package/scripts/music/gen/ob7_run.sh +42 -0
  227. package/scripts/music/gen/orchestral.json +3187 -0
  228. package/scripts/music/gen/own_score.py +486 -0
  229. package/scripts/music/gen/ph-jobs.json +27 -0
  230. package/scripts/music/gen/ph_page.py +222 -0
  231. package/scripts/music/gen/piano.json +3175 -0
  232. package/scripts/music/gen/rank_v3.py +248 -0
  233. package/scripts/music/gen/sfx-best.json +2486 -0
  234. package/scripts/music/gen/sfx-ezaudio.json +4082 -0
  235. package/scripts/music/gen/sfx-jobs.json +57 -0
  236. package/scripts/music/gen/sfx-minimax-jobs.json +16 -0
  237. package/scripts/music/gen/sfx-minimax.json +289 -0
  238. package/scripts/music/gen/sfx-moss.json +4082 -0
  239. package/scripts/music/gen/sfx-nalati-b3-jobs.json +17 -0
  240. package/scripts/music/gen/sfx-nalati-jobs.json +338 -0
  241. package/scripts/music/gen/sfx-nalati.json +11202 -0
  242. package/scripts/music/gen/sfx-nd-jobs.json +57 -0
  243. package/scripts/music/gen/sfx-nd-moss.json +2097 -0
  244. package/scripts/music/gen/sfx-nd-sa3-medium.json +2097 -0
  245. package/scripts/music/gen/sfx-nd-summary.json +38 -0
  246. package/scripts/music/gen/sfx-peaks.json +7 -0
  247. package/scripts/music/gen/sfx-ph-jobs.json +169 -0
  248. package/scripts/music/gen/sfx-ph-moss.json +6564 -0
  249. package/scripts/music/gen/sfx-ph-sa3-medium.json +7239 -0
  250. package/scripts/music/gen/sfx-ph-summary.json +63 -0
  251. package/scripts/music/gen/sfx-sa3-medium.json +4082 -0
  252. package/scripts/music/gen/sfx-sa3.json +4082 -0
  253. package/scripts/music/gen/sfx-summary.json +107 -0
  254. package/scripts/music/gen/sfx_build.py +332 -0
  255. package/scripts/music/gen/sfx_merge.py +255 -0
  256. package/scripts/music/gen/sfx_minimax.py +61 -0
  257. package/scripts/music/gen/sfx_nalati.py +331 -0
  258. package/scripts/music/gen/sfx_sprite.py +424 -0
  259. package/scripts/music/gen/stems.py +539 -0
  260. package/scripts/music/gen/test_loop_meter.py +29 -0
  261. package/scripts/music/gen/test_ob7_provenance.py +77 -0
  262. package/scripts/music/gen/v3-folk-build.json +148 -0
  263. package/scripts/music/gen/v3-folk.json +1818 -0
  264. package/scripts/music/gen/v3-jobs.json +145 -0
  265. package/scripts/music/gen/v3-orchestral-build.json +148 -0
  266. package/scripts/music/gen/v3-orchestral.json +1813 -0
  267. package/scripts/music/gen/v3-ph-folk-build.json +94 -0
  268. package/scripts/music/gen/v3-ph-folk.json +1806 -0
  269. package/scripts/music/gen/v3-ph-orchestral-build.json +94 -0
  270. package/scripts/music/gen/v3-ph-orchestral.json +1824 -0
  271. package/scripts/music/gen/v3-ph-piano-build.json +94 -0
  272. package/scripts/music/gen/v3-ph-piano.json +1818 -0
  273. package/scripts/music/gen/v3-piano-build.json +148 -0
  274. package/scripts/music/gen/v3-piano.json +1813 -0
  275. package/scripts/music/wildshard-theme.mid +0 -0
  276. package/scripts/music/wildshard-trailer30.mid +0 -0
  277. package/scripts/named-blob-output.d.mts +8 -0
  278. package/scripts/named-blob-output.mjs +48 -0
  279. package/scripts/pack-all.mjs +15 -0
  280. package/scripts/pid-lock.d.mts +1 -0
  281. package/scripts/pid-lock.mjs +63 -0
  282. package/scripts/practice/bake_dummy.py +53 -0
  283. package/scripts/practice/build_dummies.sh +43 -0
  284. package/scripts/practice/dummy_parts.py +568 -0
  285. package/scripts/practice/dummy_rig_gate.py +139 -0
  286. package/scripts/practice/gate_sheet.py +36 -0
  287. package/scripts/practice/generate_dummy_unimate.py +132 -0
  288. package/scripts/practice/pack_dummy.mjs +59 -0
  289. package/scripts/practice/repair_dummy_weights.mjs +68 -0
  290. package/scripts/practice/rig_dummy.py +828 -0
  291. package/scripts/practice/verify_unimate_skin.mjs +356 -0
  292. package/scripts/preparation-seed.mjs +15 -0
  293. package/scripts/prepare-basis-tool.mjs +6 -0
  294. package/scripts/prepare-product.d.mts +14 -0
  295. package/scripts/prepare-product.mjs +101 -0
  296. package/scripts/product-build-tools.d.mts +3 -0
  297. package/scripts/product-build-tools.json +3 -0
  298. package/scripts/product-build-tools.mjs +31 -0
  299. package/scripts/publish-public.mjs +7 -0
  300. package/scripts/push-tables.d.mts +1 -0
  301. package/scripts/push-tables.mjs +28 -0
  302. package/scripts/record-shard-mounts.mjs +133 -0
  303. package/scripts/sdk-externals.d.mts +2 -0
  304. package/scripts/sdk-externals.mjs +2 -0
  305. package/scripts/section-inventory.ts +209 -0
  306. package/scripts/select-candidate.mjs +15 -0
  307. package/scripts/shard-build-pool.d.mts +4 -0
  308. package/scripts/shard-build-pool.mjs +53 -0
  309. package/scripts/shard-line-baseline.json +17 -0
  310. package/scripts/shard-milestones.d.mts +15 -0
  311. package/scripts/shard-milestones.mjs +105 -0
  312. package/scripts/shard-output-report.d.mts +9 -0
  313. package/scripts/shard-output-report.mjs +85 -0
  314. package/scripts/shard-platform-cli.mjs +93 -0
  315. package/scripts/shard-progress.mjs +212 -0
  316. package/scripts/shard-timelapse.py +102 -0
  317. package/scripts/shardfile-cold-boot.mjs +79 -0
  318. package/scripts/shardfile-vite.d.mts +4 -0
  319. package/scripts/shardfile-vite.mjs +20 -0
  320. package/scripts/simplify-models.mjs +24 -0
  321. package/scripts/site-facts.mjs +88 -0
  322. package/scripts/test-template-gate.mjs +44 -0
  323. package/scripts/test_golden_compare.py +68 -0
  324. package/scripts/tex-tiers.cache.json +181 -0
  325. package/scripts/tex-tiers.mjs +240 -0
  326. package/scripts/texmem-probe.mjs +184 -0
  327. package/scripts/unused-assets.mjs +173 -0
  328. package/scripts/vite-tmp.d.mts +23 -0
  329. package/scripts/vite-tmp.mjs +157 -0
  330. package/scripts/wave-line-baselines.json +32 -0
  331. package/scripts/wildshard.d.mts +4 -0
  332. package/scripts/wildshard.mjs +105 -0
  333. package/scripts/witness-checkpoints.d.mts +10 -0
  334. package/scripts/witness-checkpoints.mjs +84 -0
  335. package/scripts/witness-generation.d.mts +10 -0
  336. package/scripts/witness-generation.mjs +45 -0
  337. package/scripts/witness-manifests.d.mts +8 -0
  338. package/scripts/witness-manifests.mjs +157 -0
  339. package/scripts/worktree-ignore.d.mts +4 -0
  340. package/scripts/worktree-ignore.mjs +36 -0
  341. package/scripts/worktree-reap.mjs +214 -0
  342. package/scripts/worktree.mjs +396 -0
  343. package/scripts/worldclaw/capture-front.sh +28 -0
  344. package/scripts/worldclaw/design-template.md +62 -0
  345. package/scripts/worldclaw/spec-map.py +92 -0
  346. package/scripts/worldclaw/spec.ts +96 -0
  347. package/skills/wildshard/SKILL.md +50 -0
  348. package/skills/wildshard-goldens/SKILL.md +54 -0
  349. package/skills/wildshard-mockup-to-model/SKILL.md +56 -0
  350. package/skills/wildshard-upgrade/SKILL.md +47 -0
  351. package/src/.oxfmtrc.json +50 -0
  352. package/src/.oxlintrc.json +173 -0
  353. package/src/cli/account/account.ts +199 -0
  354. package/src/cli/account/command.ts +193 -0
  355. package/src/cli/account/key.ts +154 -0
  356. package/src/cli/args.ts +97 -0
  357. package/src/cli/audio/audio.ts +39 -0
  358. package/src/cli/bin.mjs +8 -0
  359. package/src/cli/delete/delete.ts +258 -0
  360. package/src/cli/help.ts +204 -0
  361. package/src/cli/hero/adopt.ts +103 -0
  362. package/src/cli/hero/hero.ts +112 -0
  363. package/src/cli/hero/stamp.ts +298 -0
  364. package/src/cli/main.ts +291 -0
  365. package/src/cli/report.ts +20 -0
  366. package/src/cli/shardfile/command.ts +49 -0
  367. package/src/cli/shardfile/shardfile.ts +192 -0
  368. package/src/cli/upload/api.ts +246 -0
  369. package/src/cli/upload/compress.ts +55 -0
  370. package/src/cli/upload/hero.ts +62 -0
  371. package/src/cli/upload/placement.ts +115 -0
  372. package/src/cli/upload/provenance.ts +192 -0
  373. package/src/cli/upload/signature.ts +30 -0
  374. package/src/cli/upload/upload.ts +269 -0
  375. package/src/cli/upload/validate.ts +74 -0
  376. package/src/cli/upload/wire.ts +147 -0
  377. package/src/cli/version.ts +63 -0
  378. package/src/commons/bake/portableMath.ts +187 -0
  379. package/src/commons/catalogue.ts +10 -0
  380. package/src/commons/courseProgram.ts +32 -0
  381. package/src/commons/practiceCourse.ts +16 -0
  382. package/src/commons/scripts/abi.as +14 -0
  383. package/src/commons/scripts/bridge.as +14 -0
  384. package/src/commons/scripts/course.as +63 -0
  385. package/src/scripts/ask-new.sh +29 -0
  386. package/src/scripts/asks.mjs +141 -0
  387. package/src/scripts/herdr-prompt.sh +34 -0
  388. package/src/scripts/herdr-question-open.sh +67 -0
  389. package/src/scripts/md-wrap.mjs +229 -0
  390. package/src/server/app.ts +19 -0
  391. package/src/server/serve.ts +49 -0
  392. package/src/sharddev/admission.ts +7 -0
  393. package/src/sharddev/agentFiles.ts +127 -0
  394. package/src/sharddev/arenaView.ts +15 -0
  395. package/src/sharddev/as/groupBankV2.ts +36 -0
  396. package/src/sharddev/as/groupStepV2.ts +13 -0
  397. package/src/sharddev/as/ws.ts +30 -0
  398. package/src/sharddev/as/wsV2.ts +180 -0
  399. package/src/sharddev/assemblyscriptCompiler.d.mts +5 -0
  400. package/src/sharddev/assemblyscriptCompiler.mjs +14 -0
  401. package/src/sharddev/assetHandle.ts +84 -0
  402. package/src/sharddev/assetOwner.ts +70 -0
  403. package/src/sharddev/assetScope.ts +30 -0
  404. package/src/sharddev/assets.ts +21 -0
  405. package/src/sharddev/audio.ts +9 -0
  406. package/src/sharddev/audioEncode.ts +211 -0
  407. package/src/sharddev/author.ts +3 -0
  408. package/src/sharddev/authorError.ts +28 -0
  409. package/src/sharddev/authorManifest.ts +39 -0
  410. package/src/sharddev/bake/annulus.ts +19 -0
  411. package/src/sharddev/bake/assemblyscriptMemo.ts +76 -0
  412. package/src/sharddev/bake/assemblyscriptMemoPort.ts +4 -0
  413. package/src/sharddev/bake/authoredWorld.ts +201 -0
  414. package/src/sharddev/bake/basisEncoder.ts +95 -0
  415. package/src/sharddev/bake/basisGlb.ts +85 -0
  416. package/src/sharddev/bake/basisTool.ts +74 -0
  417. package/src/sharddev/bake/basisToolInputs.ts +476 -0
  418. package/src/sharddev/bake/byteCodec.ts +33 -0
  419. package/src/sharddev/bake/canvasAtlas.ts +406 -0
  420. package/src/sharddev/bake/coarseCopy.ts +59 -0
  421. package/src/sharddev/bake/colliders.ts +87 -0
  422. package/src/sharddev/bake/compactGlb.ts +224 -0
  423. package/src/sharddev/bake/compileScript.ts +119 -0
  424. package/src/sharddev/bake/compileScriptV2.ts +75 -0
  425. package/src/sharddev/bake/contactRows.ts +84 -0
  426. package/src/sharddev/bake/creaturePlacement.ts +117 -0
  427. package/src/sharddev/bake/export.ts +67 -0
  428. package/src/sharddev/bake/facetedGeometry.ts +379 -0
  429. package/src/sharddev/bake/farImpostor.ts +120 -0
  430. package/src/sharddev/bake/forest.ts +100 -0
  431. package/src/sharddev/bake/format-hook.mjs +2 -0
  432. package/src/sharddev/bake/generatorGlb.ts +23 -0
  433. package/src/sharddev/bake/geometryBounds.ts +77 -0
  434. package/src/sharddev/bake/geometryError.ts +48 -0
  435. package/src/sharddev/bake/glb.ts +355 -0
  436. package/src/sharddev/bake/glbCompression.ts +143 -0
  437. package/src/sharddev/bake/gltfSource.ts +59 -0
  438. package/src/sharddev/bake/groundMap.ts +142 -0
  439. package/src/sharddev/bake/image.ts +20 -0
  440. package/src/sharddev/bake/isleMap.ts +64 -0
  441. package/src/sharddev/bake/json.mjs +84 -0
  442. package/src/sharddev/bake/keyedSky.ts +47 -0
  443. package/src/sharddev/bake/keyedSkyMemo.ts +39 -0
  444. package/src/sharddev/bake/kinds.ts +137 -0
  445. package/src/sharddev/bake/lightSources.ts +31 -0
  446. package/src/sharddev/bake/mapAssembly.ts +84 -0
  447. package/src/sharddev/bake/mapRaster.ts +173 -0
  448. package/src/sharddev/bake/mapRest.ts +57 -0
  449. package/src/sharddev/bake/mapScenes.ts +234 -0
  450. package/src/sharddev/bake/materialGraph.ts +32 -0
  451. package/src/sharddev/bake/meadow.ts +27 -0
  452. package/src/sharddev/bake/meshoptChoiceMemo.ts +34 -0
  453. package/src/sharddev/bake/nativeInteractionFacts.ts +5 -0
  454. package/src/sharddev/bake/nativeLattice.ts +178 -0
  455. package/src/sharddev/bake/nativeRaster.ts +106 -0
  456. package/src/sharddev/bake/nativeTerrainField.ts +11 -0
  457. package/src/sharddev/bake/navigation-json.mjs +38 -0
  458. package/src/sharddev/bake/navigation.ts +113 -0
  459. package/src/sharddev/bake/navigationAsset.ts +18 -0
  460. package/src/sharddev/bake/nearPlaceholder.ts +206 -0
  461. package/src/sharddev/bake/normalizeRig.ts +80 -0
  462. package/src/sharddev/bake/phoneAstc.ts +93 -0
  463. package/src/sharddev/bake/placeholders.ts +581 -0
  464. package/src/sharddev/bake/placement.ts +80 -0
  465. package/src/sharddev/bake/portableBytes.ts +18 -0
  466. package/src/sharddev/bake/portableBytesMemo.ts +50 -0
  467. package/src/sharddev/bake/practiceCourse.ts +49 -0
  468. package/src/sharddev/bake/primitives.ts +96 -0
  469. package/src/sharddev/bake/props.ts +443 -0
  470. package/src/sharddev/bake/questPlacement.ts +98 -0
  471. package/src/sharddev/bake/rawTexture.ts +26 -0
  472. package/src/sharddev/bake/riderArms.ts +97 -0
  473. package/src/sharddev/bake/rig.ts +95 -0
  474. package/src/sharddev/bake/riggedHullRecipes.ts +40 -0
  475. package/src/sharddev/bake/signPlacements.ts +25 -0
  476. package/src/sharddev/bake/simplifier.ts +52 -0
  477. package/src/sharddev/bake/skinned.ts +312 -0
  478. package/src/sharddev/bake/slabChunks.ts +149 -0
  479. package/src/sharddev/bake/slabs.ts +263 -0
  480. package/src/sharddev/bake/source-loader.mjs +55 -0
  481. package/src/sharddev/bake/sourceMetadata.ts +54 -0
  482. package/src/sharddev/bake/species.ts +368 -0
  483. package/src/sharddev/bake/specimenCatalogue.ts +47 -0
  484. package/src/sharddev/bake/splatGround.ts +141 -0
  485. package/src/sharddev/bake/staticMaterials.ts +171 -0
  486. package/src/sharddev/bake/terrain.ts +195 -0
  487. package/src/sharddev/bake/texture.ts +33 -0
  488. package/src/sharddev/bake/textureWasm.ts +81 -0
  489. package/src/sharddev/bake/tileEncoder.ts +11 -0
  490. package/src/sharddev/bake/tileGrid.ts +62 -0
  491. package/src/sharddev/bake/v2Finite.ts +160 -0
  492. package/src/sharddev/bake/v2Fuel.ts +71 -0
  493. package/src/sharddev/bake/wholePartition.ts +74 -0
  494. package/src/sharddev/bake/wholePieceJoin.ts +147 -0
  495. package/src/sharddev/bake/world.ts +173 -0
  496. package/src/sharddev/bake/worldCollision.ts +128 -0
  497. package/src/sharddev/bake/worldGeometry.ts +237 -0
  498. package/src/sharddev/bake/worldGlb.ts +123 -0
  499. package/src/sharddev/bake/worldImage.ts +12 -0
  500. package/src/sharddev/bake/worldLod.ts +128 -0
  501. package/src/sharddev/bake/worldRows.ts +102 -0
  502. package/src/sharddev/bake/worldTextureMemo.ts +63 -0
  503. package/src/sharddev/bake/zstdBytesMemo.ts +52 -0
  504. package/src/sharddev/bake.ts +193 -0
  505. package/src/sharddev/bakePublication.ts +31 -0
  506. package/src/sharddev/behaviourSource.ts +94 -0
  507. package/src/sharddev/bin/wildshard.mjs +7 -0
  508. package/src/sharddev/blobBytes.ts +65 -0
  509. package/src/sharddev/blobs.ts +138 -0
  510. package/src/sharddev/bootInventory.ts +129 -0
  511. package/src/sharddev/bossProfiles.ts +18 -0
  512. package/src/sharddev/buildBehaviour.ts +77 -0
  513. package/src/sharddev/buildCacheMetrics.ts +17 -0
  514. package/src/sharddev/buildDecisionScripts.ts +122 -0
  515. package/src/sharddev/check.ts +118 -0
  516. package/src/sharddev/checkProject.ts +127 -0
  517. package/src/sharddev/cli.ts +200 -0
  518. package/src/sharddev/clientChannels.ts +169 -0
  519. package/src/sharddev/clientScripts.ts +10 -0
  520. package/src/sharddev/commons.ts +77 -0
  521. package/src/sharddev/commonsCosts.ts +11 -0
  522. package/src/sharddev/compileMovers.ts +11 -0
  523. package/src/sharddev/configBoundary.ts +6 -0
  524. package/src/sharddev/cookInput.ts +40 -0
  525. package/src/sharddev/crowds.ts +6 -0
  526. package/src/sharddev/decisionBindingMap.ts +11 -0
  527. package/src/sharddev/decisionScriptBindings.ts +117 -0
  528. package/src/sharddev/decisionScripts.ts +28 -0
  529. package/src/sharddev/decisionSource.ts +51 -0
  530. package/src/sharddev/dev.ts +113 -0
  531. package/src/sharddev/director.ts +26 -0
  532. package/src/sharddev/directorAbi.ts +77 -0
  533. package/src/sharddev/discoveryDocument.ts +97 -0
  534. package/src/sharddev/draft.ts +11 -0
  535. package/src/sharddev/eliteEntryRows.ts +29 -0
  536. package/src/sharddev/entries.ts +76 -0
  537. package/src/sharddev/entryReads.ts +73 -0
  538. package/src/sharddev/executeBundle.ts +55 -0
  539. package/src/sharddev/finds.ts +5 -0
  540. package/src/sharddev/formatJsonSchema.ts +3 -0
  541. package/src/sharddev/generationCache.ts +257 -0
  542. package/src/sharddev/generationRecipe.ts +94 -0
  543. package/src/sharddev/handwritten.ts +110 -0
  544. package/src/sharddev/immutable.ts +14 -0
  545. package/src/sharddev/interactions.ts +38 -0
  546. package/src/sharddev/kit/bakedGeometry.ts +16 -0
  547. package/src/sharddev/kit/geometryPack.ts +110 -0
  548. package/src/sharddev/ledger.ts +13 -0
  549. package/src/sharddev/looks/tileField.ts +67 -0
  550. package/src/sharddev/materialGraphFiles.ts +57 -0
  551. package/src/sharddev/materials.ts +574 -0
  552. package/src/sharddev/measure.ts +18 -0
  553. package/src/sharddev/modes.ts +115 -0
  554. package/src/sharddev/moverPrograms.ts +213 -0
  555. package/src/sharddev/movers.ts +75 -0
  556. package/src/sharddev/nativePopulationRows.ts +46 -0
  557. package/src/sharddev/newProject.ts +226 -0
  558. package/src/sharddev/noise.ts +54 -0
  559. package/src/sharddev/outputProduct.ts +188 -0
  560. package/src/sharddev/outputRuntime.ts +66 -0
  561. package/src/sharddev/performancePolicy.ts +29 -0
  562. package/src/sharddev/phasedBoss.ts +34 -0
  563. package/src/sharddev/physics.ts +194 -0
  564. package/src/sharddev/platformSections.ts +42 -0
  565. package/src/sharddev/plumbing.ts +8 -0
  566. package/src/sharddev/productOutput.ts +128 -0
  567. package/src/sharddev/project.ts +337 -0
  568. package/src/sharddev/projectCompilerIdentity.ts +94 -0
  569. package/src/sharddev/projectDecisions.ts +66 -0
  570. package/src/sharddev/projectEntryProof.ts +32 -0
  571. package/src/sharddev/projectGeneration.ts +219 -0
  572. package/src/sharddev/projectInputFiles.ts +47 -0
  573. package/src/sharddev/projectManifest.ts +108 -0
  574. package/src/sharddev/projectMap.ts +35 -0
  575. package/src/sharddev/projectOutput.ts +242 -0
  576. package/src/sharddev/projectPolicy.ts +17 -0
  577. package/src/sharddev/projectSections.ts +27 -0
  578. package/src/sharddev/questGraph.ts +25 -0
  579. package/src/sharddev/quests.ts +65 -0
  580. package/src/sharddev/random.ts +61 -0
  581. package/src/sharddev/refusals.ts +304 -0
  582. package/src/sharddev/reportCard.ts +13 -0
  583. package/src/sharddev/returnProjectionV2.ts +81 -0
  584. package/src/sharddev/rows.ts +192 -0
  585. package/src/sharddev/runtimeImports.ts +38 -0
  586. package/src/sharddev/runtimeMirrors.ts +39 -0
  587. package/src/sharddev/runtimePerformance.ts +38 -0
  588. package/src/sharddev/scene.ts +321 -0
  589. package/src/sharddev/sceneAnimation.ts +54 -0
  590. package/src/sharddev/sceneAudio.ts +64 -0
  591. package/src/sharddev/sceneDeclarations.ts +100 -0
  592. package/src/sharddev/sceneGraph.ts +139 -0
  593. package/src/sharddev/sceneTransform.ts +12 -0
  594. package/src/sharddev/schemaValidation.ts +61 -0
  595. package/src/sharddev/sections.ts +47 -0
  596. package/src/sharddev/shardSource.ts +59 -0
  597. package/src/sharddev/sourceReader.ts +26 -0
  598. package/src/sharddev/spawns.ts +38 -0
  599. package/src/sharddev/species/clips.ts +24 -0
  600. package/src/sharddev/species.ts +29 -0
  601. package/src/sharddev/speciesBrains.ts +19 -0
  602. package/src/sharddev/synth.ts +66 -0
  603. package/src/sharddev/test/compileDualScriptV2.ts +71 -0
  604. package/src/sharddev/test/compileSimV2.ts +21 -0
  605. package/src/sharddev/test/diskScriptScenario.ts +86 -0
  606. package/src/sharddev/test/scriptScenario.ts +249 -0
  607. package/src/sharddev/test/scriptSource.ts +12 -0
  608. package/src/sharddev/version.ts +4 -0
  609. package/src/sharddev/weapons/bowProfile.ts +20 -0
  610. package/src/sharddev/weapons/firearmRows.ts +11 -0
  611. package/src/sharddev/weapons/meleeProfile.ts +71 -0
  612. package/src/sharddev/weapons/thrownProfile.ts +10 -0
  613. package/src/sharddev/worldScenes.ts +308 -0
  614. package/src/sharddev/worldSource.ts +82 -0
  615. package/src/shards/_template/README.md +78 -0
  616. package/src/shards/_template/assets/2bf489fdb15f1734ddb4c4f32d500ec6da85c765ec7a4eb28dc6781160e7ec8c +0 -0
  617. package/src/shards/_template/assets/97ec4d8f75f5fa6239ee919444d6dc19fd35896bb305930c1f050ac6e0e0e6a6 +1 -0
  618. package/src/shards/_template/assets/a6a587a31327f936b1b04c05ade818c73fc8964260918662db43539465e27586 +0 -0
  619. package/src/shards/_template/assets/b4fbde0422e125b498c3dc8b9a5cc2516c8598f09e9d0e5f6b639b32f98179e6 +0 -0
  620. package/src/shards/_template/assets/bfa4dfc9c18979f904557ee8deab0058b8a399be10266f5fb1578b403f482fd4 +1 -0
  621. package/src/shards/_template/assets/ef3b7ff4fd22715771cb7d68a3977a903c5e7c3dc293542687d04b3ef3ace2cb +0 -0
  622. package/src/shards/_template/assets/f2db05998615ce1cb79ea96be32c168842eb6a2b34ec01feb86d36404603ee54 +0 -0
  623. package/src/shards/_template/assets/fef98ebb7fce6f66b26e78ac699e5c90f9bdcfaf8cabeb2b58125347eea8b4ab +0 -0
  624. package/src/shards/_template/behaviour/boss.as +39 -0
  625. package/src/shards/_template/behaviour/door.as +32 -0
  626. package/src/shards/_template/behaviour/hooks.json +129 -0
  627. package/src/shards/_template/behaviour/idle.as +75 -0
  628. package/src/shards/_template/behaviour/items.as +22 -0
  629. package/src/shards/_template/card/landscape.jpg +0 -0
  630. package/src/shards/_template/card/portrait.jpg +0 -0
  631. package/src/shards/_template/card/thumb.jpg +0 -0
  632. package/src/shards/_template/data/audio.json +45 -0
  633. package/src/shards/_template/data/bossDecision.json +83 -0
  634. package/src/shards/_template/data/budgets.json +70 -0
  635. package/src/shards/_template/data/card.json +281 -0
  636. package/src/shards/_template/data/clientScripts.json +987 -0
  637. package/src/shards/_template/data/creatures.json +65 -0
  638. package/src/shards/_template/data/director.json +39 -0
  639. package/src/shards/_template/data/encounters.json +96 -0
  640. package/src/shards/_template/data/items.json +172 -0
  641. package/src/shards/_template/data/layout.json +66 -0
  642. package/src/shards/_template/data/ledger.json +32 -0
  643. package/src/shards/_template/data/look.json +521 -0
  644. package/src/shards/_template/data/map.json +64 -0
  645. package/src/shards/_template/data/moves.json +16 -0
  646. package/src/shards/_template/data/placeholder.json +8 -0
  647. package/src/shards/_template/data/plumbing.json +32 -0
  648. package/src/shards/_template/data/quests.json +223 -0
  649. package/src/shards/_template/data/rows.json +423 -0
  650. package/src/shards/_template/data/skins.json +66 -0
  651. package/src/shards/_template/data/spawn.json +6 -0
  652. package/src/shards/_template/data/targets.json +150 -0
  653. package/src/shards/_template/data/text.json +12 -0
  654. package/src/shards/_template/data/ui.json +33 -0
  655. package/src/shards/_template/data/water.json +13 -0
  656. package/src/shards/_template/generators/behaviour.ts +34 -0
  657. package/src/shards/_template/generators/boss.ts +29 -0
  658. package/src/shards/_template/generators/buildOptions.ts +2 -0
  659. package/src/shards/_template/generators/cell.ts +224 -0
  660. package/src/shards/_template/generators/districts.ts +215 -0
  661. package/src/shards/_template/generators/farLook.ts +15 -0
  662. package/src/shards/_template/generators/generate.ts +27 -0
  663. package/src/shards/_template/generators/ground.ts +15 -0
  664. package/src/shards/_template/generators/kit.ts +69 -0
  665. package/src/shards/_template/generators/landscape.ts +59 -0
  666. package/src/shards/_template/generators/landscapeNoise.ts +62 -0
  667. package/src/shards/_template/generators/mapInputs.ts +10 -0
  668. package/src/shards/_template/generators/product.ts +100 -0
  669. package/src/shards/_template/generators/productOutput.ts +18 -0
  670. package/src/shards/_template/generators/props.ts +9 -0
  671. package/src/shards/_template/generators/templatePropsSource.ts +58 -0
  672. package/src/shards/_template/generators/terrain.ts +17 -0
  673. package/src/shards/_template/generators/world.ts +630 -0
  674. package/src/shards/_template/hero.json +10 -0
  675. package/src/shards/_template/look/entry-reads.json +20 -0
  676. package/src/shards/_template/manifest.json +281 -0
  677. package/src/shards/_template/shard.config.ts +10 -0
  678. package/src/shared/health.ts +10 -0
  679. package/src/tools/build-web.ts +59 -0
  680. package/src/tsconfig.json +30 -0
  681. package/src/web/app.tsx +53 -0
  682. package/src/web/index.html +12 -0
  683. package/src/web/main.tsx +10 -0
  684. package/src/web/tsconfig.json +13 -0
  685. package/tsconfig.author.json +23 -0
  686. package/tsconfig.commons.json +21 -0
  687. package/tsconfig.json +47 -0
  688. package/tsconfig.sharddev.json +20 -0
@@ -0,0 +1,157 @@
1
+ #!/usr/bin/env node
2
+ // repo-kit's Vite/Vitest temp redirect and janitor. One copy lives in repo-kit; every org repo carries a byte-identical
3
+ // copy at scripts/vite-tmp.mjs, and repo-kit's test/tooling/vite-tmp-coverage.test.mjs fails when a repo's Vite or
4
+ // Vitest config does not use it or its copy drifts. Background: meta docs/plans/TEMP-HYGIENE-PLAN.md.
5
+ //
6
+ // macOS empties /private/tmp and $TMPDIR at boot, before login, and a boot with many files there hangs. Vitest 5 writes
7
+ // every transformed module under join(os.tmpdir(), nanoid()) (a 21-character folder holding client/ and ssr/), and a
8
+ // killed run never removes it. viteTmpRoot() points TMPDIR at <repo>/tmp/vitest/<pid> while the config loads, which is
9
+ // before Vitest creates either temp folder, and removes that folder when Vitest closes or the process exits.
10
+ // Run directly (`node scripts/vite-tmp.mjs [--dry-run]`) it is the janitor: dead runs' folders in tmp/vitest, the
11
+ // stale Vitest folders already in the system temp dir, and an over-size compile cache.
12
+ import { spawn } from 'node:child_process';
13
+ import { lstatSync, mkdirSync, readdirSync, rmSync, statSync, writeFileSync } from 'node:fs';
14
+ import { tmpdir } from 'node:os';
15
+ import { join, resolve } from 'node:path';
16
+ import { pathToFileURL } from 'node:url';
17
+
18
+ const HOUR = 3_600_000, GIB = 1024 ** 3;
19
+ const ROOT = resolve(import.meta.dirname, '..');
20
+ /** Vitest's folder name: nanoid(), 21 characters of [A-Za-z0-9_-]. */
21
+ const VITEST_FOLDER = /^[A-Za-z0-9_-]{21}$/u;
22
+ const VITEST_CHILDREN = new Set(['client', 'ssr']);
23
+
24
+ /** @param {string} path @returns {import('node:fs').Dirent[]} */
25
+ function entries(path) {
26
+ try { return readdirSync(path, { withFileTypes: true }); } catch { return []; }
27
+ }
28
+ /** Milliseconds since a path changed; a folder another process has just removed counts as new.
29
+ * @param {string} path @param {number} now */
30
+ export function age(path, now) {
31
+ try { return now - lstatSync(path).mtimeMs; } catch { return 0; }
32
+ }
33
+ /** @param {number} pid */
34
+ function alive(pid) {
35
+ try { process.kill(pid, 0); return true; } catch (error) { return error instanceof Error && 'code' in error && error.code === 'EPERM'; }
36
+ }
37
+ /** @param {string} path @param {boolean} dryRun */
38
+ function remove(path, dryRun) {
39
+ if (dryRun) return true;
40
+ try { rmSync(path, { recursive: true, force: true }); return true; } catch { return false; }
41
+ }
42
+
43
+ /** tmp/vitest/<pid> of a dead process, idle for an hour. A reused pid only delays the sweep.
44
+ * @param {string} root @param {{now?:number,dryRun?:boolean}} [options] */
45
+ export function sweepVitestRuns(root, { now = Date.now(), dryRun = false } = {}) {
46
+ const parent = join(root, 'tmp/vitest');
47
+ return entries(parent).filter(row => {
48
+ if (!row.isDirectory() || !/^[1-9][0-9]*$/u.test(row.name) || alive(Number(row.name))) return false;
49
+ const path = join(parent, row.name);
50
+ return age(path, now) > HOUR && remove(path, dryRun);
51
+ }).length;
52
+ }
53
+
54
+ /** Vitest folders left in the system temp dir by runs from before the redirect, or by a config that skipped it: a
55
+ * 21-character folder whose only children are client/ and/or ssr/, none of the three touched for an hour.
56
+ * @param {string} directory @param {{now?:number,dryRun?:boolean}} [options] */
57
+ export function sweepSystemTemp(directory, { now = Date.now(), dryRun = false } = {}) {
58
+ let removed = 0, files = 0;
59
+ for (const row of entries(directory)) {
60
+ if (!row.isDirectory() || !VITEST_FOLDER.test(row.name)) continue;
61
+ const path = join(directory, row.name), children = entries(path);
62
+ if (children.length === 0 || !children.every(child => child.isDirectory() && VITEST_CHILDREN.has(child.name))) continue;
63
+ if (Math.min(age(path, now), ...children.map(child => age(join(path, child.name), now))) <= HOUR) continue;
64
+ const count = children.reduce((sum, child) => sum + entries(join(path, child.name)).length, 0);
65
+ if (remove(path, dryRun)) { removed++; files += count; }
66
+ }
67
+ return { removed, files };
68
+ }
69
+
70
+ /** Node's compile cache has no eviction. Keep a day, then cap it oldest first; a deleted entry is only a recompile.
71
+ * @param {string} directory @param {{capBytes?:number,maxAgeMs?:number,now?:number,dryRun?:boolean}} [options] */
72
+ export function pruneCompileCache(directory, { capBytes = 4 * GIB, maxAgeMs = 24 * HOUR, now = Date.now(), dryRun = false } = {}) {
73
+ const files = entries(directory).filter(row => row.isDirectory()).flatMap(version => {
74
+ const parent = join(directory, version.name);
75
+ return entries(parent).filter(row => row.isFile()).flatMap(row => {
76
+ try {
77
+ const path = join(parent, row.name), { mtimeMs, blocks } = lstatSync(path);
78
+ return [{ path, mtimeMs, bytes: blocks * 512 }];
79
+ } catch { return []; }
80
+ });
81
+ }).sort((a, b) => a.mtimeMs - b.mtimeMs);
82
+ const beforeBytes = files.reduce((sum, file) => sum + file.bytes, 0);
83
+ let bytes = beforeBytes, removed = 0;
84
+ for (const file of files) {
85
+ if (now - file.mtimeMs <= maxAgeMs && bytes <= capBytes) break;
86
+ if (remove(file.path, dryRun)) { bytes -= file.bytes; removed++; }
87
+ }
88
+ return { files: files.length, beforeBytes, removed, keptBytes: bytes };
89
+ }
90
+
91
+ /** A killed run never reaches its own cleanup, so a later one sweeps, detached, at most every ten minutes.
92
+ * @param {NodeJS.ProcessEnv} env @param {string} root @param {string} janitor */
93
+ function sweepAfterKilledRuns(env, root, janitor) {
94
+ if (env.CI !== undefined || env.VITEST_TMP_ROOT !== undefined) return;
95
+ const stamp = join(root, 'tmp/.temp-janitor-stamp');
96
+ try {
97
+ if (Date.now() - statSync(stamp).mtimeMs < 600_000) return;
98
+ } catch { /* Never swept here. */ }
99
+ try {
100
+ writeFileSync(stamp, '');
101
+ spawn(process.execPath, [janitor], { detached: true, stdio: 'ignore', env: { ...env, WS_SYSTEM_TMPDIR: env.TMPDIR ?? tmpdir() } })
102
+ .on('error', () => undefined).unref();
103
+ } catch { /* Housekeeping never fails a run. */ }
104
+ }
105
+
106
+ /**
107
+ * Point TMPDIR (and NODE_COMPILE_CACHE) at <root>/tmp/vitest/<pid>, or $VITEST_TMP_ROOT/<pid>, until cleanup().
108
+ * Workers and their children inherit it. A second call in the same process reuses the folder and its exit handler.
109
+ * @param {NodeJS.ProcessEnv} [env] @param {{root?:string,janitor?:string}} [options]
110
+ */
111
+ export function temporaryRun(env = process.env, { root = ROOT, janitor = import.meta.filename } = {}) {
112
+ const parent = env.VITEST_TMP_ROOT ?? join(root, 'tmp/vitest');
113
+ mkdirSync(parent, { recursive: true });
114
+ try { writeFileSync(join(root, 'tmp/.gitignore'), '*\n', { flag: 'wx' }); } catch { /* Already there, or root's own. */ }
115
+ sweepAfterKilledRuns(env, root, janitor);
116
+ const original = env.TMPDIR, originalCompileCache = env.NODE_COMPILE_CACHE;
117
+ const dir = join(parent, String(process.pid));
118
+ mkdirSync(dir, { recursive: true });
119
+ env.TMPDIR = dir;
120
+ // Workers import the cache files by their per-run path, so a shared compile cache gains an entry per module per run.
121
+ const compileCache = join(dir, 'node-compile-cache');
122
+ env.NODE_COMPILE_CACHE = compileCache;
123
+ const cleanup = () => {
124
+ rmSync(dir, { recursive: true, force: true });
125
+ if (env.TMPDIR === dir) {
126
+ if (original === undefined) Reflect.deleteProperty(env, 'TMPDIR');
127
+ else env.TMPDIR = original;
128
+ }
129
+ if (env.NODE_COMPILE_CACHE === compileCache) {
130
+ if (originalCompileCache === undefined) Reflect.deleteProperty(env, 'NODE_COMPILE_CACHE');
131
+ else env.NODE_COMPILE_CACHE = originalCompileCache;
132
+ }
133
+ };
134
+ if (env.WS_VITEST_TMP_DIR !== dir) {
135
+ env.WS_VITEST_TMP_DIR = dir;
136
+ process.once('exit', cleanup);
137
+ }
138
+ return { dir, cleanup };
139
+ }
140
+
141
+ /** The plugin every vite.config.* and vitest.config.* in an org repo lists first in `plugins`.
142
+ * @param {{root?:string,janitor?:string}} [options] */
143
+ export function viteTmpRoot(options = {}) {
144
+ const { cleanup } = temporaryRun(process.env, options);
145
+ return {
146
+ name: 'wildshard:vite-tmp-root',
147
+ /** @param {{vitest:{onClose:(listener:()=>void)=>void}}} context */
148
+ configureVitest({ vitest }) { vitest.onClose(cleanup); },
149
+ };
150
+ }
151
+
152
+ if (process.argv[1] !== undefined && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {
153
+ const dryRun = process.argv.includes('--dry-run'), cache = process.env.NODE_COMPILE_CACHE;
154
+ const system = process.env.WS_SYSTEM_TMPDIR ?? tmpdir();
155
+ console.info(JSON.stringify({ dryRun, vitestRuns: sweepVitestRuns(ROOT, { dryRun }), systemTemp: sweepSystemTemp(system, { dryRun }),
156
+ compileCache: cache === undefined ? null : pruneCompileCache(cache, { dryRun }) }));
157
+ }
@@ -0,0 +1,32 @@
1
+ [
2
+ {
3
+ "wave": "W1",
4
+ "revision": "adb48b6a08619986f16a3c2e304c4db5610df932",
5
+ "record": "b9fb99185:docs/plans/shard-platform/STATE.md",
6
+ "customLines": {
7
+ "far-reach": 3158,
8
+ "sunscar-dunes": 1841
9
+ },
10
+ "platformLines": {
11
+ "engine": 67206,
12
+ "game": 33346,
13
+ "sdk": 7240,
14
+ "format": 7102
15
+ }
16
+ },
17
+ {
18
+ "wave": "W2",
19
+ "revision": "68e72579516106c8307cb72e1ec1b91d3b7f649e",
20
+ "record": "project/archive/2026-11-04-shard-platform/w2-m0-inventory.md",
21
+ "customLines": {
22
+ "pine-hollow": 22996,
23
+ "driftwood-isle": 18015
24
+ },
25
+ "platformLines": {
26
+ "engine": 67897,
27
+ "game": 35276,
28
+ "sdk": 7536,
29
+ "format": 7749
30
+ }
31
+ }
32
+ ]
@@ -0,0 +1,4 @@
1
+ /** Execute the same author CLI used by the packed SDK, bundled against the current workspace sources. */
2
+ export function runWildshard(args: readonly string[]): Promise<void>;
3
+
4
+ export function prepareWildshard():Promise<{code:string,modules:string[],reused:boolean}>;
@@ -0,0 +1,105 @@
1
+ #!/usr/bin/env node
2
+ // Execute the workspace's author CLI without requiring a previously packed SDK or a Vite dev server.
3
+ import { build } from 'vite';
4
+ import { createBuildCacheCounters, observeBuildCache, formatBuildCacheReport } from '@wildshard/engine/scripts/build-cache-report.mjs';
5
+ import { captureProductInputs, recordBundle, inputRecorderPlugin } from '@wildshard/engine/scripts/shardfile-inputs.mjs';
6
+ import { basename, resolve } from 'node:path';
7
+ import { existsSync, readFileSync } from 'node:fs';
8
+ import { createHash } from 'node:crypto';
9
+ import { pathToFileURL } from 'node:url';
10
+ import { createRequire } from 'node:module';
11
+ import { importBundle } from './import-bundle.mjs';
12
+ import { shardfileValidationRevision } from '@wildshard/engine/scripts/shardfile-validation-revision.mjs';
13
+ import { rapierAlias } from '@wildshard/engine/vite/rapier.ts';
14
+ import { authorBundleCached } from '@wildshard/engine/scripts/author-bundle-cache.mjs';
15
+ import { decisionLegacyLines } from '@wildshard/engine/scripts/decision-legacy-lines.mjs';
16
+ import { outputManifest, shardOutputs } from '@wildshard/engine/scripts/shard-outputs.mjs';
17
+ import { findShardSource, shardFolderName } from '../src/sharddev/shardSource.ts';
18
+
19
+ /** The verbs whose first operand is a shard source (or, for validate and prove, a built folder). */
20
+ const SOURCE_VERBS = new Set(['check', 'synth', 'build', 'dev', 'validate', 'prove']);
21
+
22
+ let runner;
23
+ /** SA3 (J170): `build` and `check` end by writing the folder's shard file, the step `pack` was. It stays out of the author
24
+ * bundle: the same module serves `wildshard build <folder>` and the deprecated `pack` (src/cli/main.ts). */
25
+ async function writeShardfile(dir, source, options = {}) {
26
+ const { writeShardfile: write } = await import('../src/cli/shardfile/shardfile.ts');
27
+ return (await write({ dir, source, report: line => console.info(line), ...options })).file;
28
+ }
29
+ // The bundle's import.meta.dirname stays src/sdk: headless.ts finds bake/headlessWorker.ts beside it, and src/sdk keeps the
30
+ // author tools' dependency links until the host leaves at P3 (P1-F4).
31
+ const authorRequire = createRequire(resolve(import.meta.dirname, '../src/sharddev/package.json'));
32
+ // P4: the project is the repo the author stands in; the tools are this package.
33
+ const projectRoot = () => process.cwd();
34
+ /** Compile the trusted CLI once before product children; later invocations
35
+ * verify the same content-addressed compiler and replay its complete inputs. */
36
+ export function prepareWildshard() {
37
+ const root=projectRoot();
38
+ // Resolver policy is executable compiler input too: a source-only cache hit
39
+ // must not replay a bundle built before an externalization change.
40
+ const policy = createHash('sha256').update(readFileSync(import.meta.filename)).digest('hex');
41
+ return authorBundleCached(root,[shardfileValidationRevision(root),policy],async()=>{
42
+ const result = await build({ configFile: false, publicDir: false, resolve: { alias: rapierAlias }, logLevel: 'silent', define: { __SHARDFILE_VALIDATOR__: JSON.stringify(shardfileValidationRevision()), 'import.meta.dirname': JSON.stringify(resolve(import.meta.dirname, '../src/sharddev')) }, plugins: [inputRecorderPlugin({execution:true}), { name: 'author-node-vite', enforce: 'pre', resolveId(id) {
43
+ if (id === 'vite') return { id: pathToFileURL(resolve(import.meta.dirname,'shardfile-vite.mjs')).href, external: true };
44
+ if (id === 'sharp' || id === 'binaryen' || id === '@typescript/typescript6' || /^assemblyscript(?:\/|$)/u.test(id)) return { id: pathToFileURL(authorRequire.resolve(id)).href, external: true };
45
+ return null;
46
+ } }], build: { write: false, minify: false, lib: { entry: resolve(import.meta.dirname, '../src/sharddev/cli.ts'), formats: ['es'], fileName: 'cli' }, rolldownOptions: { platform: 'node', external: [/^node:/u], output: { codeSplitting: false } } } });
47
+ recordBundle(result,{execution:true});
48
+ const output = Array.isArray(result) ? result.at(0) : result;
49
+ if (output === undefined || !('output' in output)) throw new Error('Author CLI build produced no output');
50
+ const chunks = output.output.filter((chunk) => chunk.type === 'chunk');
51
+ if (chunks.length !== 1) throw new Error('Author CLI must bundle to one module');
52
+ return { code: chunks[0].code, modules: chunks[0].moduleIds ?? Object.keys(chunks[0].modules) };
53
+ });
54
+ }
55
+ /** Bundle trusted workspace tooling once; external Vite resolves against this installed tool, not a data URL. */
56
+ export async function runWildshard(args) {
57
+ const receipt = args.find(arg=>arg.startsWith('--input-receipt='))?.slice('--input-receipt='.length);
58
+ if (receipt !== undefined) { await captureProductInputs(projectRoot(),receipt,()=>runWildshard(args.filter(arg=>!arg.startsWith('--input-receipt=')))); return; }
59
+ runner ??= (async () => {
60
+ const started = performance.now(), bundle = await prepareWildshard();
61
+ recordBundle({output:[{type:'chunk',moduleIds:bundle.modules}]},{execution:true});
62
+ const cli = await importBundle(bundle.code);
63
+ if (cli === null || typeof cli !== 'object' || !('runCli' in cli) || typeof cli.runCli !== 'function') throw new Error('Author CLI has no runner');
64
+ if (process.env.GITHUB_ACTIONS === 'true') console.info(`author timing: ${JSON.stringify({ pid: process.pid, phase: 'compiler-bundle', reused:bundle.reused, product: args[1] ?? null, seconds: Number(((performance.now() - started) / 1000).toFixed(3)) })}`);
65
+ return cli.runCli;
66
+ })();
67
+ const root = projectRoot();
68
+ // SA16 (J317): a repo path names its shard source at src/ (one shard) or its one src/shards/<slug>/ (several).
69
+ if (SOURCE_VERBS.has(args[0] ?? '') && args[1] !== undefined && !args[1].startsWith('--')) args = [args[0], findShardSource(args[1]), ...args.slice(2)];
70
+ const project = args[1] === undefined ? undefined : resolve(args[1]);
71
+ // The folder build checks the manifest slug against: a src/ source takes its manifest's slug (new <dir> <slug>).
72
+ const folder = project === undefined ? '' : shardFolderName(project);
73
+ // SF88g: `--output=<slug>` builds one declared output of the folder, under its own slug and composed manifest
74
+ const selected = args.find(arg => arg.startsWith('--output='))?.slice(9);
75
+ const output = project === undefined || selected === undefined ? undefined : shardOutputs(root, folder)?.find(row => row.slug === selected);
76
+ if (selected !== undefined && output === undefined) throw new Error(`wildshard: ${basename(project ?? '')} declares no output ${selected}`);
77
+ const manifest = project === undefined || !['build', 'check', 'validate', 'prove'].includes(args[0] ?? '') || !existsSync(resolve(project, 'shard.config.ts')) ? undefined : {
78
+ folder: output?.slug ?? folder, ...(output !== undefined ? { composed: outputManifest(root, folder, output.row) } : existsSync(resolve(project, 'manifest.json')) ? { file: resolve(project, 'manifest.json') } : {}),
79
+ imageRoots: [{ prefix: `/src/shards/${folder}/`, directory: project }, { prefix: '/assets/', directory: resolve(root, 'public/assets') }],
80
+ };
81
+ const legacy = project === undefined ? undefined : decisionLegacyLines(root, folder);
82
+ await (await runner)(args, { ...(legacy === undefined ? {} : { decisionLegacyLines: legacy }), ...(manifest === undefined ? {} : { manifest }), writeShardfile });
83
+ }
84
+
85
+ if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {
86
+ const counters=createBuildCacheCounters(),stop=observeBuildCache(counters);
87
+ let complete=false;
88
+ try {
89
+ let args=process.argv.slice(2);
90
+ // SA4: `check` takes its flags anywhere; with --json, stdout is the verdict document alone, so every log goes to stderr.
91
+ if(args[0]==='check'){
92
+ const rest=args.slice(1);
93
+ args=['check',...rest.filter(arg=>!arg.startsWith('--')),...rest.filter(arg=>arg.startsWith('--'))];
94
+ if(args.includes('--json'))for(const level of ['info','log','warn','debug'])console[level]=console.error.bind(console);
95
+ }
96
+ if(args[0]==='--prepare-compiler') {
97
+ if(args.length!==1)throw new Error('Compiler preparation accepts no other arguments');
98
+ const started=performance.now(),compiler=await prepareWildshard();
99
+ console.info(`Author compiler ${compiler.reused?'reused':'built'} in ${((performance.now()-started)/1000).toFixed(3)}s (before product workers)`);
100
+ } else await runWildshard(args);
101
+ complete=true;
102
+ }
103
+ catch (error) { console.error(error instanceof Error ? error.message : String(error)); process.exitCode = 1; }
104
+ finally {stop();console.error(`\n${formatBuildCacheReport(counters.snapshot(complete))}`);}
105
+ }
@@ -0,0 +1,10 @@
1
+ /** SHA256 for every bounded regular checkpoint file. */
2
+ export function checkpointHashes(directory: string): Record<string, string>;
3
+ /** Validate transport metadata and return the original native outcome. */
4
+ export function readWitnessManifest(file: string | URL): Record<string, unknown>;
5
+ /** Validated payload metadata for a cached witness; legacy manifests have no transport table. */
6
+ export function witnessPayloadHashes(file: string | URL): Record<string, string> | undefined;
7
+ /** Small generated manifest carrying every checkpoint SHA256. */
8
+ export function cachedWitnessManifest(directory: string): string;
9
+ /** Darwin compares normative bit identity; every platform verifies its local cache independently. */
10
+ export function compareWitnessManifests(expected: string, actual: string, platform?: string): void;
@@ -0,0 +1,84 @@
1
+ // Native checkpoint hash metadata; the explicit native recorder owns caching and publication.
2
+ import { createHash } from 'node:crypto';
3
+ import { readFileSync, readdirSync, statSync } from 'node:fs';
4
+ import { resolve } from 'node:path';
5
+ import * as v from 'valibot';
6
+
7
+ const digest = v.pipe(v.string(), v.regex(/^[0-9a-f]{64}$/u));
8
+ const fileName = v.pipe(v.string(), v.regex(/^[a-zA-Z0-9_-]+(?:\.snap|\.json)?\.(?:gz|json)$/u));
9
+ /** Every bounded regular checkpoint file and its SHA256; never follow directories or links.
10
+ * @param {string} dir */
11
+ export function checkpointHashes(dir) {
12
+ const files = readdirSync(dir, { withFileTypes: true });
13
+ if (files.length === 0 || files.length > 64) throw new Error('Invalid checkpoint file count');
14
+ return Object.fromEntries(files.sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0).map(entry => {
15
+ v.parse(fileName, entry.name);
16
+ if (!entry.isFile()) throw new Error(`Invalid checkpoint file ${entry.name}`);
17
+ const path = resolve(dir, entry.name);
18
+ if (statSync(path).size > 64 * 1024 * 1024) throw new Error(`Unbounded checkpoint file ${entry.name}`);
19
+ return [entry.name, createHash('sha256').update(readFileSync(path)).digest('hex')];
20
+ }));
21
+ }
22
+
23
+ const Metadata = v.strictObject({ version: v.literal(1), notice: v.literal('DO NOT EDIT: generated by the retained TypeScript witness; run.mjs checkpoints regenerates and compares.'), payloads: v.record(fileName, digest) });
24
+
25
+ /** Read the validated committed hash table without requiring old generated payloads in the source directory.
26
+ * Native readers validate actual cache files through the shared runner before admitting a continuation.
27
+ * @param {string | URL} file @returns {Record<string, string> | undefined} */
28
+ export function witnessPayloadHashes(file) {
29
+ const parsed = v.parse(v.record(v.string(), v.unknown()), JSON.parse(readFileSync(file, 'utf8')));
30
+ return parsed.cache === undefined ? undefined : v.parse(Metadata, parsed.cache).payloads;
31
+ }
32
+
33
+ /** Read the native outcome while validating and removing only the cache transport metadata.
34
+ * @param {string | URL} file @returns {Record<string, unknown>} */
35
+ export function readWitnessManifest(file) {
36
+ const parsed = v.parse(v.record(v.string(), v.unknown()), JSON.parse(readFileSync(file, 'utf8')));
37
+ if (parsed.cache !== undefined) v.parse(Metadata, parsed.cache);
38
+ const { cache: _cache, ...outcome } = parsed;
39
+ return outcome;
40
+ }
41
+
42
+ /** Add a small, reproducible hash table to a native manifest without committing its generated payloads.
43
+ * @param {string} directory @returns {string} */
44
+ export function cachedWitnessManifest(directory) {
45
+ const file = resolve(directory, 'manifest.json'), outcome = readWitnessManifest(file);
46
+ const { 'manifest.json': _manifest, ...payloads } = checkpointHashes(directory);
47
+ if (Object.keys(payloads).length === 0) throw new Error('Witness generated no checkpoint payloads');
48
+ const cache = v.parse(Metadata, { version: 1, notice: 'DO NOT EDIT: generated by the retained TypeScript witness; run.mjs checkpoints regenerates and compares.', payloads });
49
+ return `${JSON.stringify({ ...outcome, cache }, null, 2)}\n`;
50
+ }
51
+
52
+ /** Fields Linux records exactly as Darwin does, measured on CI run 42367941424: Pine's ticks and canonical hashes, and
53
+ * Driftwood's ticks, effects and each checkpoint's name, tick and profile. Gzip payload hashes differ by host, and
54
+ * Driftwood's `sha`, `digest`, `endDigest` and `tape` carry float state that differs on Linux.
55
+ * @param {Record<string, unknown>} outcome */
56
+ function portableOutcome({ ticks, hashes, effects, checkpoints }) {
57
+ const rows = v.parse(v.optional(v.array(v.looseObject({ name: v.string(), tick: v.number(), profile: v.unknown() }))), checkpoints);
58
+ return { ticks, hashes, effects, checkpoints: rows?.map(({ name, tick, profile }) => ({ name, tick, profile })) };
59
+ }
60
+
61
+ /** Two manifests that played nothing would match, and the match would prove nothing (E7's empty room).
62
+ * @param {Record<string, unknown>} outcome */
63
+ function assertPlayed({ ticks }) {
64
+ const counts = typeof ticks === 'number' ? [ticks] : Object.values(v.parse(v.optional(v.record(v.string(), v.number()), {}), ticks));
65
+ if (!counts.some(count => count > 0)) throw new Error('Witness played no ticks; its match would prove nothing');
66
+ }
67
+
68
+ /** Validate a regenerated witness against the committed one. Darwin compares it whole: native bit identity is normative
69
+ * there. Other hosts compare the portable outcome, so a behaviour drift goes red on Linux too.
70
+ * @param {string} expected @param {string} actual @param {string} [platform] */
71
+ export function compareWitnessManifests(expected, actual, platform = process.platform) {
72
+ /** @param {string} text */
73
+ const parse = (text) => {
74
+ const manifest = v.parse(v.record(v.string(), v.unknown()), JSON.parse(text));
75
+ v.parse(Metadata, manifest.cache);
76
+ const { inputs: _inputs, ...outcome } = manifest;
77
+ return outcome;
78
+ };
79
+ const before = parse(expected), after = parse(actual);
80
+ assertPlayed(before); assertPlayed(after);
81
+ const same = platform === 'darwin' ? JSON.stringify(before) === JSON.stringify(after)
82
+ : JSON.stringify(portableOutcome(before)) === JSON.stringify(portableOutcome(after));
83
+ if (!same) throw new Error('Regenerated witness hashes or outcomes changed; record this behaviour change deliberately');
84
+ }
@@ -0,0 +1,10 @@
1
+ /** A native retained TypeScript recorder and its exact loaded input closure. */
2
+ export interface WitnessGenerationSpec {
3
+ root: URL; slug: string; inputs: string; files: Iterable<string>; manifest: URL;
4
+ select: (directory: URL) => void; generate: () => Promise<unknown>;
5
+ record?: boolean; forceCompare?: boolean; compare?: boolean;
6
+ }
7
+ /** Generate into the shared cache, select its output for readers, and optionally record only the small hash manifest. */
8
+ export function generateWitness(spec: WitnessGenerationSpec): Promise<{
9
+ directory: string; key: string; hit: boolean; hashes: Record<string, string>; manifest: string;
10
+ }>;
@@ -0,0 +1,45 @@
1
+ // G292: native witness recorders use the shared generation cache, with their original TypeScript tapes and outcomes.
2
+ import { createHash } from 'node:crypto';
3
+ import { readFileSync, writeFileSync } from 'node:fs';
4
+ import { dirname, resolve } from 'node:path';
5
+ import { fileURLToPath, pathToFileURL } from 'node:url';
6
+ import * as v from 'valibot';
7
+ import { runNativeRecorder } from '@wildshard/engine/scripts/native-recorder-cache.mjs';
8
+ import { cachedWitnessManifest, compareWitnessManifests } from './witness-checkpoints.mjs';
9
+
10
+ const Payloads = v.record(v.string(), v.pipe(v.string(), v.regex(/^[0-9a-f]{64}$/u)));
11
+ const Header = v.object({ cache: v.object({ payloads: Payloads }) });
12
+
13
+ /** Play a retained native recorder into the shared cache; all consumers read that verified output directory.
14
+ * During migration a legacy manifest is decorated from its still-committed payloads. Those files remain until CI
15
+ * proves the cold cache path. Only explicit recording writes the small manifest back to the repository.
16
+ * @param {{root:URL,slug:string,inputs:string,files:Iterable<string>,manifest:URL,
17
+ * select:(directory:URL)=>void,generate:()=>Promise<unknown>,record?:boolean,forceCompare?:boolean,compare?:boolean}} spec
18
+ * @returns {Promise<{directory:string,key:string,hit:boolean,hashes:Record<string,string>,manifest:string}>} */
19
+ export async function generateWitness(spec) {
20
+ const root = fileURLToPath(spec.root), source = fileURLToPath(spec.manifest);
21
+ const committed = readFileSync(source, 'utf8');
22
+ const parsed = v.safeParse(Header, JSON.parse(committed));
23
+ const expected = parsed.success ? committed : cachedWitnessManifest(dirname(source));
24
+ const outputs = [...Object.keys(v.parse(Header, JSON.parse(expected)).cache.payloads), 'manifest.json'].sort();
25
+ const inputs = Object.fromEntries([...new Set(spec.files)].sort().map(url => {
26
+ if (!url.startsWith(spec.root.href)) throw new Error('Witness input is outside its repository');
27
+ return [decodeURIComponent(url.slice(spec.root.href.length)), createHash('sha256').update(readFileSync(new URL(url))).digest('hex')];
28
+ }));
29
+ const result = await runNativeRecorder(root, {
30
+ id: `witness-${spec.slug}`, inputs, outputs, platform: 'native',
31
+ command: ['node', '--experimental-transform-types', '--import', './scripts/sim-node-loader.mjs', `test/proof/${spec.slug}/run.mjs`, 'checkpoints'],
32
+ }, {
33
+ ...(spec.forceCompare === undefined ? {} : { forceCompare: spec.forceCompare }),
34
+ generate: async directory => {
35
+ spec.select(pathToFileURL(`${resolve(directory)}/`));
36
+ await spec.generate();
37
+ writeFileSync(resolve(directory, 'manifest.json'), cachedWitnessManifest(directory));
38
+ },
39
+ });
40
+ const manifest = readFileSync(resolve(result.directory, 'manifest.json'), 'utf8');
41
+ if (spec.compare !== false) compareWitnessManifests(expected, manifest);
42
+ spec.select(pathToFileURL(`${resolve(result.directory)}/`));
43
+ if (spec.record === true) writeFileSync(source, manifest);
44
+ return { directory: result.directory, key: result.key, hit: result.hit, hashes: result.hashes, manifest };
45
+ }
@@ -0,0 +1,8 @@
1
+ export const WITNESS_MANIFEST: RegExp;
2
+ export function isWitnessManifest(file: string): boolean;
3
+ export function manifestOutcome(text: string): string;
4
+ export function withInputs(text: string, inputs: string): string;
5
+ export function witnessSlugs(root: string): string[];
6
+ /** Verify native cached witnesses before bounded tests, without writing committed manifests or payloads. */
7
+ export function prepareWitnesses(root: string): Promise<void>;
8
+ export function refreshWitnesses(root: string, cache: string): Promise<Record<string, string>>;
@@ -0,0 +1,157 @@
1
+ #!/usr/bin/env node
2
+ // SF6b for the native witnesses: every test/proof/<slug>/checkpoints/manifest.json fences its committed payloads with an
3
+ // `inputs` hash of every module the witness loads (and pnpm-lock), so almost any landing leaves it stale. Builders no
4
+ // longer refresh that hash: the serialized pusher (scripts/regenerate-committed.mjs) re-records every stale witness with
5
+ // its real recorder on the clean export and commits the refreshed manifests only when every payload and recorded outcome
6
+ // is byte-identical. Any other byte is a behaviour change: the push fails, naming the shard and the payload, and the
7
+ // owner rebakes on purpose (`run.mjs checkpoints`, committed with the source).
8
+ //
9
+ // node scripts/witness-manifests.mjs --refresh <export> <cache-dir> <result.json> (regenerate-committed spawns it)
10
+ import { spawn } from 'node:child_process';
11
+ import { once } from 'node:events';
12
+ import { createHash } from 'node:crypto';
13
+ import { closeSync, existsSync, mkdirSync, mkdtempSync, openSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs';
14
+ import { tmpdir } from 'node:os';
15
+ import { resolve } from 'node:path';
16
+ import { pathToFileURL } from 'node:url';
17
+ import { compareWitnessManifests } from './witness-checkpoints.mjs';
18
+
19
+ export const WITNESS_MANIFEST = /^test\/proof\/[^/]+\/checkpoints\/manifest\.json$/u;
20
+ /** @param {string} file */
21
+ export const isWitnessManifest = (file) => WITNESS_MANIFEST.test(file);
22
+ const INPUTS = /^ {2}"inputs": "[^"\n]*"(,?)$/mu;
23
+ /** The manifest with its `inputs` value blanked: every byte a re-record must reproduce exactly. @param {string} text */
24
+ export function manifestOutcome(text) {
25
+ if (text.split('\n').filter((line) => line.startsWith(' "inputs": ')).length !== 1 || !INPUTS.test(text)) throw new Error('Witness manifest has no single top-level "inputs" line');
26
+ return text.replace(INPUTS, ' "inputs": ""$1');
27
+ }
28
+ /** @param {string} text @param {string} inputs */
29
+ export function withInputs(text, inputs) {
30
+ manifestOutcome(text);
31
+ if (!/^[0-9a-f]+$/u.test(inputs)) throw new Error(`Invalid witness inputs hash ${inputs}`);
32
+ return text.replace(INPUTS, ` "inputs": "${inputs}"$1`);
33
+ }
34
+
35
+ /** Every witness with committed checkpoints: test/proof/<slug>/{run.mjs,checkpoints/manifest.json}. @param {string} root */
36
+ export function witnessSlugs(root) {
37
+ const proof = resolve(root, 'test/proof');
38
+ if (!existsSync(proof)) return [];
39
+ return readdirSync(proof).filter((slug) => existsSync(resolve(proof, slug, 'run.mjs')) && existsSync(resolve(proof, slug, 'checkpoints/manifest.json'))).sort();
40
+ }
41
+
42
+ /** One witness mode in a fresh Node (the tests' own invocation; transform types for the Driftwood worker classes).
43
+ * @param {string} root @param {string} slug @param {string} mode @param {string} logs */
44
+ async function witness(root, slug, mode, logs) {
45
+ const out = resolve(logs, `${slug}-${mode}.out`), err = resolve(logs, `${slug}-${mode}.err`);
46
+ const outFd = openSync(out, 'w'), errFd = openSync(err, 'w');
47
+ try {
48
+ const child = spawn(process.execPath, ['--experimental-transform-types', '--import', './scripts/sim-node-loader.mjs', `test/proof/${slug}/run.mjs`, mode], { cwd: root, stdio: ['ignore', outFd, errFd] });
49
+ const [code] = await once(child, 'close');
50
+ return { code, stdout: readFileSync(out, 'utf8'), stderr: readFileSync(err, 'utf8') };
51
+ } finally { closeSync(outFd); closeSync(errFd); }
52
+ }
53
+ /** The `fresh` mode's JSON report: { status, inputs, recorded }.
54
+ * @param {string} root @param {string} slug @param {string} logs */
55
+ async function freshness(root, slug, logs) {
56
+ const run = await witness(root, slug, 'fresh', logs);
57
+ const line = run.stdout.trim().split('\n').at(-1) ?? '';
58
+ let report;
59
+ try { report = JSON.parse(line); } catch { throw new Error(`${slug}: the witness's fresh mode printed no report (exit ${String(run.code)}):\n${run.stderr.slice(-2000)}`); }
60
+ if ((report.status !== 'fresh' && report.status !== 'stale') || typeof report.inputs !== 'string') throw new Error(`${slug}: unexpected fresh report ${line}`);
61
+ return report;
62
+ }
63
+ /** @param {string | Uint8Array} bytes */
64
+ const sha = (bytes) => createHash('sha256').update(bytes).digest('hex');
65
+ /** name → bytes of every committed checkpoint file. @param {string} root @param {string} slug */
66
+ function payloads(root, slug) {
67
+ const dir = resolve(root, 'test/proof', slug, 'checkpoints');
68
+ return new Map(readdirSync(dir).sort().map((name) => [name, readFileSync(resolve(dir, name))]));
69
+ }
70
+
71
+ /** Prepare native witness caches before Vitest's bounded continuations; cold generation belongs outside their timeout.
72
+ * @param {string} root @returns {Promise<void>} */
73
+ export async function prepareWitnesses(root) {
74
+ const logs = mkdtempSync(resolve(tmpdir(), 'wildshard-witness-prepare-'));
75
+ try {
76
+ const results = await Promise.allSettled(witnessSlugs(root).map(async slug => {
77
+ const committed = readFileSync(resolve(root, 'test/proof', slug, 'checkpoints/manifest.json'), 'utf8');
78
+ if (!Object.hasOwn(JSON.parse(committed), 'cache')) return;
79
+ const run = await witness(root, slug, 'cache-verify', logs);
80
+ if (run.code !== 0) throw new Error(`${slug}: native cache preparation failed (exit ${String(run.code)}):\n${run.stderr.slice(-2000)}`);
81
+ const result = JSON.parse(run.stdout.trim().split('\n').at(-1) ?? '');
82
+ if (typeof result.manifest !== 'string') throw new Error(`${slug}: cache preparation returned no manifest`);
83
+ compareWitnessManifests(committed, result.manifest);
84
+ }));
85
+ const failures = results.flatMap(result => result.status === 'rejected' ? [result.reason instanceof Error ? result.reason.message : String(result.reason)] : []);
86
+ if (failures.length > 0) throw new Error(`Native cache preparation failed:\n${failures.join('\n')}`);
87
+ } finally { rmSync(logs, { recursive: true, force: true }); }
88
+ }
89
+
90
+ /**
91
+ * Refresh every stale witness manifest in an immutable export. Returns { file: refreshed manifest text } for the stale
92
+ * ones; throws, naming each shard and its differing payloads, when a re-record changes any byte but the inputs hash.
93
+ * `cache` remembers (slug, inputs, payloads) triples a recorder already reproduced, so a retried push skips the replay.
94
+ * @param {string} root @param {string} cache @returns {Promise<Record<string, string>>}
95
+ */
96
+ export async function refreshWitnesses(root, cache) {
97
+ const logs = mkdtempSync(resolve(tmpdir(), 'wildshard-witness-'));
98
+ mkdirSync(cache, { recursive: true });
99
+ try {
100
+ const results = await Promise.allSettled(witnessSlugs(root).map(async (slug) => {
101
+ const file = `test/proof/${slug}/checkpoints/manifest.json`, before = payloads(root, slug);
102
+ const committed = (before.get('manifest.json') ?? Buffer.alloc(0)).toString('utf8');
103
+ const report = await freshness(root, slug, logs);
104
+ if (Object.hasOwn(JSON.parse(committed), 'cache')) {
105
+ const run = await witness(root, slug, 'cache-record', logs);
106
+ if (run.code !== 0) throw new Error(`${slug}: cached recorder failed (exit ${String(run.code)}):\n${run.stderr.slice(-2000)}`);
107
+ const result = JSON.parse(run.stdout.trim().split('\n').at(-1) ?? '');
108
+ if (typeof result.manifest !== 'string') throw new Error(`${slug}: cached recorder returned no manifest`);
109
+ compareWitnessManifests(committed, result.manifest);
110
+ if (result.manifest !== withInputs(committed, report.inputs)) throw new Error(`${slug}: cached recorder changed its recorded outcome or input fence`);
111
+ if (result.manifest === committed) return null;
112
+ writeFileSync(resolve(root, file), result.manifest);
113
+ const check = await freshness(root, slug, logs);
114
+ if (check.status !== 'fresh') throw new Error(`${slug}: cached manifest is still stale`);
115
+ return [file, result.manifest];
116
+ }
117
+ if (report.status === 'fresh') return null;
118
+ const key = sha([slug, report.inputs, manifestOutcome(committed), ...[...before].filter(([name]) => name !== 'manifest.json').map(([name, bytes]) => `${name}:${sha(bytes)}`)].join('\0'));
119
+ const receipt = resolve(cache, key);
120
+ let refreshed = withInputs(committed, report.inputs);
121
+ if (!existsSync(receipt)) {
122
+ const run = await witness(root, slug, 'checkpoints', logs);
123
+ if (run.code !== 0) throw new Error(`${slug}: the recorder failed (exit ${String(run.code)}):\n${run.stderr.slice(-2000)}`);
124
+ const after = payloads(root, slug), differing = [...new Set([...before.keys(), ...after.keys()])].filter((name) => {
125
+ const a = before.get(name), b = after.get(name);
126
+ if (a === undefined || b === undefined) return true;
127
+ return name === 'manifest.json' ? manifestOutcome(a.toString('utf8')) !== manifestOutcome(b.toString('utf8')) : !a.equals(b);
128
+ });
129
+ if (differing.length > 0) throw new Error(`${slug}: the re-record on clean HEAD changed ${differing.map((name) => name === 'manifest.json' ? 'manifest.json (recorded outcome)' : name).join(', ')}; a behaviour change needs its owner to rebake on purpose (run.mjs checkpoints, committed with the source)`);
130
+ refreshed = (after.get('manifest.json') ?? Buffer.alloc(0)).toString('utf8');
131
+ if (refreshed !== withInputs(committed, report.inputs)) throw new Error(`${slug}: the recorder wrote inputs ${JSON.stringify(INPUTS.exec(refreshed)?.[0])} but fresh reported ${report.inputs}`);
132
+ }
133
+ writeFileSync(resolve(root, file), refreshed);
134
+ const check = await freshness(root, slug, logs);
135
+ if (check.status !== 'fresh') throw new Error(`${slug}: the refreshed manifest is still stale (${JSON.stringify(check)})`);
136
+ writeFileSync(receipt, `${file} ${report.inputs}\n`);
137
+ return [file, refreshed];
138
+ }));
139
+ const failures = results.flatMap((result) => result.status === 'rejected' ? [result.reason instanceof Error ? result.reason.message : String(result.reason)] : []);
140
+ if (failures.length > 0) throw new Error(`witness-manifests: payloads changed; the push refuses them:\n${failures.map((line) => ` ${line}`).join('\n')}`);
141
+ return Object.fromEntries(results.flatMap((result) => result.status === 'fulfilled' && result.value !== null ? [result.value] : []));
142
+ } finally { rmSync(logs, { recursive: true, force: true }); }
143
+ }
144
+
145
+ if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {
146
+ const args = process.argv.slice(2), [flag = '', root = '', cache = '', result = ''] = args;
147
+ try {
148
+ if (args.length === 2 && flag === '--prepare') {
149
+ await prepareWitnesses(resolve(root)); console.log('witness-manifests: native checkpoint caches verified');
150
+ } else {
151
+ if (args.length !== 4 || flag !== '--refresh') throw new Error('Use --prepare <export> or --refresh <export> <cache-dir> <result.json>');
152
+ const from = performance.now(), refreshed = await refreshWitnesses(resolve(root), resolve(cache));
153
+ writeFileSync(resolve(result), JSON.stringify(refreshed));
154
+ console.log(`witness-manifests: ${String(Object.keys(refreshed).length)} of ${String(witnessSlugs(resolve(root)).length)} re-recorded in ${((performance.now() - from) / 1000).toFixed(1)} s, payloads byte-identical`);
155
+ }
156
+ } catch (error) { console.error(error instanceof Error ? error.message : String(error)); process.exitCode = 1; }
157
+ }
@@ -0,0 +1,4 @@
1
+ export const WORKTREES: '.worktrees';
2
+ export const WORKTREE_GLOB: string;
3
+ export function isWorktreePath(path: string): boolean;
4
+ export function worktreeWatchIgnored(root?: string): RegExp[];