@aephia/atlas-kit 0.7.1-next.1 → 0.8.0-next.2

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 (249) hide show
  1. package/README.md +1 -0
  2. package/dist/claim-stakes/actions/index.d.ts +60 -14
  3. package/dist/claim-stakes/actions/index.d.ts.map +1 -1
  4. package/dist/claim-stakes/actions/index.js +314 -61
  5. package/dist/claim-stakes/actions/index.js.map +1 -1
  6. package/dist/client/context.d.ts.map +1 -1
  7. package/dist/client/context.js +20 -1
  8. package/dist/client/context.js.map +1 -1
  9. package/dist/client/contracts.d.ts +9 -0
  10. package/dist/client/contracts.d.ts.map +1 -1
  11. package/dist/client/deployments.d.ts +16 -0
  12. package/dist/client/deployments.d.ts.map +1 -1
  13. package/dist/client/deployments.js +16 -0
  14. package/dist/client/deployments.js.map +1 -1
  15. package/dist/client/errors.d.ts +1 -1
  16. package/dist/client/errors.d.ts.map +1 -1
  17. package/dist/client/errors.js.map +1 -1
  18. package/dist/client/index.d.ts +18 -0
  19. package/dist/client/index.d.ts.map +1 -1
  20. package/dist/client/index.js +18 -0
  21. package/dist/client/index.js.map +1 -1
  22. package/dist/combat/actions/index.d.ts.map +1 -1
  23. package/dist/combat/actions/index.js +4 -0
  24. package/dist/combat/actions/index.js.map +1 -1
  25. package/dist/combat/index.d.ts +4 -2
  26. package/dist/combat/index.d.ts.map +1 -1
  27. package/dist/combat/index.js.map +1 -1
  28. package/dist/crafting/actions/index.d.ts +4 -2
  29. package/dist/crafting/actions/index.d.ts.map +1 -1
  30. package/dist/crafting/actions/index.js +6 -8
  31. package/dist/crafting/actions/index.js.map +1 -1
  32. package/dist/fleets/actions/index.d.ts +14 -10
  33. package/dist/fleets/actions/index.d.ts.map +1 -1
  34. package/dist/fleets/actions/index.js +19 -14
  35. package/dist/fleets/actions/index.js.map +1 -1
  36. package/dist/fleets/composition-stats.d.ts.map +1 -1
  37. package/dist/fleets/composition-stats.js +15 -13
  38. package/dist/fleets/composition-stats.js.map +1 -1
  39. package/dist/fleets/movement-arithmetic.d.ts +9 -1
  40. package/dist/fleets/movement-arithmetic.d.ts.map +1 -1
  41. package/dist/fleets/movement-arithmetic.js +11 -6
  42. package/dist/fleets/movement-arithmetic.js.map +1 -1
  43. package/dist/fleets/warp-lane-toll.d.ts +40 -22
  44. package/dist/fleets/warp-lane-toll.d.ts.map +1 -1
  45. package/dist/fleets/warp-lane-toll.js +36 -33
  46. package/dist/fleets/warp-lane-toll.js.map +1 -1
  47. package/dist/identity/actions/index.d.ts +1 -1
  48. package/dist/identity/actions/index.d.ts.map +1 -1
  49. package/dist/identity/actions/index.js +6 -4
  50. package/dist/identity/actions/index.js.map +1 -1
  51. package/dist/identity/actions/research-unlock.d.ts.map +1 -1
  52. package/dist/identity/actions/research-unlock.js +3 -0
  53. package/dist/identity/actions/research-unlock.js.map +1 -1
  54. package/dist/internal/c4/career-xp.d.ts +26 -2
  55. package/dist/internal/c4/career-xp.d.ts.map +1 -1
  56. package/dist/internal/c4/career-xp.js +31 -4
  57. package/dist/internal/c4/career-xp.js.map +1 -1
  58. package/dist/internal/c4/character.d.ts +10 -0
  59. package/dist/internal/c4/character.d.ts.map +1 -1
  60. package/dist/internal/c4/character.js +38 -11
  61. package/dist/internal/c4/character.js.map +1 -1
  62. package/dist/internal/c4/claim-stake-plots.d.ts +25 -7
  63. package/dist/internal/c4/claim-stake-plots.d.ts.map +1 -1
  64. package/dist/internal/c4/claim-stake-plots.js +64 -16
  65. package/dist/internal/c4/claim-stake-plots.js.map +1 -1
  66. package/dist/internal/c4/claim-stake-standing.d.ts.map +1 -1
  67. package/dist/internal/c4/claim-stake-standing.js +9 -2
  68. package/dist/internal/c4/claim-stake-standing.js.map +1 -1
  69. package/dist/internal/c4/claim-stake-storage.d.ts +3 -2
  70. package/dist/internal/c4/claim-stake-storage.d.ts.map +1 -1
  71. package/dist/internal/c4/claim-stake-storage.js +14 -8
  72. package/dist/internal/c4/claim-stake-storage.js.map +1 -1
  73. package/dist/internal/c4/claim-stake-system-cap.d.ts +15 -0
  74. package/dist/internal/c4/claim-stake-system-cap.d.ts.map +1 -0
  75. package/dist/internal/c4/claim-stake-system-cap.js +31 -0
  76. package/dist/internal/c4/claim-stake-system-cap.js.map +1 -0
  77. package/dist/internal/c4/claim-stake.js +1 -1
  78. package/dist/internal/c4/crafting-process-codec.d.ts +6 -9
  79. package/dist/internal/c4/crafting-process-codec.d.ts.map +1 -1
  80. package/dist/internal/c4/crafting-process-codec.js +9 -30
  81. package/dist/internal/c4/crafting-process-codec.js.map +1 -1
  82. package/dist/internal/c4/crafting-storage.d.ts.map +1 -1
  83. package/dist/internal/c4/crafting-storage.js +1 -0
  84. package/dist/internal/c4/crafting-storage.js.map +1 -1
  85. package/dist/internal/c4/crafting.d.ts +11 -4
  86. package/dist/internal/c4/crafting.d.ts.map +1 -1
  87. package/dist/internal/c4/crafting.js +16 -15
  88. package/dist/internal/c4/crafting.js.map +1 -1
  89. package/dist/internal/c4/discriminators.d.ts +5 -1
  90. package/dist/internal/c4/discriminators.d.ts.map +1 -1
  91. package/dist/internal/c4/discriminators.js +11 -3
  92. package/dist/internal/c4/discriminators.js.map +1 -1
  93. package/dist/internal/c4/fleet-creation.d.ts.map +1 -1
  94. package/dist/internal/c4/fleet-creation.js +3 -2
  95. package/dist/internal/c4/fleet-creation.js.map +1 -1
  96. package/dist/internal/c4/fleet-storage.d.ts.map +1 -1
  97. package/dist/internal/c4/fleet-storage.js +6 -1
  98. package/dist/internal/c4/fleet-storage.js.map +1 -1
  99. package/dist/internal/c4/fleet.d.ts +37 -17
  100. package/dist/internal/c4/fleet.d.ts.map +1 -1
  101. package/dist/internal/c4/fleet.js +4 -1
  102. package/dist/internal/c4/fleet.js.map +1 -1
  103. package/dist/internal/c4/game.d.ts +9 -0
  104. package/dist/internal/c4/game.d.ts.map +1 -1
  105. package/dist/internal/c4/game.js +18 -3
  106. package/dist/internal/c4/game.js.map +1 -1
  107. package/dist/internal/c4/local-market-order.d.ts +1 -0
  108. package/dist/internal/c4/local-market-order.d.ts.map +1 -1
  109. package/dist/internal/c4/local-market-order.js +1 -0
  110. package/dist/internal/c4/local-market-order.js.map +1 -1
  111. package/dist/internal/c4/pda.d.ts +16 -1
  112. package/dist/internal/c4/pda.d.ts.map +1 -1
  113. package/dist/internal/c4/pda.js +26 -1
  114. package/dist/internal/c4/pda.js.map +1 -1
  115. package/dist/internal/c4/profile-permissions.d.ts +1 -1
  116. package/dist/internal/c4/profile-permissions.d.ts.map +1 -1
  117. package/dist/internal/c4/profile-permissions.js +9 -11
  118. package/dist/internal/c4/profile-permissions.js.map +1 -1
  119. package/dist/internal/c4/region-building-policy.d.ts +17 -0
  120. package/dist/internal/c4/region-building-policy.d.ts.map +1 -0
  121. package/dist/internal/c4/region-building-policy.js +40 -0
  122. package/dist/internal/c4/region-building-policy.js.map +1 -0
  123. package/dist/internal/c4/runtime-bindings.d.ts +1 -1
  124. package/dist/internal/c4/runtime-bindings.d.ts.map +1 -1
  125. package/dist/internal/c4/runtime-bindings.js +1 -1
  126. package/dist/internal/c4/runtime-bindings.js.map +1 -1
  127. package/dist/internal/c4/ship-stats.js +17 -17
  128. package/dist/internal/c4/ship-stats.js.map +1 -1
  129. package/dist/internal/c4/world.d.ts +5 -4
  130. package/dist/internal/c4/world.d.ts.map +1 -1
  131. package/dist/internal/c4/world.js +18 -2
  132. package/dist/internal/c4/world.js.map +1 -1
  133. package/dist/internal/cargo.d.ts +3 -0
  134. package/dist/internal/cargo.d.ts.map +1 -1
  135. package/dist/internal/cargo.js +5 -0
  136. package/dist/internal/cargo.js.map +1 -1
  137. package/dist/internal/planning/action-runtime.d.ts +6 -3
  138. package/dist/internal/planning/action-runtime.d.ts.map +1 -1
  139. package/dist/internal/planning/action-runtime.js +1 -6
  140. package/dist/internal/planning/action-runtime.js.map +1 -1
  141. package/dist/internal/planning/arrival-guards.js +2 -2
  142. package/dist/internal/planning/arrival-guards.js.map +1 -1
  143. package/dist/internal/planning/authorization-adapter.d.ts +20 -8
  144. package/dist/internal/planning/authorization-adapter.d.ts.map +1 -1
  145. package/dist/internal/planning/authorization-adapter.js +32 -9
  146. package/dist/internal/planning/authorization-adapter.js.map +1 -1
  147. package/dist/internal/planning/character-access.d.ts +1 -6
  148. package/dist/internal/planning/character-access.d.ts.map +1 -1
  149. package/dist/internal/planning/character-access.js +2 -7
  150. package/dist/internal/planning/character-access.js.map +1 -1
  151. package/dist/internal/planning/character-registration.js +1 -1
  152. package/dist/internal/planning/character-registration.js.map +1 -1
  153. package/dist/internal/planning/crafting-storage-actions.js +3 -3
  154. package/dist/internal/planning/crafting-storage-actions.js.map +1 -1
  155. package/dist/internal/planning/democracy-history.d.ts +5 -0
  156. package/dist/internal/planning/democracy-history.d.ts.map +1 -1
  157. package/dist/internal/planning/democracy-history.js +48 -6
  158. package/dist/internal/planning/democracy-history.js.map +1 -1
  159. package/dist/internal/planning/fleet-arrival.d.ts +2 -2
  160. package/dist/internal/planning/fleet-attack-xp.d.ts.map +1 -1
  161. package/dist/internal/planning/fleet-attack-xp.js +6 -5
  162. package/dist/internal/planning/fleet-attack-xp.js.map +1 -1
  163. package/dist/internal/planning/fleet-dock-funding.js +2 -2
  164. package/dist/internal/planning/fleet-dock-funding.js.map +1 -1
  165. package/dist/internal/planning/fleet-respawn.d.ts.map +1 -1
  166. package/dist/internal/planning/fleet-respawn.js +3 -4
  167. package/dist/internal/planning/fleet-respawn.js.map +1 -1
  168. package/dist/internal/planning/governance-fees.d.ts +14 -4
  169. package/dist/internal/planning/governance-fees.d.ts.map +1 -1
  170. package/dist/internal/planning/governance-fees.js +66 -21
  171. package/dist/internal/planning/governance-fees.js.map +1 -1
  172. package/dist/internal/planning/local-market-order-funding.d.ts.map +1 -1
  173. package/dist/internal/planning/local-market-order-funding.js +2 -2
  174. package/dist/internal/planning/local-market-order-funding.js.map +1 -1
  175. package/dist/internal/planning/mining-stop.js +1 -1
  176. package/dist/internal/planning/mining-stop.js.map +1 -1
  177. package/dist/internal/planning/movement-xp-guard.d.ts.map +1 -1
  178. package/dist/internal/planning/movement-xp-guard.js +0 -1
  179. package/dist/internal/planning/movement-xp-guard.js.map +1 -1
  180. package/dist/internal/planning/plan-guards.js +2 -2
  181. package/dist/internal/planning/rent-catalog.d.ts.map +1 -1
  182. package/dist/internal/planning/rent-catalog.js +14 -4
  183. package/dist/internal/planning/rent-catalog.js.map +1 -1
  184. package/dist/internal/planning/research-unlock.d.ts.map +1 -1
  185. package/dist/internal/planning/research-unlock.js +12 -1
  186. package/dist/internal/planning/research-unlock.js.map +1 -1
  187. package/dist/internal/planning/runtime-guards.d.ts.map +1 -1
  188. package/dist/internal/planning/runtime-guards.js +90 -71
  189. package/dist/internal/planning/runtime-guards.js.map +1 -1
  190. package/dist/internal/planning/xp-runtime.d.ts +4 -5
  191. package/dist/internal/planning/xp-runtime.d.ts.map +1 -1
  192. package/dist/internal/planning/xp-runtime.js +26 -51
  193. package/dist/internal/planning/xp-runtime.js.map +1 -1
  194. package/dist/mining/actions/index.d.ts +5 -3
  195. package/dist/mining/actions/index.d.ts.map +1 -1
  196. package/dist/mining/actions/index.js +7 -5
  197. package/dist/mining/actions/index.js.map +1 -1
  198. package/dist/planning/assembly.d.ts +12 -5
  199. package/dist/planning/assembly.d.ts.map +1 -1
  200. package/dist/planning/assembly.js +22 -18
  201. package/dist/planning/assembly.js.map +1 -1
  202. package/dist/planning/execution.d.ts.map +1 -1
  203. package/dist/planning/execution.js +3 -5
  204. package/dist/planning/execution.js.map +1 -1
  205. package/dist/planning/index.d.ts +3 -2
  206. package/dist/planning/index.d.ts.map +1 -1
  207. package/dist/planning/index.js +2 -2
  208. package/dist/planning/index.js.map +1 -1
  209. package/dist/planning/plan-construction.js +1 -1
  210. package/dist/planning/selected-references.d.ts +17 -0
  211. package/dist/planning/selected-references.d.ts.map +1 -0
  212. package/dist/planning/selected-references.js +42 -0
  213. package/dist/planning/selected-references.js.map +1 -0
  214. package/dist/planning/simulation.d.ts.map +1 -1
  215. package/dist/planning/simulation.js +2 -3
  216. package/dist/planning/simulation.js.map +1 -1
  217. package/dist/ptr/account.d.ts +109 -0
  218. package/dist/ptr/account.d.ts.map +1 -0
  219. package/dist/ptr/account.js +421 -0
  220. package/dist/ptr/account.js.map +1 -0
  221. package/dist/ptr/context.d.ts +4 -0
  222. package/dist/ptr/context.d.ts.map +1 -0
  223. package/dist/ptr/context.js +15 -0
  224. package/dist/ptr/context.js.map +1 -0
  225. package/dist/ptr/errors.d.ts +91 -0
  226. package/dist/ptr/errors.d.ts.map +1 -0
  227. package/dist/ptr/errors.js +74 -0
  228. package/dist/ptr/errors.js.map +1 -0
  229. package/dist/ptr/faucet.d.ts +231 -0
  230. package/dist/ptr/faucet.d.ts.map +1 -0
  231. package/dist/ptr/faucet.js +395 -0
  232. package/dist/ptr/faucet.js.map +1 -0
  233. package/dist/ptr/index.d.ts +22 -0
  234. package/dist/ptr/index.d.ts.map +1 -0
  235. package/dist/ptr/index.js +22 -0
  236. package/dist/ptr/index.js.map +1 -0
  237. package/dist/registry/index.d.ts +1 -1
  238. package/dist/registry/index.js +2 -2
  239. package/dist/registry/onboarding.d.ts +3 -1
  240. package/dist/registry/onboarding.d.ts.map +1 -1
  241. package/dist/registry/onboarding.js +4 -5
  242. package/dist/registry/onboarding.js.map +1 -1
  243. package/dist/registry/ship-stats-snapshot.js +17 -17
  244. package/dist/registry/ship-stats-snapshot.js.map +1 -1
  245. package/dist/world/planet-claim-stake-plots.d.ts +18 -14
  246. package/dist/world/planet-claim-stake-plots.d.ts.map +1 -1
  247. package/dist/world/planet-claim-stake-plots.js +11 -8
  248. package/dist/world/planet-claim-stake-plots.js.map +1 -1
  249. package/package.json +7 -2
