@wildshard/sdk 0.0.0 → 0.2.3

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 (687) hide show
  1. package/GUIDE.md +790 -0
  2. package/README.md +14 -4
  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 +371 -4
  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 +46 -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 +24 -0
  358. package/src/cli/bin.mjs +8 -0
  359. package/src/cli/delete/delete.ts +258 -0
  360. package/src/cli/help.ts +196 -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 +292 -0
  365. package/src/cli/report.ts +16 -0
  366. package/src/cli/shardfile/command.ts +50 -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/arenaView.ts +15 -0
  394. package/src/sharddev/as/groupBankV2.ts +36 -0
  395. package/src/sharddev/as/groupStepV2.ts +13 -0
  396. package/src/sharddev/as/ws.ts +30 -0
  397. package/src/sharddev/as/wsV2.ts +180 -0
  398. package/src/sharddev/assemblyscriptCompiler.d.mts +5 -0
  399. package/src/sharddev/assemblyscriptCompiler.mjs +14 -0
  400. package/src/sharddev/assetHandle.ts +84 -0
  401. package/src/sharddev/assetOwner.ts +70 -0
  402. package/src/sharddev/assetScope.ts +30 -0
  403. package/src/sharddev/assets.ts +21 -0
  404. package/src/sharddev/audio.ts +9 -0
  405. package/src/sharddev/audioEncode.ts +211 -0
  406. package/src/sharddev/author.ts +3 -0
  407. package/src/sharddev/authorError.ts +28 -0
  408. package/src/sharddev/authorManifest.ts +39 -0
  409. package/src/sharddev/bake/annulus.ts +19 -0
  410. package/src/sharddev/bake/assemblyscriptMemo.ts +76 -0
  411. package/src/sharddev/bake/assemblyscriptMemoPort.ts +4 -0
  412. package/src/sharddev/bake/authoredWorld.ts +201 -0
  413. package/src/sharddev/bake/basisEncoder.ts +95 -0
  414. package/src/sharddev/bake/basisGlb.ts +85 -0
  415. package/src/sharddev/bake/basisTool.ts +74 -0
  416. package/src/sharddev/bake/basisToolInputs.ts +476 -0
  417. package/src/sharddev/bake/byteCodec.ts +33 -0
  418. package/src/sharddev/bake/canvasAtlas.ts +406 -0
  419. package/src/sharddev/bake/coarseCopy.ts +59 -0
  420. package/src/sharddev/bake/colliders.ts +87 -0
  421. package/src/sharddev/bake/compactGlb.ts +224 -0
  422. package/src/sharddev/bake/compileScript.ts +119 -0
  423. package/src/sharddev/bake/compileScriptV2.ts +75 -0
  424. package/src/sharddev/bake/contactRows.ts +84 -0
  425. package/src/sharddev/bake/creaturePlacement.ts +117 -0
  426. package/src/sharddev/bake/export.ts +67 -0
  427. package/src/sharddev/bake/facetedGeometry.ts +379 -0
  428. package/src/sharddev/bake/farImpostor.ts +120 -0
  429. package/src/sharddev/bake/forest.ts +100 -0
  430. package/src/sharddev/bake/format-hook.mjs +2 -0
  431. package/src/sharddev/bake/generatorGlb.ts +23 -0
  432. package/src/sharddev/bake/geometryBounds.ts +77 -0
  433. package/src/sharddev/bake/geometryError.ts +48 -0
  434. package/src/sharddev/bake/glb.ts +355 -0
  435. package/src/sharddev/bake/glbCompression.ts +143 -0
  436. package/src/sharddev/bake/gltfSource.ts +59 -0
  437. package/src/sharddev/bake/groundMap.ts +142 -0
  438. package/src/sharddev/bake/image.ts +20 -0
  439. package/src/sharddev/bake/isleMap.ts +64 -0
  440. package/src/sharddev/bake/json.mjs +84 -0
  441. package/src/sharddev/bake/keyedSky.ts +47 -0
  442. package/src/sharddev/bake/keyedSkyMemo.ts +39 -0
  443. package/src/sharddev/bake/kinds.ts +137 -0
  444. package/src/sharddev/bake/lightSources.ts +31 -0
  445. package/src/sharddev/bake/mapAssembly.ts +84 -0
  446. package/src/sharddev/bake/mapRaster.ts +173 -0
  447. package/src/sharddev/bake/mapRest.ts +57 -0
  448. package/src/sharddev/bake/mapScenes.ts +234 -0
  449. package/src/sharddev/bake/materialGraph.ts +32 -0
  450. package/src/sharddev/bake/meadow.ts +27 -0
  451. package/src/sharddev/bake/meshoptChoiceMemo.ts +34 -0
  452. package/src/sharddev/bake/nativeInteractionFacts.ts +5 -0
  453. package/src/sharddev/bake/nativeLattice.ts +178 -0
  454. package/src/sharddev/bake/nativeRaster.ts +106 -0
  455. package/src/sharddev/bake/nativeTerrainField.ts +11 -0
  456. package/src/sharddev/bake/navigation-json.mjs +38 -0
  457. package/src/sharddev/bake/navigation.ts +113 -0
  458. package/src/sharddev/bake/navigationAsset.ts +18 -0
  459. package/src/sharddev/bake/nearPlaceholder.ts +206 -0
  460. package/src/sharddev/bake/normalizeRig.ts +80 -0
  461. package/src/sharddev/bake/phoneAstc.ts +93 -0
  462. package/src/sharddev/bake/placeholders.ts +581 -0
  463. package/src/sharddev/bake/placement.ts +80 -0
  464. package/src/sharddev/bake/portableBytes.ts +18 -0
  465. package/src/sharddev/bake/portableBytesMemo.ts +50 -0
  466. package/src/sharddev/bake/practiceCourse.ts +49 -0
  467. package/src/sharddev/bake/primitives.ts +96 -0
  468. package/src/sharddev/bake/props.ts +443 -0
  469. package/src/sharddev/bake/questPlacement.ts +98 -0
  470. package/src/sharddev/bake/rawTexture.ts +26 -0
  471. package/src/sharddev/bake/riderArms.ts +97 -0
  472. package/src/sharddev/bake/rig.ts +95 -0
  473. package/src/sharddev/bake/riggedHullRecipes.ts +40 -0
  474. package/src/sharddev/bake/signPlacements.ts +25 -0
  475. package/src/sharddev/bake/simplifier.ts +52 -0
  476. package/src/sharddev/bake/skinned.ts +312 -0
  477. package/src/sharddev/bake/slabChunks.ts +149 -0
  478. package/src/sharddev/bake/slabs.ts +263 -0
  479. package/src/sharddev/bake/source-loader.mjs +55 -0
  480. package/src/sharddev/bake/sourceMetadata.ts +54 -0
  481. package/src/sharddev/bake/species.ts +368 -0
  482. package/src/sharddev/bake/specimenCatalogue.ts +47 -0
  483. package/src/sharddev/bake/splatGround.ts +141 -0
  484. package/src/sharddev/bake/staticMaterials.ts +171 -0
  485. package/src/sharddev/bake/terrain.ts +195 -0
  486. package/src/sharddev/bake/texture.ts +33 -0
  487. package/src/sharddev/bake/textureWasm.ts +81 -0
  488. package/src/sharddev/bake/tileEncoder.ts +11 -0
  489. package/src/sharddev/bake/tileGrid.ts +62 -0
  490. package/src/sharddev/bake/v2Finite.ts +160 -0
  491. package/src/sharddev/bake/v2Fuel.ts +71 -0
  492. package/src/sharddev/bake/wholePartition.ts +74 -0
  493. package/src/sharddev/bake/wholePieceJoin.ts +147 -0
  494. package/src/sharddev/bake/world.ts +173 -0
  495. package/src/sharddev/bake/worldCollision.ts +128 -0
  496. package/src/sharddev/bake/worldGeometry.ts +237 -0
  497. package/src/sharddev/bake/worldGlb.ts +123 -0
  498. package/src/sharddev/bake/worldImage.ts +12 -0
  499. package/src/sharddev/bake/worldLod.ts +128 -0
  500. package/src/sharddev/bake/worldRows.ts +102 -0
  501. package/src/sharddev/bake/worldTextureMemo.ts +63 -0
  502. package/src/sharddev/bake/zstdBytesMemo.ts +52 -0
  503. package/src/sharddev/bake.ts +193 -0
  504. package/src/sharddev/bakePublication.ts +31 -0
  505. package/src/sharddev/behaviourSource.ts +94 -0
  506. package/src/sharddev/bin/wildshard.mjs +7 -0
  507. package/src/sharddev/blobBytes.ts +65 -0
  508. package/src/sharddev/blobs.ts +138 -0
  509. package/src/sharddev/bootInventory.ts +129 -0
  510. package/src/sharddev/bossProfiles.ts +18 -0
  511. package/src/sharddev/buildBehaviour.ts +77 -0
  512. package/src/sharddev/buildCacheMetrics.ts +17 -0
  513. package/src/sharddev/buildDecisionScripts.ts +122 -0
  514. package/src/sharddev/check.ts +117 -0
  515. package/src/sharddev/checkProject.ts +126 -0
  516. package/src/sharddev/cli.ts +191 -0
  517. package/src/sharddev/clientChannels.ts +169 -0
  518. package/src/sharddev/clientScripts.ts +10 -0
  519. package/src/sharddev/commons.ts +77 -0
  520. package/src/sharddev/commonsCosts.ts +11 -0
  521. package/src/sharddev/compileMovers.ts +11 -0
  522. package/src/sharddev/configBoundary.ts +6 -0
  523. package/src/sharddev/cookInput.ts +40 -0
  524. package/src/sharddev/crowds.ts +6 -0
  525. package/src/sharddev/decisionBindingMap.ts +11 -0
  526. package/src/sharddev/decisionScriptBindings.ts +117 -0
  527. package/src/sharddev/decisionScripts.ts +28 -0
  528. package/src/sharddev/decisionSource.ts +51 -0
  529. package/src/sharddev/dev.ts +113 -0
  530. package/src/sharddev/director.ts +26 -0
  531. package/src/sharddev/directorAbi.ts +77 -0
  532. package/src/sharddev/discoveryDocument.ts +97 -0
  533. package/src/sharddev/draft.ts +11 -0
  534. package/src/sharddev/eliteEntryRows.ts +29 -0
  535. package/src/sharddev/entries.ts +76 -0
  536. package/src/sharddev/entryReads.ts +73 -0
  537. package/src/sharddev/executeBundle.ts +55 -0
  538. package/src/sharddev/finds.ts +5 -0
  539. package/src/sharddev/formatJsonSchema.ts +3 -0
  540. package/src/sharddev/generationCache.ts +257 -0
  541. package/src/sharddev/generationRecipe.ts +94 -0
  542. package/src/sharddev/handwritten.ts +110 -0
  543. package/src/sharddev/immutable.ts +14 -0
  544. package/src/sharddev/interactions.ts +38 -0
  545. package/src/sharddev/kit/bakedGeometry.ts +16 -0
  546. package/src/sharddev/kit/geometryPack.ts +110 -0
  547. package/src/sharddev/ledger.ts +13 -0
  548. package/src/sharddev/looks/tileField.ts +67 -0
  549. package/src/sharddev/materialGraphFiles.ts +57 -0
  550. package/src/sharddev/materials.ts +574 -0
  551. package/src/sharddev/measure.ts +18 -0
  552. package/src/sharddev/modes.ts +115 -0
  553. package/src/sharddev/moverPrograms.ts +213 -0
  554. package/src/sharddev/movers.ts +75 -0
  555. package/src/sharddev/nativePopulationRows.ts +46 -0
  556. package/src/sharddev/newProject.ts +247 -0
  557. package/src/sharddev/noise.ts +54 -0
  558. package/src/sharddev/outputProduct.ts +188 -0
  559. package/src/sharddev/outputRuntime.ts +66 -0
  560. package/src/sharddev/performancePolicy.ts +18 -0
  561. package/src/sharddev/phasedBoss.ts +34 -0
  562. package/src/sharddev/physics.ts +194 -0
  563. package/src/sharddev/platformSections.ts +42 -0
  564. package/src/sharddev/plumbing.ts +8 -0
  565. package/src/sharddev/productOutput.ts +128 -0
  566. package/src/sharddev/project.ts +337 -0
  567. package/src/sharddev/projectCompilerIdentity.ts +94 -0
  568. package/src/sharddev/projectDecisions.ts +66 -0
  569. package/src/sharddev/projectEntryProof.ts +32 -0
  570. package/src/sharddev/projectGeneration.ts +219 -0
  571. package/src/sharddev/projectInputFiles.ts +47 -0
  572. package/src/sharddev/projectManifest.ts +108 -0
  573. package/src/sharddev/projectMap.ts +35 -0
  574. package/src/sharddev/projectOutput.ts +242 -0
  575. package/src/sharddev/projectPolicy.ts +17 -0
  576. package/src/sharddev/projectSections.ts +27 -0
  577. package/src/sharddev/questGraph.ts +25 -0
  578. package/src/sharddev/quests.ts +65 -0
  579. package/src/sharddev/random.ts +61 -0
  580. package/src/sharddev/refusals.ts +234 -0
  581. package/src/sharddev/reportCard.ts +13 -0
  582. package/src/sharddev/returnProjectionV2.ts +81 -0
  583. package/src/sharddev/rows.ts +192 -0
  584. package/src/sharddev/runtimeImports.ts +38 -0
  585. package/src/sharddev/runtimeMirrors.ts +39 -0
  586. package/src/sharddev/runtimePerformance.ts +38 -0
  587. package/src/sharddev/scene.ts +321 -0
  588. package/src/sharddev/sceneAnimation.ts +54 -0
  589. package/src/sharddev/sceneAudio.ts +64 -0
  590. package/src/sharddev/sceneDeclarations.ts +100 -0
  591. package/src/sharddev/sceneGraph.ts +139 -0
  592. package/src/sharddev/sceneTransform.ts +12 -0
  593. package/src/sharddev/schemaValidation.ts +61 -0
  594. package/src/sharddev/sections.ts +47 -0
  595. package/src/sharddev/shardSource.ts +59 -0
  596. package/src/sharddev/sourceReader.ts +26 -0
  597. package/src/sharddev/spawns.ts +38 -0
  598. package/src/sharddev/species/clips.ts +24 -0
  599. package/src/sharddev/species.ts +29 -0
  600. package/src/sharddev/speciesBrains.ts +19 -0
  601. package/src/sharddev/synth.ts +66 -0
  602. package/src/sharddev/test/compileDualScriptV2.ts +71 -0
  603. package/src/sharddev/test/compileSimV2.ts +21 -0
  604. package/src/sharddev/test/diskScriptScenario.ts +86 -0
  605. package/src/sharddev/test/scriptScenario.ts +249 -0
  606. package/src/sharddev/test/scriptSource.ts +12 -0
  607. package/src/sharddev/version.ts +4 -0
  608. package/src/sharddev/weapons/bowProfile.ts +20 -0
  609. package/src/sharddev/weapons/firearmRows.ts +11 -0
  610. package/src/sharddev/weapons/meleeProfile.ts +71 -0
  611. package/src/sharddev/weapons/thrownProfile.ts +10 -0
  612. package/src/sharddev/worldScenes.ts +308 -0
  613. package/src/sharddev/worldSource.ts +82 -0
  614. package/src/shards/_template/README.md +78 -0
  615. package/src/shards/_template/assets/2bf489fdb15f1734ddb4c4f32d500ec6da85c765ec7a4eb28dc6781160e7ec8c +0 -0
  616. package/src/shards/_template/assets/97ec4d8f75f5fa6239ee919444d6dc19fd35896bb305930c1f050ac6e0e0e6a6 +1 -0
  617. package/src/shards/_template/assets/a6a587a31327f936b1b04c05ade818c73fc8964260918662db43539465e27586 +0 -0
  618. package/src/shards/_template/assets/b4fbde0422e125b498c3dc8b9a5cc2516c8598f09e9d0e5f6b639b32f98179e6 +0 -0
  619. package/src/shards/_template/assets/bfa4dfc9c18979f904557ee8deab0058b8a399be10266f5fb1578b403f482fd4 +1 -0
  620. package/src/shards/_template/assets/ef3b7ff4fd22715771cb7d68a3977a903c5e7c3dc293542687d04b3ef3ace2cb +0 -0
  621. package/src/shards/_template/assets/f2db05998615ce1cb79ea96be32c168842eb6a2b34ec01feb86d36404603ee54 +0 -0
  622. package/src/shards/_template/assets/fef98ebb7fce6f66b26e78ac699e5c90f9bdcfaf8cabeb2b58125347eea8b4ab +0 -0
  623. package/src/shards/_template/behaviour/boss.as +39 -0
  624. package/src/shards/_template/behaviour/door.as +32 -0
  625. package/src/shards/_template/behaviour/hooks.json +129 -0
  626. package/src/shards/_template/behaviour/idle.as +75 -0
  627. package/src/shards/_template/behaviour/items.as +22 -0
  628. package/src/shards/_template/card/landscape.jpg +0 -0
  629. package/src/shards/_template/card/portrait.jpg +0 -0
  630. package/src/shards/_template/card/thumb.jpg +0 -0
  631. package/src/shards/_template/data/audio.json +45 -0
  632. package/src/shards/_template/data/bossDecision.json +83 -0
  633. package/src/shards/_template/data/budgets.json +70 -0
  634. package/src/shards/_template/data/card.json +281 -0
  635. package/src/shards/_template/data/clientScripts.json +987 -0
  636. package/src/shards/_template/data/creatures.json +65 -0
  637. package/src/shards/_template/data/director.json +39 -0
  638. package/src/shards/_template/data/encounters.json +96 -0
  639. package/src/shards/_template/data/items.json +172 -0
  640. package/src/shards/_template/data/layout.json +66 -0
  641. package/src/shards/_template/data/ledger.json +32 -0
  642. package/src/shards/_template/data/look.json +521 -0
  643. package/src/shards/_template/data/map.json +64 -0
  644. package/src/shards/_template/data/moves.json +16 -0
  645. package/src/shards/_template/data/placeholder.json +8 -0
  646. package/src/shards/_template/data/plumbing.json +32 -0
  647. package/src/shards/_template/data/quests.json +223 -0
  648. package/src/shards/_template/data/rows.json +423 -0
  649. package/src/shards/_template/data/skins.json +66 -0
  650. package/src/shards/_template/data/spawn.json +6 -0
  651. package/src/shards/_template/data/targets.json +150 -0
  652. package/src/shards/_template/data/text.json +12 -0
  653. package/src/shards/_template/data/ui.json +33 -0
  654. package/src/shards/_template/data/water.json +13 -0
  655. package/src/shards/_template/generators/behaviour.ts +34 -0
  656. package/src/shards/_template/generators/boss.ts +29 -0
  657. package/src/shards/_template/generators/buildOptions.ts +2 -0
  658. package/src/shards/_template/generators/cell.ts +224 -0
  659. package/src/shards/_template/generators/districts.ts +215 -0
  660. package/src/shards/_template/generators/farLook.ts +15 -0
  661. package/src/shards/_template/generators/generate.ts +27 -0
  662. package/src/shards/_template/generators/ground.ts +15 -0
  663. package/src/shards/_template/generators/kit.ts +69 -0
  664. package/src/shards/_template/generators/landscape.ts +59 -0
  665. package/src/shards/_template/generators/landscapeNoise.ts +62 -0
  666. package/src/shards/_template/generators/mapInputs.ts +10 -0
  667. package/src/shards/_template/generators/product.ts +100 -0
  668. package/src/shards/_template/generators/productOutput.ts +18 -0
  669. package/src/shards/_template/generators/props.ts +9 -0
  670. package/src/shards/_template/generators/templatePropsSource.ts +58 -0
  671. package/src/shards/_template/generators/terrain.ts +17 -0
  672. package/src/shards/_template/generators/world.ts +630 -0
  673. package/src/shards/_template/hero.json +10 -0
  674. package/src/shards/_template/look/entry-reads.json +20 -0
  675. package/src/shards/_template/manifest.json +281 -0
  676. package/src/shards/_template/shard.config.ts +10 -0
  677. package/src/shared/health.ts +10 -0
  678. package/src/tools/build-web.ts +59 -0
  679. package/src/tsconfig.json +30 -0
  680. package/src/web/app.tsx +53 -0
  681. package/src/web/index.html +12 -0
  682. package/src/web/main.tsx +10 -0
  683. package/src/web/tsconfig.json +13 -0
  684. package/tsconfig.author.json +23 -0
  685. package/tsconfig.commons.json +21 -0
  686. package/tsconfig.json +47 -0
  687. package/tsconfig.sharddev.json +20 -0
