@aephia/atlas-kit 0.8.0-next.13 → 0.8.0-next.15

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 (41) hide show
  1. package/dist/client/deployments.d.ts +1 -1
  2. package/dist/client/deployments.js +1 -1
  3. package/dist/crafting/actions/habs.d.ts +133 -0
  4. package/dist/crafting/actions/habs.d.ts.map +1 -1
  5. package/dist/crafting/actions/habs.js +498 -10
  6. package/dist/crafting/actions/habs.js.map +1 -1
  7. package/dist/crafting/actions/index.d.ts +1 -1
  8. package/dist/crafting/actions/index.d.ts.map +1 -1
  9. package/dist/crafting/actions/index.js +1 -1
  10. package/dist/crafting/actions/index.js.map +1 -1
  11. package/dist/internal/c4/crafting-hab-storage.d.ts +13 -0
  12. package/dist/internal/c4/crafting-hab-storage.d.ts.map +1 -1
  13. package/dist/internal/c4/crafting-hab-storage.js +47 -1
  14. package/dist/internal/c4/crafting-hab-storage.js.map +1 -1
  15. package/dist/internal/c4/discriminators.d.ts +3 -0
  16. package/dist/internal/c4/discriminators.d.ts.map +1 -1
  17. package/dist/internal/c4/discriminators.js +7 -1
  18. package/dist/internal/c4/discriminators.js.map +1 -1
  19. package/dist/internal/c4/runtime-bindings.d.ts +1 -1
  20. package/dist/internal/c4/runtime-bindings.d.ts.map +1 -1
  21. package/dist/internal/c4/runtime-bindings.js +1 -1
  22. package/dist/internal/c4/runtime-bindings.js.map +1 -1
  23. package/dist/internal/planning/authorization-adapter.d.ts +36 -0
  24. package/dist/internal/planning/authorization-adapter.d.ts.map +1 -1
  25. package/dist/internal/planning/authorization-adapter.js +62 -1
  26. package/dist/internal/planning/authorization-adapter.js.map +1 -1
  27. package/dist/internal/planning/crafting-hab-storage-actions.d.ts +6 -6
  28. package/dist/internal/planning/crafting-hab-storage-actions.d.ts.map +1 -1
  29. package/dist/internal/planning/crafting-hab-storage-actions.js +22 -7
  30. package/dist/internal/planning/crafting-hab-storage-actions.js.map +1 -1
  31. package/dist/internal/planning/profile-storage-funding-guard.d.ts +1 -1
  32. package/dist/internal/planning/profile-storage-funding-guard.d.ts.map +1 -1
  33. package/dist/internal/planning/profile-storage-funding-guard.js +8 -1
  34. package/dist/internal/planning/profile-storage-funding-guard.js.map +1 -1
  35. package/dist/internal/planning/runtime-guards.d.ts.map +1 -1
  36. package/dist/internal/planning/runtime-guards.js +30 -2
  37. package/dist/internal/planning/runtime-guards.js.map +1 -1
  38. package/dist/internal/planning/storage-action-readers.d.ts.map +1 -1
  39. package/dist/internal/planning/storage-action-readers.js +1 -0
  40. package/dist/internal/planning/storage-action-readers.js.map +1 -1
  41. package/package.json +1 -1
@@ -13,15 +13,16 @@ import { starbasePlayerAccountDefinition } from '../../internal/c4/starbase.js';
13
13
  import { starSystemAccountDefinition, } from '../../internal/c4/world.js';
14
14
  import { requireGameAddress } from '../../internal/game-context.js';
15
15
  import { accountAbsentPrecondition, accountStatePrecondition, } from '../../internal/planning/account-state.js';
16
- import { adaptCraftingHabRentTopUpInstruction, adaptDeconstructCraftingHabInstruction, adaptPlaceCraftingHabInstruction, readPlanAuthorization, } from '../../internal/planning/authorization-adapter.js';
16
+ import { adaptCancelCraftingHabBuildingChangesInstruction, adaptCraftingHabBuildingChangesInstruction, adaptCraftingHabRentTopUpInstruction, adaptDeconstructCraftingHabInstruction, adaptFinalizeCraftingHabBuildingChangesInstruction, adaptPlaceCraftingHabInstruction, readPlanAuthorization, } from '../../internal/planning/authorization-adapter.js';
17
17
  import { readCraftingHabStorageAction } from '../../internal/planning/crafting-hab-storage-actions.js';
18
18
  import { structurePlacementFee } from '../../internal/planning/placement-fee.js';
19
19
  import { RENT_ADDRESS } from '../../internal/planning/rent.js';
20
20
  import { CLOCK_ADDRESS, readClock, } from '../../internal/planning/faction-enrollment.js';
21
21
  import { planStorageFunding } from '../../internal/planning/storage-actions.js';
22
+ import { resolveXpRuntime } from '../../internal/planning/xp-runtime.js';
22
23
  import { buildPlannerPlan } from '../../planning/plan-construction.js';
