Settle multiple immediate deal payments
Verify and publish checkpoint container / container (push) Successful in 10m59s

This commit is contained in:
Quintine committed 2026-11-16 14:44:06 +11:00
1 parent cacc88906c
commit b03efd2371
11 files changed
+652 -18

No files matched your search

+122 -6
View File
@@ -11,7 +11,8 @@ import { createFactionSwap, validateFactionSwap, answerFactionSwap, cancelFactio
FactionSwapError, type FactionSwap } from './faction-swap';
import { createPublicDeal, createMultipartyPublicDeal, validatePublicDeals, respondPublicDeal, withdrawPublicDeal,
releasePublicDeal, markPublicDealPaid, voidPublicDealPayment, setPublicDealTravel, setPublicDealAdditionalPayments,
publicDealDeferredTerms, publicDealTravelActor, publicDealTravelDueTurn, PublicDealError, type PublicDeal, type PublicDealPayment } from './public-deals';
setPublicDealAdditionalImmediatePayments, publicDealDeferredTerms, publicDealTravelActor, publicDealTravelDueTurn,
PublicDealError, type PublicDeal, type PublicDealPayment, type PublicDealImmediatePayment } from './public-deals';
import { outstandingPublicDealPayments, pendingPublicDealPayments, publicDealPaymentTotal, publicDealPaymentOptionKey, PublicDealObligationError, type PendingPublicDealPayment } from './public-deal-obligations';
import { CharityPromiseError, liveCharityPromises, charityPromiseAnswers, bindCharityPromise, guardCharityClaim, guardCharityReady, reconcileCharityPromises, type CharityPromise } from './charity-promises';
import { victoryFinalTurn, continueVictoryCalendar, VictoryCalendarError } from './victory-calendar';
@@ -1492,6 +1493,9 @@ export type Game = {
coalitionWormProtection?: CoalitionWormProtectionFrame;
/** Public written agreements. Their prose is honored by players, not parsed. */
deals?: PublicDeal[];
/** Only present while a native Bureaucrat decision pauses an accepted deal. */
pendingPublicDealSettlement?: {deal:string;next:number;initiator:string;turn:number;phase:number;signature:string};
publicDealSettlementHistory?: {deal:string;signature:string}[];
/** A human-to-human lobby offer, pending the recipient's consent. */
factionSwap?: FactionSwap;
/** Public prediction-number faction selection, present only while in progress. */
@@ -6052,8 +6056,48 @@ function publicDealRule<T>(operation: () => T): T {
throw error;
}
}
function publicDealIntegrity(g: Game): void {
function publicDealImmediateLegs(deal: PublicDeal): PublicDealImmediatePayment[] {
return [...(deal.payment?.kind === 'immediateBribe' ? [deal.payment] : []), ...(deal.additionalImmediatePayments ?? [])];
}
/** Bind receipts to immutable terms, not release votes or later deferred status. */
function publicDealImmediateSignature(deal: PublicDeal): string {
return JSON.stringify([deal.id,deal.turn,deal.from,deal.to,deal.participants,deal.terms,
deal.payment,deal.additionalImmediatePayments,deal.additionalPayments?.map(term => term.payment),deal.travel]);
}
function publicDealSettlementSignature(deal: PublicDeal, frame: NonNullable<Game['pendingPublicDealSettlement']>): string {
return JSON.stringify([publicDealImmediateSignature(deal),frame.next,frame.initiator,frame.turn,frame.phase]);
}
function publicDealIntegrity(g: Game, internalSettlement?: string): void {
if (g.deals !== undefined) publicDealRule(() => validatePublicDeals(g.deals, g.players));
const history = g.publicDealSettlementHistory ?? [];
requireRule(Array.isArray(history) && history.every(row => row && typeof row.deal === 'string' &&
typeof row.signature === 'string' && Object.keys(row).sort().join(',') === 'deal,signature') &&
new Set(history.map(row => row.deal)).size === history.length,
'Immediate deal payment receipts must have unique agreements.');
for (const row of history) {
const deal = g.deals?.find(entry => entry.id === row.deal);
requireRule(deal && ['active','released'].includes(deal.status) && !!deal.additionalImmediatePayments?.length &&
row.signature === publicDealImmediateSignature(deal), 'An immediate deal payment receipt lost its original terms.');
}
const frame = g.pendingPublicDealSettlement;
if (frame) {
const deal = g.deals?.find(entry => entry.id === frame.deal), native = g.bureaucratPayments?.pending;
const legs = deal ? publicDealImmediateLegs(deal) : [];
const leg = legs[frame.next - 1];
requireRule(Object.keys(frame).sort().join(',') === 'deal,initiator,next,phase,signature,turn' &&
deal && deal.status === 'active' && !!deal.additionalImmediatePayments?.length &&
!history.some(row => row.deal === deal.id) && Number.isSafeInteger(frame.next) && frame.next >= 1 &&
frame.next <= legs.length && frame.turn === g.turn && frame.phase === g.phase &&
[deal.from,deal.to,...(deal.participants ?? [])].includes(frame.initiator) &&
frame.signature === publicDealSettlementSignature(deal,frame) && native?.continuation.kind === 'bribe' &&
native.source.kind === 'bribe' && native.source.payer === leg?.payer && native.source.payee === leg.recipient &&
native.source.amount === leg.amount && g.decision?.kind === 'bureaucratPayment' &&
g.decision.event === native.source.event,
'The pending immediate deal payment lost its original native response or terms.');
}
for (const deal of g.deals ?? []) if (deal.additionalImmediatePayments?.length && ['active','released'].includes(deal.status))
requireRule(deal.id === internalSettlement || history.some(row => row.deal === deal.id) || frame?.deal === deal.id,
'The immediate deal payments have no completed or pending settlement.');
const linked = (g.travelPromises ?? []).filter(row => row.sourceDeal !== undefined);
for (const row of linked) {
const deal = g.deals?.find(entry => entry.id === row.sourceDeal);
@@ -6071,6 +6115,57 @@ function publicDealIntegrity(g: Game): void {
for (const deal of g.deals ?? []) if (deal.travel && ['active', 'released'].includes(deal.status))
requireRule(linked.some(row => row.sourceDeal === deal.id), 'The accepted public travel deal is missing its commitment.');
}
/** Exercise the actual native payments on detached states before consent.
* Passing Bureaucrat can leave a later payment eligible, so prove both native
* responses at each opportunity rather than assuming which recipient loses
* the redirected spice. The live owner still makes every real decision. */
function preflightPublicDealSettlement(g: Game, deal: PublicDeal, initiator: string): void {
requireRule(!bribeTimingBlock(g), 'Finish the current decision or response before paying a deal.');
const legs = publicDealImmediateLegs(deal);
const visit = (trial: Game, index: number): void => {
if (index === legs.length) return;
const leg = legs[index];
requireRule(!getPlayer(trial,leg.payer).autopilot, 'The payer is not controlling this seat.');
const next = applyActionWithInitiator(trial,leg.payer,{type:'bribe',target:leg.recipient,amount:leg.amount},initiator,
{publicDealSettlement:deal.id});
const pending = next.bureaucratPayments?.pending;
const candidates = pending ? [false,true].map(redirect => applyActionWithInitiator(next,pending.owner,
{type:'decision',event:pending.source.event,redirect},pending.owner,{publicDealSettlement:deal.id})) : [next];
for (const candidate of candidates) {
for (const player of candidate.players) if (pendingPublicDealPayments(candidate.deals ?? [],player.id,candidate.turn).length)
requireRule(publicDealCompletion(candidate,player), 'Retain a funded completion for each due deal payment.');
visit(candidate,index + 1);
}
};
visit(structuredClone(g),0);
}
/** Run ordered native payments until an actual Bureaucrat response suspends
* them; only immutable deal terms identify the remaining legs. */
function continuePublicDealSettlement(state: Game, dealId: string, initiator: string, start: number): Game {
let g = structuredClone(state);
delete g.pendingPublicDealSettlement;
const deal = g.deals?.find(row => row.id === dealId);
requireRule(deal && deal.status === 'active' && deal.additionalImmediatePayments?.length,
'The accepted immediate deal is no longer available.');
const legs = publicDealImmediateLegs(deal);
for (let index = start; index < legs.length; index++) {
const leg = legs[index];
g = applyActionWithInitiator(g,leg.payer,{type:'bribe',target:leg.recipient,amount:leg.amount},initiator,
{publicDealSettlement:deal.id});
if (g.bureaucratPayments?.pending) {
const frame: NonNullable<Game['pendingPublicDealSettlement']> = {
deal:deal.id,next:index + 1,initiator,turn:g.turn,phase:g.phase,signature:'',
};
frame.signature = publicDealSettlementSignature(deal,frame);
g.pendingPublicDealSettlement = frame;
publicDealIntegrity(g);
return g;
}
}
(g.publicDealSettlementHistory ??= []).push({deal:deal.id,signature:publicDealImmediateSignature(deal)});
publicDealIntegrity(g);
return g;
}
function publicDealObligationRule<T>(operation: () => T): T {
try { return operation(); }
catch (error) { if (error instanceof PublicDealObligationError) throw new RuleError(error.message); throw error; }
@@ -43549,7 +43644,7 @@ export function applyAction(state: Game, id: string, action: Action): Game {
/** The initiator can differ from the payer only for a previously consented
* automatic deal payment; it is never supplied by a client action. */
function applyActionWithInitiator(state: Game, id: string, action: Action, initiator: string,
options?: {insolventDealPayment?: boolean}): Game {
options?: {insolventDealPayment?: boolean;publicDealSettlement?:string}): Game {
emperorPhaseOpeningGiftIntegrity(state);
emperorExtortionGiftIntegrity(state);
emperorAuctionGiftIntegrity(state);
@@ -43574,7 +43669,12 @@ function applyActionWithInitiator(state: Game, id: string, action: Action, initi
twoPlayerControllersIntegrity(state);
factionDraftIntegrity(state);
factionSwapIntegrity(state);
publicDealIntegrity(state);
publicDealIntegrity(state,options?.publicDealSettlement);
if (state.pendingPublicDealSettlement && action?.type !== 'advanceBots') {
const native = state.bureaucratPayments?.pending;
requireRule(action?.type === 'decision' && id === native?.owner && action.event === native.source.event,
'Finish the current Bureaucrat decision before continuing the accepted deal.');
}
if (state.coalitionState?.proposal) {
requireRule(coalitionNexusAvailable(state) && state.coalitionState.proposal.turn === state.turn,
'The group invitation no longer belongs to this Nexus.');
@@ -43688,7 +43788,7 @@ function applyActionWithInitiator(state: Game, id: string, action: Action, initi
const deals = g.deals ?? [];
if (action.type === 'dealOffer') {
const keys = Object.keys(action);
const supportedKeys = keys.every(key => ['type','terms','target','targets','payment','additionalPayments','travel'].includes(key));
const supportedKeys = keys.every(key => ['type','terms','target','targets','payment','additionalPayments','additionalImmediatePayments','travel'].includes(key));
const single = supportedKeys && !Object.hasOwn(action,'targets') && typeof action.target === 'string';
const multiple = supportedKeys && !Object.hasOwn(action,'target') && Array.isArray(action.targets) &&
action.targets.every(target => typeof target === 'string');
@@ -43708,6 +43808,8 @@ function applyActionWithInitiator(state: Game, id: string, action: Action, initi
: createMultipartyPublicDeal(seats, id, action.targets as string[], action.terms as string, g.turn, event));
if (Object.hasOwn(action,'additionalPayments'))
offer = publicDealRule(() => setPublicDealAdditionalPayments(offer,action.additionalPayments,seats));
if (Object.hasOwn(action,'additionalImmediatePayments'))
offer = publicDealRule(() => setPublicDealAdditionalImmediatePayments(offer,action.additionalImmediatePayments,seats));
if (Object.hasOwn(action, 'travel')) {
requireRule(!g.advanced && g.expansions.length === 0 && nativePromiseScopeSupported(g),
'Choose a travel agreement in a supported Basic table.');
@@ -43764,6 +43866,16 @@ function applyActionWithInitiator(state: Game, id: string, action: Action, initi
g.ready.includes(payer.id)) g.ready = g.ready.filter(playerId => playerId !== payer.id);
log(g, `${payer.name} agreed to pay ${payment.amount} spice to ${getPlayer(g,payment.recipient).name} by the end of turn ${dueTurn}.`);
}
if (current.status === 'offered' && next.status === 'active' && next.additionalImmediatePayments?.length) {
try {
preflightPublicDealSettlement(g,next,id);
return continuePublicDealSettlement(g,next.id,id,0);
} catch (error) {
if (error instanceof RuleError)
throw new RuleError('The agreed immediate payments could not all be completed. Check timing, funds and existing commitments.');
throw error;
}
}
if (current.status === 'offered' && next.status === 'active' && next.payment?.kind === 'immediateBribe') {
// The payer consented to these immutable terms. Run the native action
// on the same cloned state so a failed payment also rolls back consent.
@@ -43975,7 +44087,11 @@ function applyActionWithInitiator(state: Game, id: string, action: Action, initi
Object.keys(guide.action).every(key => action[key] === guide.action[key]),
'This Richese bid guide is stale or belongs to another lot.');
}
const g = applyActionInner(state, id, action, 'live', initiator);
let g = applyActionInner(state, id, action, 'live', initiator);
if (state.pendingPublicDealSettlement && !g.bureaucratPayments?.pending) {
const frame = state.pendingPublicDealSettlement;
g = continuePublicDealSettlement(g,frame.deal,frame.initiator,frame.next);
}
if (state.phase === 3 && liveTurnActionPromises(state.turnActionPromises ?? [], id, state.turn).some(row => {
const stage = row.windowCards?.karamaAuction;
return stage && !stage.closed && (windowCardOpportunity(g, 'karamaAuction')?.source !== stage.source ||