@@ -6,9 +6,9 @@ import { StarbaseLevel } from '../../internal/c4/runtime-bindings.js';
6
6
  import { readFreshGameClaimStakeConfiguration, } from '../../registry/claim-stakes.js';
7
7
  import { characterAccountDefinition, findCharacterPda, } from '../../internal/c4/character.js';
8
8
  import { deriveFactionOwnershipAddress, factionOwnershipAccountDefinition, } from '../../internal/c4/factions.js';
9
- import { claimStakeAccountDefinition } from '../../internal/c4/claim-stake.js';
9
+ import { claimStakeAccountDefinition, } from '../../internal/c4/claim-stake.js';
10
10
  import { deriveClaimStakeRegistration } from '../../internal/c4/claim-stake-standing.js';
11
- import { CLAIM_STAKE_PLOT_ROWS, claimStakePlacementRow, claimStakePlotPositions, } from '../../internal/c4/claim-stake-plots.js';
11
+ import { CLAIM_STAKE_PLOT_ROWS, claimStakePlacementRow, claimStakePlotPositions, claimStakeTierRowKey, activeClaimStakesOfTier, } from '../../internal/c4/claim-stake-plots.js';
12
12
  import { factionValue } from '../../internal/c4/faction.js';
13
13
  import { deriveFleetCrewBindingAddress, fleetCrewBindingAccountDefinition, matchesFleetCrewBindingIdentity, } from '../../internal/c4/fleet-crew-binding.js';