23
24
  import { resolveCraftingHabDefinition } from '../../registry/index.js';
24
- import { decodeRegistryGame, gameCraftingHabsRegistrySection, } from '../../internal/c4/game.js';
25
+ import { decodeRegistryGame, gameCraftingHabsRegistrySection, gameHabBuildingsRegistrySection, } from '../../internal/c4/game.js';
25
26
  const U64_MAX = 18446744073709551615n;
26
27
  const LEVELS = [
27
28
  'level-0',
@@ -275,6 +276,16 @@ export async function planPlaceCraftingHab(ctx, starbasePlayer, input) {
275
276
  summary: description,
276
277
  });
277
278
  }
279
+ /** The rent a Hab owes since its rent clock. The game settles rent first and
280
+ * refuses a Hab whose balance cannot cover it. Rent accrues fractionally, so
281
+ * callers refuse only a clear shortfall. */
282
+ async function rentDueRaw(ctx, data, starbase, definition) {
283
+ const [clock] = await readContextRawAccounts(ctx, [CLOCK_ADDRESS]);
284
+ const now = readClock(present(clock, CLOCK_ADDRESS, 'The Clock sysvar is missing. Refresh chain time and retry.'));
285
+ const rate = deriveCraftingHabPlacementQuote(starbase, definition).rentAtlasRawPerSecond;
286
+ const elapsed = now > data.lastRentAtUnixSeconds ? now - data.lastRentAtUnixSeconds : 0n;
287
+ return BigInt(Math.floor(Number(elapsed) * rate));
288
+ }
278
289
  /** Reads a Crafting Hab of the authorization Profile, fresh. */
279
290
  async function readHab(ctx, hab, authorization, game) {
280
291
  if (hab.ownerProfile.address !== authorization.profile)
@@ -385,14 +396,7 @@ export async function planDeconstructCraftingHab(ctx, hab, input) {
385
396
  const group = fresh.starbase.craftingHabs.find((entry) => entry.chronoAddresses.includes(hab.address));
386
397
  if (group === undefined)
387
398
  return fail(`Crafting Hab ${hab.address} is not on any plot of the Starbase at Star System ${fresh.system}. Refresh the System and retry.`, fresh.system);
388
- // The game settles rent first and refuses a Hab whose balance cannot cover
389
- // it. Rent accrues fractionally, so this refuses only a clear shortfall.
390
- const definition = await resolveCraftingHabDefinition(ctx, data.definitionId);
391
- const [clock] = await readContextRawAccounts(ctx, [CLOCK_ADDRESS]);
392
- const now = readClock(present(clock, CLOCK_ADDRESS, 'The Clock sysvar is missing. Refresh chain time and retry.'));
393
- const rate = deriveCraftingHabPlacementQuote(fresh.starbase, definition).rentAtlasRawPerSecond;
394
- const elapsed = now > data.lastRentAtUnixSeconds ? now - data.lastRentAtUnixSeconds : 0n;
395
- const due = BigInt(Math.floor(Number(elapsed) * rate));
399
+ const due = await rentDueRaw(ctx, data, fresh.starbase, await resolveCraftingHabDefinition(ctx, data.definitionId));
396
400
  if (data.rentBalanceRaw + topUp < due)
397
401
  fail(`Crafting Hab ${hab.address} owes about ${String(due)} raw ATLAS of rent but holds ${String(data.rentBalanceRaw + topUp)}${topUp > 0n ? ' with the top-up' : ''}, so the game refuses to deconstruct it. Pass topUpAtlasRaw of at least ${String(due - data.rentBalanceRaw)}, with some margin for rent accruing until the transaction lands, then retry.`, hab.address);
398
402
  if (fresh.characterData.atlasRaw < topUp)
@@ -440,4 +444,488 @@ export async function planDeconstructCraftingHab(ctx, hab, input) {
440
444
  summary: description,
441
445
  });
442
446
  }