@@ -0,0 +1,809 @@
1
+ // LAND-SIMPLIFY (J240, J249, J250, J258): land a plan worktree on main by fast-forward, then get out of the way.
2
+ // 1. From .worktrees/<slug> on plan/<slug> (scripts/worktree.mjs new): one land per worktree (its lock).
3
+ // 2. Rebase first if main is already ahead, then push plan/<slug> under a lease its own reflog vouches for; the
4
+ // split pre-push runs (DS9).
5
+ // 3. Wait for that exact SHA's `ci` to go green.
6
+ // 4. Rebase onto origin/main if it moved during CI. Any conflict stops (no stamps are tracked since LS1, J250). A rebase
7
+ // that changes the lockfile or a package.json runs `pnpm install --frozen-lockfile` before any push.
8
+ // A clean rebase carries the branch's green run (J249: "they don't have to re-CI on rebase").
9
+ // 5. Push the SHA to main, never forced. The pre-push knows it is land's (WS_LAND_MAIN_PUSH): exact runs nothing
10
+ // more, carried runs lint, TypeScript and the static checks, no Vitest (LS3). A lost race rebases and retries,
11
+ // at most 5 tries (J258).
12
+ // 6. Fast-forward the canonical checkout when it is on main and clean (J247, WL7).
13
+ // 7. A `landed` receipt; main-watch follows main's own `ci` and reports it (LS5).
14
+ // 8. Delete origin's plan branch and remove this worktree (--keep skips it).
15
+ // Main's CI runs after every landing; if it goes red, the lane that landed last fixes it forward or reverts it.
16
+ //
17
+ // WORKTREE-LAND-STANDARD WL3: this is repo-kit's copy (files/scripts/land.mjs). What differs between repos lives in
18
+ // the repo's own `land.config.json` at its root, every key optional (no file: all defaults):
19
+ // workflows the hosted workflows, by name, whose exact-SHA push runs must be green (default ["ci"]);
20
+ // gh the GitHub CLI land asks Actions through (default "gh"; a path with a slash is from the repo root);
21
+ // install the command run when a rebase moves pnpm-lock.yaml or a package.json (default pnpm's frozen install;
22
+ // null: no install);
23
+ // flaky TEST-SPEED TS10's flaky re-run and quarantine (default null: off; a red run stays red). An object
24
+ // {quarantine, artifacts, packedStep, owner}: the J200 quarantine file, the artifact pattern holding
25
+ // the shard reports, the packed step a flaky failure must be limited to, and the quarantine's owner.
26
+ import {execFileSync,spawn,spawnSync} from 'node:child_process';
27
+ import {appendFileSync,existsSync,linkSync,lstatSync,mkdirSync,mkdtempSync,readFileSync,readdirSync,realpathSync,renameSync,rmSync,writeFileSync} from 'node:fs';
28
+ import {homedir} from 'node:os';
29
+ import {dirname,join,resolve} from 'node:path';
30
+ import {pathToFileURL} from 'node:url';
31
+ import {canonicalRoot,followMain,withStoreUse} from './worktree.mjs';
32
+ import {stopWorktreeProcesses} from './worktree-reap.mjs';
33
+
34
+ /** The settings a repo without `land.config.json` gets: J195/J240's one `ci` workflow, pnpm's frozen install, no TS10. */
35
+ export const LAND_DEFAULTS=Object.freeze({
36
+ workflows:Object.freeze(['ci']),
37
+ gh:'gh',
38
+ install:Object.freeze(['pnpm','install','--frozen-lockfile','--config.confirmModulesPurge=false']),
39
+ flaky:null,
40
+ });
41
+ /** The hosted workflows a landing needs green by default, by workflow name (J195, J240). */
42
+ export const LAND_WORKFLOWS=LAND_DEFAULTS.workflows;
43
+ const FLAKY_KEYS=['quarantine','artifacts','packedStep','owner'];
44
+ const PLAN_BRANCH=/^plan\/[a-z0-9][a-z0-9._-]*$/u;
45
+ const SHA=/^[a-f0-9]{40}$/u;
46
+
47
+ class StopError extends Error{name='StopError';}
48
+
49
+ /** @typedef {{quarantine:string,artifacts:string,packedStep:string,owner:string}} FlakyConfig */
50
+ /** @typedef {{workflows:readonly string[],gh:string,install:readonly string[]|null,flaky:FlakyConfig|null}} LandConfig */
51
+
52
+ /** Read `<root>/land.config.json` over LAND_DEFAULTS; a missing file is all defaults, anything malformed stops land.
53
+ * @param {string} root the worktree's top level @returns {LandConfig} */
54
+ export function loadLandConfig(root){
55
+ const file=join(root,'land.config.json');
56
+ if(!existsSync(file))return {...LAND_DEFAULTS};
57
+ const bad=(/** @type {string} */why)=>new StopError(`land.config.json: ${why} (keys: about, workflows, gh, install, flaky; scripts/land.mjs says what each means)`);
58
+ /** @type {unknown} */let raw;
59
+ try{raw=JSON.parse(readFileSync(file,'utf8'));}catch(error){throw bad(`not JSON (${error instanceof Error?error.message:String(error)})`);}
60
+ if(raw===null||typeof raw!=='object'||Array.isArray(raw))throw bad('not an object');
61
+ const given=/** @type {Record<string,unknown>} */(raw);
62
+ const unknown=Object.keys(given).filter(key=>!['about','workflows','gh','install','flaky'].includes(key));
63
+ if(unknown.length>0)throw bad(`unknown key ${unknown.join(', ')}`);
64
+ const words=(/** @type {unknown} */value)=>Array.isArray(value)&&value.length>0&&value.every(item=>typeof item==='string'&&item!=='');
65
+ /** @type {LandConfig} */const config={...LAND_DEFAULTS};
66
+ if('workflows'in given){if(!words(given.workflows))throw bad('workflows must be a non-empty list of workflow names');config.workflows=Object.freeze([.../** @type {string[]} */(given.workflows)]);}
67
+ if('gh'in given){
68
+ if(typeof given.gh!=='string'||given.gh==='')throw bad('gh must be a command name or path');
69
+ config.gh=given.gh.includes('/')?resolve(root,given.gh):given.gh;
70
+ }
71
+ if('install'in given){
72
+ if(given.install!==null&&!words(given.install))throw bad('install must be a command as a list of words, or null');
73
+ config.install=given.install===null?null:Object.freeze([.../** @type {string[]} */(given.install)]);
74
+ }
75
+ if('flaky'in given&&given.flaky!==null){
76
+ const flaky=given.flaky;
77
+ if(typeof flaky!=='object'||Array.isArray(flaky))throw bad('flaky must be null or an object');
78
+ const entries=/** @type {Record<string,unknown>} */(flaky);
79
+ const wrong=Object.keys(entries).filter(key=>!FLAKY_KEYS.includes(key));
80
+ if(wrong.length>0)throw bad(`unknown flaky key ${wrong.join(', ')}`);
81
+ const missing=FLAKY_KEYS.filter(key=>typeof entries[key]!=='string'||entries[key]==='');
82
+ if(missing.length>0)throw bad(`flaky needs ${missing.join(', ')} as non-empty strings`);
83
+ config.flaky=/** @type {FlakyConfig} */(Object.freeze({...entries}));
84
+ }
85
+ return config;
86
+ }
87
+
88
+ /** @param {string} cwd @param {string[]} args @param {NodeJS.ProcessEnv} [env] */
89
+ const git=(cwd,args,env=process.env)=>execFileSync('git',args,{cwd,env,encoding:'utf8',stdio:['ignore','pipe','pipe'],maxBuffer:64<<20}).trim();
90
+ /** @param {string} cwd @param {string[]} args @param {NodeJS.ProcessEnv} [env] */
91
+ const tryGit=(cwd,args,env=process.env)=>spawnSync('git',args,{cwd,env,encoding:'utf8',maxBuffer:64<<20});
92
+ /** @param {string} cwd @param {string} ancestor @param {string} descendant */
93
+ const isAncestor=(cwd,ancestor,descendant)=>tryGit(cwd,['merge-base','--is-ancestor',ancestor,descendant]).status===0;
94
+ /** @param {string} cwd @param {string} from @param {string} to */
95
+ const short=(/** @type {string} */ sha)=>sha.slice(0,10);
96
+
97
+ /** `owner/name` of a GitHub remote URL, or null.
98
+ * @param {string} remote */
99
+ export function githubSlug(remote){
100
+ const match=/^(?:git@github\.com:|ssh:\/\/git@github\.com\/|https:\/\/github\.com\/)([-\w.]+\/[-\w.]+?)(?:\.git)?\/?$/u.exec(remote.trim());
101
+ return match?.[1]??null;
102
+ }
103
+
104
+ /** Refuse anything but the known options. Any spelling of force is refused by name.
105
+ * @param {string[]} argv */
106
+ export function parseArgs(argv){
107
+ const options={pollSeconds:30,timeoutMinutes:60,appearMinutes:5,rounds:5,keep:false};
108
+ for(const arg of argv){
109
+ if(/^-f$|force/iu.test(arg))throw new StopError(`refused ${arg}: land never force-pushes main (J240: fast-forward only). If main moved, land rebases and retries by itself`);
110
+ const [name,value]=arg.split('=',2);
111
+ const number=Number(value);
112
+ // --no-watch-main is accepted for old callers: land never watches main now (LS8).
113
+ if(name==='--no-watch-main'&&value===undefined)continue;
114
+ if(name==='--keep'&&value===undefined)options.keep=true;
115
+ else if(value!==undefined&&Number.isFinite(number)&&number>0&&name==='--poll')options.pollSeconds=number;
116
+ else if(value!==undefined&&Number.isFinite(number)&&number>0&&name==='--timeout')options.timeoutMinutes=number;
117
+ else if(value!==undefined&&Number.isFinite(number)&&number>0&&name==='--appear')options.appearMinutes=number;
118
+ else if(value!==undefined&&Number.isSafeInteger(number)&&number>0&&name==='--rounds')options.rounds=number;
119
+ else throw new StopError(`unknown option ${arg}; usage: node scripts/land.mjs [--poll=SECONDS] [--timeout=MINUTES] [--appear=MINUTES] [--rounds=N] [--keep]`);
120
+ }
121
+ return options;
122
+ }
123
+
124
+ /** Exact-SHA verdict from the Actions `runs?head_sha=` response: the newest
125
+ * push run of each landing workflow, decided only when all are complete.
126
+ * @param {unknown} data @param {string} sha @param {readonly string[]} [workflows] */
127
+ export function shaVerdict(data,sha,workflows=LAND_WORKFLOWS){
128
+ const runs=data!==null&&typeof data==='object'&&'workflow_runs'in data&&Array.isArray(data.workflow_runs)?data.workflow_runs:[];
129
+ /** @type {Record<string,{id:number,status:string,conclusion:string|null,branch:string,url:string,attempt:number}>} */const latest={};
130
+ for(const run of runs){
131
+ if(run===null||typeof run!=='object'||run.head_sha!==sha||run.event!=='push'||typeof run.id!=='number'||!workflows.includes(run.name))continue;
132
+ const current=latest[run.name];
133
+ if(current===undefined||run.id>current.id)latest[run.name]={id:run.id,status:String(run.status),conclusion:run.conclusion===null||run.conclusion===undefined?null:String(run.conclusion),branch:String(run.head_branch??''),url:String(run.html_url??''),attempt:Number.isSafeInteger(run.run_attempt)?Number(run.run_attempt):1};
134
+ }
135
+ const rows=workflows.map(name=>({name,run:latest[name]}));
136
+ const state=rows.some(row=>row.run===undefined||row.run.status!=='completed')?'pending':rows.every(row=>row.run?.conclusion==='success')?'green':'red';
137
+ return {state,runs:latest,summary:rows.map(row=>`${row.name} ${row.run===undefined?'none':row.run.status==='completed'?row.run.conclusion:row.run.status}`).join(', ')};
138
+ }
139
+
140
+ /** @param {string} gh the GitHub CLI (land.config.json) @param {string} repo @param {string} path */
141
+ function ghApi(gh,repo,path){
142
+ const result=spawnSync(gh,['api',`repos/${repo}/${path}`],{encoding:'utf8',timeout:30_000,maxBuffer:64<<20});
143
+ if(result.error!==undefined||result.status!==0)throw new Error(`gh api ${path} failed: ${`${result.stderr}${result.error?.message??''}`.trim().slice(0,300)}`);
144
+ return /** @type {unknown} */(JSON.parse(result.stdout));
145
+ }
146
+
147
+ /** J193/J200: `quarantine (n)` jobs run quarantined files with their ordinary exit code and are continue-on-error;
148
+ * they are red by design until rewritten and never block a landing. */
149
+ const NONBLOCKING_JOB=/^quarantine(?: \(\d+\))?$/u;
150
+ const FAILED=new Set(['failure','timed_out','cancelled','startup_failure']);
151
+
152
+ /** A run's failed jobs, split into the blocking ones and the non-blocking quarantine ones.
153
+ * @param {unknown} data the Actions `runs/<id>/jobs` response
154
+ * @returns {{blocking:string[],nonblocking:string[]}} */
155
+ export function failedJobs(data){
156
+ const jobs=data!==null&&typeof data==='object'&&'jobs'in data&&Array.isArray(data.jobs)?data.jobs:[];
157
+ /** @type {{blocking:string[],nonblocking:string[]}} */const split={blocking:[],nonblocking:[]};
158
+ for(const job of jobs){
159
+ if(job===null||typeof job!=='object'||!FAILED.has(String(job.conclusion)))continue;
160
+ const name=String(job.name);
161
+ (NONBLOCKING_JOB.test(name)?split.nonblocking:split.blocking).push(`${name} (${String(job.conclusion)})`);
162
+ }
163
+ return split;
164
+ }
165
+
166
+ /** @param {string} gh @param {string} repo @param {number} id @returns {{blocking:string[],nonblocking:string[]}} */
167
+ function runFailures(gh,repo,id){
168
+ try{return failedJobs(ghApi(gh,repo,`actions/runs/${id}/jobs?filter=latest&per_page=100`));}
169
+ catch{return {blocking:['(job list unavailable)'],nonblocking:[]};}
170
+ }
171
+
172
+ const sleep=(/** @type {number} */ ms)=>new Promise(_resolve=>{setTimeout(_resolve,ms);});
173
+
174
+ /** True when every failed blocking job of the run failed only in its packed-share step (TS10).
175
+ * @param {string} gh @param {string} repo @param {number} id @param {string} packedStep the step's name */
176
+ function onlyPackedStepsFailed(gh,repo,id,packedStep){
177
+ try{
178
+ const data=ghApi(gh,repo,`actions/runs/${id}/jobs?filter=latest&per_page=100`);
179
+ const jobs=data!==null&&typeof data==='object'&&'jobs'in data&&Array.isArray(data.jobs)?data.jobs:[];
180
+ const failed=jobs.filter(job=>job!==null&&typeof job==='object'&&FAILED.has(String(job.conclusion))&&!NONBLOCKING_JOB.test(String(job.name)));
181
+ return failed.length>0&&failed.every(job=>Array.isArray(job.steps)&&job.steps.filter(step=>step!==null&&typeof step==='object'&&FAILED.has(String(step.conclusion)))
182
+ .every(step=>step.name===packedStep)&&job.steps.some(step=>step!==null&&typeof step==='object'&&FAILED.has(String(step.conclusion))));
183
+ }catch{return false;}
184
+ }
185
+
186
+ // TEST-SPEED TS10 (J255): a hosted red whose only failures are test files gets one re-run of its failed jobs. If the
187
+ // re-run is green, each of those files takes a strike in the machine's strike book; a file with strikes from two
188
+ // different plans within 24 h is quarantined under J200 (two days, owned by the standing TEST-SPEED lane) by a
189
+ // commit land adds to the plan before its main push. A red re-run stops land as before: it blocks only its plan.
190
+ const STRIKE_WINDOW_MS=24*60*60*1000,QUARANTINE_MS=48*60*60*1000;
191
+ /** The test files to strike when a packed ci run's every blocking failure is a test file, from its downloaded
192
+ * artifacts (land.config.json flaky.artifacts; engine's `engine-ci-*`) and the names of its failed jobs; null when any failure is something else (a static check,
193
+ * a unit, a shard over its wall, a job with no report) or nothing names a file.
194
+ * @param {string} directory @param {readonly string[]} jobNames blocking failed job names, e.g. `tests (2)`
195
+ * @returns {string[]|null} */
196
+ export function flakyFiles(directory,jobNames){
197
+ /** @type {Map<string,unknown>} */const reports=new Map();
198
+ /** @param {string} at */
199
+ const walk=at=>{
200
+ /** @type {import('node:fs').Dirent[]} */let rows=[];
201
+ try{rows=readdirSync(at,{withFileTypes:true});}catch{return;}
202
+ for(const row of rows){
203
+ const path=join(at,row.name);
204
+ if(row.isDirectory())walk(path);
205
+ else if(/^(?:shard-\d+-(?:native|ordinary|wall)|job-\d+)\.json$/u.test(row.name)){
206
+ try{reports.set(row.name,JSON.parse(readFileSync(path,'utf8')));}catch{reports.set(row.name,null);}
207
+ }
208
+ }
209
+ };
210
+ walk(directory);
211
+ /** @type {Set<string>} */const files=new Set();
212
+ for(const name of jobNames){
213
+ const job=/^tests \((\d+)\)(?: \([a-z_]+\))?$/u.exec(name)?.[1];
214
+ if(job===undefined)return null;
215
+ const report=reports.get(`job-${job}.json`);
216
+ if(report===null||typeof report!=='object'||!('units'in report)||!Array.isArray(report.units)||('pinsCode'in report&&report.pinsCode!==0))return null;
217
+ const red=report.units.filter(unit=>unit!==null&&typeof unit==='object'&&unit.blocking===true&&unit.code!==0);
218
+ if(red.length===0)return null;
219
+ for(const unit of red){
220
+ const shard=/^shard:(\d+)$/u.exec(String(unit.name))?.[1];
221
+ if(shard===undefined)return null;
222
+ const wall=reports.get(`shard-${shard}-wall.json`);
223
+ if(wall!==undefined&&(wall===null||typeof wall!=='object'||('overBudget'in wall&&wall.overBudget!==false)))return null;
224
+ let named=0;
225
+ for(const phase of ['native','ordinary']){
226
+ const shardReport=reports.get(`shard-${shard}-${phase}.json`);
227
+ if(shardReport===undefined)continue;
228
+ if(shardReport===null||typeof shardReport!=='object'||!('files'in shardReport)||!Array.isArray(shardReport.files))return null;
229
+ // An unhandled error outside any test file is not a flaky file.
230
+ if('errorCount'in shardReport&&shardReport.errorCount!==0)return null;
231
+ for(const file of shardReport.files){
232
+ if(file===null||typeof file!=='object'||typeof file.file!=='string')return null;
233
+ if(file.state==='failed'||(typeof file.durationMs==='number'&&file.durationMs>60_000)){files.add(file.file);named++;}
234
+ }
235
+ }
236
+ if(named===0)return null;
237
+ }
238
+ }
239
+ return files.size===0?null:[...files].sort();
240
+ }
241
+ /** The plans with a strike on `file` in the 24 h before `now`, from strike-book rows (one JSON object per line).
242
+ * @param {string} book @param {string} file @param {number} now @returns {string[]} */
243
+ export function strikePlans(book,file,now){
244
+ /** @type {Set<string>} */const plans=new Set();
245
+ for(const line of book.split('\n')){
246
+ if(line.trim()==='')continue;
247
+ try{
248
+ const row=/** @type {unknown} */(JSON.parse(line));
249
+ if(row===null||typeof row!=='object'||!('file'in row)||row.file!==file||!('plan'in row)||typeof row.plan!=='string'||!('at'in row)||typeof row.at!=='string')continue;
250
+ const at=Date.parse(row.at);
251
+ if(Number.isFinite(at)&&at<=now&&now-at<STRIKE_WINDOW_MS)plans.add(row.plan);
252
+ }catch{/* A torn line is skipped. */}
253
+ }
254
+ return [...plans].sort();
255
+ }
256
+ /** Add a J200 quarantine entry for `file` unless one is already there; false when it was.
257
+ * @param {string} path the quarantine file (land.config.json flaky.quarantine) @param {string} file @param {string} owner @param {string} reason @param {number} now */
258
+ export function quarantineFile(path,file,owner,reason,now){
259
+ const data=/** @type {{entries:{file:string}[]}} */(JSON.parse(readFileSync(path,'utf8')));
260
+ if(!Array.isArray(data.entries))throw new Error(`${path} has no entries list`);
261
+ if(data.entries.some(entry=>entry.file===file))return false;
262
+ // J193 history: addedAt is the introducing commit's own (whole-second) time, and the deadline 48 h after it.
263
+ const at=Math.floor(now/1000)*1000;
264
+ data.entries.push({file,owner,addedAt:new Date(at).toISOString(),deadline:new Date(at+QUARANTINE_MS).toISOString(),reason});
265
+ writeFileSync(path,`${JSON.stringify(data,null,2)}\n`);
266
+ return true;
267
+ }
268
+
269
+ /** One landing, start to finish, for the worktree at `cwd`. */
270
+ class Landing{
271
+ /** @param {string} cwd @param {ReturnType<typeof parseArgs>} options @param {NodeJS.ProcessEnv} env */
272
+ constructor(cwd,options,env){
273
+ this.options=options;this.env=env;this.started=Date.now();
274
+ /** @type {{file:string,plans:string[],run:number}[]} */this.pendingQuarantine=[];
275
+ /** @type {string[]} */this.quarantined=[];
276
+ this.quarantineAt=0;
277
+ /** @type {unknown[]} */this.quarantinedEntries=[];
278
+ /** @type {LandConfig} */this.config=LAND_DEFAULTS;
279
+ this.lane=/^[a-z][a-z0-9_-]*$/u.test(env.WS_LANE_NAME??'')?String(env.WS_LANE_NAME):'land';
280
+ const inside=tryGit(cwd,['rev-parse','--show-toplevel']);
281
+ if(inside.status!==0)throw new StopError('not inside a git checkout');
282
+ this.root=inside.stdout.trim();
283
+ this.branch=git(this.root,['branch','--show-current']);
284
+ if(!PLAN_BRANCH.test(this.branch))throw new StopError(`land runs on a plan/<slug> branch (J240); this checkout is on ${this.branch===''?'a detached HEAD':this.branch}`);
285
+ const gitDir=resolve(this.root,git(this.root,['rev-parse','--git-dir'])),common=resolve(this.root,git(this.root,['rev-parse','--git-common-dir']));
286
+ if(gitDir===common)throw new StopError('land runs in a linked plan worktree (<repo>/.worktrees/<plan>), never in the canonical checkout');
287
+ this.config=loadLandConfig(this.root);
288
+ this.remote=git(this.root,['remote','get-url','origin']);
289
+ const repo=env.WS_LAND_REPO??githubSlug(this.remote);
290
+ if(repo===null||!/^[-\w.]+\/[-\w.]+$/u.test(repo))throw new StopError(`origin ${this.remote} is not a GitHub repo; land polls GitHub Actions`);
291
+ this.repo=repo;
292
+ /** @type {number[]} */this.runs=[];
293
+ /** @type {string|null} */this.planTip=null;
294
+ this.expected='';
295
+ /** @type {string|null} */this.landedSha=null;
296
+ }
297
+
298
+ /** @param {string} state @param {string} detail */
299
+ say(state,detail){process.stdout.write(`land ${new Date().toISOString().slice(11,19)} ${state.padEnd(9)} ${detail}\n`);}
300
+
301
+ /** @param {string} message */
302
+ receipt(message){
303
+ const file=resolve(this.env.WS_LANE_RECEIPTS??join(homedir(),'.cache/wildshard/lane-receipts.log'));
304
+ try{mkdirSync(dirname(file),{recursive:true});appendFileSync(file,`${new Date().toISOString().slice(11,16)} UTC ${this.lane} land ${this.branch} ${message.replaceAll(/\s+/gu,' ').slice(0,1000)}\n`);}
305
+ catch(error){process.stderr.write(`land receipt unavailable: ${String(error)}\n`);}
306
+ }
307
+
308
+ /** One land per worktree at a time; worktrees never wait on each other.
309
+ * The lock file appears whole (a hard link of a written file), and a stale
310
+ * one is taken over by rename, so two contenders can't both clear it. */
311
+ lock(){
312
+ const file=resolve(this.root,git(this.root,['rev-parse','--git-path','wildshard-land.lock'])),mine=`${file}.${process.pid}`;
313
+ writeFileSync(mine,String(process.pid));
314
+ try{
315
+ for(let attempt=0;attempt<3;attempt++){
316
+ try{linkSync(mine,file);return ()=>{rmSync(file,{force:true});};}
317
+ catch(error){if(!(error instanceof Error&&'code'in error&&error.code==='EEXIST'))throw error;}
318
+ const owner=Number(readFileSync(file,'utf8'));
319
+ let alive=Number.isSafeInteger(owner)&&owner>0;
320
+ if(alive){try{process.kill(owner,0);}catch{alive=false;}}
321
+ if(alive)throw new StopError(`land already running in this worktree (pid ${owner})`);
322
+ // Claim the stale file by renaming it; only the contender whose rename
323
+ // took the dead owner's file may drop it. Anything else goes back.
324
+ const taken=`${file}.stale.${process.pid}`;
325
+ try{renameSync(file,taken);}catch{continue;}
326
+ if(Number(readFileSync(taken,'utf8'))===owner)rmSync(taken,{force:true});
327
+ else{try{linkSync(taken,file);}catch{/* A live owner already holds it again. */}rmSync(taken,{force:true});}
328
+ }
329
+ throw new StopError('cannot take this worktree\'s land lock');
330
+ }finally{rmSync(mine,{force:true});}
331
+ }
332
+
333
+ /** Stop if HEAD is not the SHA this landing is working on: a commit made
334
+ * while land waits must never ride along unchecked.
335
+ * @param {string} where */
336
+ holds(where){
337
+ const head=this.head();
338
+ if(head!==this.expected){
339
+ this.receipt(`STOP HEAD moved ${where}: ${short(this.expected)} -> ${short(head)}`);
340
+ throw new StopError(`HEAD moved ${where} (${short(this.expected)} -> ${short(head)}): a commit or checkout during the landing. Run land again to land the new HEAD.`);
341
+ }
342
+ return head;
343
+ }
344
+
345
+ head(){return git(this.root,['rev-parse','HEAD']);}
346
+
347
+ fetchMain(){
348
+ const fetched=tryGit(this.root,['fetch','--quiet','origin','+refs/heads/main:refs/remotes/origin/main']);
349
+ if(fetched.status!==0)throw new StopError(`git fetch origin main failed: ${fetched.stderr.trim()}`);
350
+ return git(this.root,['rev-parse','refs/remotes/origin/main']);
351
+ }
352
+
353
+ clean(){
354
+ for(const name of ['rebase-merge','rebase-apply','MERGE_HEAD','CHERRY_PICK_HEAD']){
355
+ if(existsSync(resolve(this.root,git(this.root,['rev-parse','--git-path',name]))))throw new StopError(`a ${name} is in progress in this worktree; finish or abort it first`);
356
+ }
357
+ const dirty=git(this.root,['status','--porcelain','--untracked-files=no']);
358
+ if(dirty!=='')throw new StopError(`commit or drop tracked changes first:\n${dirty}`);
359
+ }
360
+
361
+ /** Rebase onto origin/main; a conflict aborts and stops with the paths.
362
+ * @param {string} main */
363
+ rebase(main){
364
+ const before=this.head();
365
+ const result=tryGit(this.root,['-c','rebase.autoStash=false','-c','rebase.updateRefs=false','rebase','--quiet',main]);
366
+ if(result.status===0){
367
+ this.expected=this.head();
368
+ this.say('rebased',`${short(before)} -> ${short(this.expected)} onto main ${short(main)}`);
369
+ this.installIfDependenciesMoved(before);
370
+ return;
371
+ }
372
+ const conflicts=git(this.root,['diff','--name-only','--diff-filter=U']).split('\n').filter(Boolean);
373
+ const aborted=tryGit(this.root,['rebase','--abort']);
374
+ const paths=conflicts.length>0?conflicts.join(', '):'(none reported)';
375
+ if(aborted.status!==0||this.head()!==before||existsSync(resolve(this.root,git(this.root,['rev-parse','--git-path','rebase-merge'])))){
376
+ this.receipt(`STOP rebase onto ${short(main)} failed and its abort did not restore ${short(before)}`);
377
+ throw new StopError(`rebase onto main ${short(main)} failed (${paths}) and git rebase --abort did not restore ${short(before)}: ${aborted.stderr.trim()}\nInspect the worktree by hand: git status, git rebase --abort.`);
378
+ }
379
+ this.receipt(`STOP rebase conflict onto main ${short(main)}: ${paths}`);
380
+ throw new StopError(`rebase onto main ${short(main)} conflicts in: ${paths}\nResolve: git rebase origin/main, fix those paths, git rebase --continue, then run land again. HEAD is back at ${short(before)}.`);
381
+ }
382
+
383
+ /** A rebase that brought in a lockfile or package.json change: install before any pre-push, or every check fails on a
384
+ * missing module (WR2's `@wildshard/wire` turned older worktrees red, 2026-11-11). Frozen, so the lockfile is the law.
385
+ * @param {string} before */
386
+ installIfDependenciesMoved(before){
387
+ if(this.config.install===null)return;
388
+ const moved=git(this.root,['diff','--name-only',before,'HEAD','--','pnpm-lock.yaml','package.json','**/package.json']).split('\n').filter(Boolean);
389
+ if(moved.length===0)return;
390
+ // Owed until it succeeds: a stop here leaves HEAD rebased, so the next land must not skip it.
391
+ writeFileSync(this.installMarker(),`${moved.join('\n')}\n`);
392
+ this.install(moved);
393
+ }
394
+
395
+ /** Where an owed install is remembered, inside this worktree's own git dir. */
396
+ installMarker(){return resolve(this.root,git(this.root,['rev-parse','--git-path','wildshard-land-install']));}
397
+
398
+ /** GVS G9/G10: confirmModulesPurge=false lets a worktree made before a store-layout flip reinstall without a TTY
399
+ * (pnpm otherwise aborts: ERR_PNPM_ABORTED_REMOVE_MODULES_DIR_NO_TTY). Purging is only safe in this worktree's own
400
+ * node_modules, never through a link to the canonical checkout's, so a linked one stops. withStoreUse keeps the
401
+ * install out of a running store prune (meta make prune), as worktree.mjs's install does.
402
+ * @param {string[]} moved */
403
+ install(moved){
404
+ const [command='pnpm',...args]=this.config.install??LAND_DEFAULTS.install,shown=[command,...args].join(' ');
405
+ const modules=join(this.root,'node_modules');
406
+ let linked=false;
407
+ try{linked=lstatSync(modules).isSymbolicLink();}catch{/* no node_modules yet */}
408
+ if(linked){
409
+ this.receipt('STOP node_modules here is a link; land will not purge through it');
410
+ throw new StopError(`${modules} is a symlink; land installs only into this worktree's own node_modules. Replace it with a real install (rm the link, ${shown}), then run land again.`);
411
+ }
412
+ this.say('install',`${moved.join(', ')} changed in the rebase; ${shown}`);
413
+ let installed;
414
+ try{
415
+ installed=withStoreUse(this.env,'land install',()=>spawnSync(command,args,{cwd:this.root,env:this.env,encoding:'utf8',stdio:['ignore','pipe','pipe'],maxBuffer:64<<20}));
416
+ }catch(error){
417
+ const why=error instanceof Error?error.message:String(error);
418
+ const busy=/store prune is running/u.test(why);
419
+ this.receipt(busy?'STOP pnpm install waits: a pnpm store prune is running':`STOP pnpm install could not start: ${why}`);
420
+ throw new StopError(`${why}\n${busy?'Run land again once the prune ends; the install is still owed and runs first.':'Fix that, then run land again; the install is still owed and runs first.'}`);
421
+ }
422
+ if(installed.status===0){rmSync(this.installMarker(),{force:true});return;}
423
+ this.receipt(`STOP ${shown} failed after the rebase`);
424
+ throw new StopError(`${shown} failed after the rebase (${moved.join(', ')} changed): ${`${installed.stderr}${installed.stdout}`.trim().split('\n').slice(-3).join(' ')}\nRun it by hand in the worktree, then run land again.`);
425
+ }
426
+
427
+ /** J249 provenance: what goes to main on the branch's green run must be exactly main plus that run's SHA. Git's own
428
+ * three-way merge of the two is computed apart from the rebase, and the rebased HEAD must match it file for file; a
429
+ * commit made during the rebase, or anything else, stops land (J206 review).
430
+ * @param {string} main @param {string} tested */
431
+ verifyReplay(main,tested){
432
+ const merged=tryGit(this.root,['merge-tree','--write-tree','--name-only','--no-messages',main,tested]);
433
+ const [tree='',...conflicted]=merged.stdout.split('\n').map(line=>line.trim()).filter(Boolean);
434
+ const excluded=this.quarantined.length===0||this.config.flaky===null?[]:[`:(exclude)${this.config.flaky.quarantine}`];
435
+ const same=SHA.test(tree)&&merged.status===0&&conflicted.length===0&&tryGit(this.root,['diff','--quiet',tree,'HEAD','--','.',...excluded]).status===0
436
+ &&this.onlyQuarantineAdded(tree,'HEAD');
437
+ if(same)return;
438
+ this.receipt(`STOP rebased ${short(this.head())} is not main ${short(main)} plus the hosted-green ${short(tested)}`);
439
+ throw new StopError(`after the rebase, ${short(this.head())} is not main ${short(main)} plus the hosted-green ${short(tested)}: a commit or edit came in during the land. Check git log, keep what you meant, and run land again; a new commit gets its own branch CI.`);
440
+ }
441
+
442
+ /** Push the exact SHA to this worktree's own plan branch (LAND-SIMPLIFY LS4, J258). Land reads origin's real tip
443
+ * (refreshing the remote-tracking ref, which a hand push by URL leaves stale) and rewrites it only when the local
444
+ * branch's reflog reached it: a tip this worktree pushed, by land or by hand, or once held. Anything else is
445
+ * someone else's push and stops land before any push. The push itself carries an explicit lease on that tip, so a
446
+ * push landing in between is refused by git. This is `--force-if-includes`'s rule without its timestamp window,
447
+ * which made git refuse a fresh fetch of the worktree's own tip (J206 review). No record files.
448
+ * @param {string} sha */
449
+ pushPlan(sha){
450
+ const ref=`refs/heads/${this.branch}`,tracking=`refs/remotes/origin/${this.branch}`;
451
+ if(git(this.root,['rev-parse',ref])!==sha)throw new StopError(`${this.branch} is not at ${short(sha)}; run land again`);
452
+ if(tryGit(this.root,['fetch','--quiet','origin',`+${ref}:${tracking}`]).status!==0)tryGit(this.root,['update-ref','-d',tracking]);
453
+ const tip=tryGit(this.root,['rev-parse','--verify','--quiet',`${tracking}^{commit}`]).stdout.trim()||null;
454
+ if(tip===sha){this.say('pushed',`${this.branch} already at ${short(sha)}`);this.planTip=sha;return;}
455
+ const rewrite=tip!==null&&!isAncestor(this.root,tip,sha);
456
+ if(rewrite&&!this.reached(tip)){
457
+ this.receipt(`STOP plan push ${short(sha)} refused (origin has commits this worktree never had)`);
458
+ throw new StopError(`origin ${this.branch} is at ${short(tip)}, which this worktree's branch never reached: someone else pushed it. Fetch and integrate their commits (git rebase origin/${this.branch}), then run land again; or start a new worktree with a new slug. Never force over it.`);
459
+ }
460
+ const args=['push','--porcelain',`--force-with-lease=${ref}:${tip??''}`,'origin',`${ref}:${ref}`];
461
+ this.say('pushing',`${this.branch} ${short(sha)}${rewrite?` (rebased; replaces its own ${short(tip)} under a lease)`:''}; the pre-push runs`);
462
+ const result=spawnSync('git',args,{cwd:this.root,env:this.env,encoding:'utf8',stdio:['ignore','pipe','inherit']});
463
+ if(result.status!==0){
464
+ const leased=/\[rejected\].*\((?:stale info|fetch first)\)/u.test(result.stdout);
465
+ this.receipt(`STOP plan push ${short(sha)} refused (${leased?'origin moved during the push':'pre-push red'})`);
466
+ throw new StopError(leased
467
+ ?`origin ${this.branch} moved while land pushed, so git refused the lease: someone else pushed it. Fetch and integrate their commits, then run land again. Never force over it.`
468
+ :`push of ${this.branch} ${short(sha)} failed: ${result.stdout.trim()}\nA red pre-push names its failing check above; fix forward and run land again.`);
469
+ }
470
+ this.planTip=sha;
471
+ }
472
+
473
+ /** The local branch reached `tip`: some reflog entry of it is `tip` or a descendant (the newest 200).
474
+ * @param {string} tip */
475
+ /** TS10: re-run a red ci run's failed jobs once when every failure is a test file; on a green re-run, give each
476
+ * file a strike and queue a quarantine for one with strikes from two plans in 24 h.
477
+ * @param {string} sha @param {Awaited<ReturnType<Landing['waitCI']>>} verdict @returns {Promise<Awaited<ReturnType<Landing['waitCI']>>|null>} */
478
+ async retryFlaky(sha,verdict){
479
+ const flaky=this.config.flaky,gh=this.config.gh;
480
+ if(flaky===null)return null;
481
+ const run=verdict.runs[this.config.workflows[0]??'ci'];
482
+ if(run===undefined||run.conclusion!=='failure'||run.attempt>1)return null;
483
+ const jobs=runFailures(gh,this.repo,run.id);
484
+ // A failure after the tests (the wall check after the artifact upload, a later step) is never a flaky file.
485
+ if(!onlyPackedStepsFailed(gh,this.repo,run.id,flaky.packedStep))return null;
486
+ mkdirSync(join(this.root,'tmp'),{recursive:true});
487
+ const scratch=mkdtempSync(join(this.root,'tmp','land-flaky-'));
488
+ /** @type {string[]|null} */let files=null;
489
+ try{
490
+ const fetched=spawnSync(gh,['run','download',String(run.id),'-R',this.repo,'-p',flaky.artifacts,'-D',scratch],{encoding:'utf8',timeout:120_000});
491
+ if(fetched.status===0&&jobs.blocking.length>0)files=flakyFiles(scratch,jobs.blocking);
492
+ }finally{rmSync(scratch,{recursive:true,force:true});}
493
+ if(files===null)return null;
494
+ this.say('flaky',`ci run ${run.id} red only on test files ${files.join(', ')}; re-running its failed jobs once (TS10)`);
495
+ const rerun=spawnSync(gh,['run','rerun',String(run.id),'-R',this.repo,'--failed'],{encoding:'utf8',timeout:60_000});
496
+ if(rerun.status!==0){this.say('flaky',`re-run refused (${rerun.stderr.trim().split('\n').at(-1)??''}); stopping as red`);return null;}
497
+ // Wait for this run's own second attempt: never attempt one's stale verdict, never another run of the SHA.
498
+ const deadline=Date.now()+this.options.timeoutMinutes*60_000;
499
+ for(;;){
500
+ /** @type {unknown} */let data=null;
501
+ try{data=ghApi(gh,this.repo,`actions/runs/${run.id}`);}catch{/* retried below */}
502
+ const field=(/** @type {string} */key)=>data!==null&&typeof data==='object'&&key in data?String(/** @type {Record<string,unknown>} */(data)[key]):'';
503
+ if(Number(field('run_attempt'))>2){this.say('flaky',`ci run ${run.id} is past its second attempt; stopping as red`);return null;}
504
+ if(Number(field('run_attempt'))===2&&field('status')==='completed'){
505
+ if(field('conclusion')!=='success'){
506
+ this.receipt(`TS10 re-run of ci ${run.id} red again on ${files.join(', ')}: not flaky; blocks only ${this.branch}`);
507
+ return {...verdict,failed:[`ci run ${run.id} red on its re-run too (TS10): ${runFailures(gh,this.repo,run.id).blocking.join('; ')}`]};
508
+ }
509
+ break;
510
+ }
511
+ if(Date.now()>deadline)throw new StopError(`the TS10 re-run of ci ${run.id} did not finish in ${this.options.timeoutMinutes} min; run land again to keep waiting`);
512
+ await sleep(this.options.pollSeconds*1000);
513
+ }
514
+ const again=await this.waitCI(sha,`${this.branch} re-run`);
515
+ if(again.state!=='green')return again;
516
+ const book=resolve(this.env.WS_FLAKE_STRIKES??join(homedir(),'.cache/wildshard/flake-strikes.jsonl')),now=Date.now();
517
+ mkdirSync(dirname(book),{recursive:true});
518
+ for(const file of files){
519
+ appendFileSync(book,`${JSON.stringify({at:new Date(now).toISOString(),file,plan:this.branch,sha,run:run.id,lane:this.lane})}\n`);
520
+ const plans=strikePlans(readFileSync(book,'utf8'),file,now);
521
+ this.receipt(`TS10 strike: ${file} flaky on ci ${run.id} (red, then green on its re-run); plans with a strike in 24 h: ${plans.join(', ')}`);
522
+ if(plans.length>=2)this.pendingQuarantine.push({file,plans,run:run.id});
523
+ }
524
+ return again;
525
+ }
526
+
527
+ /** TS10: commit the queued quarantine entries on this plan branch, dated to their addedAt (J193's history check);
528
+ * true when a commit was made. The commit must sit on the tested HEAD and change only those entries. */
529
+ quarantineCommit(){
530
+ const flaky=this.config.flaky;
531
+ if(this.pendingQuarantine.length===0||flaky===null)return false;
532
+ const path=join(this.root,flaky.quarantine),added=[],now=Date.now(),parent=this.holds('before the TS10 quarantine');
533
+ for(const {file,plans,run} of this.pendingQuarantine.splice(0)){
534
+ const reason=`TS10 (J255): flaky on hosted CI, red then green on its re-run, with strikes from ${plans.join(' and ')} within 24 h (last: ci run ${run}); J200 deadline`;
535
+ if(quarantineFile(path,file,this.env.WS_QUARANTINE_OWNER??flaky.owner,reason,now)){
536
+ added.push(file);
537
+ const written=/** @type {{entries:{file:string}[]}} */(JSON.parse(readFileSync(path,'utf8'))).entries.find(entry=>entry.file===file);
538
+ if(written!==undefined)this.quarantinedEntries.push(written);
539
+ }
540
+ }
541
+ if(added.length===0)return false;
542
+ this.quarantined.push(...added);this.quarantineAt=Math.floor(now/1000);
543
+ const message=`test: quarantine ${added.length===1?added[0]?.replace(/^.*\//u,'').replace(/\.test\.[cm]?[jt]s$/u,''):`${added.length} flaky files`}\n\nTEST-SPEED TS10 (J255): strikes from two plans within 24 h. Land added\nthis entry; it expires in 48 h (J200) and the TEST-SPEED lane owns it.\n\nAssisted-by: land:ts10-strikes`;
544
+ const committed=spawnSync('git',['commit','--quiet','-m',message,'--',flaky.quarantine],{cwd:this.root,env:this.datedEnv(),encoding:'utf8'});
545
+ if(committed.status!==0)throw new StopError(`TS10 quarantine commit failed: ${committed.stderr.trim()}`);
546
+ this.checkQuarantineCommit(parent);
547
+ this.say('quarantine',`${added.join(', ')} quarantined for 48 h on ${this.branch} ${short(this.expected)} (TS10: two plans' strikes in 24 h)`);
548
+ this.receipt(`TS10 quarantined ${added.join(', ')} (commit ${short(this.expected)})`);
549
+ return true;
550
+ }
551
+
552
+ /** After a rebase replays it, the quarantine commit takes back its addedAt date (J193 compares the commit time). */
553
+ redateQuarantine(){
554
+ if(this.quarantined.length===0||this.config.flaky===null)return;
555
+ const parent=tryGit(this.root,['rev-parse','HEAD^']).stdout.trim();
556
+ const amended=spawnSync('git',['commit','--quiet','--amend','--no-edit','--',this.config.flaky.quarantine],{cwd:this.root,env:this.datedEnv(),encoding:'utf8'});
557
+ if(amended.status!==0)throw new StopError(`TS10 quarantine re-date failed: ${amended.stderr.trim()}`);
558
+ this.checkQuarantineCommit(parent);
559
+ }
560
+
561
+ /** @returns {NodeJS.ProcessEnv} git's author and committer dates pinned to the quarantine's addedAt */
562
+ datedEnv(){
563
+ const date=`${String(this.quarantineAt)} +0000`;
564
+ return {...this.env,GIT_AUTHOR_DATE:date,GIT_COMMITTER_DATE:date};
565
+ }
566
+
567
+ /** HEAD must be one commit on `parent` that changes only test/quarantine.json by land's own entries.
568
+ * @param {string} parent */
569
+ checkQuarantineCommit(parent){
570
+ const head=this.head(),changed=tryGit(this.root,['diff','--name-only',parent,head]).stdout.trim();
571
+ if(tryGit(this.root,['rev-parse',`${head}^`]).stdout.trim()!==parent||changed!==this.config.flaky?.quarantine||!this.onlyQuarantineAdded(parent,head)){
572
+ this.receipt(`STOP TS10 quarantine commit ${short(head)} is not just land's entries on ${short(parent)}`);
573
+ throw new StopError(`the TS10 quarantine commit ${short(head)} is not exactly land's entries on ${short(parent)}; nothing landed`);
574
+ }
575
+ this.expected=head;
576
+ }
577
+
578
+ /** True when `to`'s test/quarantine.json is `from`'s plus exactly land's entries (or equal when land added none).
579
+ * @param {string} from @param {string} to */
580
+ onlyQuarantineAdded(from,to){
581
+ const quarantine=this.config.flaky?.quarantine;
582
+ if(quarantine===undefined)return true;
583
+ const read=(/** @type {string} */ref)=>{
584
+ const shown=tryGit(this.root,['show',`${ref}:${quarantine}`]);
585
+ if(shown.status!==0)return null;
586
+ try{return /** @type {{entries:{file:string,addedAt?:string}[]}&Record<string,unknown>} */(JSON.parse(shown.stdout));}catch{return null;}
587
+ };
588
+ const before=read(from),after=read(to);
589
+ if(this.quarantined.length===0)return JSON.stringify(before)===JSON.stringify(after);
590
+ if(before===null||after===null||!Array.isArray(before.entries)||!Array.isArray(after.entries))return false;
591
+ // Exactly the merged entries, then land's own entries byte for byte, in that order.
592
+ return JSON.stringify(after)===JSON.stringify({...before,entries:[...before.entries,...this.quarantinedEntries]});
593
+ }
594
+
595
+ reached(tip){
596
+ const entries=tryGit(this.root,['reflog','show','--format=%H','-n','200',`refs/heads/${this.branch}`]).stdout.split('\n').filter(line=>SHA.test(line));
597
+ return [...new Set(entries)].some(entry=>entry===tip||isAncestor(this.root,tip,entry));
598
+ }
599
+
600
+ /** Poll the exact SHA until both landing workflows are complete.
601
+ * @param {string} sha @param {string} what */
602
+ async waitCI(sha,what){
603
+ const deadline=Date.now()+this.options.timeoutMinutes*60_000,appear=Date.now()+this.options.appearMinutes*60_000;
604
+ let last='';
605
+ for(;;){
606
+ /** @type {ReturnType<typeof shaVerdict>} */let verdict;
607
+ try{verdict=shaVerdict(ghApi(this.config.gh,this.repo,`actions/runs?head_sha=${sha}&event=push&per_page=100`),sha,this.config.workflows);}
608
+ catch(error){verdict={state:'pending',runs:{},summary:`lookup failed (${error instanceof Error?error.message:String(error)}); retrying`};}
609
+ if(verdict.summary!==last){this.say('ci',`${what} ${short(sha)}: ${verdict.summary}`);last=verdict.summary;}
610
+ if(verdict.state==='green'){for(const run of Object.values(verdict.runs))this.runs.push(run.id);return verdict;}
611
+ if(verdict.state==='red'){
612
+ // The run conclusion decides, never a job list: quarantine jobs are continue-on-error, so they can't make a run
613
+ // red on their own, and a list (paged, re-run, cancelled) can't prove the blocking jobs passed. The stop line
614
+ // names the blocking failures and sets the quarantine reds apart, so nobody chases a non-blocking job.
615
+ const reds=Object.entries(verdict.runs).filter(([,run])=>run.conclusion!=='success').map(([name,run])=>({name,run,jobs:runFailures(this.config.gh,this.repo,run.id)}));
616
+ const failed=reds.map(({name,run,jobs})=>`${name} run ${run.id} ${run.conclusion}: ${jobs.blocking.join('; ')||'no blocking failed job listed'}${jobs.nonblocking.length===0?'':` (non-blocking: ${jobs.nonblocking.join('; ')})`}${run.url===''?'':` ${run.url}`}`);
617
+ return {...verdict,failed};
618
+ }
619
+ if(Object.keys(verdict.runs).length===0&&Date.now()>appear)throw new StopError(`no hosted ci run for ${short(sha)} after ${this.options.appearMinutes} min; is ci.yml triggered on plan/** pushes?`);
620
+ if(Date.now()>deadline)throw new StopError(`hosted CI for ${short(sha)} not finished after ${this.options.timeoutMinutes} min (${verdict.summary}); run land again to keep waiting`);
621
+ await sleep(this.options.pollSeconds*1000);
622
+ }
623
+ }
624
+
625
+ /** Fast-forward main to HEAD. Refuses before pushing unless origin/main is
626
+ * an ancestor; the refspec has no `+` and no force flag ever.
627
+ * @param {boolean} carried @returns {'landed'|'moved'} */
628
+ pushMain(carried){
629
+ const head=this.holds('before the merge'),main=this.fetchMain();
630
+ if(!isAncestor(this.root,main,head))return 'moved';
631
+ if(main===head)return 'landed';
632
+ const args=mainPushArgs(head);
633
+ this.say('merging',`main ${short(main)} -> ${short(head)} fast-forward only${carried?'; static pre-push on the rebased tree, no Vitest (LS3)':'; the hosted-green SHA, no local gate'}`);
634
+ // LS3 (J258): the pre-push knows this is land's main push and of which kind (.githooks/run-checks.mjs).
635
+ const env={...this.env,WS_LAND_MAIN_PUSH:`${carried?'carried':'exact'}:${head}`};
636
+ const result=spawnSync('git',args,{cwd:this.root,env,encoding:'utf8',stdio:['ignore','pipe','inherit']});
637
+ if(result.status===0)return 'landed';
638
+ // A lost race is main having moved; anything else (a red pre-push) stops.
639
+ const now=this.fetchMain();
640
+ if(now!==main&&!isAncestor(this.root,now,head))return 'moved';
641
+ this.receipt(`STOP main push of ${short(head)} refused: ${result.stdout.trim().split('\n').slice(-2).join(' ')}`);
642
+ throw new StopError(`main push of ${short(head)} failed and main did not move: ${result.stdout.trim()}\nA red pre-push names its failing check above; fix forward and run land again.`);
643
+ }
644
+
645
+ async run(){
646
+ this.clean();
647
+ const start=this.head();this.expected=start;
648
+ let main=this.fetchMain();
649
+ if(start===main||isAncestor(this.root,start,main)){this.say('nothing',`${this.branch} ${short(start)} has nothing main lacks`);return 0;}
650
+ this.say('start',`${this.branch} ${short(start)} -> main ${short(main)} (repo ${this.repo})`);
651
+ // An install a stopped land owed (its rebase had already moved HEAD) runs before anything else (J206 review).
652
+ if(existsSync(this.installMarker()))this.install(['an earlier land\'s rebase']);
653
+ if(!isAncestor(this.root,main,start)){
654
+ this.rebase(main);
655
+ if(this.head()===main){this.say('nothing',`every commit on ${this.branch} is already on main`);return 0;}
656
+ }
657
+ /** @type {{sha:string,base:string}|null} */let tested=null;
658
+ let needHosted=true,rule='exact',why='main had not moved since the hosted run';
659
+ for(let round=1;round<=this.options.rounds;round++){
660
+ if(needHosted){
661
+ const sha=this.holds('before the branch push');
662
+ this.pushPlan(sha);
663
+ let verdict=await this.waitCI(sha,this.branch);
664
+ this.holds('while hosted CI ran');
665
+ if(verdict.state==='red'){
666
+ const retried=await this.retryFlaky(sha,verdict);
667
+ if(retried!==null){verdict=retried;this.holds('while the re-run ran');}
668
+ }
669
+ if(verdict.state!=='green'){
670
+ const failed='failed'in verdict?verdict.failed:[];
671
+ this.receipt(`STOP hosted CI red for ${short(sha)}: ${failed.join(' | ')}`);
672
+ throw new StopError(`hosted CI is red for ${short(sha)}; main is unchanged.\n ${failed.join('\n ')}\nFix forward on ${this.branch} and run land again.`);
673
+ }
674
+ tested={sha,base:git(this.root,['merge-base',sha,'refs/remotes/origin/main'])};
675
+ needHosted=false;rule='exact';why='main had not moved since the hosted run';
676
+ if(this.quarantineCommit()){rule='carried';why=`TS10 quarantine on top of the branch's green run ${short(sha)}: it only adds ${this.config.flaky?.quarantine??'quarantine'} entries`;}
677
+ }
678
+ if(tested===null)throw new Error('unreachable: no hosted-tested SHA');
679
+ main=this.fetchMain();
680
+ if(!isAncestor(this.root,main,this.holds('before the rebase'))){
681
+ this.say('moved',`main moved to ${short(main)}; rebasing (round ${round})`);
682
+ this.rebase(main);
683
+ this.verifyReplay(main,tested.sha);
684
+ this.redateQuarantine();
685
+ rule='carried';why=`clean rebase onto ${short(main)}: the branch's green run ${short(tested.sha)} carries (J249)`;
686
+ this.say('carried',why);
687
+ }
688
+ const outcome=this.pushMain(rule==='carried');
689
+ if(outcome==='moved'){this.say('moved','main moved during the merge; rebasing and retrying');continue;}
690
+ return this.landed(rule,why,round,main);
691
+ }
692
+ this.receipt(`STOP gave up after ${this.options.rounds} tries; main kept moving`);
693
+ throw new StopError(`main kept moving: ${this.options.rounds} tries each lost the race to another push (J258 stops at 5). Nothing landed; run land again when main is quieter`);
694
+ }
695
+
696
+ /** After GitHub's main moved, bring the canonical checkout's main along (Jake, 2026-11-10 ~23:50 Cancún: "go to
697
+ * the main checkout, pull main, make sure it's up to date, and then merge fast forward only in the main checkout").
698
+ * The push came first, so the canonical checkout is never ahead of GitHub. Only a fast-forward, under worktree.mjs's
699
+ * followMain guards (on main, clean, not diverged, no git operation in progress); anything else is a
700
+ * warning and a receipt, never a reset or a stash. The landing stands either way. */
701
+ followCanonical(){
702
+ let canonical='',outcome='';
703
+ try{
704
+ canonical=canonicalRoot(this.root);
705
+ git(canonical,['fetch','--quiet','origin','main']);
706
+ outcome=followMain(canonical,git(canonical,['rev-parse','origin/main']).trim());
707
+ }catch(error){outcome=`could not check it (${error instanceof Error?error.message.split('\n')[0]:String(error)})`;}
708
+ if(/fast-forwarded|current$/u.test(outcome)){this.say('canonical',outcome);return;}
709
+ this.say('canonical',`WARNING ${outcome}; canonical ${canonical||'checkout'} was not updated`);
710
+ this.receipt(`canonical checkout not fast-forwarded after landing: ${outcome}`);
711
+ }
712
+
713
+ /** LAND-SIMPLIFY LS5 (J258): main's verdict belongs to scripts/main-watch.mjs. It follows this SHA in the
714
+ * background until main's ci judges it, writes the receipt and messages this pane on red. It runs from the
715
+ * canonical checkout, so it outlives this worktree. WS_MAIN_WATCH=0 turns it off.
716
+ * @param {string} head */
717
+ startWatcher(head){
718
+ const own=join(this.root,'scripts/main-watch.mjs');
719
+ if(this.env.WS_MAIN_WATCH==='0'||!existsSync(own))return;
720
+ // Run the canonical checkout's copy when it has one: this worktree may be removed before node has read its own
721
+ // (J206 review). Otherwise a private copy, rooted at the canonical checkout.
722
+ const canonical=canonicalRoot(this.root),shared=join(canonical,'scripts/main-watch.mjs');
723
+ let script=shared,env=this.env;
724
+ if(!existsSync(shared)){
725
+ script=join(homedir(),'.cache/wildshard/main-watch/main-watch.mjs');
726
+ mkdirSync(dirname(script),{recursive:true});writeFileSync(script,readFileSync(own));
727
+ env={...this.env,WS_MAIN_WATCH_ROOT:canonical};
728
+ }
729
+ const args=[script,`--follow=${head}`,`--lane=${this.lane}`,...(this.env.HERDR_PANE_ID?[`--pane=${this.env.HERDR_PANE_ID}`]:[])];
730
+ try{
731
+ spawn(process.execPath,args,{cwd:canonical,env,detached:true,stdio:'ignore'}).unref();
732
+ this.say('watch',`main-watch follows ${short(head)} and reports main's ci (receipt, and a message here on red)`);
733
+ }catch(error){this.say('watch',`main-watch not started (${error instanceof Error?error.message:String(error)}); run node scripts/main-watch.mjs by hand`);}
734
+ }
735
+
736
+ /** LS5 (J258, Jake: "Yes, land cleans up its own"): after landing, delete origin's plan branch (under a lease on the
737
+ * SHA land pushed) and remove this worktree with its local branch, from the canonical checkout. A worktree with
738
+ * uncommitted or untracked work is kept and named. The reaper stays only for abandoned worktrees.
739
+ * @returns {string} what happened */
740
+ cleanUp(){
741
+ const head=this.landedSha;
742
+ if(head===null)return 'nothing landed';
743
+ const canonical=canonicalRoot(this.root),parts=[];
744
+ if(this.planTip!==null){
745
+ const deleted=tryGit(this.root,['push','--quiet',`--force-with-lease=refs/heads/${this.branch}:${this.planTip}`,'origin','--delete',this.branch]);
746
+ parts.push(deleted.status===0?`origin ${this.branch} deleted`:`origin ${this.branch} kept (${deleted.stderr.trim().split('\n').at(-1)??'push refused'})`);
747
+ }
748
+ const dirty=tryGit(this.root,['status','--porcelain']).stdout.trim();
749
+ const now=tryGit(this.root,['symbolic-ref','--quiet','HEAD']).stdout.trim(),at=tryGit(this.root,['rev-parse','HEAD']).stdout.trim();
750
+ if(now!==`refs/heads/${this.branch}`||at!==head)parts.push(`worktree kept: HEAD moved off ${this.branch} ${short(head)} after landing`);
751
+ else if(dirty!=='')parts.push(`worktree kept: ${dirty.split('\n').length} uncommitted or untracked path(s)`);
752
+ else{
753
+ // TEST-SPEED FL30: nothing started here may outlive the folder (an orphaned Vitest held the CPU slots).
754
+ let stopped=[];
755
+ try{stopped=stopWorktreeProcesses(realpathSync(this.root));}catch{/* Listing failed: remove as before. */}
756
+ if(stopped.length>0)parts.push(`stopped ${String(stopped.length)} process(es) still running there (pid ${stopped.join(', ')})`);
757
+ const removed=tryGit(canonical,['worktree','remove',this.root]);
758
+ if(removed.status===0){
759
+ tryGit(canonical,['update-ref','-d',`refs/heads/${this.branch}`,head]);
760
+ parts.push(`worktree and ${this.branch} removed; continue from ${canonical}`);
761
+ }else parts.push(`worktree kept (${removed.stderr.trim().split('\n').at(-1)??'git worktree remove refused'})`);
762
+ }
763
+ const line=parts.join('; ');
764
+ this.say('cleaned',line);
765
+ return line;
766
+ }
767
+
768
+ /** @param {string} rule @param {string} why @param {number} round @param {string} before */
769
+ landed(rule,why,round,before){
770
+ const head=this.head();
771
+ this.say('landed',`main ${short(before)} -> ${short(head)} (${rule}: ${why})`);
772
+ this.landedSha=head;
773
+ this.followCanonical();
774
+ this.startWatcher(head);
775
+ this.say('rule',`main's own CI runs on ${short(head)} now. If it goes red, the lane that landed last fixes it forward or reverts it, at once (J249)`);
776
+ const seconds=Math.round((Date.now()-this.started)/1000);
777
+ this.receipt(`landed ${short(head)} on main (${short(before)}..${short(head)}); ${rule}; rounds ${round}; branch ci ${this.runs.join(', ')||'none'}; main ci ${rule==='carried'?'followed by main-watch':'reuses the branch run'}; ${seconds} s`);
778
+ return 0;
779
+ }
780
+ }
781
+
782
+ /** The only main push land makes: the exact SHA, an explicit non-forced refspec.
783
+ * @param {string} sha */
784
+ export function mainPushArgs(sha){
785
+ if(!SHA.test(sha))throw new Error('land pushes an exact SHA to main');
786
+ const args=['push','--porcelain','origin',`${sha}:refs/heads/main`];
787
+ if(args.some(arg=>arg.startsWith('+')||/force|^-f$/u.test(arg)))throw new Error('land never forces main');
788
+ return args;
789
+ }
790
+
791
+ /** Land the worktree at `cwd`; resolves to the exit code.
792
+ * @param {string[]} argv @param {string} [cwd] @param {NodeJS.ProcessEnv} [env] */
793
+ export async function land(argv,cwd=process.cwd(),env=process.env){
794
+ /** @type {(() => void)|null} */let unlock=null;
795
+ try{
796
+ const landing=new Landing(cwd,parseArgs(argv),env);
797
+ unlock=landing.lock();
798
+ const code=await landing.run();
799
+ // Cleanup runs under the land lock (J206 review): no second land can start here meanwhile. The lock file lives in
800
+ // this worktree's git dir, so removing the worktree removes it too; the release below then finds nothing.
801
+ if(!landing.options.keep)landing.cleanUp();
802
+ return code;
803
+ }catch(error){
804
+ if(error instanceof StopError){process.stdout.write(`land STOP ${error.message}\n`);return 1;}
805
+ throw error;
806
+ }finally{unlock?.();}
807
+ }
808
+
809
+ if(process.argv[1]!==undefined&&import.meta.url===pathToFileURL(resolve(process.argv[1])).href)process.exitCode=await land(process.argv.slice(2));