14
14
  import { deriveFleetAddress, fleetAccountDefinition, } from '../../internal/c4/fleet.js';
@@ -20,19 +20,20 @@ import { readClaimStakeStorageAction } from '../../internal/planning/claim-stake
20
20
  import { RENT_ADDRESS } from '../../internal/planning/rent.js';
21
21
  import { planStorageFunding } from '../../internal/planning/storage-actions.js';
22
22
  import { requireDisabledStakeRent, requireNewStakeRent, } from '../../internal/planning/rent-catalog.js';
23
- import { deriveStructureXpAccrualAddress } from '../../internal/c4/pda.js';
23
+ import { deriveClaimStakeSystemCapConfigAddress, deriveRegionBuildingPolicyAddress, deriveStructureXpAccrualAddress, } from '../../internal/c4/pda.js';
24
+ import { readClaimStakeSystemCaps } from '../../internal/c4/claim-stake-system-cap.js';
25
+ import { readRegionBuildingPolicy } from '../../internal/c4/region-building-policy.js';
24
26
  import { requireProfileStarbasePlayer } from '../../internal/planning/starbase-player-owner.js';
25
27
  import { requireGameAddress } from '../../internal/game-context.js';
26
- import { cargoStorageUnits } from '../../internal/cargo.js';
28
+ import { cargoStorageUnits, cargoStorageUnitsFloor, } from '../../internal/cargo.js';
27
29
  import { adaptCancelClaimStakeBuildingChangesInstruction, adaptClaimStakeBuildingChangesInstruction, adaptDeconstructClaimStakeInstruction, adaptFinalizeClaimStakeBuildingChangesInstruction, adaptPlaceClaimStakeInstruction, adaptRecoverClaimStakeFleetTransferInstruction, adaptStartClaimStakeFleetTransferInstruction, adaptTopUpClaimStakeRentInstruction, readPlanAuthorization, } from '../../internal/planning/authorization-adapter.js';
28
30
  import { buildPlannerPlan } from '../../planning/plan-construction.js';
29
31
  import { readFreshGameCargoDefinitions } from '../../registry/cargo.js';
30
- import { resolveCargo } from '../../registry/index.js';
32
+ import { listClaimStakeBuildingDefinitions, resolveCargo, } from '../../registry/index.js';
31
33
  import { accountAbsentPrecondition, accountStatePrecondition, } from '../../internal/planning/account-state.js';