447
+ const U16_MAX = 65_535;
448
+ const U32_MAX = 4_294_967_295;
449
+ const I32_MAX = 2_147_483_647;
450
+ function readBuildingChanges(value) {
451
+ if (!Array.isArray(value) || value.length === 0)
452
+ invalid('buildingChanges', value, 'a non-empty array of add/remove building changes', 'Provide at least one building change, then retry.');
453
+ const seen = new Set();
454
+ return Array.from(value, (entry, index) => {
455
+ const field = `buildingChanges[${String(index)}]`;
456
+ const change = readOptions(entry, ['buildingId', 'kind', 'quantity']);
457
+ const { buildingId, kind, quantity } = change;
458
+ if (!Number.isInteger(buildingId) ||
459
+ buildingId < 0 ||
460
+ buildingId > U16_MAX)
461
+ invalid(`${field}.buildingId`, buildingId, 'a Hab building id', 'Choose a building from listHabBuildingDefinitions, then retry.');
462
+ if (kind !== 'add' && kind !== 'remove')
463
+ invalid(`${field}.kind`, kind, 'add or remove', `Set ${field}.kind to the intended building operation, then retry.`);
464
+ if (!Number.isInteger(quantity) ||
465
+ quantity < 1 ||
466
+ quantity > I32_MAX)
467
+ invalid(`${field}.quantity`, quantity, `a positive integer up to ${String(I32_MAX)}`, `Set ${field}.quantity to the number of buildings, then retry.`);
468
+ if (seen.has(buildingId))
469
+ invalid(`${field}.buildingId`, buildingId, 'one change per building id', 'Combine duplicate changes into one entry, then retry.');
470
+ seen.add(buildingId);
471
+ return change;
472
+ });
473
+ }
474
+ /** A Hab of the authorization Profile, its Starbase Player and the Game's Hab
475
+ * catalog, read fresh and checked the way every design step checks them: the
476
+ * Hab is in the Player's System, on a plot of the current Starbase and not
477
+ * evicted, and its rent is current. */
478
+ async function readDesignHab(ctx, hab, options, action) {
479
+ const authorization = readPlanAuthorization(options.authorization);
480
+ const game = requireGameAddress(ctx);
481
+ const current = await readHab(ctx, hab, authorization, game);
482
+ const fresh = await readPlayer(ctx, options.starbasePlayer, authorization, game);
483
+ const { data } = current;
484
+ if (data.system !== fresh.system)
485
+ fail(`Crafting Hab ${hab.address} is in Star System ${data.system}, not ${fresh.system}. Use the Starbase Player in the Hab's System and retry.`, hab.address);
486
+ if (data.systemSequenceId !== fresh.systemData.sequenceId)
487
+ fail(`Crafting Hab ${hab.address} belongs to an earlier Starbase at Star System ${fresh.system}, so the game refuses ${action}. Respawn or replace the Hab.`, hab.address);
488
+ if (data.state.kind === 'deactivated')
489
+ fail(`Crafting Hab ${hab.address} is deactivated for unpaid rent, so the game refuses ${action}. Top up its rent to reactivate it, refresh it and retry.`, hab.address);
490
+ const level = levelIndex(fresh.starbase);
491
+ const plot = fresh.starbase.craftingHabs
492
+ .filter((group) => group.key <= level)
493
+ .flatMap((group) => group.structures)
494
+ .find((entry) => entry.address === hab.address);
495
+ if (plot === undefined || plot.deactivationTimeUnixSeconds !== 0n)
496
+ fail(`Crafting Hab ${hab.address} ${plot === undefined ? 'holds no plot the Starbase at Star System ' + fresh.system + ' can reach' : 'was evicted from its plot'}, so the game refuses ${action}. Refresh the System and Hab; only respawning reclaims an evicted Hab.`, hab.address);
497
+ const [gameCandidate] = await readContextRawAccounts(ctx, [game]);
498
+ const gameRaw = present(gameCandidate, game, `The configured Game ${game} is missing. Verify the cluster and Game, then retry.`);
499
+ const decodedGame = decodeRegistryGame(ctx.programs, gameRaw);
500
+ const definition = gameCraftingHabsRegistrySection(gameRaw, decodedGame).definitions.find(({ id }) => id === data.definitionId);
501
+ if (definition === undefined)
502
+ return fail(`Crafting Hab ${hab.address}'s definition ${String(data.definitionId)} is absent from the configured Game. Refresh the definitions and Hab, then retry.`, game);
503
+ const buildings = new Map(gameHabBuildingsRegistrySection(gameRaw, decodedGame).definitions.map((building) => [building.id, building]));
504
+ const due = await rentDueRaw(ctx, data, fresh.starbase, definition);
505
+ if (data.rentBalanceRaw < due)
506
+ fail(`Crafting Hab ${hab.address} owes about ${String(due)} raw ATLAS of rent but holds ${String(data.rentBalanceRaw)}, so the game would deactivate it and refuse ${action}. Top up its rent with planTopUpCraftingHabRent, with some margin for rent accruing until the transaction lands, then retry.`, hab.address);
507
+ return {
508
+ authorization,
509
+ game,
510
+ current,
511
+ fresh,
512
+ gameRaw,
513
+ definition,
514
+ buildings,
515
+ };
516
+ }
517
+ /** The building layout a Hab reaches when its design finalizes: its buildings
518
+ * plus each signed change. The game refuses to finalize a removal beyond the
519
+ * buildings placed. */
520
+ function habFinalLayout(hab, placed, changes, buildings) {
521
+ const layout = new Map(placed.map(({ buildingId, quantity }) => [buildingId, quantity]));
522
+ for (const [buildingId, delta] of changes) {
523
+ const next = (layout.get(buildingId) ?? 0) + delta;
524
+ if (next < 0)
525
+ fail(`The design removes ${String(-delta)} ${buildings.get(buildingId).name} from Crafting Hab ${hab}, which holds only ${String(layout.get(buildingId) ?? 0)}; the game refuses to finalize it. Remove fewer and retry.`, hab);
526
+ if (next > U32_MAX)
527
+ fail(`The design would hold more than ${String(U32_MAX)} of building ${String(buildingId)} on Crafting Hab ${hab}. Add fewer and retry.`, hab);
528
+ if (next === 0)
529
+ layout.delete(buildingId);
530
+ else
531
+ layout.set(buildingId, next);
532
+ }
533
+ return layout;
534
+ }
535
+ /** A warning when a design adds a copy of a hub the final layout already
536
+ * holds more than once of; the game accepts it, but each copy costs its
537
+ * construction cargo. */
538
+ function hubCopyWarning(hub, design) {
539
+ return hub !== undefined && hub.quantity > 1 && (design.get(hub.id) ?? 0) > 0
540
+ ? `The final layout holds ${String(hub.quantity)} copies of hub ${hub.name}. The game refuses a second hub type but accepts more copies of the matching hub; each copy takes its construction cargo and adds its effects.`
541
+ : '';
542
+ }
543
+ /** Checks a final Hab layout against the rules the game applies at
544
+ * finalization: every building known, at or below the Hab's tier, hub
545
+ * buildings of a single type matching the Hab's hub, every required building
546
+ * tag provided by the Hab, the Starbase or a building, and the slots within
547
+ * the Hab's. The game refuses a second hub type but accepts several copies of
548
+ * the matching hub, so the hub's count is returned rather than checked.
549
+ * Returns the crew the layout needs, the hub and each building whose research
550
+ * the Character lacks. */
551
+ function checkHabLayout(hab, layout, buildings, definition, starbase, researchTags, game) {
552
+ const provided = new Set([
553
+ ...definition.providedTagIds,
554
+ ...starbase.buildingTags,
555
+ ]);
556
+ const required = new Set();
557
+ const unresearched = [];
558
+ let hub;
559
+ let slots = 0;
560
+ let neededCrew = 0;
561
+ let jobs = 0;
562
+ for (const [buildingId, quantity] of layout) {
563
+ const building = buildings.get(buildingId);
564
+ if (building === undefined)
565
+ return fail(`Building ${String(buildingId)} has no Hab building definition in the configured Game. Refresh the definitions and choose a valid building, then retry.`, game);
566
+ if (TIERS.indexOf(building.minimumTier) > TIERS.indexOf(definition.tier))
567
+ fail(`${building.name} needs a tier-${building.minimumTier} Hab, above ${definition.name}'s tier ${definition.tier}, so the game refuses to finalize it. Remove it from the design and retry.`, hab);
568
+ if (building.hubValue !== 0) {
569
+ if (hub !== undefined || building.hubValue !== definition.hubValue)
570
+ fail(`${hub === undefined ? `Hub building ${building.name} does not match ${definition.name}'s hub` : `The design holds two hub types, ${hub.name} and ${building.name}`}, so the game refuses to finalize it. Keep at most one hub matching the Hab and retry.`, hab);
571
+ hub = { id: buildingId, name: building.name, quantity };
572
+ }
573
+ const missing = building.researchRequirementIds.filter((tag) => !researchTags.includes(tag));
574
+ if (missing.length > 0)
575
+ unresearched.push(`${building.name} (research ${missing.join(', ')})`);
576
+ building.providedTagIds.forEach((tag) => provided.add(tag));
577
+ building.requiredTagIds.forEach((tag) => required.add(tag));
578
+ slots += building.slots * quantity;
579
+ neededCrew += building.neededCrew * quantity;
580
+ jobs += building.jobCapacity * quantity;
581
+ }
582
+ const missingTags = [...required].filter((tag) => !provided.has(tag));
583
+ if (missingTags.length > 0)
584
+ fail(`The design needs building tags ${missingTags.join(', ')}, which neither ${definition.name}, the Starbase nor its buildings provide, so the game refuses to finalize it. Add a building that provides them, or remove the ones that need them, and retry.`, hab);
585
+ if (slots > definition.slots)
586
+ fail(`The design uses ${String(slots)} slots, more than ${definition.name}'s ${String(definition.slots)}, so the game refuses to finalize it. Remove buildings and retry.`, hab);
587
+ if (neededCrew > U16_MAX || jobs > U16_MAX)
588
+ fail(`The design needs ${String(neededCrew)} crew and ${String(jobs)} job slots, beyond what a Hab records (${String(U16_MAX)}). Remove buildings and retry.`, hab);
589
+ return { neededCrew, unresearched, ...(hub === undefined ? {} : { hub }) };
590
+ }
591
+ /** Construction cargo a design takes from the Starbase Player, net of the
592
+ * refunds its removals return, and the construction time it adds. */
593
+ function habConstruction(changes, buildings) {
594
+ const cargo = new Map();
595
+ let seconds = 0n;
596
+ for (const [buildingId, delta] of changes) {
597
+ const building = buildings.get(buildingId);
598
+ const count = BigInt(Math.abs(delta));
599
+ if (delta > 0)
600
+ seconds += building.constructionDurationSeconds * count;
601
+ for (const { cargoId, quantityRaw } of delta > 0
602
+ ? building.constructionCost
603
+ : building.refunds)
604
+ cargo.set(cargoId, (cargo.get(cargoId) ?? 0n) +
605
+ (delta > 0 ? quantityRaw : -quantityRaw) * count);
606
+ }
607
+ return { cargo, seconds };
608
+ }
609
+ /** The crew and cargo a design's finalization needs beyond what the Starbase
610
+ * Player holds. A Building Legacy rank discounts construction cargo, so a
611
+ * shortfall against the full cost only counts when the Character holds no
612
+ * such rank. */
613
+ function habFinalizeShortfalls(fresh, hab, neededCrew, cargo) {
614
+ const certain = [];
615
+ const possible = [];
616
+ const crew = neededCrew - hab.neededCrew;
617
+ const available = fresh.player.totalCrew - fresh.player.busyCrew;
618
+ if (crew > available)
619
+ certain.push(`${String(crew)} more crew, while Starbase Player ${fresh.playerRaw.address} has ${String(available)} available`);
620
+ const discounted = fresh.characterData.xp.progression.legacy.ranks.building > 0;
621
+ for (const [cargoId, amount] of cargo) {
622
+ if (amount <= 0n)
623
+ continue;
624
+ const held = fresh.player.cargo.amounts.find((entry) => entry.cargoId === cargoId)
625
+ ?.amount ?? 0n;
626
+ if (held < amount)
627
+ (discounted ? possible : certain).push(`${String(amount)} raw of cargo ${String(cargoId)}${discounted ? ' before the Building Legacy discount' : ''}, while the Starbase Player holds ${String(held)}`);
628
+ }
629
+ return { certain, possible };
630
+ }
631
+ async function habXpGuard(ctx, game, character) {
632
+ const xp = await resolveXpRuntime(ctx, {
633
+ game,
634
+ ...(character === undefined ? {} : { character }),
635
+ });
636
+ return {
637
+ accounts: xp.accounts,
638
+ guard: {
639
+ kind: 'xp-runtime',
640
+ address: game,
641
+ intent: xp.intent,
642
+ accounts: xp.accounts,
643
+ describes: character === undefined
644
+ ? 'The Game runtime remains supported. Wait for the phase change or update Atlas Kit, then recreate the Plan.'
645
+ : 'The Game runtime and the Character Career XP accounts remain supported and reconciled. Repair missing XP state using the game client, then recreate the Plan.',
646
+ },
647
+ };
648
+ }
649
+ /** Plans recording building additions and removals in a Crafting Hab's design.
650
+ *
651
+ * An Active Hab enters Design; a Hab already in Design adds these changes to
652
+ * the ones it records. The game records the changes without checking them and
653
+ * applies its building rules only at finalization, so the planner refuses a
654
+ * design that could never finalize: an unknown building, a removal beyond the
655
+ * buildings placed, a building above the Hab's tier, a second hub type or one
656
+ * that does not match the Hab's, a building tag nothing provides, or more
657
+ * slots than the Hab has. It warns instead about what the Profile can still
658
+ * fix before finalizing: research the Character lacks, and the crew and
659
+ * construction cargo the Starbase Player must hold. The game accepts several
660
+ * copies of the matching hub, so adding one warns rather than refuses.
661
+ *
662
+ * The Hab must not be under construction or running Crafting Processes, and
663
+ * its rent must be current. The Profile funds the design's storage growth.
664
+ * Concurrent design changes remain chain-authoritative.
665
+ *
666
+ * @example
667
+ * ```ts
668
+ * declare const ctx: SageContext;
669
+ * declare const hab: CraftingHabSnapshot;
670
+ * declare const options: PlanCraftingHabBuildingChangesOptions;
671
+ * const plan = await planCraftingHabBuildingChanges(ctx, hab, options);
672
+ * console.log(plan.describe());
673
+ * ```
674
+ */
675
+ export async function planCraftingHabBuildingChanges(ctx, hab, input) {
676
+ const options = readOptions(input, [
677
+ 'authorization',
678
+ 'starbasePlayer',
679
+ 'buildingChanges',
680
+ ]);
681
+ const changes = readBuildingChanges(options.buildingChanges);
682
+ const action = 'building changes';
683
+ const { authorization, game, current, fresh, gameRaw, definition, buildings, } = await readDesignHab(ctx, hab, options, action);
684
+ const { data } = current;
685
+ if (data.version !== 1)
686
+ fail(`Crafting Hab ${hab.address} is a version ${String(data.version)} Hab, which records no committed crew, so the game can never finalize its design. Only version-1 Habs support building changes.`, hab.address);
687
+ if (data.constructionRemainingSeconds > 0n)
688
+ fail(`Crafting Hab ${hab.address} records ${String(data.constructionRemainingSeconds)} seconds of construction remaining, and the game refuses building changes while a Hab is under construction. The stored time advances only when the Hab is processed: wait, refresh the Hab and retry.`, hab.address);
689
+ if (data.jobsRunning > 0)
690
+ fail(`Crafting Hab ${hab.address} runs ${String(data.jobsRunning)} Crafting Processes; complete or cancel them before changing its buildings.`, hab.address);
691
+ const profileFaction = await deriveProfileFactionAddress(ctx.programs, authorization.profile);
692
+ const [factionCandidate, profileCandidate, rent] = await readContextRawAccounts(ctx, [
693
+ profileFaction,
694
+ authorization.profile,
695
+ RENT_ADDRESS,
696
+ ]);
697
+ const factionRaw = present(factionCandidate, profileFaction, `Profile ${authorization.profile} has no faction. Join a faction and retry.`);
698
+ if (profileFactionIdentityAccountDefinition.decode(factionRaw, ctx.programs)
699
+ .profile !== authorization.profile)
700
+ fail(`ProfileFaction ${profileFaction} does not belong to Profile ${authorization.profile}. Refresh or repair the Profile faction and retry.`, profileFaction);
701
+ const design = new Map(data.state.kind === 'design'
702
+ ? data.state.buildings.map(({ buildingId, quantity }) => [
703
+ buildingId,
704
+ quantity,
705
+ ])
706
+ : []);
707
+ for (const change of changes) {
708
+ if (!buildings.has(change.buildingId))
709
+ invalid('buildingChanges', change.buildingId, 'a Hab building id of the configured Game', 'Choose a building from listHabBuildingDefinitions, then retry.');
710
+ const next = (design.get(change.buildingId) ?? 0) +
711
+ (change.kind === 'add' ? change.quantity : -change.quantity);
712
+ if (Math.abs(next) > I32_MAX)
713
+ fail(`The design would record a change of ${String(next)} ${buildings.get(change.buildingId).name}, beyond what the game can record. Change fewer buildings and retry.`, hab.address);
714
+ design.set(change.buildingId, next);
715
+ }
716
+ const layout = habFinalLayout(hab.address, data.buildings, design, buildings);
717
+ const { neededCrew, unresearched, hub } = checkHabLayout(hab.address, layout, buildings, definition, fresh.starbase, fresh.characterData.modifiers.values.researchTags, game);
718
+ const { certain, possible } = habFinalizeShortfalls(fresh, data, neededCrew, habConstruction(design, buildings).cargo);
719
+ const hubCopies = hubCopyWarning(hub, design);
720
+ const warnings = [
721
+ ...(unresearched.length === 0
722
+ ? []
723
+ : [
724
+ `Character ${fresh.character} lacks the research for ${unresearched.join('; ')}; the game records the design but refuses to finalize it until that research is unlocked.`,
725
+ ]),
726
+ ...(certain.length + possible.length === 0
727
+ ? []
728
+ : [
729
+ `Finalizing needs ${[...certain, ...possible].join('; ')}; bring them to the Starbase before finalizing.`,
730
+ ]),
731
+ ...(hubCopies === '' ? [] : [hubCopies]),
732
+ ];
733
+ const [currencyCache] = await deriveCurrencyCache(ctx.programs, game);
734
+ const xp = await habXpGuard(ctx, game);
735
+ const sequenceId = data.state.kind === 'design' ? data.state.sequenceId : 0;
736
+ const instruction = adaptCraftingHabBuildingChangesInstruction(ctx.programs, {
737
+ authorization,
738
+ game,
739
+ profileFaction,
740
+ craftingHab: hab.address,
741
+ system: fresh.system,
742
+ starbasePlayer: fresh.playerRaw.address,
743
+ currencyCache,
744
+ sequenceId,
745
+ buildingChanges: changes.map(({ buildingId, kind, quantity }) => [
746
+ buildingId,
747
+ kind === 'add' ? quantity : -quantity,
748
+ ]),
749
+ });
750
+ const accounts = new Map([
751
+ [hab.address, current.raw],
752
+ [authorization.profile, profileCandidate],
753
+ [RENT_ADDRESS, rent],
754
+ ]);
755
+ const storage = planStorageFunding(ctx.programs, {
756
+ action: readCraftingHabStorageAction(ctx.programs, instruction, accounts),
757
+ accounts,
758
+ label: 'Crafting Hab building changes',
759
+ });
760
+ const description = `Record building changes in Crafting Hab ${hab.address}'s design: ${changes
761
+ .map(({ buildingId, kind, quantity }) => `${kind} ${String(quantity)} ${buildings.get(buildingId).name}`)
762
+ .join('; ')}. Nothing is built until the design is finalized.${warnings.map((w) => ` Warning: ${w}`).join('')} ${storage.disclosure}`;
763
+ return buildPlannerPlan(ctx.programs, {
764
+ kind: 'crafting.crafting-hab-building-changes',
765
+ preconditions: [
766
+ ...(await Promise.all([
767
+ accountStatePrecondition(gameRaw, `The configured Game keeps ${definition.name}'s and the Hab buildings' definitions.`),
768
+ accountStatePrecondition(current.raw, `Crafting Hab ${hab.address} keeps its buildings, design, rent and state.`),
769
+ accountStatePrecondition(fresh.systemRaw, `Star System ${fresh.system} keeps the Hab on its plot.`),
770
+ accountStatePrecondition(factionRaw, `ProfileFaction ${profileFaction} stays assigned to Profile ${authorization.profile}.`),
771
+ ])),
772
+ xp.guard,
773
+ storage.guard,
774
+ ],
775
+ steps: [
776
+ {
777
+ describes: description,
778
+ instruction,
779
+ signers: [authorization.authority],
780
+ },
781
+ ],
782
+ summary: description,
783
+ });
784
+ }
785
+ /** Plans finalizing a Crafting Hab's building design.
786
+ *
787
+ * The game applies the design: it checks the final layout's tier, hub type,
788
+ * building tags and slots and the Character's research for every building in
789
+ * it, takes construction cargo from the Starbase Player and returns removed
790
+ * buildings' refunds to it, reserves or releases the crew the layout needs,
791
+ * and starts construction. The planner
792
+ * refuses any of those the game would refuse, and a crew or cargo shortfall
793
+ * it can see; a Building Legacy rank discounts construction cargo, so a
794
+ * shortfall against the full cost only warns when the Character holds one.
795
+ *
796
+ * The Hab must be in Design, running no Crafting Processes, and its rent
797
+ * current. Finalization can draw Profile storage this Plan does not bound: a
798
+ * refund can open a Starbase Player cargo line, and new buildings grow the
799
+ * Hab, which the program funds from the Profile vault, so simulate before
800
+ * signing.
801
+ *
802
+ * @example
803
+ * ```ts
804
+ * declare const ctx: SageContext;
805
+ * declare const hab: CraftingHabSnapshot;
806
+ * declare const options: PlanFinalizeCraftingHabBuildingChangesOptions;
807
+ * const plan = await planFinalizeCraftingHabBuildingChanges(ctx, hab, options);
808
+ * ```
809
+ */
810
+ export async function planFinalizeCraftingHabBuildingChanges(ctx, hab, input) {
811
+ const options = readOptions(input, ['authorization', 'starbasePlayer']);
812
+ const action = 'finalization';
813
+ const { authorization, game, current, fresh, gameRaw, definition, buildings, } = await readDesignHab(ctx, hab, options, action);
814
+ const { data } = current;
815
+ if (data.state.kind !== 'design')
816
+ return fail(`Crafting Hab ${hab.address} has no pending building design to finalize. Record building changes first, refresh the Hab and retry.`, hab.address);
817
+ if (data.version !== 1)
818
+ fail(`Crafting Hab ${hab.address} is a version ${String(data.version)} Hab, which records no committed crew, so the game refuses to finalize its design. Cancel the design instead.`, hab.address);
819
+ if (data.jobsRunning > 0)
820
+ fail(`Crafting Hab ${hab.address} runs ${String(data.jobsRunning)} Crafting Processes; complete or cancel them before finalizing.`, hab.address);
821
+ const design = new Map(data.state.buildings.map(({ buildingId, quantity }) => [
822
+ buildingId,
823
+ quantity,
824
+ ]));
825
+ const unknown = [...design.keys()].find((id) => !buildings.has(id));
826
+ if (unknown !== undefined)
827
+ fail(`The design names building ${String(unknown)}, which has no Hab building definition in the configured Game, so the game refuses to finalize it. Cancel the design and record a new one.`, hab.address);
828
+ const layout = habFinalLayout(hab.address, data.buildings, design, buildings);
829
+ const { neededCrew, unresearched, hub } = checkHabLayout(hab.address, layout, buildings, definition, fresh.starbase, fresh.characterData.modifiers.values.researchTags, game);
830
+ if (unresearched.length > 0)
831
+ fail(`Character ${fresh.character} lacks the research for ${unresearched.join('; ')}, so the game refuses to finalize the design. Unlock that research, or cancel the design and record one without those buildings.`, fresh.character);
832
+ const { cargo, seconds } = habConstruction(design, buildings);
833
+ const { certain, possible } = habFinalizeShortfalls(fresh, data, neededCrew, cargo);
834
+ if (certain.length > 0)
835
+ fail(`Finalizing Crafting Hab ${hab.address}'s design needs ${certain.join('; ')}. Bring them to the Starbase, refresh the Starbase Player and retry.`, fresh.playerRaw.address);
836
+ const [currencyCache] = await deriveCurrencyCache(ctx.programs, game);
837
+ const xp = await habXpGuard(ctx, game, fresh.character);
838
+ const instruction = adaptFinalizeCraftingHabBuildingChangesInstruction(ctx.programs, {
839
+ authorization,
840
+ game,
841
+ character: fresh.character,
842
+ craftingHab: hab.address,
843
+ system: fresh.system,
844
+ starbasePlayer: fresh.playerRaw.address,
845
+ currencyCache,
846
+ ...xp.accounts,
847
+ });
848
+ const crew = neededCrew - data.neededCrew;
849
+ const amounts = (sign) => [...cargo]
850
+ .filter(([, amount]) => amount * sign > 0n)
851
+ .map(([cargoId, amount]) => `${String(amount * sign)} raw of cargo ${String(cargoId)}`)
852
+ .join(', ');
853
+ const hubCopy = hubCopyWarning(hub, design);
854
+ const takes = amounts(1n);
855
+ const returns = amounts(-1n);
856
+ const movement = takes === '' && returns === ''
857
+ ? 'moves no cargo'
858
+ : `${[
859
+ ...(takes === '' ? [] : [`takes ${takes} from`]),
860
+ ...(returns === '' ? [] : [`returns ${returns} to`]),
861
+ ].join(' and ')} Starbase Player ${fresh.playerRaw.address}`;
862
+ const description = `Finalize Crafting Hab ${hab.address}'s building design: the game ${movement}, ${crew >= 0 ? `reserves ${String(crew)} more crew` : `releases ${String(-crew)} crew`}, and starts ${String(seconds)} seconds of construction before Building Legacy and Council Rank adjustments.${hubCopy === '' ? '' : ` Warning: ${hubCopy}`}${possible.length === 0 ? '' : ` Warning: the Starbase Player may lack ${possible.join('; ')}; the game refuses if the discounted cost still exceeds it.`} Finalization can draw Profile storage this Plan does not bound, for a new cargo line or the Hab's growth; simulate before signing.`;
863
+ return buildPlannerPlan(ctx.programs, {
864
+ kind: 'crafting.finalize-crafting-hab-building-changes',
865
+ preconditions: [
866
+ ...(await Promise.all([
867
+ accountStatePrecondition(gameRaw, `The configured Game keeps ${definition.name}'s and the Hab buildings' definitions.`),
868
+ accountStatePrecondition(current.raw, `Crafting Hab ${hab.address} keeps its design, buildings, crew and rent.`),
869
+ accountStatePrecondition(fresh.systemRaw, `Star System ${fresh.system} keeps the Hab on its plot and its building tags.`),
870
+ accountStatePrecondition(fresh.playerRaw, `Starbase Player ${fresh.playerRaw.address} keeps its crew and cargo.`),
871
+ accountStatePrecondition(fresh.characterRaw, `Character ${fresh.character} keeps its research and Building Legacy rank.`),
872
+ ])),
873
+ xp.guard,
874
+ ],
875
+ steps: [
876
+ {
877
+ describes: description,
878
+ instruction,
879
+ signers: [authorization.authority],
880
+ },
881
+ ],
882
+ summary: description,
883
+ });
884
+ }
885
+ /** Plans cancelling a Crafting Hab's pending building design, returning the
886
+ * Hab to Active with its buildings unchanged. Its rent must be current.
887
+ *
888
+ * @example
889
+ * ```ts
890
+ * declare const ctx: SageContext;
891
+ * declare const hab: CraftingHabSnapshot;
892
+ * declare const options: PlanCancelCraftingHabBuildingChangesOptions;
893
+ * const plan = await planCancelCraftingHabBuildingChanges(ctx, hab, options);
894
+ * ```
895
+ */
896
+ export async function planCancelCraftingHabBuildingChanges(ctx, hab, input) {
897
+ const options = readOptions(input, ['authorization', 'starbasePlayer']);
898
+ const { authorization, game, current, fresh } = await readDesignHab(ctx, hab, options, 'cancellation');
899
+ if (current.data.state.kind !== 'design')
900
+ fail(`Crafting Hab ${hab.address} has no pending building design to cancel. Refresh the Hab and retry.`, hab.address);
901
+ const [currencyCache] = await deriveCurrencyCache(ctx.programs, game);
902
+ const xp = await habXpGuard(ctx, game);
903
+ const instruction = adaptCancelCraftingHabBuildingChangesInstruction(ctx.programs, {
904
+ authorization,
905
+ game,
906
+ craftingHab: hab.address,
907
+ system: fresh.system,
908
+ starbasePlayer: fresh.playerRaw.address,
909
+ currencyCache,
910
+ });
911
+ const description = `Cancel Crafting Hab ${hab.address}'s pending building design; the Hab returns to Active with its buildings unchanged. The game settles rent first; rent accrual remains chain-authoritative.`;
912
+ return buildPlannerPlan(ctx.programs, {
913
+ kind: 'crafting.cancel-crafting-hab-building-changes',
914
+ preconditions: [
915
+ ...(await Promise.all([
916
+ accountStatePrecondition(current.raw, `Crafting Hab ${hab.address} keeps its pending design and rent.`),
917
+ accountStatePrecondition(fresh.systemRaw, `Star System ${fresh.system} keeps the Hab on its plot.`),
918
+ ])),
919
+ xp.guard,
920
+ ],
921
+ steps: [
922
+ {
923
+ describes: description,
924
+ instruction,
925
+ signers: [authorization.authority],
926
+ },
927
+ ],
928
+ summary: description,
929
+ });
930
+ }
443
931
  //# sourceMappingURL=habs.js.map