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 ||
+37 -1
View File
@@ -15,6 +15,7 @@ export type PublicDealPayment = {
dueTurn: number;
};
export type PublicDealPaymentStatus = 'pending' | 'paid' | 'void' | 'released';
export type PublicDealImmediatePayment = Extract<PublicDealPayment, { kind: 'immediateBribe' }>;
export type PublicDealDeferredPayment = Extract<PublicDealPayment, { kind: 'deferredBribe' }>;
/** The index is the stable identity of a term within its immutable offer. */
export type PublicDealAdditionalPayment = {
@@ -22,6 +23,7 @@ export type PublicDealAdditionalPayment = {
paymentStatus?: PublicDealPaymentStatus;
};
export const MAX_ADDITIONAL_DEAL_PAYMENTS = 12;
export const MAX_ADDITIONAL_IMMEDIATE_DEAL_PAYMENTS = 12;
/** One invited recipient commits to one native action (or its absence).
* Old two-party records identify that recipient through `to`. */
export type PublicDealTravel = {
@@ -50,6 +52,8 @@ export type PublicDeal = {
/** Present only for accepted or released deferred payments. */
paymentStatus?: PublicDealPaymentStatus;
additionalPayments?: PublicDealAdditionalPayment[];
/** Immutable additional transfers, executed under final acceptance. */
additionalImmediatePayments?: PublicDealImmediatePayment[];
travel?: PublicDealTravel;
};
@@ -173,7 +177,7 @@ export function validatePublicDeals(value: unknown, players: readonly PublicDeal
requireDeal(Array.isArray(value), 'The public deal ledger is malformed.');
const ids = new Set<string>();
for (const deal of value) {
const keys = object(deal) ? Object.keys(deal).filter(key => key !== 'payment' && key !== 'paymentStatus' && key !== 'travel' && key !== 'additionalPayments').sort().join(',') : '';
const keys = object(deal) ? Object.keys(deal).filter(key => key !== 'payment' && key !== 'paymentStatus' && key !== 'travel' && key !== 'additionalPayments' && key !== 'additionalImmediatePayments').sort().join(',') : '';
const multi = keys === 'acceptVotes,from,id,participants,releaseVotes,status,terms,to,turn';
requireDeal(object(deal) && (multi || keys === 'from,id,releaseVotes,status,terms,to,turn') &&
id(deal.id) && id(deal.from) && id(deal.to) && deal.from !== deal.to &&
@@ -242,6 +246,15 @@ export function validatePublicDeals(value: unknown, players: readonly PublicDeal
'An additional payment status does not match the deal lifecycle.');
}
}
if (Object.hasOwn(deal, 'additionalImmediatePayments')) {
requireDeal(Array.isArray(deal.additionalImmediatePayments) && deal.additionalImmediatePayments.length >= 1 &&
deal.additionalImmediatePayments.length <= MAX_ADDITIONAL_IMMEDIATE_DEAL_PAYMENTS,
'Choose between one and twelve additional immediate payments.');
for (const term of deal.additionalImmediatePayments) {
const parsed = parsePublicDealPayment(term, parties, deal.turn as number);
requireDeal(parsed.kind === 'immediateBribe', 'Additional immediate payments must settle on acceptance.');
}
}
const votes = deal.releaseVotes as string[];
requireDeal(new Set(votes).size === votes.length && votes.every(vote => parties.includes(vote)) &&
(!multi || orderedSubset(votes, parties)) &&
@@ -306,6 +319,29 @@ export function setPublicDealAdditionalPayments(deal: PublicDeal, value: unknown
return result;
}
/** Attach immutable transfers to an unchanged fresh offer. Settlement progress
* belongs to the engine continuation, never the public offer or its caller. */
export function setPublicDealAdditionalImmediatePayments(deal: PublicDeal, value: unknown, players: readonly PublicDealSeat[]): PublicDeal {
validatePublicDeals([deal], players);
requireDeal(deal.status === 'offered' && !Object.hasOwn(deal, 'additionalImmediatePayments') &&
!Object.hasOwn(deal, 'paymentStatus') && (deal.participants
? !!deal.acceptVotes && deal.acceptVotes.length === 1 && deal.acceptVotes[0] === deal.from
: !Object.hasOwn(deal, 'acceptVotes')),
'Only a fresh offer may add immediate payment terms.');
requireDeal(Array.isArray(value) && value.length >= 1 && value.length <= MAX_ADDITIONAL_IMMEDIATE_DEAL_PAYMENTS,
'Choose between one and twelve additional immediate payments.');
const parties = publicDealParticipants(deal);
notAllied(participants(players, parties));
const additionalImmediatePayments = value.map(value => {
const payment = parsePublicDealPayment(value, parties, deal.turn);
requireDeal(payment.kind === 'immediateBribe', 'Additional immediate payments must settle on acceptance.');
return payment;
});
const result = {...deal, additionalImmediatePayments};
validatePublicDeals([result], players);
return result;
}
/** Attach a travel term while constructing a fresh offer. */
export function setPublicDealTravel(deal: PublicDeal, value: unknown, players: readonly PublicDealSeat[]): PublicDeal {
validatePublicDeals([deal], players);
+1 -1
View File
@@ -304,7 +304,7 @@ export const RULE_TOPICS: RuleTopic[] = [
'A deal may include one immediate spice payment between two participants. The last acceptance invokes the normal bribe action: the payer loses the gross amount immediately, Bureaucrat may divert two, and the recipient collects the remaining share at the next Mentat opening. Nothing is reserved before acceptance, and an unavailable payment leaves the offer open.',
'A deal may also specify multiple exact deferred payments due this turn or later. After everyone accepts, each payer can use the matching Pay button early or by its deadline. Future payments do not reserve current funds; obligations due now must still be respected. Each term requires its own payment, even when the amounts match. A compatible Truthtrance bribe answer can be satisfied by the same payment. Mutual release cancels unpaid terms; paid amounts are not refunded.',
'In a supported Basic classic table, two to six people can agree that one invited recipient will make or avoid one reserve shipment or ground move of at least a selected number of physical forces to a named territory in the current or a later turn. In a group offer the other recipients accept first and the named traveler accepts last. A current-turn term is checked on acceptance; a later-turn term is scheduled without reserving present forces or spice. The actual action fulfills a required term; a forbidden action cannot be taken. Compatible travel terms can share one action. A bounded due-turn search protects witnessed completions; when the travel turn closes without a witness, the game provisionally voids that term. Unsupported combinations remain in development.',
'Two-party or group travel can include deferred payments and at most one immediate payment between participants. All parties accept, including the payers, and the traveler accepts last. An immediate payment settles with final consent; each deferred payment can be paid by its chosen deadline. When payment and travel are due this turn, acceptance checks that the payer can complete both with the available resources. Multiple immediate payments remain unfinished.',
'Two-party or group travel can include immediate and deferred payments between participants. All parties accept, including the payers, and the traveler accepts last. Immediate payments settle in order after final consent; a Bureaucrat decision can pause the sequence. Each deferred payment can be paid by its chosen deadline. When payment and travel are due this turn, acceptance checks that the payer can complete both with the available resources.',
'Players must honor legal deal terms; an impossible part is void. The game does not interpret or enforce free-text promises or determine impossibility. Free text alone pays no spice. Deals must not transfer cards, leaders, forces or faction advantages or contradict the rules.',
'Minimal AI follows supported Truthtrance ordinary-payment answers and their legal guides. AI deal negotiation and automatic enforcement of prose remain unfinished.',
],