32
- async function resolveClaimStakeXp(ctx, game, structure, character) {
34
+ async function resolveClaimStakeXp(ctx, game, character) {
33
35
  const xp = await resolveXpRuntime(ctx, {
34
36
  game,
35
- structure,
36
37
  ...(character === undefined ? {} : { character }),
37
38
  });
38
39
  const guard = {
@@ -40,7 +41,9 @@ async function resolveClaimStakeXp(ctx, game, structure, character) {
40
41
  address: game,
41
42
  intent: xp.intent,
42
43
  accounts: xp.accounts,
43
- describes: 'The Game and canonical Claim Stake XP accounts remain supported; accrued XP may change. Initialize or repair missing XP state using the game client, then recreate the Plan.',
44
+ describes: character === undefined
45
+ ? 'The Game runtime remains supported. Wait for the phase change or update Atlas Kit, then recreate the Plan.'
46
+ : 'The Game runtime and the Character Career XP accounts remain supported and reconciled; accrued XP may change. Initialize or repair missing XP state using the game client, then recreate the Plan.',
44
47
  };
45
48
  return { accounts: xp.accounts, guard };
46
49
  }
@@ -264,8 +267,9 @@ function findHub(configuration, id, game) {
264
267
  * graph, current catalog membership, known plot/cargo/crew availability, and
265
268
  * absence of the caller-created Claim Stake account. It also checks the
266
269
  * Character's productive plot count and tier limits, the bundled hub's tags
267
- * against the Planet and Claim Stake definition, and that the Character's
268
- * ATLAS covers the placement fee plus any initial rent. It returns one inert Plan;
270
+ * against the Planet and Claim Stake definition, the hub's research against the
271
+ * Character's research tags, and that the Character's ATLAS covers the
272
+ * placement fee plus any initial rent. It returns one inert Plan;
269
273
  * permissions, placement races, rent arithmetic, and program capacity remain
270
274
  * chain-authoritative.
271
275
  *
@@ -391,12 +395,81 @@ export async function planPlaceClaimStake(ctx, body, player, input) {
391
395
  const level = LEVEL_INDEX[currentSystem.starbase.level];
392
396
  const tier = TIER_INDEX[definition.tier];
393
397
  // The program places the stake in the first plot row up to the Starbase's
394
- // level with room for its tier; stakes of every tier share each row.
398
+ // level whose row for the stake's tier is below that row's limit.
395
399
  if (claimStakePlacementRow(currentDetails.claimStakePlots, currentDetails.claimedPlots, tier, level) === undefined) {
396
400
  fail(`Planet ${body.name} (${body.address}) has no free tier-${definition.tier} Claim Stake plot at Starbase ${currentSystem.starbase.level} or any lower level; every reachable plot row is full. Choose another eligible Planet or tier, refresh it, and retry.`, body.address);
397
401
  }
402
+ // The game caps the System's active Claim Stakes of each tier across all of
403
+ // its Planets. Placement passes the System's cap configuration and every
404
+ // other Celestial Body of the System, each exactly once, so none is left out
405
+ // of the count; the game counts and enforces the cap itself.
406
+ const otherCelestialBodies = currentSystem.celestialBodyAddresses.filter((address) => address !== body.address);
407
+ if (otherCelestialBodies.length + 1 !==
408
+ currentSystem.celestialBodyAddresses.length ||
409
+ new Set(otherCelestialBodies).size !== otherCelestialBodies.length) {
410
+ fail(`Celestial Body ${body.address} is not registered exactly once in Star System ${body.system.address}, or the System lists a body twice. Refresh the System and retry.`, body.address);
411
+ }
412
+ const [capConfigAddress] = await deriveClaimStakeSystemCapConfigAddress(ctx.programs, game, body.system.address);
413
+ // A System in a Region passes that Region's building policy; a System
414
+ // outside every Region passes the SAGE program, which the game ignores.
415
+ const regionId = currentSystem.regionId;
416
+ const policyAddress = regionId === undefined
417
+ ? ctx.programs.sage
418
+ : (await deriveRegionBuildingPolicyAddress(ctx.programs, game, regionId))[0];
419
+ const policyReads = regionId === undefined ? [] : [policyAddress];
420
+ const [capAccount, ...otherAccounts] = await readContextRawAccounts(ctx, [
421
+ capConfigAddress,
422
+ ...policyReads,
423
+ ...otherCelestialBodies,
424
+ ]);
425
+ const policyAccount = regionId === undefined ? undefined : otherAccounts[0];
426
+ const siblingAccounts = otherAccounts.slice(policyReads.length);
427
+ const systemCaps = readClaimStakeSystemCaps(ctx.programs, capAccount, capConfigAddress, { game, system: body.system.address });
428
+ // The generated tier cap set always decodes one cap per tier.
429
+ const tierCap = systemCaps.caps[tier];
430
+ if (tierCap === 0) {
431
+ fail(`Star System ${body.system.address} allows no active tier-${definition.tier} Claim Stakes: its cap for that tier is 0. Choose another System or tier.`, capConfigAddress);
432
+ }
433
+ const siblings = otherCelestialBodies.map((address, index) => {
434
+ const sibling = celestialBodyAccountDefinition.decode(requireAccount(siblingAccounts[index], address, `Celestial Body ${address} of Star System ${body.system.address} is missing. Refresh the System and retry placement.`), ctx.programs);
435
+ if (sibling.game !== game || sibling.system !== body.system.address)
436
+ fail(`Celestial Body ${address} listed by Star System ${body.system.address} belongs to another Game or System. Refresh the System and retry.`, address);
437
+ return sibling;
438
+ });
439
+ // The game counts each Planet's active stakes of this tier: none on a body
440
+ // out of sequence with the System, and after the Starbase was rebuilt only
441
+ // the levels up to its current level until the body syncs.
442
+ const starbaseState = currentSystem.starbase;
443
+ const activeOfTier = [currentBody, ...siblings].reduce((total, candidate) => {
444
+ if (candidate.kind !== 'planet' ||
445
+ candidate.systemSequenceId !== currentSystem.sequenceId)
446
+ return total;
447
+ const maxLevel = starbaseState.builtDestroyedAtUnixSeconds >=
448
+ candidate.lastSyncAtUnixSeconds
449
+ ? level
450
+ : CLAIM_STAKE_PLOT_ROWS - 1;
451
+ return (total +
452
+ activeClaimStakesOfTier(candidate.details.claimedPlots, tier, maxLevel));
453
+ }, 0);
454
+ if (activeOfTier >= tierCap) {
455
+ fail(`Star System ${body.system.address} already holds ${String(activeOfTier)} active tier-${definition.tier} Claim Stakes, its cap of ${String(tierCap)}. Wait for a stake to be removed, or choose another System or tier.`, capConfigAddress);
456
+ }
398
457
  // The Character's research caps the productive plot tier and count.
399
458
  const modifiers = currentCharacter.modifiers.values;
459
+ // A Region's building policy requires every research tag it lists.
460
+ const regionPolicy = regionId === undefined
461
+ ? undefined
462
+ : readRegionBuildingPolicy(ctx.programs, policyAccount, policyAddress, {
463
+ game,
464
+ regionId,
465
+ });
466
+ const missingRegionTags = regionPolicy?.requiredResearchTags.filter((tag) => !modifiers.researchTags.includes(tag)) ?? [];
467
+ if (missingRegionTags.length > 0)
468
+ fail(`Character ${character} lacks research tag${missingRegionTags.length === 1 ? '' : 's'} ${missingRegionTags.join(', ')}, which Region ${String(regionId)} requires for Claim Stake placement in Star System ${body.system.address}. Unlock the research that provides ${missingRegionTags.length === 1 ? 'it' : 'them'}, or choose a System in another Region.`, policyAddress);
469
+ // The game checks the bundled hub's research at placement (#1177).
470
+ const missingHubTags = hub.researchRequirementIds.filter((tag) => !modifiers.researchTags.includes(tag));
471
+ if (missingHubTags.length > 0)
472
+ fail(`Character ${character} lacks research tag${missingHubTags.length === 1 ? '' : 's'} ${missingHubTags.join(', ')}, which bundled hub ${hub.name} requires, so the game refuses this placement. Unlock that research, refresh the Character, and retry.`, character);
400
473
  if (modifiers.maxProductivePlotTier !== undefined &&
401
474
  tier + 1 > modifiers.maxProductivePlotTier)
402
475
  fail(`Character ${character} may place up to tier ${String(modifiers.maxProductivePlotTier)}, below ${definition.name}'s tier ${definition.tier}. Research a higher plot tier or pick a lower tier.`, character);
@@ -422,16 +495,27 @@ export async function planPlaceClaimStake(ctx, body, player, input) {
422
495
  rentAuthority: rent.rentAuthority,
423
496
  systemAndStarbasePlayerStarbasePlayer: player.address,
424
497
  systemAndStarbasePlayerSystem: body.system.address,
498
+ claimStakeSystemCapConfig: capConfigAddress,
499
+ regionBuildingPolicy: policyAddress,
500
+ otherCelestialBodies,
425
501
  });
426
502
  // The new stake and the claimed plot are funded from the Profile vault.
427
503
  const storage = await planClaimStakeStorage(ctx, instruction, options.authorization.profile, [freshGame.account, currentBodyAccount, currentSystemAccount], 'Claim Stake placement');
428
- const description = `Place ${definition.name} on Planet ${body.name} (${body.address}) with bundled hub ${hub.name}, ${String(hub.neededCrew)} crew, a ${String(placementFee)} raw ATLAS placement fee and ${String(rentDeposit)} raw initial rent. ${storage.disclosure}`;
504
+ const description = `Place ${definition.name} on Planet ${body.name} (${body.address}) with bundled hub ${hub.name}, ${String(hub.neededCrew)} crew, a ${String(placementFee)} raw ATLAS placement fee and ${String(rentDeposit)} raw initial rent. Star System ${body.system.address} holds ${String(activeOfTier)} of at most ${String(tierCap)} active tier-${definition.tier} Claim Stakes across its Planets; the game counts all ${String(otherCelestialBodies.length + 1)} Celestial Bodies and refuses placement at the cap.${regionPolicy === undefined ? '' : regionPolicy.requiredResearchTags.length === 0 ? ` Region ${String(regionId)} requires no building research.` : ` Region ${String(regionId)} requires research tags ${regionPolicy.requiredResearchTags.join(', ')}, which Character ${character} holds.`} ${storage.disclosure}`;
429
505
  return buildPlannerPlan(ctx.programs, {
430
506
  kind: 'claim-stakes.place',
431
507
  preconditions: [
432
508
  ...(await Promise.all([
433
509
  accountStatePrecondition(freshGame.account, `The configured Game retains Claim Stake definition ${String(definition.id)} and bundled hub ${String(hub.id)} eligibility.`),
434
510
  accountStatePrecondition(currentBodyAccount, `Planet ${body.name} retains an available ${definition.name} plot and its configured Game/System relationship.`),
511
+ accountStatePrecondition(requireAccount(capAccount, capConfigAddress, `Claim Stake cap configuration ${capConfigAddress} is missing.`), `Star System ${body.system.address} keeps its tier-${definition.tier} Claim Stake cap of ${String(tierCap)}.`),
512
+ ...(regionId === undefined
513
+ ? []
514
+ : [
515
+ policyAccount === undefined
516
+ ? accountAbsentPrecondition(policyAddress, `Region ${String(regionId)} still has no building policy, so placement needs no Region research.`)
517
+ : accountStatePrecondition(policyAccount, `Region ${String(regionId)} keeps its building policy, whose research Character ${character} holds.`),
518
+ ]),
435
519
  accountStatePrecondition(currentPlayerAccount, `Starbase Player ${player.address} retains its Profile, Character, System, available crew, and ${cargoName} balance.`),
436
520
  characterPrecondition(currentCharacterAccount, options.authorization.profile),
437
521
  accountStatePrecondition(currentSystemAccount, `Star System ${currentSystem.name} retains its configured Game, sequence, and active Starbase level.`),
@@ -478,6 +562,42 @@ function claimStakePlacementFee(baseFeeRaw, multiplierRaw) {
478
562
  function quantities(buildings) {
479
563
  return new Map(buildings.map(({ buildingId, quantity }) => [buildingId, quantity]));
480
564
  }
565
+ /** The layout a design finalizes to. A design records signed changes, not a
566
+ * layout: the game adds them to the stake's buildings, and a building that
567
+ * reaches zero drops out (#1177). */
568
+ function finalLayout(buildings, changes) {
569
+ const layout = quantities(buildings);
570
+ for (const { buildingId, quantity } of changes) {
571
+ const next = (layout.get(buildingId) ?? 0) + quantity;
572
+ if (next === 0)
573
+ layout.delete(buildingId);
574
+ else
575
+ layout.set(buildingId, next);
576
+ }
577
+ return layout;
578
+ }
579
+ /** Whether a design only removes buildings. The game skips its final-layout
580
+ * checks, building research included, when such a design finalizes. */
581
+ function removesOnly(changes) {
582
+ const amounts = [...changes.values()];
583
+ return (amounts.some((amount) => amount < 0) &&
584
+ amounts.every((amount) => amount <= 0));
585
+ }
586
+ /** Names each building in a layout that needs research the Character lacks,
587
+ * with the missing research tags. The game refuses to finalize such a layout. */
588
+ function missingBuildingResearch(layout, definitions, researchTags, game) {
589
+ const missing = [];
590
+ for (const [buildingId] of layout) {
591
+ const definition = definitions.get(buildingId);
592
+ if (definition === undefined) {
593
+ fail(`Building ${String(buildingId)} has no definition in the current Game catalog. Refresh the Claim Stake and definitions before retrying.`, game);
594
+ }
595
+ const tags = definition.researchRequirementIds.filter((tag) => !researchTags.includes(tag));
596
+ if (tags.length > 0)
597
+ missing.push(`${definition.name} (research tag${tags.length === 1 ? '' : 's'} ${tags.join(', ')})`);
598
+ }
599
+ return missing;
600
+ }
481
601
  function sameQuantities(left, right) {
482
602
  const leftById = quantities(left);
483
603
  const rightById = quantities(right);
@@ -701,13 +821,28 @@ function buildingDescription(change, name) {
701
821
  * the planner checks the fresh Starbase Player pod. Rent synchronization and
702
822
  * the final concurrent sequence race remain chain-authoritative.
703
823
  *
824
+ * The design's resource storage is the sum of its buildings' storage without
825
+ * Storage Modules, which hold the stake's Fuel instead. Finalization sets the
826
+ * stake to that storage even when the stake's cargo exceeds it; the game
827
+ * accepts such a design, so the planner does not refuse it. Its description
828
+ * warns instead that the finalized stake would be over-full, which leaves
829
+ * Fleet transfers unable to unload into it until enough cargo is loaded out.
830
+ *
831
+ * A pending design records signed changes on top of the stake's buildings, so
832
+ * the planner checks the layout the stake's buildings, the recorded changes and
833
+ * these changes produce. The game records a design whose buildings need
834
+ * research the Character lacks but refuses to finalize it, so the description
835
+ * warns and names each building and missing research tag. A design that only
836
+ * removes buildings gets no research warning: the game skips its final-layout
837
+ * checks when such a design finalizes.
838
+ *
704
839
  * Entering a design adds the design state and an entry for each building id
705
840
  * the design does not yet hold. The program funds that growth, up to the
706
841
  * stake's rent floor, from the Profile vault with the signing key; the Plan
707
842
  * bounds the debit with the same key and balance checks as placement.
708
843
  *
709
- * Requires Game 2 and its existing canonical Claim Stake XP ledger.
710
- * Missing XP state must be repaired outside this Plan; no accounts are created.
844
+ * Requires a supported Game runtime. The current game keeps no per-Claim-Stake
845
+ * XP ledger, so the Plan passes none and creates no accounts.
711
846
  *
712
847
  * Requires Disabled rent: the Game's rent catalog and the Claim Stake's rent
713
848
  * settlement authority must not exist, and both stay guarded absent until
@@ -749,7 +884,7 @@ export async function planClaimStakeBuildingChanges(ctx, stake, input) {
749
884
  }
750
885
  const planetBody = await requireDesignStakePlanet(ctx.programs, loaded.currentBody, stake, game, action);
751
886
  const { system } = planetBody;
752
- const { account: characterAccount } = requireProfileCharacter(ctx.programs, loaded.extraAccounts[0], character, profile, game, action);
887
+ const { account: characterAccount, current: currentCharacter } = requireProfileCharacter(ctx.programs, loaded.extraAccounts[0], character, profile, game, action);
753
888
  const [ownership, profileFaction] = await Promise.all([
754
889
  deriveFactionOwnershipAddress(ctx.programs, game, 'starbase', system),
755
890
  deriveProfileFactionAddress(ctx.programs, profile),
@@ -789,7 +924,8 @@ export async function planClaimStakeBuildingChanges(ctx, stake, input) {
789
924
  if (claimDefinition === undefined) {
790
925
  fail(`Claim Stake definition ${String(stake.claimStakeDefinitionId)} is absent from the current Game catalog. Refresh the Claim Stake and definitions before retrying.`, game);
791
926
  }
792
- const sourceBuildings = stake.state.kind === 'design' ? stake.state.buildings : stake.buildings;
927
+ // A pending design holds signed changes on top of the stake's buildings.
928
+ const pendingChanges = stake.state.kind === 'design' ? stake.state.buildings : [];
793
929
  if (currentStake.state.kind !== stake.state.kind ||
794
930
  (stake.state.kind === 'design' &&
795
931
  (currentStake.state.kind !== 'design' ||
@@ -798,7 +934,7 @@ export async function planClaimStakeBuildingChanges(ctx, stake, input) {
798
934
  fail(`Claim Stake ${stake.address} lifecycle state or exact design sequence changed. Refresh it and retry building changes.`, stake.address);
799
935
  }
800
936
  const sequenceId = stake.state.kind === 'design' ? stake.state.sequenceId : 0;
801
- const result = quantities(sourceBuildings);
937
+ const result = finalLayout(stake.buildings, pendingChanges);
802
938
  const definitions = new Map(freshGame.data.buildings.definitions.map((definition) => [
803
939
  definition.id,
804
940
  definition,
@@ -859,7 +995,9 @@ export async function planClaimStakeBuildingChanges(ctx, stake, input) {
859
995
  usedSlots += definition.slots * quantity;
860
996
  neededCrew += definition.neededCrew * quantity;
861
997
  power += definition.power * quantity;
862
- resourceStorageRaw += definition.resourceStorageRaw * BigInt(quantity);
998
+ // Storage Modules hold the stake's Fuel, not its resources (#1166).
999
+ if (!definition.providedTagIds.includes(STORAGE_MODULE_TAG))
1000
+ resourceStorageRaw += definition.resourceStorageRaw * BigInt(quantity);
863
1001
  if (neededCrew > U16_MAX) {
864
1002
  fail(`The resulting Claim Stake design has ${String(neededCrew)} needed crew, exceeding the ${String(U16_MAX)} maximum representable by its unsigned u16 needed-crew field. Remove crew-requiring buildings and retry.`, stake.address);
865
1003
  }
@@ -917,11 +1055,25 @@ export async function planClaimStakeBuildingChanges(ctx, stake, input) {
917
1055
  stake.resources.inventory.usedStorageUnitsRaw) {
918
1056
  fail(`Claim Stake ${stake.address} cargo capacity changed from the loaded snapshot. Refresh its resources and retry building changes.`, stake.address);
919
1057
  }
920
- if (currentStake.production.cargoPod.storageCost > resourceStorageRaw) {
921
- fail(`The resulting Claim Stake design provides ${String(resourceStorageRaw)} raw storage capacity, below the fresh known cargo usage of ${String(currentStake.production.cargoPod.storageCost)}. Keep enough storage buildings, remove cargo, refresh the Claim Stake, and retry building changes.`, stake.address);
922
- }
1058
+ // The game accepts a design that leaves the stake over-full and finalizes
1059
+ // it to the smaller storage (#1166), so this only warns.
1060
+ const overFull = currentStake.production.cargoPod.storageCost > resourceStorageRaw
1061
+ ? ` Warning: after finalization Claim Stake ${stake.address} would have ${String(resourceStorageRaw)} raw resource storage for the ${String(currentStake.production.cargoPod.storageCost)} storage units of cargo it holds; the game accepts this and leaves the stake over-full, so Fleet transfers cannot unload into it until enough cargo is loaded out.`
1062
+ : '';
1063
+ // The game records a design whose buildings need research the Character
1064
+ // lacks, but refuses to finalize it (#1177), so this only warns.
1065
+ const designChanges = finalLayout(pendingChanges, options.buildingChanges.map(({ buildingId, kind, quantity }) => ({
1066
+ buildingId,
1067
+ quantity: kind === 'add' ? quantity : -quantity,
1068
+ })));
1069
+ const unresearched = removesOnly(designChanges)
1070
+ ? []
1071
+ : missingBuildingResearch(result, definitions, currentCharacter.modifiers.values.researchTags, game);
1072
+ const researchWarning = unresearched.length === 0
1073
+ ? ''
1074
+ : ` Warning: Character ${character} lacks the research for ${unresearched.join('; ')}. The game records this design but refuses to finalize it until the Character unlocks that research; unlock it before finalizing, or remove the building.`;
923
1075
  const currencyCache = await claimStakeCurrencyCache(ctx.programs, game);
924
- const xp = await resolveClaimStakeXp(ctx, game, stake.address);
1076
+ const xp = await resolveClaimStakeXp(ctx, game);
925
1077
  const instruction = adaptClaimStakeBuildingChangesInstruction(ctx.programs, {
926
1078
  ...xp.accounts,
927
1079
  authorization: options.authorization,
@@ -939,7 +1091,7 @@ export async function planClaimStakeBuildingChanges(ctx, stake, input) {
939
1091
  });
940
1092
  // The grown design is funded from the Profile vault.
941
1093
  const storage = await planClaimStakeStorage(ctx, instruction, profile, [stakeAccount], 'Claim Stake building changes');
942
- const description = `Change buildings on Claim Stake ${stake.address}: ${descriptions.join('; ')}. ${storage.disclosure}`;
1094
+ const description = `Change buildings on Claim Stake ${stake.address}: ${descriptions.join('; ')}.${overFull}${researchWarning} ${storage.disclosure}`;
943
1095
  return buildPlannerPlan(ctx.programs, {
944
1096
  kind: 'claim-stakes.building-changes',
945
1097
  preconditions: [
@@ -974,15 +1126,22 @@ export async function planClaimStakeBuildingChanges(ctx, stake, input) {
974
1126
  * CurrencyCache, and a known positive rent balance. Rent timing and the final
975
1127
  * crew/building validation remain chain-authoritative.
976
1128
  *
1129
+ * The finalized layout is the stake's buildings plus the design's recorded
1130
+ * changes. The game refuses to finalize a design that adds buildings when any
1131
+ * building in that layout needs research the Character lacks, so the planner
1132
+ * refuses it first and names each building and missing research tag. A design
1133
+ * that only removes buildings is not checked, as in the game.
1134
+ *
977
1135
  * Finalization can draw Profile storage this Plan does not bound: a removed
978
1136
  * building's refund can open a Starbase Player cargo line, and a final layout
979
1137
  * that produces a new resource raises the stake's rent floor. The program
980
1138
  * funds both from the Profile vault with the signing key, so simulate before
981
1139
  * signing.
982
1140
  *
983
- * Requires Game 2 and its existing canonical Claim Stake XP ledger.
984
- * The Character XP budget and configuration must also be reconciled.
985
- * Missing XP state must be repaired outside this Plan; no accounts are created.
1141
+ * Requires a supported Game runtime and the Character's reconciled Career XP
1142
+ * budget and configuration. The current game keeps no per-Claim-Stake XP
1143
+ * ledger, so the Plan passes none. Missing XP state must be repaired outside
1144
+ * this Plan; no accounts are created.
986
1145
  *
987
1146
  * Requires Disabled rent: the Game's rent catalog and the Claim Stake's rent
988
1147
  * settlement authority must not exist, and both stay guarded absent until
@@ -1035,13 +1194,25 @@ export async function planFinalizeClaimStakeBuildingChanges(ctx, stake, input) {
1035
1194
  requireCommittedCrewVersion(currentStake, stake, 'finalized');
1036
1195
  const planet = await requireDesignStakePlanet(ctx.programs, loaded.currentBody, stake, game, action);
1037
1196
  const { system } = planet;
1038
- const { account: characterAccount } = requireProfileCharacter(ctx.programs, loaded.extraAccounts[0], character, profile, game, action);
1197
+ const { account: characterAccount, current: currentCharacter } = requireProfileCharacter(ctx.programs, loaded.extraAccounts[0], character, profile, game, action);
1198
+ // The game checks every building's research when a design that adds
1199
+ // buildings finalizes (#1177).
1200
+ const designChanges = quantities(stake.state.buildings);
1201
+ const unresearched = removesOnly(designChanges)
1202
+ ? []
1203
+ : missingBuildingResearch(finalLayout(stake.buildings, stake.state.buildings), new Map(freshGame.data.buildings.definitions.map((definition) => [
1204
+ definition.id,
1205
+ definition,
1206
+ ])), currentCharacter.modifiers.values.researchTags, game);
1207
+ if (unresearched.length > 0) {
1208
+ fail(`Character ${character} lacks the research for ${unresearched.join('; ')}, which the finalized design of Claim Stake ${stake.address} needs, and the game refuses this finalization. Unlock that research, refresh the Character, and retry, or cancel the design.`, character);
1209
+ }
1039
1210
  const currencyCache = await claimStakeCurrencyCache(ctx.programs, game);
1040
1211
  const { currentSystem, extraAccounts: [currencyCandidate], player, playerAccount, starbase, systemAccount, } = await readStakeStarbase(ctx, stake, game, system, character, profile, action, [currencyCache]);
1041
1212
  requireStakeRegistered(planet.details.claimedPlots, stake, starbase.level, action);
1042
1213
  const currencyGuard = await requireCurrencyCache(ctx.programs, currencyCandidate, currencyCache, game, action, 'Claim Stake finalization');
1043
1214
  const description = `Finalize building changes on Claim Stake ${stake.address}. A building refund that opens a Starbase Player cargo line, or a new resource that raises the stake's rent floor, is funded from the Profile vault with the signing key, which this Plan does not bound; simulate before signing.`;
1044
- const xp = await resolveClaimStakeXp(ctx, game, stake.address, character);
1215
+ const xp = await resolveClaimStakeXp(ctx, game, character);
1045
1216
  return buildPlannerPlan(ctx.programs, {
1046
1217
  kind: 'claim-stakes.finalize-building-changes',
1047
1218
  preconditions: [
@@ -1086,8 +1257,8 @@ export async function planFinalizeClaimStakeBuildingChanges(ctx, stake, input) {
1086
1257
  * state; rent arithmetic and concurrent state transitions remain
1087
1258
  * chain-authoritative.
1088
1259
  *
1089
- * Requires Game 2 and its existing canonical Claim Stake XP ledger.
1090
- * Missing XP state must be repaired outside this Plan; no accounts are created.
1260
+ * Requires a supported Game runtime. The current game keeps no per-Claim-Stake
1261
+ * XP ledger, so the Plan passes none and creates no accounts.
1091
1262
  *
1092
1263
  * Requires Disabled rent: the Game's rent catalog and the Claim Stake's rent
1093
1264
  * settlement authority must not exist, and both stay guarded absent until
@@ -1130,7 +1301,7 @@ export async function planCancelClaimStakeBuildingChanges(ctx, stake, input) {
1130
1301
  requireStakeRegistered(planet.details.claimedPlots, stake, starbase.level, action);
1131
1302
  const currencyGuard = await requireCurrencyCache(ctx.programs, currencyCandidate, currencyCache, game, action, 'Claim Stake cancellation');
1132
1303
  const description = `Cancel the pending building design on Claim Stake ${stake.address} and return it to active state.`;
1133
- const xp = await resolveClaimStakeXp(ctx, game, stake.address);
1304
+ const xp = await resolveClaimStakeXp(ctx, game);
1134
1305
  return buildPlannerPlan(ctx.programs, {
1135
1306
  kind: 'claim-stakes.cancel-building-changes',
1136
1307
  preconditions: [
@@ -1176,8 +1347,10 @@ export async function planCancelClaimStakeBuildingChanges(ctx, stake, input) {
1176
1347
  * Requires Disabled rent: the Game's rent catalog and the Claim Stake's rent
1177
1348
  * settlement authority must not exist, and both stay guarded absent until
1178
1349
  * signing. The instruction carries no rent history. Deconstruction also
1179
- * requires the canonical Currency Cache and closes the Claim Stake's XP ledger;
1180
- * a Claim Stake without a ledger accrued no XP.
1350
+ * requires the canonical Currency Cache and the owner Character's reconciled
1351
+ * Career XP budget and configuration. The instruction names the stake's derived
1352
+ * structure XP ledger address, which the current game never creates; the Plan
1353
+ * guards it as absent.
1181
1354
  *
1182
1355
  * @example
1183
1356
  * ```ts
@@ -1245,21 +1418,18 @@ export async function planDeconstructClaimStake(ctx, stake, input) {
1245
1418
  ? `Claim Stake ${stake.address} does not contain exactly one verified bundled hub. Refresh it and restore the definition-compatible bundled hub before retrying deconstruction.`
1246
1419
  : `Claim Stake ${stake.address} holds ${bundledHub.name} (${String(bundledHub.id)}), which is not the zero-cost ${claimDefinition.tier} bundled hub for Claim Stake definition ${String(claimDefinition.id)} (${claimDefinition.name}). Refresh the Claim Stake and Game definitions so the recorded hub matches its definition before retrying deconstruction.`, stake.address);
1247
1420
  }
1248
- // Each plot row is a Starbase level; the stake's row and its position in
1249
- // that row's chronology give the deconstruction level and index.
1421
+ // Each plot row is one Starbase level and tier; the stake's level and its
1422
+ // position in that row's chronology give the deconstruction level and index.
1423
+ // The game finds the stake by identity within its row.
1250
1424
  const positions = claimStakePlotPositions(planet.details.claimedPlots, stake.address);
1251
1425
  if (positions.length !== 1) {
1252
1426
  fail(`Claim Stake ${stake.address} must appear exactly once in Planet ${stake.body.address}'s plot chronology before its deconstruction level and index can be derived. Refresh the Body and retry.`, stake.body.address);
1253
1427
  }
1254
- const { index: claimStakeIndex, row } = positions[0];
1255
- const rowGroups = planet.details.claimedPlots.filter(({ key }) => key === row);
1256
- if (!Number.isInteger(row) ||
1257
- row < 0 ||
1258
- row >= CLAIM_STAKE_PLOT_ROWS ||
1259
- rowGroups.length !== 1) {
1260
- fail(`Planet ${stake.body.address} records Claim Stake ${stake.address} in plot row ${String(row)}, which is not exactly one Starbase level row. Refresh the Body and verify the pinned binding version before retrying deconstruction.`, stake.body.address);
1261
- }
1262
- const activeStructures = rowGroups[0].structures.filter(({ address, deactivationTimeUnixSeconds }) => address === stake.address && deactivationTimeUnixSeconds === 0n);
1428
+ const { index: claimStakeIndex, row, tier: rowTier } = positions[0];
1429
+ // The Body decoder accepts only valid, unique level-and-tier row keys, so
1430
+ // the stake's position names exactly one decoded row.
1431
+ const rowGroup = planet.details.claimedPlots.find(({ key }) => key === claimStakeTierRowKey(row, rowTier));
1432
+ const activeStructures = rowGroup.structures.filter(({ address, deactivationTimeUnixSeconds }) => address === stake.address && deactivationTimeUnixSeconds === 0n);
1263
1433
  if (activeStructures.length !== 1) {
1264
1434
  fail(`Claim Stake ${stake.address} is not represented exactly once as an active structure in the Planet Body data. Refresh the Body and retry deconstruction.`, stake.body.address);
1265
1435
  }
@@ -1271,13 +1441,13 @@ export async function planDeconstructClaimStake(ctx, stake, input) {
1271
1441
  const { currentSystem, extraAccounts: [characterCandidate, currencyCandidate, ledgerCandidate], player, playerAccount, systemAccount, } = await readStakeStarbase(ctx, stake, game, system, character, profile, action, [character, currencyCache, xpAccrual]);
1272
1442
  const { account: characterAccount } = requireProfileCharacter(ctx.programs, characterCandidate, character, profile, game, action);
1273
1443
  const currencyGuard = await requireCurrencyCache(ctx.programs, currencyCandidate, currencyCache, game, action, 'Claim Stake deconstruction');
1274
- // Deconstruction closes an existing XP ledger; a stake without one accrued nothing.
1275
- const xp = ledgerCandidate === undefined
1276
- ? {
1277
- accounts: {},
1278
- guard: accountAbsentPrecondition(xpAccrual, `Claim Stake ${stake.address} XP ledger ${xpAccrual} remains absent, so no Building XP has accrued.`),
1279
- }
1280
- : await resolveClaimStakeXp(ctx, game, stake.address, character);
1444
+ // The game names the stake's derived structure XP ledger, which it never
1445
+ // creates, and always settles the owner's Career XP budget.
1446
+ if (ledgerCandidate !== undefined)
1447
+ fail(`Claim Stake ${stake.address} has a structure XP ledger ${xpAccrual}, which the current game does not create and this release does not support. Update Atlas Kit before retrying deconstruction.`, xpAccrual);
1448
+ const xp = await resolveClaimStakeXp(ctx, game, character);
1449
+ const { xpBudget, xpBudgetConfig } = xp.accounts;
1450
+ const ledgerGuard = accountAbsentPrecondition(xpAccrual, `Claim Stake ${stake.address} structure XP ledger ${xpAccrual} remains absent; the current game never creates it.`);
1281
1451
  const description = `Deconstruct Claim Stake ${stake.address} and discard its bundled hub ${bundledHub.name}; rent settlement, cargo return, account closure, and any refund remain chain-authoritative.`;
1282
1452
  return buildPlannerPlan(ctx.programs, {
1283
1453
  kind: 'claim-stakes.deconstruct',
@@ -1292,13 +1462,13 @@ export async function planDeconstructClaimStake(ctx, stake, input) {
1292
1462
  ])),
1293
1463
  currencyGuard,
1294
1464
  xp.guard,
1465
+ ledgerGuard,
1295
1466
  ...rent.guards,
1296
1467
  ],
1297
1468
  steps: [
1298
1469
  {
1299
1470
  describes: description,
1300
1471
  instruction: adaptDeconstructClaimStakeInstruction(ctx.programs, {
1301
- ...xp.accounts,
1302
1472
  authorization: options.authorization,
1303
1473
  celestialBody: stake.body.address,
1304
1474
  character,
@@ -1311,6 +1481,8 @@ export async function planDeconstructClaimStake(ctx, stake, input) {
1311
1481
  systemAndStarbasePlayerStarbasePlayer: player,
1312
1482
  systemAndStarbasePlayerSystem: system,
1313
1483
  xpAccrual,
1484
+ xpBudget: xpBudget,
1485
+ xpBudgetConfig: xpBudgetConfig,
1314
1486
  }),
1315
1487
  signers: [options.authorization.authority],
1316
1488
  },
@@ -1422,6 +1594,58 @@ function requireTransferCapacity(destination, address, used, requested, total) {
1422
1594
  fail(`${destination} has ${String(remaining)} raw capacity units remaining, but this transfer requires ${String(requested)}. Reduce the request or free capacity, refresh both snapshots, and retry.`, address);
1423
1595
  }
1424
1596
  }
1597
+ /** Refuses unloads that would overfill a Claim Stake's resource storage. The
1598
+ * game checks the stake's whole cargo, its stored Fuel included, minus the
1599
+ * loads, plus the unloads, against the resource storage capacity when the
1600
+ * transfer starts. */
1601
+ function requireClaimStakeStorage(address, usedAfterLoads, requested, total) {
1602
+ if (usedAfterLoads + requested > total) {
1603
+ const remaining = usedAfterLoads < total ? total - usedAfterLoads : 0n;
1604
+ fail(`Claim Stake ${address} resource storage has ${String(remaining)} raw capacity units remaining after this transfer's loads, counting the Fuel the stake stores, but this transfer requires ${String(requested)} for its unloads. The game checks every unloaded line, Fuel included, against this storage when the transfer starts. Reduce the unloads, load more cargo out of the stake, or free storage, refresh both snapshots, and retry.`, address);
1605
+ }
1606
+ }
1607
+ /** Fuel a Claim Stake with a Tier 1 Central Hub was observed to store on z.ink
1608
+ * PTR, before its Storage Modules' storage (#1162, D123). */
1609
+ const OBSERVED_TIER_1_HUB_FUEL = 169n;
1610
+ /** Building tags of Claim Stake Central Hubs and Storage Modules. */
1611
+ const CENTRAL_HUB_TAG = 40001;
1612
+ const STORAGE_MODULE_TAG = 40002;
1613
+ /** Warns, without refusing, when a transfer's Fuel unload would leave a Claim
1614
+ * Stake with a Tier 1 Central Hub holding more Fuel than such stakes were
1615
+ * observed to store: 169 plus each Storage Module's storage. The game applies
1616
+ * a Fuel limit only when the transfer exits, which a simulation cannot reach,
1617
+ * so other hub tiers get no warning. */
1618
+ async function observedFuelStorageWarning(ctx, address, stake, fuelCargoId, unload) {
1619
+ // A transfer never loads and unloads the same cargo, so an unloaded Fuel
1620
+ // line means no Fuel leaves the stake.
1621
+ const unloaded = unload.find(({ cargoId }) => cargoId === fuelCargoId)?.amount;
1622
+ if (unloaded === undefined)
1623
+ return undefined;
1624
+ const catalog = new Map((await listClaimStakeBuildingDefinitions(ctx)).map((definition) => [
1625
+ definition.id,
1626
+ definition,
1627
+ ]));
1628
+ let tier1Hub = false;
1629
+ let moduleStorage = 0n;
1630
+ for (const { buildingId, quantity } of stake.buildings) {
1631
+ const definition = catalog.get(buildingId);
1632
+ if (definition === undefined)
1633
+ return undefined;
1634
+ if (definition.hubValue > 0 &&
1635
+ definition.providedTagIds.includes(CENTRAL_HUB_TAG))
1636
+ tier1Hub = definition.minimumTier === 'one';
1637
+ if (definition.providedTagIds.includes(STORAGE_MODULE_TAG))
1638
+ moduleStorage += definition.resourceStorageRaw * BigInt(quantity);
1639
+ }
1640
+ if (!tier1Hub)
1641
+ return undefined;
1642
+ const observed = OBSERVED_TIER_1_HUB_FUEL + moduleStorage;
1643
+ const stored = cargoAmount(stake.production.cargoPod.amounts, fuelCargoId);
1644
+ if (stored + unloaded <= observed)
1645
+ return undefined;
1646
+ const room = stored < observed ? observed - stored : 0n;
1647
+ return `Warning: Claim Stake ${address} would hold ${String(stored + unloaded)} Fuel after this transfer, more than the ${String(observed)} Fuel that z.ink PTR stakes with the same Tier 1 Central Hub and Storage Modules have been observed to store. On PTR such transfers start, but their exit returns the Fleet to idle without moving any cargo. Unload at most ${String(room)} Fuel, or add Storage Modules, to stay within the observed amount; the game decides at exit.`;
1648
+ }
1425
1649
  /** Reads a Fleet's cargo-hold balance; Claim Stake transfers never touch the
1426
1650
  * fuel tank or ammo bank, so Fuel and Ammunition count only when in the hold. */
1427
1651
  function fleetCargoHoldAmount(fleet, cargoId) {
@@ -1434,21 +1658,34 @@ function describeCargoRequests(direction, requests) {
1434
1658
  *
1435
1659
  * The planner validates the shared Profile/Game, idle Fleet with normalized
1436
1660
  * crew, active Claim Stake, canonical Planet/System/Starbase Player graph,
1437
- * exact source balances, exact destination capacities, and an optional present
1661
+ * exact source balances, both destination capacities, and an optional present
1438
1662
  * FleetCrewBinding. Both legs use the Fleet cargo hold only: loaded Fuel and
1439
1663
  * Ammunition arrive in the cargo hold and consume cargo capacity, and unloads
1440
1664
  * are sourced from the cargo hold, never from the fuel tank or ammo bank. The
1441
1665
  * chain remains authoritative for range, duration, permission bits, concurrent
1442
1666
  * state changes, and transfer arithmetic.
1443
1667
  *
1668
+ * The Claim Stake check follows the one the game makes when the transfer
1669
+ * starts: the stake's stored cargo, Fuel included, less what the loads free,
1670
+ * plus what the unloads add, must fit its resource storage capacity. The game
1671
+ * accrues the stake's production before that check, which the planner does not
1672
+ * project, so a transfer near the limit stays chain-authoritative. When the
1673
+ * transfer exits, the game accrues production again and also limits Fuel to the
1674
+ * stake's separate fuel storage. The planner does not enforce that storage: if
1675
+ * the cargo no longer fits at exit, the exit returns the Fleet to idle without
1676
+ * moving cargo. For a stake with a Tier 1 Central Hub, the description warns,
1677
+ * without refusing, when a Fuel unload would leave the stake holding more Fuel
1678
+ * than such stakes were observed to store on z.ink PTR: 169 plus each Storage
1679
+ * Module's storage. Other hub tiers were not observed and get no warning.
1680
+ *
1444
1681
  * The Fleet stores the requested load and unload lines while the transfer
1445
1682
  * runs. The program settles the Fleet and stake together: the stake's lamports
1446
1683
  * above its rent floor fund the Fleet first and the Profile vault, with the
1447
1684
  * signing key, funds the rest. The Plan bounds that debit with the same key and
1448
1685
  * balance checks as placement.
1449
1686
  *
1450
- * Requires Game 2 and its existing canonical Claim Stake XP ledger.
1451
- * Missing XP state must be repaired outside this Plan; no accounts are created.
1687
+ * Requires a supported Game runtime. The current game keeps no per-Claim-Stake
1688
+ * XP ledger, so the Plan passes none and creates no accounts.
1452
1689
  *
1453
1690
  * Requires Disabled rent: the Game's rent catalog and the Claim Stake's rent
1454
1691
  * settlement authority must not exist, and both stay guarded absent until
@@ -1538,12 +1775,15 @@ export async function planStartClaimStakeFleetTransfer(ctx, fleet, stake, input)
1538
1775
  const loadCargoStorage = options.load.reduce((total, { amount, cargoId }) => total + cargoStorageUnits(amount, definitions.get(cargoId).storageCost), 0n);
1539
1776
  requireTransferCapacity(`Fleet ${fleet.name} cargo destination`, fleet.address, currentFleet.cargoHold.storageCost, loadCargoStorage, currentFleet.stats.cargo.cargoCapacity);
1540
1777
  const unloadStorage = options.unload.reduce((total, { amount, cargoId }) => total + cargoStorageUnits(amount, definitions.get(cargoId).storageCost), 0n);
1541
- requireTransferCapacity(`Claim Stake ${stake.address} resource destination`, stake.address, currentStake.production.cargoPod.storageCost, unloadStorage, currentStake.production.resourceCapacityRaw);
1778
+ // Loads leave the stake in the same swap, so they free storage for unloads.
1779
+ const loadStorageFreed = options.load.reduce((total, { amount, cargoId }) => total +
1780
+ cargoStorageUnitsFloor(amount, definitions.get(cargoId).storageCost), 0n);
1781
+ requireClaimStakeStorage(stake.address, currentStake.production.cargoPod.storageCost - loadStorageFreed, unloadStorage, currentStake.production.resourceCapacityRaw);
1542
1782
  const descriptions = [
1543
1783
  ...describeCargoRequests('load', options.load),
1544
1784
  ...describeCargoRequests('unload', options.unload),
1545
1785
  ];
1546
- const xp = await resolveClaimStakeXp(ctx, game, stake.address);
1786
+ const xp = await resolveClaimStakeXp(ctx, game);
1547
1787
  const instruction = adaptStartClaimStakeFleetTransferInstruction(ctx.programs, {
1548
1788
  ...xp.accounts,
1549
1789
  authorization: options.authorization,
@@ -1563,7 +1803,8 @@ export async function planStartClaimStakeFleetTransfer(ctx, fleet, stake, input)
1563
1803
  // The Fleet's transfer state is funded first from the stake's surplus over
1564
1804
  // its rent floor, then from the Profile vault.
1565
1805
  const storage = await planClaimStakeStorage(ctx, instruction, profile, [fleetAccount, stakeAccount], 'Claim Stake Fleet transfer start');
1566
- const description = `Start fleet ${fleet.name}'s transfer to Claim Stake ${stake.address}: ${descriptions.join('; ')}. Loaded cargo, including Fuel and Ammunition, arrives in the Fleet cargo hold; unloads come from the cargo hold only. Range and transfer duration remain chain-authoritative. ${storage.disclosure}`;
1806
+ const fuelWarning = await observedFuelStorageWarning(ctx, stake.address, currentStake, currentFleet.fuelTank.cargoId, options.unload);
1807
+ const description = `Start fleet ${fleet.name}'s transfer to Claim Stake ${stake.address}: ${descriptions.join('; ')}. Loaded cargo, including Fuel and Ammunition, arrives in the Fleet cargo hold; unloads come from the cargo hold only. Range and transfer duration remain chain-authoritative. The game accrues the Claim Stake's production before checking its resource storage; at exit it checks again and also limits Fuel to the stake's separate fuel storage, which this Plan does not enforce. If the cargo no longer fits then, the exit returns the Fleet to idle without moving cargo.${fuelWarning === undefined ? '' : ` ${fuelWarning}`} ${storage.disclosure}`;
1567
1808
  return buildPlannerPlan(ctx.programs, {
1568
1809
  kind: 'claim-stakes.start-fleet-transfer',
1569
1810
  preconditions: [
@@ -1604,6 +1845,14 @@ export async function planStartClaimStakeFleetTransfer(ctx, fleet, stake, input)
1604
1845
  * Recovery returns the Fleet to idle without moving cargo or changing the
1605
1846
  * Claim Stake.
1606
1847
  *
1848
+ * Claim Stake overflow is proved the way the transfer start checks it: the
1849
+ * stake's stored cargo, Fuel included, less what the queued loads free, plus
1850
+ * what the queued unloads add, exceeds its resource storage capacity. The game
1851
+ * decides executability after accruing production and also limits Fuel to the
1852
+ * stake's separate fuel storage, which the planner does not enforce. A transfer
1853
+ * that fails only those checks reads as executable here; its permissionless
1854
+ * normal exit then returns the Fleet to idle without moving cargo.
1855
+ *
1607
1856
  * @example
1608
1857
  * ```ts
1609
1858
  * declare const ctx: SageContext;
@@ -1700,15 +1949,19 @@ export async function planRecoverClaimStakeFleetTransfer(ctx, fleet, stake, inpu
1700
1949
  // Every queued load, including Fuel and Ammunition, targets the cargo hold.
1701
1950
  const loadCargoStorage = currentFleet.state.load.reduce((total, { amount, cargoId }) => total +
1702
1951
  cargoStorageUnits(amount, queuedDefinitions.get(cargoId).storageCost), 0n);
1952
+ // Only an overflow the unloads certainly cause, after the loads free
1953
+ // their storage, proves the stake side non-executable.
1703
1954
  const unloadStorage = currentFleet.state.unload.reduce((total, { amount, cargoId }) => total +
1704
- cargoStorageUnits(amount, queuedDefinitions.get(cargoId).storageCost), 0n);
1955
+ cargoStorageUnitsFloor(amount, queuedDefinitions.get(cargoId).storageCost), 0n);
1705
1956
  if (currentFleet.cargoHold.storageCost + loadCargoStorage >
1706
1957
  currentFleet.stats.cargo.cargoCapacity) {
1707
1958
  reason = 'Fleet cargo destination overflow';
1708
1959
  }
1709
- else if (currentStake.production.cargoPod.storageCost + unloadStorage >
1960
+ else if (currentStake.production.cargoPod.storageCost -
1961
+ loadCargoStorage +
1962
+ unloadStorage >
1710
1963
  currentStake.production.resourceCapacityRaw) {
1711
- reason = 'Claim Stake resource destination overflow';
1964
+ reason = 'Claim Stake resource storage overflow';
1712
1965
  }
1713
1966
  }
1714
1967
  if (reason === undefined) {