Support multiple deferred payments in public deals
Verify and publish checkpoint container / container (push) Successful in 10m22s

This commit is contained in:
Quintine committed 2026-11-16 14:30:36 +11:00
1 parent 0b8a147388
commit cacc88906c
12 files changed
+742 -50

No files matched your search

+83 -5
View File
@@ -17,6 +17,8 @@ type DealTravelStatus = 'scheduled' | 'pending' | 'fulfilled' | 'void' | 'releas
type TravelDeal = Deal & { travel?: DealTravel };
type TravelProjection = GameView & { dealTravelStatus?: Record<string, DealTravelStatus> };
type DeferredPaymentStatus = 'pending' | 'paid' | 'void' | 'released';
type AdditionalPayment = { payment: DeferredBribe; paymentStatus?: DeferredPaymentStatus };
type AdditionalPaymentDraft = { key: number; payer: string; recipient: string; amount: string; dueTurn: string };
type DeferredPaymentProjection = GameView & {
deferredDealPaymentOptions?: Record<string, { blocked: string | null }>;
};
@@ -49,6 +51,11 @@ export function publicDealRequests(game: GameView): string[][] {
if (deal.status === 'active' && pending.payment?.kind === 'deferredBribe' &&
pending.payment.payer === game.me && pending.paymentStatus === 'pending' && pending.payment.dueTurn <= game.turn)
requests.push(['payment', deal.id]);
const additional = (deal as unknown as { additionalPayments?: AdditionalPayment[] }).additionalPayments ?? [];
if (deal.status === 'active') additional.forEach((term, index) => {
if (term.payment.payer === game.me && term.paymentStatus === 'pending' && term.payment.dueTurn <= game.turn)
requests.push(['payment', deal.id, String(index)]);
});
if (deal.status === 'active' && travel && publicDealTravelActor(deal) === game.me &&
(game as TravelProjection).dealTravelStatus?.[deal.id] === 'pending')
requests.push(['travel', deal.id]);
@@ -57,7 +64,7 @@ export function publicDealRequests(game: GameView): string[][] {
}
/** Keep the legacy single-recipient wire packet when only one seat is chosen. */
export function publicDealOfferAction(targets: readonly string[], terms: string, payment?: DealPayment, proposer?: string, currentTurn?: number, travel?: DealTravel): Action | null {
export function publicDealOfferAction(targets: readonly string[], terms: string, payment?: DealPayment, proposer?: string, currentTurn?: number, travel?: DealTravel, additionalPayments?: readonly DeferredBribe[]): Action | null {
const text = terms.trim();
if (!targets.length || targets.length > 5 || new Set(targets).size !== targets.length || !text || text.length > 500) return null;
if (payment && (!proposer || (payment.kind !== 'immediateBribe' && payment.kind !== 'deferredBribe') || payment.payer === payment.recipient ||
@@ -65,6 +72,11 @@ export function publicDealOfferAction(targets: readonly string[], terms: string,
!Number.isSafeInteger(payment.amount) || payment.amount < 1 ||
(payment.kind === 'deferredBribe' && (!Number.isSafeInteger(payment.dueTurn) || payment.dueTurn < 1 ||
(currentTurn !== undefined && (!Number.isSafeInteger(currentTurn) || currentTurn < 1 || payment.dueTurn < currentTurn)))))) return null;
if (additionalPayments && (additionalPayments.length > 12 || additionalPayments.some(term =>
!proposer || term.kind !== 'deferredBribe' || term.payer === term.recipient ||
![proposer, ...targets].includes(term.payer) || ![proposer, ...targets].includes(term.recipient) ||
!Number.isSafeInteger(term.amount) || term.amount < 1 || !Number.isSafeInteger(term.dueTurn) || term.dueTurn < 1 ||
currentTurn !== undefined && (!Number.isSafeInteger(currentTurn) || currentTurn < 1 || term.dueTurn < currentTurn)))) return null;
const groupTravel = !!travel && targets.length > 1;
const travelKeys = travel ? Object.keys(travel).filter(key => key !== 'dueTurn').sort().join(',') : '';
const travelDeadline = travel && Object.hasOwn(travel, 'dueTurn') ? travel.dueTurn : undefined;
@@ -78,12 +90,15 @@ export function publicDealOfferAction(targets: readonly string[], terms: string,
!Number.isSafeInteger(travel.minimum) || travel.minimum < 1 || travel.minimum > 20 ||
typeof travel.answer !== 'boolean')) return null;
const offeredPayment = payment ? { payment } : {};
const offeredAdditional = additionalPayments?.length
? { additionalPayments: additionalPayments.map(term => ({kind:term.kind, payer:term.payer,
recipient:term.recipient, amount:term.amount, dueTurn:term.dueTurn})) } : {};
const normalizedTravel = travel ? {...travel} : undefined;
if (normalizedTravel && travelDeadline === currentTurn) delete normalizedTravel.dueTurn;
const offeredTravel = normalizedTravel ? { travel: normalizedTravel } : {};
return targets.length === 1
? { type: 'dealOffer', target: targets[0], terms: text, ...offeredPayment, ...offeredTravel }
: { type: 'dealOffer', targets: [...targets], terms: text, ...offeredPayment, ...offeredTravel };
? { type: 'dealOffer', target: targets[0], terms: text, ...offeredPayment, ...offeredAdditional, ...offeredTravel }
: { type: 'dealOffer', targets: [...targets], terms: text, ...offeredPayment, ...offeredAdditional, ...offeredTravel };
}
/** The whole table can read an offer and its history; only its parties act. */
@@ -111,6 +126,7 @@ export function PublicDealList({ game, act, disabled }: {
other && !allied(game, player, other)));
const payment = (deal as unknown as { payment?: DealPayment }).payment;
const paymentStatus = (deal as unknown as { paymentStatus?: DeferredPaymentStatus }).paymentStatus;
const additional = (deal as unknown as { additionalPayments?: AdditionalPayment[] }).additionalPayments ?? [];
const travel = (deal as TravelDeal).travel;
const travelActor = travel ? publicDealTravelActor(deal) : undefined;
const travelStatus = (game as TravelProjection).dealTravelStatus?.[deal.id];
@@ -121,7 +137,8 @@ export function PublicDealList({ game, act, disabled }: {
const travelActorWaiting = !!travel && participants.length > 2 && game.me === travelActor &&
participants.some(participant => participant !== travelActor && !accepted.includes(participant));
const paymentBlocked = payment?.kind === 'immediateBribe' && finalAcceptance && payment.payer === game.me ? game.bribeOptions?.blocked : null;
const paymentExpired = payment?.kind === 'deferredBribe' && game.turn > payment.dueTurn;
const paymentExpired = payment?.kind === 'deferredBribe' && game.turn > payment.dueTurn ||
additional.some(term => game.turn > term.payment.dueTurn);
const deferredOption = (game as DeferredPaymentProjection).deferredDealPaymentOptions?.[deal.id];
const mayPay = payment?.kind === 'deferredBribe' && deal.status === 'active' && paymentStatus === 'pending' &&
payment.payer === game.me && canAct;
@@ -131,6 +148,19 @@ export function PublicDealList({ game, act, disabled }: {
{payment?.kind === 'immediateBribe' && <p><strong>Immediate payment term:</strong> {name(payment.payer)} pays {payment.amount} spice to {name(payment.recipient)} on final acceptance. The payer loses the gross amount immediately; the recipient collects their share at the next Mentat opening. A Bureaucrat may divert two spice to the bank before that share is allocated. Releasing the deal later does not refund the payment.</p>}
{payment?.kind === 'immediateBribe' && travel && <p>The recipient cannot spend this payment before its next Mentat collection; after collection it can fund travel in a later turn.</p>}
{payment?.kind === 'deferredBribe' && <p><strong>Deferred payment term:</strong> {name(payment.payer)} pays exactly {payment.amount} spice to {name(payment.recipient)} on or before the end of turn {payment.dueTurn}. The recipient collects their share at the next Mentat opening; a Bureaucrat may divert two spice to the bank. {paymentStatus ? `Payment status: ${paymentStatus}.` : 'Payment becomes binding on final acceptance.'}</p>}
{additional.map((term, index) => {
const option = (game as DeferredPaymentProjection).deferredDealPaymentOptions?.[`${deal.id}:payment:${index}`];
const canPay = deal.status === 'active' && term.paymentStatus === 'pending' &&
term.payment.payer === game.me && canAct;
return <div key={index}>
<p><strong>Additional payment {index + 1}:</strong> {name(term.payment.payer)} pays exactly {term.payment.amount} spice to {name(term.payment.recipient)} on or before the end of turn {term.payment.dueTurn}. {term.paymentStatus ? `Payment status: ${term.paymentStatus}.` : 'Payment becomes binding on final acceptance.'}</p>
{canPay && <div>
{option?.blocked && <p>Payment is unavailable: {option.blocked}</p>}
<Button type="button" disabled={disabled || !option || !!option.blocked}
onClick={() => act({type:'dealPay',deal:deal.id,paymentIndex:index})}>Pay additional payment {index + 1}</Button>
</div>}
</div>;
})}
{travel && <p><strong>{travelTurn === deal.turn ? 'Current-turn travel term:' : 'Travel term:'}</strong> {name(travelActor!)} {deal.status === 'offered' || deal.status === 'declined' || deal.status === 'withdrawn' ? 'would' : 'agrees to'} {travel.answer ? 'make' : 'avoid'} {travel.kind === 'ship' ? 'a reserve shipment' : 'a ground movement'} of at least {travel.minimum} physical forces in one action to {travelDestination ?? travel.territory} during turn {travelTurn}. {travelStatus ? `Travel status: ${travelStatus}.` : deal.status === 'offered' ? 'The term becomes binding on final acceptance.' : deal.status === 'declined' || deal.status === 'withdrawn' ? 'The term did not become binding.' : 'Travel status is unavailable.'}</p>}
{travel && travelTurn !== undefined && travelTurn > deal.turn && <p>Before turn {travelTurn}, this term reserves no forces or spice. Its status and legal options update during that turn.</p>}
{travel && participants.length > 2 && deal.status === 'offered' && <p>{name(travelActor!)} must accept last, after the other recipients. Anyone invited may decline at any time.</p>}
@@ -182,6 +212,8 @@ export function PublicDeals({ game, act, busy }: {
const [payer, setPayer] = useState('');
const [paymentRecipient, setPaymentRecipient] = useState('');
const [paymentAmount, setPaymentAmount] = useState('1');
const [additionalDrafts, setAdditionalDrafts] = useState<AdditionalPaymentDraft[]>([]);
const nextAdditionalKey = useRef(0);
const [deadlineDraft, setDeadlineDraft] = useState(() => ({ value: String(game.turn), turn: game.turn }));
const [travelDeadlineDraft, setTravelDeadlineDraft] = useState(() => ({ value: String(game.turn), turn: game.turn }));
const previousDeadline = Number(deadlineDraft.value);
@@ -219,6 +251,10 @@ export function PublicDeals({ game, act, busy }: {
parties.some(player => player.id === payer) && parties.some(player => player.id === paymentRecipient) &&
Number.isSafeInteger(amount) && amount > 0;
const paymentValid = !includePayment || paymentPeopleAndAmountValid && (paymentKind !== 'deferredBribe' || dueValid);
const additionalPayments: DeferredBribe[] = additionalDrafts.map(draft => ({
kind:'deferredBribe', payer:draft.payer, recipient:draft.recipient,
amount:Number(draft.amount), dueTurn:Number(draft.dueTurn),
}));
const travelTurn = Number(travelDueTurn);
const travelDueValid = travelDueTurn.trim() !== '' && Number.isSafeInteger(travelTurn) && travelTurn >= game.turn;
const travel: DealTravel | undefined = includeTravel ? {kind:travelKind, territory:travelTerritory,
@@ -226,7 +262,7 @@ export function PublicDeals({ game, act, busy }: {
...(selected.length > 1 ? {actor:travelActor} : {}),
...(travelTurn > game.turn ? {dueTurn:travelTurn} : {})} : undefined;
const offer = legalSelection && paymentValid && (!includeTravel || travelDueValid)
? publicDealOfferAction(selected, terms, payment, me?.id, game.turn, travel) : null;
? publicDealOfferAction(selected, terms, payment, me?.id, game.turn, travel, additionalPayments) : null;
const disabled = busy || !!game.roomControl?.paused || !!game.roomControl?.closed || !!me?.autopilot;
const mayOffer = game.status === 'playing' && me && !me.bot;
return <details ref={panel} className="notice public-deals-panel">
@@ -296,6 +332,48 @@ export function PublicDeals({ game, act, busy }: {
{legalSelection && !paymentPeopleAndAmountValid && <p>Choose two different participants and a positive whole spice amount.</p>}
{paymentKind === 'deferredBribe' && !dueValid && <p role="alert">Choose a whole due turn no earlier than turn {game.turn}.</p>}
</fieldset>}
{additionalDrafts.map((draft, index) => {
const valid = draft.payer !== draft.recipient && parties.some(player => player.id === draft.payer) &&
parties.some(player => player.id === draft.recipient) && Number.isSafeInteger(Number(draft.amount)) &&
Number(draft.amount) > 0 && draft.dueTurn.trim() !== '' && Number.isSafeInteger(Number(draft.dueTurn)) &&
Number(draft.dueTurn) >= game.turn;
const update = (change: Partial<AdditionalPaymentDraft>) => setAdditionalDrafts(current =>
current.map(row => row.key === draft.key ? {...row,...change} : row));
return <fieldset key={draft.key}>
<legend>Additional payment {index + 1}</legend>
<label>Paying participant
<select value={parties.some(player => player.id === draft.payer) ? draft.payer : ''} disabled={disabled}
onChange={event => update({payer:event.target.value})}>
<option value="">Choose a payer</option>
{parties.map(player => <option key={player.id} value={player.id}>{player.name} · {faction(player.faction).name}</option>)}
</select>
</label>
<label>Receiving participant
<select value={parties.some(player => player.id === draft.recipient) ? draft.recipient : ''} disabled={disabled}
onChange={event => update({recipient:event.target.value})}>
<option value="">Choose a recipient</option>
{parties.filter(player => player.id !== draft.payer).map(player => <option key={player.id} value={player.id}>{player.name} · {faction(player.faction).name}</option>)}
</select>
</label>
<label>Gross spice amount
<input type="number" inputMode="numeric" min={1} step={1} value={draft.amount} disabled={disabled}
onChange={event => update({amount:event.target.value})} />
</label>
<label>Payment due by the end of turn
<input type="number" inputMode="numeric" min={game.turn} step={1} value={draft.dueTurn} disabled={disabled}
required aria-invalid={!valid} onChange={event => update({dueTurn:event.target.value})} />
</label>
{legalSelection && !valid && <p>Choose two different participants, a positive whole amount and a current or future due turn.</p>}
<Button type="button" variant="outline" disabled={disabled}
onClick={() => setAdditionalDrafts(current => current.filter(row => row.key !== draft.key))}>Remove additional payment {index + 1}</Button>
</fieldset>;
})}
<Button type="button" variant="outline" disabled={disabled || additionalDrafts.length >= 12 || selected.length === 0}
onClick={() => {
const key = nextAdditionalKey.current++;
setAdditionalDrafts(current => [...current, {key,payer:'',recipient:'',amount:'1',dueTurn:String(game.turn)}]);
}}>Add deferred payment</Button>
{additionalDrafts.length > 0 && <p className="fine">Each additional payment has its own deadline and pay control. The recipient collects its share at the next Mentat opening.</p>}
<label className="checkbox-row">
<input type="checkbox" checked={includeTravel} disabled={disabled || !includeTravel && selected.length === 0}
onChange={event => setIncludeTravel(event.target.checked)} />
+9
View File
@@ -17,6 +17,15 @@ open mode gates.
## Current checkpoint and work
**Multiple deferred payments in public deals — 16 November. Prototyped /
Partial.** Up to twelve additional individually payable deferred terms can
accompany the existing payment and supported travel. Funding, release, due
dates, autopilot and legacy records retain their native paths. Thirty-six
related offline files pass 215 cases, the new authenticated HTTP case passes,
and type checking, lint and the production build pass. Multiple immediate
settlements, broader interactions and deployed acceptance remain open.
[Scope](PUBLIC_DEALS.md#multiple-deferred-payments--16-november-2026).
**Deferred travel funding and bribe quotes — 16 November. Prototyped / Partial.**
Due-turn payments preserve known routes for earlier scheduled travel, and the
bribe quote accounts for accepted due payments and travel without reserving
+26
View File
@@ -1,5 +1,31 @@
# Public deal records
## Multiple deferred payments — 16 November 2026
**Prototyped / Partial.** A two-party or group offer can include up to twelve
additional deferred bribes, each with its own payer, recipient, amount and due
turn. They may accompany the existing one immediate or deferred payment and a
supported travel term. All parties consent before any term binds; the traveler
still accepts last. Current-due obligations share each payer's native funding
and travel checks, while future deadlines do not reserve today's spice.
Each accepted term has a stable per-deal index, independent status and exact
Pay action. Identical payments are separate transfers; replaying one cannot pay
another. Unanimous release cancels unpaid terms without refunding settled
payments. A human-controlled seat using autopilot follows the same legal
per-term payment action. Existing single-payment records and actions remain
unchanged. Multiple immediate payments are not yet supported: their native
bribe responses need a separate persistent settlement continuation. The bounded
term count and online consent protocol are implementation limits, not printed
restrictions on agreements.
[Public gameplay](../tests/public-deals-multiple-payments.test.ts),
[model validation](../tests/public-deals-multiple-payments-model.test.ts),
[offer and payment controls](../tests/public-deals-multiple-payments-controls.test.tsx)
and the [authenticated boundary](../tests/public-deals-multiple-payments-http.test.ts)
cover the connected prototype. Full combination, persistence and deployed
acceptance remain open.
## Scheduled travel and discretionary bribes — 16 November 2026
**Prototyped / Partial.** When evaluating a due payment, each detached native
+4 -2
View File
@@ -4401,10 +4401,12 @@ export function botActions(g: GameView): Action[] {
if ((dealPayer?.bot || dealPayer?.autopilot) && g.status === 'playing' &&
!g.roomControl?.paused && !g.roomControl?.closed && !g.automaticContinuationPending) {
const payable = Object.entries(g.deferredDealPaymentOptions ?? {}).find(([id,option]) => {
const payment = g.deals.find(deal => deal.id === id)?.payment;
const deal = g.deals.find(row => row.id === (option.deal ?? id));
const payment = option.paymentIndex === undefined ? deal?.payment : deal?.additionalPayments?.[option.paymentIndex]?.payment;
return !option.blocked && payment?.kind === 'deferredBribe' && payment.dueTurn <= g.turn;
});
if (payable) return [{type:'dealPay',deal:payable[0]}];
if (payable) return [{type:'dealPay',deal:payable[1].deal ?? payable[0],
...(payable[1].paymentIndex === undefined ? {} : {paymentIndex:payable[1].paymentIndex})}];
}
if (g.decision?.kind === 'homeworldTupileCleanup' || g.homeworldTupileCleanup)
return tupileCleanupActions(g);
+41 -32
View File
@@ -10,8 +10,9 @@ import { createFactionDraft, validateFactionDraft, currentFactionDrafter, choose
import { createFactionSwap, validateFactionSwap, answerFactionSwap, cancelFactionSwap,
FactionSwapError, type FactionSwap } from './faction-swap';
import { createPublicDeal, createMultipartyPublicDeal, validatePublicDeals, respondPublicDeal, withdrawPublicDeal,
releasePublicDeal, markPublicDealPaid, voidPublicDealPayment, setPublicDealTravel, publicDealTravelActor, publicDealTravelDueTurn, PublicDealError, type PublicDeal, type PublicDealPayment } from './public-deals';
import { outstandingPublicDealPayments, pendingPublicDealPayments, publicDealPaymentTotal, PublicDealObligationError, type PendingPublicDealPayment } from './public-deal-obligations';
releasePublicDeal, markPublicDealPaid, voidPublicDealPayment, setPublicDealTravel, setPublicDealAdditionalPayments,
publicDealDeferredTerms, publicDealTravelActor, publicDealTravelDueTurn, PublicDealError, type PublicDeal, type PublicDealPayment } 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';
import { createVictoryContinuation, validateVictoryContinuation, voteVictoryContinuation,
@@ -6148,17 +6149,17 @@ function publicDealCompletion(g: Game, payer: Player): boolean {
* possible. Only settled, proven expiry or a base-game Mentat shortfall voids
* a term; temporary pending decisions do not establish impossibility. */
function reconcilePublicDealTruth(g: Game, voluntary?: {actor:string;action:Action}, before?: Game): void {
if (!g.deals?.some(deal => deal.payment?.kind === 'deferredBribe' && deal.paymentStatus === 'pending')) return;
if (!g.deals?.some(deal => publicDealDeferredTerms(deal).some(term => term.paymentStatus === 'pending'))) return;
for (const p of g.players) {
const pending: PublicDeal[] = (g.deals ?? []).filter(deal => deal.status === 'active' && deal.payment?.kind === 'deferredBribe' &&
deal.payment.payer === p.id && deal.paymentStatus === 'pending');
const pending: Array<ReturnType<typeof publicDealDeferredTerms>[number] & {deal:string}> = (g.deals ?? []).flatMap(deal => deal.status === 'active'
? publicDealDeferredTerms(deal).filter(term => term.payment.payer === p.id && term.paymentStatus === 'pending')
.map(term => ({deal:deal.id,...term})) : []);
if (!pending.length) continue;
const beforePayer = before && getPlayer(before,p.id);
const wasPossible = !!before && !!beforePayer && voluntary?.actor === p.id &&
pendingPublicDealPayments(before.deals ?? [],p.id,before.turn).some(debt => !bribeAllied(before, beforePayer, debt.recipient)) &&
publicDealCompletion(before,beforePayer);
const expiredByAction = pending.some(deal => deal.payment?.kind === 'deferredBribe' &&
(g.turn > deal.payment.dueTurn || g.status === 'finished'));
const expiredByAction = pending.some(term => g.turn > term.payment.dueTurn || g.status === 'finished');
const closesPaymentWindow = wasPossible && voluntary?.action.type === 'ready' &&
(before!.phase === 8 || before!.phase === 7 && bribesCloseBeforeNextMentat(before!));
if (wasPossible && (closesPaymentWindow || expiredByAction || !publicDealCompletion(g,p)))
@@ -6166,15 +6167,15 @@ function reconcilePublicDealTruth(g: Game, voluntary?: {actor:string;action:Acti
const quiet = !g.truthtrance && !g.response && !g.decision && !g.phaseOpening &&
!g.pendingKarama && !g.pendingTreacheryDiscard && !g.bureaucratPayments?.pending;
const available = Math.max(0,uncommittedSpice(g,p));
for (const deal of pending) {
const payment = deal.payment!;
if (payment.kind !== 'deferredBribe') continue;
for (const term of pending) {
const payment = term.payment;
const expired = g.turn > payment.dueTurn || g.status === 'finished';
if (!expired && bribeAllied(g, p, payment.recipient)) continue;
const baseMentatShortfall = quiet && g.turn === payment.dueTurn && g.phase === 8 &&
g.expansions.length === 0 && bribePromiseModeSupported(g) && available < payment.amount;
if (expired || baseMentatShortfall) {
g.deals = g.deals!.map(row => row.id === deal.id ? publicDealRule((): PublicDeal => voidPublicDealPayment(row,g.players)) : row);
g.deals = g.deals!.map(row => row.id === term.deal
? publicDealRule((): PublicDeal => voidPublicDealPayment(row,g.players,term.paymentIndex)) : row);
log(g, `${p.name}'s agreed ${payment.amount}-spice payment can no longer be completed and is void.`);
}
}
@@ -6199,19 +6200,21 @@ function protectInsolventDueDeal(g: Game, payer: string, payment: PendingPublicD
'Keep the funding for a currently payable deal before paying a later deal.');
}
/** Only the payer receives its exact native payment quote. */
function projectedDeferredDealPaymentOptions(g: Game, player: string): Record<string,{blocked:string|null}> {
const result: Record<string,{blocked:string|null}> = {};
function projectedDeferredDealPaymentOptions(g: Game, player: string): Record<string,{blocked:string|null;deal?:string;paymentIndex?:number}> {
const result: Record<string,{blocked:string|null;deal?:string;paymentIndex?:number}> = {};
for (const debt of outstandingPublicDealPayments(g.deals ?? [],player,g.turn)) {
const key = publicDealPaymentOptionKey(debt.deal,debt.paymentIndex);
const identity = debt.paymentIndex === undefined ? {} : {deal:debt.deal,paymentIndex:debt.paymentIndex};
try {
protectInsolventDueDeal(g,player,debt);
const trial = structuredClone(g), index = trial.deals!.findIndex(deal => deal.id === debt.deal);
trial.deals![index] = publicDealRule(() => markPublicDealPaid(trial.deals![index],trial.players,player));
trial.deals![index] = publicDealRule(() => markPublicDealPaid(trial.deals![index],trial.players,player,debt.paymentIndex));
applyActionWithInitiator(trial,player,{type:'bribe',target:debt.recipient,amount:debt.amount},player,
{insolventDealPayment:debt.dueTurn === g.turn && publicDealInsolventAtBaseMentat(g,player)});
result[debt.deal] = {blocked:null};
result[key] = {blocked:null,...identity};
} catch (error) {
if (!(error instanceof RuleError)) throw error;
result[debt.deal] = {blocked:error.message};
result[key] = {blocked:error.message,...identity};
}
}
return result;
@@ -17823,7 +17826,8 @@ function basicBribeInterrupt(g: Game, p: Player): boolean {
(g.alliancePromises ?? []).some(row => row.player === p.id && row.turn === g.turn && !row.fulfilled && !row.released) ||
(g.allianceExpressionPromises ?? []).some(row => row.player === p.id && row.turn === g.turn && !row.fulfilled && !row.released) ||
(g.pledgePromises ?? []).some(row => row.player === p.id && row.turn === g.turn && !row.fulfilled && !row.released) ||
(g.deals ?? []).some(row => row.status === 'active' && row.payment?.payer === p.id && row.paymentStatus === 'pending')) return false;
(g.deals ?? []).some(row => row.status === 'active' && publicDealDeferredTerms(row)
.some(term => term.payment.payer === p.id && term.paymentStatus === 'pending'))) return false;
const classic = ['atreides', 'beneGesserit', 'emperor', 'fremen', 'guild', 'harkonnen'];
const nativeRoster = !g.expansions.length
? g.players.every(seat => classic.includes(seat.faction)) : selectedPhaseModuleRoster(g);
@@ -21229,7 +21233,8 @@ function choamMarketSkipCommitments(g: Game): boolean {
recorded(g.bribeExpressionPromises) || recorded(g.pledgePromises) || recorded(g.alliancePromises) ||
recorded(g.allianceExpressionPromises) || recorded(g.movementPromises) || recorded(g.movementExpressionPromises) ||
recorded(g.futureBattleLeaderPromises) ||
!!g.deals?.some(row => row.status === 'active' && row.paymentStatus === 'pending');
!!g.deals?.some(row => row.status === 'active' && publicDealDeferredTerms(row)
.some(term => term.paymentStatus === 'pending'));
}
function choamMarketSkipAvailable(g: Game, p: Player): boolean {
return choamMarketSkipProfile(g, p) && g.decision?.kind === 'choamMarket' &&
@@ -43659,16 +43664,19 @@ function applyActionWithInitiator(state: Game, id: string, action: Action, initi
return g;
}
if (action?.type === 'dealPay') {
requireRule(state.status === 'playing' && Object.keys(action).sort().join(',') === 'deal,type' &&
const keys = Object.keys(action).sort().join(',');
requireRule(state.status === 'playing' && (keys === 'deal,type' || keys === 'deal,paymentIndex,type') &&
(action.paymentIndex === undefined || Number.isSafeInteger(action.paymentIndex) && (action.paymentIndex as number) >= 0) &&
typeof action.deal === 'string', 'Choose your pending deal payment.');
requireRule(!bribeTimingBlock(state), 'Finish the current decision or response before paying a deal.');
const g = structuredClone(state), index = (g.deals ?? []).findIndex(deal => deal.id === action.deal);
requireRule(index >= 0, 'This deal is no longer available.');
const current = g.deals![index], payment = current.payment;
const current = g.deals![index], paymentIndex = action.paymentIndex as number | undefined;
const payment = paymentIndex === undefined ? current.payment : current.additionalPayments?.[paymentIndex]?.payment;
requireRule(payment?.kind === 'deferredBribe' && payment.dueTurn >= g.turn,
'This deferred payment is no longer available.');
protectInsolventDueDeal(state,id,{deal:current.id,...payment});
g.deals![index] = publicDealRule(() => markPublicDealPaid(current,g.players,id));
protectInsolventDueDeal(state,id,{deal:current.id,...payment,...(paymentIndex === undefined ? {} : {paymentIndex})});
g.deals![index] = publicDealRule(() => markPublicDealPaid(current,g.players,id,paymentIndex));
return applyActionWithInitiator(g,id,{type:'bribe',target:payment.recipient,amount:payment.amount},id,
{insolventDealPayment:payment.dueTurn === state.turn && publicDealInsolventAtBaseMentat(state,id)});
}
@@ -43679,11 +43687,10 @@ function applyActionWithInitiator(state: Game, id: string, action: Action, initi
const g = structuredClone(state);
const deals = g.deals ?? [];
if (action.type === 'dealOffer') {
const keys = Object.keys(action).sort().join(',');
const single = (keys === 'target,terms,type' || keys === 'payment,target,terms,type' ||
keys === 'target,terms,travel,type' || keys === 'payment,target,terms,travel,type') && typeof action.target === 'string';
const multiple = (keys === 'targets,terms,type' || keys === 'payment,targets,terms,type' ||
keys === 'targets,terms,travel,type' || keys === 'payment,targets,terms,travel,type') && Array.isArray(action.targets) &&
const keys = Object.keys(action);
const supportedKeys = keys.every(key => ['type','terms','target','targets','payment','additionalPayments','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');
const hasPayment = Object.hasOwn(action, 'payment');
requireRule((single || multiple) && typeof action.terms === 'string' &&
@@ -43699,6 +43706,8 @@ function applyActionWithInitiator(state: Game, id: string, action: Action, initi
: hasPayment
? createMultipartyPublicDeal(seats, id, action.targets as string[], action.terms as string, g.turn, event, payment!)
: 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, 'travel')) {
requireRule(!g.advanced && g.expansions.length === 0 && nativePromiseScopeSupported(g),
'Choose a travel agreement in a supported Basic table.');
@@ -43719,7 +43728,7 @@ function applyActionWithInitiator(state: Game, id: string, action: Action, initi
requireRule(typeof action.accept === 'boolean', 'Choose whether to accept or decline.');
requireRule(!action.accept || !current.travel || publicDealTravelDueTurn(current) >= g.turn,
'The travel agreement’s due turn has passed; decline or withdraw it.');
requireRule(!action.accept || current.payment?.kind !== 'deferredBribe' || current.payment.dueTurn >= g.turn,
requireRule(!action.accept || publicDealDeferredTerms(current).every(term => term.payment.dueTurn >= g.turn),
'The deferred payment deadline has passed; decline or withdraw this offer.');
next = publicDealRule(() => respondPublicDeal(current, publicDealSeats(g), id, action.accept as boolean));
} else if (action.type === 'dealRelease') {
@@ -43745,15 +43754,15 @@ function applyActionWithInitiator(state: Game, id: string, action: Action, initi
requireRule(publicDealCompletion(g,traveler),
'The traveler needs a funded completion for the travel and their payments due this turn.');
}
if (current.status === 'offered' && next.status === 'active' && next.payment?.kind === 'deferredBribe') {
const payer = getPlayer(g,next.payment.payer), dueTurn = next.payment.dueTurn;
if (current.status === 'offered' && next.status === 'active') for (const term of publicDealDeferredTerms(next)) {
const payment = term.payment, payer = getPlayer(g,payment.payer), dueTurn = payment.dueTurn;
requireRule(dueTurn >= g.turn &&
(dueTurn > g.turn || publicDealCompletion(g,payer)),
'The agreed payment needs an unexpired deadline and, when due now, a legal funded completion.');
if (next.payment.dueTurn === g.turn &&
if (dueTurn === g.turn &&
(g.phase === 2 && !g.charityOrder || g.phase === 8 || g.phase === 7 && bribesCloseBeforeNextMentat(g)) &&
g.ready.includes(payer.id)) g.ready = g.ready.filter(playerId => playerId !== payer.id);
log(g, `${payer.name} agreed to pay ${next.payment.amount} spice to ${getPlayer(g,next.payment.recipient).name} by the end of turn ${next.payment.dueTurn}.`);
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.payment?.kind === 'immediateBribe') {
// The payer consented to these immutable terms. Run the native action
+14 -6
View File
@@ -1,16 +1,22 @@
import { validatePublicDeals, voidPublicDealPayment, type PublicDeal, type PublicDealSeat } from './public-deals';
import { publicDealDeferredTerms, validatePublicDeals, voidPublicDealPayment, type PublicDeal, type PublicDealSeat } from './public-deals';
/** A deal-linked obligation is independent of every other deal and of
* Truthtrance. It is due once for its exact gross payment, not a threshold
* shared with a different agreement. */
export type PendingPublicDealPayment = {
deal: string;
paymentIndex?: number;
payer: string;
recipient: string;
dueTurn: number;
amount: number;
};
/** Projection key is stable for a term and preserves the legacy deal key. */
export function publicDealPaymentOptionKey(deal: string, paymentIndex?: number): string {
return paymentIndex === undefined ? deal : `${deal}:payment:${paymentIndex}`;
}
export class PublicDealObligationError extends Error {
constructor(message: string) {
super(message);
@@ -32,10 +38,12 @@ export function outstandingPublicDealPayments(
if (!Array.isArray(deals) || !identifier(payer) || !Number.isSafeInteger(turn) || turn < 1)
throw new PublicDealObligationError('Retain the payer and original turn of the deferred payments.');
return deals.flatMap(deal => {
const payment = deal.payment;
if (deal.status !== 'active' || deal.paymentStatus !== 'pending' ||
payment?.kind !== 'deferredBribe' || payment.payer !== payer || payment.dueTurn < turn) return [];
return [{ deal: deal.id, payer, recipient: payment.recipient, dueTurn: payment.dueTurn, amount: payment.amount }];
if (deal.status !== 'active') return [];
return publicDealDeferredTerms(deal).flatMap(({payment, paymentStatus, paymentIndex}) => {
if (paymentStatus !== 'pending' || payment.payer !== payer || payment.dueTurn < turn) return [];
return [{deal: deal.id, ...(paymentIndex === undefined ? {} : {paymentIndex}), payer,
recipient: payment.recipient, dueTurn: payment.dueTurn, amount: payment.amount}];
});
});
}
@@ -83,7 +91,7 @@ export function reconcilePublicDealPayments(
throw new PublicDealObligationError('Retain the actual funded witness and cause of the change.');
const pending = pendingPublicDealPayments(deals, payer, turn);
const ids = witness.impossibleDealIds ?? [];
if (new Set(ids).size !== ids.length || ids.some(id => !pending.some(row => row.deal === id)))
if (new Set(ids).size !== ids.length || ids.some(id => !pending.some(row => row.deal === id && row.paymentIndex === undefined)))
throw new PublicDealObligationError('Void only individually proven pending terms of this payer and turn.');
if (witness.change === 'voluntary' && (ids.length > 0 ||
witness.available !== null && witness.available < publicDealPaymentTotal(deals, payer, turn)))
+83 -3
View File
@@ -15,6 +15,13 @@ export type PublicDealPayment = {
dueTurn: number;
};
export type PublicDealPaymentStatus = 'pending' | 'paid' | 'void' | 'released';
export type PublicDealDeferredPayment = Extract<PublicDealPayment, { kind: 'deferredBribe' }>;
/** The index is the stable identity of a term within its immutable offer. */
export type PublicDealAdditionalPayment = {
payment: PublicDealDeferredPayment;
paymentStatus?: PublicDealPaymentStatus;
};
export const MAX_ADDITIONAL_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 = {
@@ -42,6 +49,7 @@ export type PublicDeal = {
payment?: PublicDealPayment;
/** Present only for accepted or released deferred payments. */
paymentStatus?: PublicDealPaymentStatus;
additionalPayments?: PublicDealAdditionalPayment[];
travel?: PublicDealTravel;
};
@@ -86,6 +94,17 @@ function notAllied(seats: readonly PublicDealSeat[]): void {
export function publicDealParticipants(deal: PublicDeal): string[] {
return deal.participants ? [...deal.participants] : [deal.from, deal.to];
}
/** Enumerate legacy and indexed deferred terms without rewriting older saves. */
export function publicDealDeferredTerms(deal: PublicDeal): Array<{
payment: PublicDealDeferredPayment;
paymentStatus?: PublicDealPaymentStatus;
paymentIndex?: number;
}> {
const legacy = deal.payment?.kind === 'deferredBribe'
? [{payment: deal.payment, ...(deal.paymentStatus ? {paymentStatus: deal.paymentStatus} : {})}]
: [];
return [...legacy, ...(deal.additionalPayments ?? []).map((term,paymentIndex) => ({...term,paymentIndex}))];
}
export function publicDealAcceptVotes(deal: PublicDeal): string[] {
if (deal.acceptVotes) return [...deal.acceptVotes];
return deal.status === 'active' || deal.status === 'released'
@@ -154,7 +173,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').sort().join(',') : '';
const keys = object(deal) ? Object.keys(deal).filter(key => key !== 'payment' && key !== 'paymentStatus' && key !== 'travel' && key !== 'additionalPayments').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 &&
@@ -206,6 +225,23 @@ export function validatePublicDeals(value: unknown, players: readonly PublicDeal
!Object.hasOwn(deal, 'paymentStatus'), 'The deferred payment status does not match the deal lifecycle.');
} else requireDeal(!Object.hasOwn(deal, 'paymentStatus'),
'Only an accepted deferred payment has a payment status.');
if (Object.hasOwn(deal, 'additionalPayments')) {
requireDeal(Array.isArray(deal.additionalPayments) && deal.additionalPayments.length >= 1 &&
deal.additionalPayments.length <= MAX_ADDITIONAL_DEAL_PAYMENTS,
'Choose between one and twelve additional deferred payments.');
for (const term of deal.additionalPayments) {
requireDeal(object(term) && (Object.keys(term).sort().join(',') === 'payment' ||
Object.keys(term).sort().join(',') === 'payment,paymentStatus'),
'An additional payment term is malformed.');
const parsed = parsePublicDealPayment(term.payment, parties, deal.turn as number);
requireDeal(parsed.kind === 'deferredBribe', 'Additional payments must have a due turn.');
const status = term.paymentStatus;
requireDeal(deal.status === 'active' ? status === 'pending' || status === 'paid' || status === 'void' :
deal.status === 'released' ? status === 'released' || status === 'paid' :
!Object.hasOwn(term, 'paymentStatus'),
'An additional payment status does not match the deal lifecycle.');
}
}
const votes = deal.releaseVotes as string[];
requireDeal(new Set(votes).size === votes.length && votes.every(vote => parties.includes(vote)) &&
(!multi || orderedSubset(votes, parties)) &&
@@ -248,6 +284,28 @@ export function createMultipartyPublicDeal(
...paymentTerm };
}
/** Attach independent deferred payment terms to an unchanged fresh offer. */
export function setPublicDealAdditionalPayments(deal: PublicDeal, value: unknown, players: readonly PublicDealSeat[]): PublicDeal {
validatePublicDeals([deal], players);
requireDeal(deal.status === 'offered' && !Object.hasOwn(deal, 'additionalPayments') &&
!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 deferred payment terms.');
requireDeal(Array.isArray(value) && value.length >= 1 && value.length <= MAX_ADDITIONAL_DEAL_PAYMENTS,
'Choose between one and twelve additional deferred payments.');
const parties = publicDealParticipants(deal);
notAllied(participants(players, parties));
const additionalPayments = value.map(value => {
const payment = parsePublicDealPayment(value, parties, deal.turn);
requireDeal(payment.kind === 'deferredBribe', 'Additional payments must have a due turn.');
return {payment};
});
const result = {...deal, additionalPayments};
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);
@@ -270,6 +328,7 @@ export function respondPublicDeal(deal: PublicDeal, players: readonly PublicDeal
if (!accept) return { ...deal, status: 'declined', releaseVotes: [] };
notAllied(participants(players, parties));
if (!deal.participants) return { ...deal, status: 'active', releaseVotes: [],
...(deal.additionalPayments ? {additionalPayments: deal.additionalPayments.map(term => ({...term, paymentStatus:'pending' as const}))} : {}),
...(deal.payment?.kind === 'deferredBribe' ? { paymentStatus: 'pending' as const } : {}) };
const alreadyAccepted = publicDealAcceptVotes(deal);
requireDeal(!alreadyAccepted.includes(actor), 'This participant already accepted the offer.');
@@ -279,6 +338,7 @@ export function respondPublicDeal(deal: PublicDeal, players: readonly PublicDeal
const accepts = parties.filter(seat => seat === actor || alreadyAccepted.includes(seat));
const active = accepts.length === parties.length;
return { ...deal, acceptVotes: accepts, status: active ? 'active' : 'offered', releaseVotes: [],
...(active && deal.additionalPayments ? {additionalPayments: deal.additionalPayments.map(term => ({...term, paymentStatus:'pending' as const}))} : {}),
...(active && deal.payment?.kind === 'deferredBribe' ? { paymentStatus: 'pending' as const } : {}) };
}
@@ -300,6 +360,8 @@ export function releasePublicDeal(deal: PublicDeal, players: readonly PublicDeal
if (deal.participants) votes = parties.filter(seat => votes.includes(seat));
const released = votes.length === parties.length;
return { ...deal, status: released ? 'released' : 'active', releaseVotes: votes,
...(released && deal.additionalPayments ? {additionalPayments: deal.additionalPayments.map(term => ({...term,
paymentStatus: term.paymentStatus === 'paid' ? 'paid' as const : 'released' as const}))} : {}),
...(released && deal.payment?.kind === 'deferredBribe' && deal.paymentStatus !== 'paid'
? { paymentStatus: 'released' as const } : {}) };
}
@@ -307,8 +369,17 @@ export function releasePublicDeal(deal: PublicDeal, players: readonly PublicDeal
/** The engine must first authorize the native payer and exact bribe action.
* Apply this transition on its detached action state, so native failure rolls
* both the payment and the status change back together. */
export function markPublicDealPaid(deal: PublicDeal, players: readonly PublicDealSeat[], payer: string): PublicDeal {
export function markPublicDealPaid(deal: PublicDeal, players: readonly PublicDealSeat[], payer: string, paymentIndex?: number): PublicDeal {
validatePublicDeals([deal], players);
if (paymentIndex !== undefined) {
requireDeal(Number.isSafeInteger(paymentIndex) && paymentIndex >= 0 &&
paymentIndex < (deal.additionalPayments?.length ?? 0), 'Choose an existing additional payment.');
const term = deal.additionalPayments![paymentIndex];
requireDeal(deal.status === 'active' && term.paymentStatus === 'pending' && term.payment.payer === payer,
'Only the payer may settle a pending deferred deal payment.');
return {...deal, additionalPayments: deal.additionalPayments!.map((row,index) =>
index === paymentIndex ? {...row, paymentStatus:'paid' as const} : row)};
}
requireDeal(deal.status === 'active' && deal.payment?.kind === 'deferredBribe' &&
deal.paymentStatus === 'pending' && deal.payment.payer === payer,
'Only the payer may settle a pending deferred deal payment.');
@@ -316,8 +387,17 @@ export function markPublicDealPaid(deal: PublicDeal, players: readonly PublicDea
}
/** The caller must establish actual external impossibility before voiding. */
export function voidPublicDealPayment(deal: PublicDeal, players: readonly PublicDealSeat[]): PublicDeal {
export function voidPublicDealPayment(deal: PublicDeal, players: readonly PublicDealSeat[], paymentIndex?: number): PublicDeal {
validatePublicDeals([deal], players);
if (paymentIndex !== undefined) {
requireDeal(Number.isSafeInteger(paymentIndex) && paymentIndex >= 0 &&
paymentIndex < (deal.additionalPayments?.length ?? 0), 'Choose an existing additional payment.');
const term = deal.additionalPayments![paymentIndex];
requireDeal(deal.status === 'active' && term.paymentStatus === 'pending',
'Only a pending deferred deal payment can become impossible.');
return {...deal, additionalPayments: deal.additionalPayments!.map((row,index) =>
index === paymentIndex ? {...row, paymentStatus:'void' as const} : row)};
}
requireDeal(deal.status === 'active' && deal.payment?.kind === 'deferredBribe' && deal.paymentStatus === 'pending',
'Only a pending deferred deal payment can become impossible.');
return { ...deal, paymentStatus: 'void' };
+2 -2
View File
@@ -302,9 +302,9 @@ export const RULE_TOPICS: RuleTopic[] = [
'A qualifying Bureaucrat may divert two spice to the Bank without reducing the payer’s cost. The remainder stays deferred. Unsupported combinations remain unavailable and do not imply an official rule prohibition.',
'In Public deals, propose written terms to one or more human seats. Every pair of participants must be nonallied when the offer is made and accepted, a provisional interpretation. Every recipient must accept; any recipient can decline, and the proposer can withdraw the outstanding offer. Any party may request release; all must agree. The record remains active until mutually released, even when players consider it fulfilled.',
'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 instead specify one exact payment due this turn or a later turn. After everyone accepts, the payer can use that deal’s Pay button early or by the deadline. Future payments do not reserve current funds; obligations due now must still be respected. Separate deals require separate payments. A compatible Truthtrance bribe answer can be satisfied by the same payment. Mutual release cancels an unpaid term; a paid amount is not refunded.',
'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 one immediate or deferred payment between two participants. All parties accept, including the payer, and the traveler accepts last. An immediate payment settles with final consent; a 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-payment travel remains unfinished.',
'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.',
'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.',
],
@@ -0,0 +1,128 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { readFileSync } from 'node:fs';
import { runInNewContext } from 'node:vm';
import { createElement, isValidElement, type ReactElement, type ReactNode } from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
import * as jsxRuntime from 'react/jsx-runtime';
import ts from 'typescript';
import * as board from '../game/board';
import * as catalog from '../game/catalog';
import * as coalitionAlliance from '../game/coalition-alliance';
import * as publicDeals from '../game/public-deals';
import { PublicDealList, PublicDeals, publicDealOfferAction, publicDealRequests } from '../components/public-deals';
import type { Action, GameView } from '../game/engine';
type Element = ReactElement<{children?:ReactNode; [key:string]:unknown}>;
function elements(node: ReactNode): Element[] {
if (Array.isArray(node)) return node.flatMap(elements);
if (!isValidElement<{children?:ReactNode; [key:string]:unknown}>(node)) return [];
return [node, ...elements(node.props.children)];
}
function label(node: ReactNode): string {
if (Array.isArray(node)) return node.map(label).join('');
return typeof node === 'string' || typeof node === 'number' ? String(node) : '';
}
const first = {kind:'deferredBribe' as const,payer:'a',recipient:'b',amount:2,dueTurn:2};
const second = {kind:'deferredBribe' as const,payer:'a',recipient:'b',amount:3,dueTurn:3};
const deal = {id:'deal',from:'a',to:'b',terms:'Two payments.',turn:2,status:'active',releaseVotes:[],
additionalPayments:[{payment:first,paymentStatus:'pending'}, {payment:second,paymentStatus:'pending'}]};
const base = {status:'playing',turn:2,me:'a',roomControl:null,coalitionState:null,
players:[{id:'a',name:'Alice',faction:'atreides',ally:null},{id:'b',name:'Basil',faction:'harkonnen',ally:null}],
deals:[deal],deferredDealPaymentOptions:{'deal:payment:0':{blocked:null},'deal:payment:1':{blocked:'Keep funds for the first payment.'}},
} as unknown as GameView;
void test('offer helper sends distinct exact payment terms with legacy payment and travel', () => {
const immediate = {kind:'immediateBribe' as const,payer:'b',recipient:'a',amount:1};
const travel = {kind:'ship' as const,territory:'carthag',minimum:1,answer:true};
assert.deepEqual(publicDealOfferAction(['b'],' Terms ',immediate,'a',2,travel,[first,second]),
{type:'dealOffer',target:'b',terms:'Terms',payment:immediate,travel,additionalPayments:[first,second]});
assert.deepEqual(publicDealOfferAction(['b'],'Terms',undefined,'a',2,undefined,[]),
{type:'dealOffer',target:'b',terms:'Terms'});
for (const terms of [[{...first,payer:'outsider'}],[{...first,recipient:'a'}],[{...first,amount:0}],
[{...first,dueTurn:1}],Array.from({length:13},() => first)])
assert.equal(publicDealOfferAction(['b'],'Terms',undefined,'a',2,undefined,terms),null);
});
void test('each additional payment has its own visible status, quote and exact pay action', () => {
const html = renderToStaticMarkup(createElement(PublicDealList,{game:base,disabled:false,act() {}}));
assert.match(html,/Additional payment 1/); assert.match(html,/Additional payment 2/);
assert.match(html,/exactly 2 spice/); assert.match(html,/exactly 3 spice/);
assert.match(html,/Keep funds for the first payment/);
const calls:Action[] = [];
const nodes = elements(PublicDealList({game:base,disabled:false,act(action) {calls.push(action);}}));
const one = nodes.find(node => label(node.props.children) === 'Pay additional payment 1');
const two = nodes.find(node => label(node.props.children) === 'Pay additional payment 2');
assert.ok(one && two); assert.equal(one.props.disabled,false); assert.equal(two.props.disabled,true);
(one.props.onClick as () => void)();
assert.deepEqual(calls,[{type:'dealPay',deal:'deal',paymentIndex:0}]);
assert.deepEqual(publicDealRequests(base),[['payment','deal','0']]);
const paid = {...base,deals:[{...deal,additionalPayments:[{payment:first,paymentStatus:'paid'},
{payment:second,paymentStatus:'pending'}]}]} as unknown as GameView;
const after = elements(PublicDealList({game:paid,disabled:false,act() {}}));
assert.equal(after.find(node => label(node.props.children) === 'Pay additional payment 1'),undefined);
assert.ok(after.find(node => label(node.props.children) === 'Pay additional payment 2'));
assert.deepEqual(publicDealRequests(paid),[]);
const recipient = {...base,me:'b'} as GameView;
assert.equal(elements(PublicDealList({game:recipient,disabled:false,act() {}}))
.some(node => label(node.props.children) === 'Pay additional payment 1'),false);
});
/** Exercise the actual hook callbacks in a stateful React-compatible VM; this
* is a component-control test, not a hydrated-browser claim. */
function form() {
const states:unknown[] = [], refs:{current:unknown}[] = [], sent:Action[] = [];
let stateCursor = 0, refCursor = 0;
const exported:{PublicDeals?:typeof PublicDeals} = {};
runInNewContext(ts.transpileModule(readFileSync(new URL('../components/public-deals.tsx',import.meta.url),'utf8'),{
compilerOptions:{module:ts.ModuleKind.CommonJS,target:ts.ScriptTarget.ES2022,jsx:ts.JsxEmit.ReactJSX},
}).outputText,{exports:exported,require(name:string) {
if (name === 'react/jsx-runtime') return jsxRuntime;
if (name === 'react') return {useState(initial:unknown) {
const index = stateCursor++;
if (!(index in states)) states[index] = typeof initial === 'function' ? initial() : initial;
return [states[index],(next:unknown) => {states[index] = typeof next === 'function' ? next(states[index]) : next;}];
},useRef(initial:unknown) {const index = refCursor++; return refs[index] ??= {current:initial};},useEffect() {}};
if (name === '@/components/ui/button') return {Button:'button'};
if (name === '@/game/board') return board;
if (name === '@/game/catalog') return catalog;
if (name === '@/game/coalition-alliance') return coalitionAlliance;
if (name === '@/game/public-deals') return publicDeals;
throw Error(`Unexpected import ${name}`);
}});
assert.ok(exported.PublicDeals);
const game = {...base,deals:[]} as GameView;
const render = () => {stateCursor = 0; refCursor = 0;
return elements(exported.PublicDeals!({game,busy:false,act(action) {sent.push(action);}}));};
const click = (name:string) => {const button = render().find(node => node.type === 'button' && label(node.props.children) === name);
assert.ok(button); assert.equal(button.props.disabled,false); (button.props.onClick as () => void)();};
const field = (index:number) => {const sets = render().filter(node => node.type === 'fieldset' &&
elements(node).some(child => child.type === 'legend' && JSON.stringify(child.props.children).includes('Additional payment')));
assert.ok(sets[index]); return elements(sets[index]);};
return {render,click,field,sent};
}
void test('authoring callbacks add, edit and remove independent deferred terms', () => {
const ui = form();
const recipient = ui.render().find(node => node.type === 'input' && node.props.type === 'checkbox'); assert.ok(recipient);
(recipient.props.onChange as (event:{target:{checked:boolean}}) => void)({target:{checked:true}});
ui.click('Add deferred payment'); ui.click('Add deferred payment');
for (let index = 0; index < 2; index++) {
for (const [position,value] of [[0,'a'],[1,'b']] as const) {
const select = ui.field(index).filter(node => node.type === 'select')[position]; assert.ok(select);
(select.props.onChange as (event:{target:{value:string}}) => void)({target:{value}});
}
for (const [position,value] of [[0,String(index+2)],[1,String(index+2)]] as const) {
const input = ui.field(index).filter(node => node.type === 'input' && node.props.type === 'number')[position]; assert.ok(input);
(input.props.onChange as (event:{target:{value:string}}) => void)({target:{value}});
}
}
ui.click('Remove additional payment 1');
const terms = ui.render().find(node => node.type === 'textarea'); assert.ok(terms);
(terms.props.onChange as (event:{target:{value:string}}) => void)({target:{value:'One retained term'}});
const submit = ui.render().find(node => node.type === 'button' && node.props.type === 'submit');
assert.ok(submit); assert.equal(submit.props.disabled,false);
const root = ui.render().find(node => node.type === 'form'); assert.ok(root);
(root.props.onSubmit as (event:{preventDefault():void}) => void)({preventDefault() {}});
assert.deepEqual(JSON.parse(JSON.stringify(ui.sent)),[{type:'dealOffer',target:'b',terms:'One retained term',additionalPayments:[second]}]);
});
@@ -0,0 +1,71 @@
// @dune-suite integration
import assert from 'node:assert/strict';
import test from 'node:test';
import type { GameView } from '../game/engine';
const base = process.env.DUNE_TEST_URL ?? 'http://localhost:3000';
async function request(path:string,cookie?:string,body?:unknown,selected?:string) {
const response = await fetch(base+path,{
method:body === undefined ? 'GET' : 'POST',signal:AbortSignal.timeout(15_000),
headers:{...(body === undefined ? {} : {'Content-Type':'application/json'}),
...(cookie ? {cookie} : {}),...(selected ? {'X-Dune-Seat':selected} : {})},
...(body === undefined ? {} : {body:JSON.stringify(body)}),
});
return {status:response.status,cookie:response.headers.get('set-cookie')?.split(';')[0],
data:await response.json() as GameView & {error?:string}};
}
/** A fresh room only; no pre-existing room is read, changed or removed. */
void test('authenticated participants accept and settle each indexed deal payment once', async () => {
const host = await request('/api/rooms',undefined,{name:'Multiple recipient',faction:'atreides',advanced:false,expansions:[]});
assert.equal(host.status,201,JSON.stringify(host.data)); assert.ok(host.cookie);
const path = `/api/rooms/${host.data.code}`;
const payer = await request(path,undefined,{type:'join',name:'Multiple payer',faction:'harkonnen'});
assert.equal(payer.status,200,JSON.stringify(payer.data)); assert.ok(payer.cookie);
const seats = [{id:host.data.me,cookie:host.cookie},{id:payer.data.me,cookie:payer.cookie}];
let view = payer.data;
const act = async (cookie:string,action:object) => {
const next = await request(path,cookie,{version:view.version,action});
assert.equal(next.status,200,JSON.stringify(next.data)); view = next.data;
};
for (const seat of seats) await act(seat.cookie,{type:'ready'});
await act(host.cookie,{type:'start'});
for (const seat of seats) {
const own = await request(path,seat.cookie); assert.equal(own.status,200,JSON.stringify(own.data)); view = own.data;
const choices = own.data.players.find(player => player.id === seat.id)?.traitorChoices;
if (choices?.length) await act(seat.cookie,{type:'traitor',leader:choices[0]});
}
assert.equal(view.status,'playing');
const before = await request(path,payer.cookie); assert.equal(before.status,200); view = before.data;
const spice = before.data.players.find(player => player.id === payer.data.me)?.spice;
assert.ok(typeof spice === 'number' && spice >= 5);
const dueTurn = view.turn+1;
const terms = [2,3].map(amount => ({kind:'deferredBribe',payer:payer.data.me,recipient:host.data.me,amount,dueTurn}));
await act(host.cookie,{type:'dealOffer',target:payer.data.me,terms:'Pay two separate amounts.',additionalPayments:terms});
const offered = view.deals.at(-1); assert.ok(offered);
assert.equal(offered.status,'offered');
assert.deepEqual(offered.additionalPayments?.map(line => line.payment),terms);
const acceptance = {type:'dealRespond',deal:offered.id,accept:true};
const forged = await request(path,host.cookie,{version:view.version,action:acceptance},payer.data.me);
assert.equal(forged.status,409,JSON.stringify(forged.data));
await act(payer.cookie,acceptance);
for (const seat of seats) {
const read = await request(path,seat.cookie); assert.equal(read.status,200,JSON.stringify(read.data));
const active:GameView['deals'][number] | undefined = read.data.deals.find(row => row.id === offered.id); assert.ok(active);
assert.equal(active.status,'active');
assert.deepEqual(active.additionalPayments?.map(line => line.paymentStatus),['pending','pending']);
}
const second = {type:'dealPay',deal:offered.id,paymentIndex:1};
const wrongPayer = await request(path,host.cookie,{version:view.version,action:second});
assert.equal(wrongPayer.status,409,JSON.stringify(wrongPayer.data));
const impersonation = await request(path,host.cookie,{version:view.version,action:second},payer.data.me);
assert.equal(impersonation.status,409,JSON.stringify(impersonation.data));
await act(payer.cookie,second);
assert.deepEqual(view.deals.find(row => row.id === offered.id)?.additionalPayments?.map(line => line.paymentStatus),['pending','paid']);
const replay = await request(path,payer.cookie,{version:view.version,action:second});
assert.equal(replay.status,409,JSON.stringify(replay.data));
await act(payer.cookie,{type:'dealPay',deal:offered.id,paymentIndex:0});
const paid = await request(path,payer.cookie); assert.equal(paid.status,200,JSON.stringify(paid.data));
assert.deepEqual(paid.data.deals.find(row => row.id === offered.id)?.additionalPayments?.map(line => line.paymentStatus),['paid','paid']);
assert.equal(paid.data.players.find(player => player.id === payer.data.me)?.spice,spice-5);
});
@@ -0,0 +1,102 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import {
createMultipartyPublicDeal, createPublicDeal, markPublicDealPaid, publicDealDeferredTerms,
PublicDealError, releasePublicDeal, respondPublicDeal, setPublicDealAdditionalPayments,
validatePublicDeals, voidPublicDealPayment, type PublicDeal, type PublicDealSeat,
} from '../game/public-deals';
import { outstandingPublicDealPayments, pendingPublicDealPayments, publicDealPaymentOptionKey,
publicDealPaymentTotal } from '../game/public-deal-obligations';
const seats: PublicDealSeat[] = [{id:'a'}, {id:'b'}, {id:'c'}];
const term = (payer: string, recipient: string, amount: number, dueTurn: number) =>
({kind:'deferredBribe' as const, payer, recipient, amount, dueTurn});
function offered() {
const initial = createMultipartyPublicDeal(seats,'a',['b','c'],'Multiple payments',2,'deal',term('a','b',1,2));
const terms = [term('a','b',2,2), term('a','b',2,2), term('b','c',3,3)];
const next = setPublicDealAdditionalPayments(initial,terms,seats);
terms[0].amount = 99;
assert.equal(next.additionalPayments![0].payment.amount,2, 'Signed terms cannot alias caller objects.');
return next;
}
function active() {
const first = respondPublicDeal(offered(),seats,'b',true);
assert.equal(first.status,'offered');
assert.deepEqual(first.additionalPayments!.map(row => row.paymentStatus),[undefined,undefined,undefined]);
return respondPublicDeal(first,seats,'c',true);
}
void test('distinct indexed payment terms bind only after unanimous consent and preserve legacy terms', () => {
const game = active();
assert.equal(game.paymentStatus,'pending');
assert.deepEqual(game.additionalPayments!.map(row => row.paymentStatus),['pending','pending','pending']);
assert.deepEqual(publicDealDeferredTerms(game).map(row => row.paymentIndex),[undefined,0,1,2]);
assert.deepEqual(pendingPublicDealPayments([game],'a',2).map(row => [row.paymentIndex,row.amount]),
[[undefined,1],[0,2],[1,2]]);
assert.equal(publicDealPaymentTotal([game],'a',2),5);
assert.equal(publicDealPaymentTotal([game],'b',2),0);
assert.deepEqual(outstandingPublicDealPayments([game],'b',2).map(row => [row.paymentIndex,row.dueTurn]),[[2,3]]);
assert.equal(publicDealPaymentOptionKey('deal'),'deal');
assert.equal(publicDealPaymentOptionKey('deal',0),'deal:payment:0');
assert.notEqual(publicDealPaymentOptionKey('deal',0),publicDealPaymentOptionKey('deal',1));
assert.deepEqual(JSON.parse(JSON.stringify(game)),game);
validatePublicDeals([game],seats);
});
void test('only the original payer can pay an exact term once; void and release affect each term independently', () => {
const original = active(), before = structuredClone(original);
for (const index of [-1,3,1.5,Number.NaN])
assert.throws(() => markPublicDealPaid(original,seats,'a',index),PublicDealError);
assert.throws(() => markPublicDealPaid(original,seats,'b',0),PublicDealError);
let game = markPublicDealPaid(original,seats,'a',1);
assert.deepEqual(game.additionalPayments!.map(row => row.paymentStatus),['pending','paid','pending']);
assert.throws(() => markPublicDealPaid(game,seats,'a',1),PublicDealError);
game = voidPublicDealPayment(game,seats,0);
assert.deepEqual(game.additionalPayments!.map(row => row.paymentStatus),['void','paid','pending']);
assert.throws(() => voidPublicDealPayment(game,seats,0),PublicDealError);
assert.throws(() => markPublicDealPaid(game,seats,'a',0),PublicDealError);
assert.equal(game.paymentStatus,'pending');
for (const actor of ['a','b','c']) game = releasePublicDeal(game,seats,actor,true);
assert.equal(game.status,'released');
assert.equal(game.paymentStatus,'released');
assert.deepEqual(game.additionalPayments!.map(row => row.paymentStatus),['released','paid','released']);
validatePublicDeals([game],seats);
assert.deepEqual(original,before, 'Failed attempts and later transitions preserve original records.');
});
void test('malformed additional arrays, term packets and lifecycle states are rejected', () => {
const initial = createPublicDeal(seats,'a','b','Terms',2,'deal');
for (const terms of [[],Array.from({length:13},() => term('a','b',1,2)),[term('a','c',1,2)],
[term('a','b',0,2)],[term('a','b',1,1)],[{kind:'immediateBribe',payer:'a',recipient:'b',amount:1}]])
assert.throws(() => setPublicDealAdditionalPayments(initial,terms,seats),PublicDealError);
const offer = setPublicDealAdditionalPayments(initial,[term('a','b',2,2)],seats);
const accepted = respondPublicDeal(offer,seats,'b',true);
const malformed = [
{...offer,additionalPayments:[]},
{...offer,additionalPayments:[{payment:term('a','b',2,2),paymentStatus:'pending'}]},
{...accepted,additionalPayments:[{payment:term('a','b',2,2)}]},
{...accepted,additionalPayments:[{payment:term('a','b',2,2),paymentStatus:'released'}]},
{...accepted,additionalPayments:[{payment:term('a','b',2,2),paymentStatus:'pending',extra:true}]},
{...accepted,additionalPayments:[{payment:{...term('a','b',2,2),extra:true},paymentStatus:'pending'}]},
];
for (const game of malformed) assert.throws(() => validatePublicDeals([game],seats),PublicDealError);
assert.throws(() => setPublicDealAdditionalPayments(accepted,[term('a','b',1,2)],seats),PublicDealError);
assert.throws(() => setPublicDealAdditionalPayments(offer,[term('a','b',1,2)],seats),PublicDealError);
validatePublicDeals([offer, {...accepted,id:'active'}],seats);
});
void test('older single deferred payment saves and no-payment deals retain exact legacy shape', () => {
const payment = term('a','b',4,3);
const legacy: PublicDeal = respondPublicDeal(createPublicDeal(seats,'a','b','Legacy',3,'legacy',payment),seats,'b',true);
const before = JSON.stringify(legacy);
assert.deepEqual(publicDealDeferredTerms(legacy),[{payment,paymentStatus:'pending'}]);
assert.deepEqual(outstandingPublicDealPayments([legacy],'a',3),
[{deal:'legacy',payer:'a',recipient:'b',dueTurn:3,amount:4}]);
assert.equal(JSON.stringify(legacy),before);
assert.equal(markPublicDealPaid(legacy,seats,'a').paymentStatus,'paid');
const empty = createPublicDeal(seats,'a','b','No payment',2,'empty');
assert.deepEqual(publicDealDeferredTerms(empty),[]);
assert.equal(Object.hasOwn(empty,'additionalPayments'),false);
});
@@ -0,0 +1,179 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { botActions } from '../game/bots';
import { viewGame, type Action, type Game } from '../game/engine';
import type { PublicDeal } from '../game/public-deals';
import {
actMentatBribe as act, createMentatBribeFixture as fixture,
mentatBribeInventory as inventory, mentatBribePlayer as player,
} from './fixture-mentat-bribes';
import {
actTruthTravel, createTruthTravelFixture, settleTruthTravel,
truthTravelInventory, truthTravelPlayer,
} from './fixture-truth-travel';
type Deferred = { kind:'deferredBribe'; payer:string; recipient:string; amount:number; dueTurn:number };
type Line = { payment:Deferred; paymentStatus?:'pending'|'paid'|'void'|'released' };
type MultiDeal = PublicDeal & { additionalPayments?:Line[] };
const term = (payer:string, recipient:string, amount:number, dueTurn:number): Deferred =>
({kind:'deferredBribe',payer,recipient,amount,dueTurn});
const key = (deal:string, index:number) => `${deal}:payment:${index}`;
function deal(game: Game, id: string): MultiDeal {
const found = game.deals?.find(row => row.id === id); assert.ok(found); return found as MultiDeal;
}
function reject(game: Game, actor: string, action: Action) {
const before = structuredClone(game);
assert.throws(() => act(game,actor,action));
assert.deepEqual(game,before,'Rejected actions leave the original state unchanged');
}
function offer(game: Game, from: string, to: string, additionalPayments: Deferred[], payment?: object) {
game = act(game,from,{type:'dealOffer',target:to,terms:'Pay the agreed separate amounts.',additionalPayments,
...(payment ? {payment} : {})});
const id = game.deals?.at(-1)?.id; assert.ok(id);
return {game,id};
}
const accept = (game: Game, actor:string, id:string) => act(game,actor,{type:'dealRespond',deal:id,accept:true});
const pay = (game: Game, actor:string, id:string, paymentIndex:number) =>
act(game,actor,{type:'dealPay',deal:id,paymentIndex});
/** Public Basic H/A/E start, real auction and first Mentat. The inherited
* fixture orders only unopened original cards and Spice; no purse or deal is
* fabricated. Every term's consent and transfer uses native player actions. */
void test('identical deferred terms have separate indices and each exact payment settles once', () => {
const f = fixture(), start = f.game, original = inventory(start);
const terms = [term(f.target,f.asker,3,start.turn),term(f.target,f.asker,3,start.turn)];
const proposed = offer(start,f.asker,f.target,terms);
assert.deepEqual(deal(proposed.game,proposed.id).additionalPayments?.map(line => line.payment),terms);
assert.equal(player(proposed.game,f.target).spice,10);
let game = accept(proposed.game,f.target,proposed.id);
assert.deepEqual(deal(game,proposed.id).additionalPayments?.map(line => line.paymentStatus),['pending','pending']);
assert.equal(viewGame(game,f.target).deferredDealPaymentOptions[key(proposed.id,0)]?.blocked,null);
assert.equal(viewGame(game,f.target).deferredDealPaymentOptions[key(proposed.id,1)]?.blocked,null);
reject(game,f.asker,{type:'dealPay',deal:proposed.id,paymentIndex:0});
reject(game,f.target,{type:'dealPay',deal:proposed.id,paymentIndex:2});
reject(game,f.target,{type:'dealPay',deal:proposed.id});
game = pay(game,f.target,proposed.id,1);
assert.deepEqual(deal(game,proposed.id).additionalPayments?.map(line => line.paymentStatus),['pending','paid']);
assert.equal(player(game,f.target).spice,7); assert.equal(player(game,f.asker).bribes,3);
reject(game,f.target,{type:'dealPay',deal:proposed.id,paymentIndex:1});
game = pay(game,f.target,proposed.id,0);
assert.deepEqual(deal(game,proposed.id).additionalPayments?.map(line => line.paymentStatus),['paid','paid']);
assert.equal(player(game,f.target).spice,4); assert.equal(player(game,f.asker).bribes,6);
assert.deepEqual(inventory(game),original);
});
void test('final consent rolls back when separate due terms overcommit the same purse', () => {
const f = fixture(), terms = [term(f.target,f.asker,6,f.game.turn),term(f.target,f.asker,5,f.game.turn)];
const proposed = offer(f.game,f.asker,f.target,terms), before = structuredClone(proposed.game);
reject(proposed.game,f.target,{type:'dealRespond',deal:proposed.id,accept:true});
assert.deepEqual(proposed.game,before);
assert.equal(deal(proposed.game,proposed.id).status,'offered');
assert.deepEqual(deal(proposed.game,proposed.id).additionalPayments?.map(line => line.paymentStatus),[undefined,undefined]);
assert.equal(player(proposed.game,f.target).spice,10);
assert.deepEqual(inventory(proposed.game),f.originalCards);
});
void test('current and future terms reserve only the current due amount and keep distinct payment receipts', () => {
const f = fixture(), due = f.game.turn;
const proposed = offer(f.game,f.asker,f.target,[term(f.target,f.asker,3,due),term(f.target,f.asker,8,due+1)]);
let game = accept(proposed.game,f.target,proposed.id);
assert.equal(viewGame(game,f.target).deferredDealPaymentOptions[key(proposed.id,0)]?.blocked,null);
assert.ok(viewGame(game,f.target).deferredDealPaymentOptions[key(proposed.id,1)]?.blocked);
reject(game,f.target,{type:'dealPay',deal:proposed.id,paymentIndex:1});
game = pay(game,f.target,proposed.id,0);
assert.equal(player(game,f.target).spice,7);
assert.deepEqual(deal(game,proposed.id).additionalPayments?.map(line => line.paymentStatus),['paid','pending']);
assert.deepEqual(inventory(game),f.originalCards);
});
void test('unanimous release cancels only unpaid terms and does not refund paid spice', () => {
const f = fixture(), proposed = offer(f.game,f.asker,f.target,
[term(f.target,f.asker,2,f.game.turn),term(f.target,f.asker,3,f.game.turn)]);
let game = accept(proposed.game,f.target,proposed.id);
game = pay(game,f.target,proposed.id,0);
game = act(game,f.asker,{type:'dealRelease',deal:proposed.id,agree:true});
assert.equal(deal(game,proposed.id).status,'active');
game = act(game,f.target,{type:'dealRelease',deal:proposed.id,agree:true});
assert.equal(deal(game,proposed.id).status,'released');
assert.deepEqual(deal(game,proposed.id).additionalPayments?.map(line => line.paymentStatus),['paid','released']);
assert.equal(player(game,f.target).spice,8); assert.equal(player(game,f.asker).bribes,2);
reject(game,f.target,{type:'dealPay',deal:proposed.id,paymentIndex:1});
assert.deepEqual(inventory(game),f.originalCards);
});
void test('a group can accept distinct payer terms without settling before all consent', () => {
const f = fixture(), start = f.game;
assert.ok(player(start,f.opponent).spice >= 1);
const terms = [term(f.target,f.asker,2,start.turn),term(f.opponent,f.asker,1,start.turn)];
let game = act(start,f.asker,{type:'dealOffer',targets:[f.target,f.opponent],terms:'Both pay agreed spice.',additionalPayments:terms});
const id = game.deals?.at(-1)?.id; assert.ok(id);
game = accept(game,f.target,id);
assert.equal(deal(game,id).status,'offered');
assert.equal(player(game,f.target).spice,player(start,f.target).spice);
game = accept(game,f.opponent,id);
assert.equal(deal(game,id).status,'active');
reject(game,f.target,{type:'dealPay',deal:id,paymentIndex:1});
game = pay(game,f.opponent,id,1);
game = pay(game,f.target,id,0);
assert.equal(player(game,f.asker).bribes,3);
assert.deepEqual(deal(game,id).additionalPayments?.map(line => line.paymentStatus),['paid','paid']);
assert.deepEqual(inventory(game),f.originalCards);
});
void test('the original immediate payment and extra deferred payments use separate native transfers', () => {
const f = fixture(), start = f.game;
const immediate = {kind:'immediateBribe',payer:f.target,recipient:f.asker,amount:2};
const proposed = offer(start,f.asker,f.target,[term(f.target,f.asker,3,start.turn)],immediate);
assert.equal(player(proposed.game,f.target).spice,10);
let game = accept(proposed.game,f.target,proposed.id);
assert.equal(player(game,f.target).spice,8); assert.equal(player(game,f.asker).bribes,2);
assert.equal(deal(game,proposed.id).additionalPayments?.[0].paymentStatus,'pending');
game = pay(game,f.target,proposed.id,0);
assert.equal(player(game,f.target).spice,5); assert.equal(player(game,f.asker).bribes,5);
assert.equal(deal(game,proposed.id).additionalPayments?.[0].paymentStatus,'paid');
assert.deepEqual(inventory(game),f.originalCards);
});
void test('autopilot uses a legal indexed action for each payment that is due', () => {
const f = fixture(), proposed = offer(f.game,f.asker,f.target,
[term(f.target,f.asker,2,f.game.turn),term(f.target,f.asker,3,f.game.turn)]);
let game = accept(proposed.game,f.target,proposed.id);
game = act(game,f.target,{type:'setAutopilot',difficulty:'Easy'});
for (let count = 0; count < 2; count++) {
const action = botActions(viewGame(game,f.target))[0]; assert.ok(action);
assert.equal(action.type,'dealPay'); assert.equal(action.deal,proposed.id);
assert.ok(action.paymentIndex === 0 || action.paymentIndex === 1);
game = act(game,f.target,action);
}
assert.deepEqual(deal(game,proposed.id).additionalPayments?.map(line => line.paymentStatus),['paid','paid']);
assert.equal(player(game,f.target).spice,5); assert.equal(player(game,f.asker).bribes,5);
assert.deepEqual(inventory(game),f.originalCards);
});
void test('multiple deferred payments can accompany an actual current-turn shipment', () => {
const f = createTruthTravelFixture(), initial = f.game, original = truthTravelInventory(initial);
const terms = [term(f.target,f.asker,1,initial.turn),term(f.target,f.asker,1,initial.turn)];
let game = actTruthTravel(initial,f.asker,{type:'dealOffer',target:f.target,terms:'Two payments and a shipment.',
additionalPayments:terms,travel:{kind:'ship',territory:f.shipmentTerritory,minimum:1,answer:true}});
const id = game.deals?.at(-1)?.id; assert.ok(id);
game = actTruthTravel(game,f.target,{type:'dealRespond',deal:id,accept:true});
assert.equal(viewGame(game,f.target).dealTravelStatus[id],'pending');
game = actTruthTravel(game,f.target,{type:'dealPay',deal:id,paymentIndex:0});
game = settleTruthTravel(actTruthTravel(game,f.target,f.shipmentAction));
game = actTruthTravel(game,f.target,{type:'dealPay',deal:id,paymentIndex:1});
assert.equal(viewGame(game,f.target).dealTravelStatus[id],'fulfilled');
assert.deepEqual(deal(game,id).additionalPayments?.map(line => line.paymentStatus),['paid','paid']);
assert.equal(truthTravelPlayer(game,f.target).forces['polar_sink:0'],1);
assert.deepEqual(truthTravelInventory(game),original);
});
void test('malformed additional payment packets are rejected without opening a deal', () => {
const f = fixture(), due = f.game.turn, valid = term(f.target,f.asker,1,due);
const packet = {type:'dealOffer',target:f.target,terms:'Invalid payment terms.'};
for (const additionalPayments of [
[{...valid,amount:0}], [{...valid,payer:f.asker,recipient:f.asker}],
[{...valid,dueTurn:due-1}], [{...valid,kind:'immediateBribe'}],
[{...valid,extra:true}], Array.from({length:13},() => valid),
]) reject(f.game,f.asker,{...packet,additionalPayments});
});