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

+57 -5
View File
@@ -19,6 +19,7 @@ type TravelProjection = GameView & { dealTravelStatus?: Record<string, DealTrave
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 AdditionalImmediateDraft = { key: number; payer: string; recipient: string; amount: string };
type DeferredPaymentProjection = GameView & {
deferredDealPaymentOptions?: Record<string, { blocked: string | null }>;
};
@@ -64,7 +65,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, additionalPayments?: readonly DeferredBribe[]): Action | null {
export function publicDealOfferAction(targets: readonly string[], terms: string, payment?: DealPayment, proposer?: string, currentTurn?: number, travel?: DealTravel, additionalPayments?: readonly DeferredBribe[], additionalImmediatePayments?: readonly ImmediateBribe[]): 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 ||
@@ -77,6 +78,10 @@ export function publicDealOfferAction(targets: readonly string[], terms: string,
![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;
if (additionalImmediatePayments && (additionalImmediatePayments.length > 12 || additionalImmediatePayments.some(term =>
!proposer || term.kind !== 'immediateBribe' || term.payer === term.recipient ||
![proposer, ...targets].includes(term.payer) || ![proposer, ...targets].includes(term.recipient) ||
!Number.isSafeInteger(term.amount) || term.amount < 1))) 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;
@@ -93,12 +98,15 @@ export function publicDealOfferAction(targets: readonly string[], terms: string,
const offeredAdditional = additionalPayments?.length
? { additionalPayments: additionalPayments.map(term => ({kind:term.kind, payer:term.payer,
recipient:term.recipient, amount:term.amount, dueTurn:term.dueTurn})) } : {};
const offeredImmediate = additionalImmediatePayments?.length
? { additionalImmediatePayments: additionalImmediatePayments.map(term => ({kind:term.kind, payer:term.payer,
recipient:term.recipient, amount:term.amount})) } : {};
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, ...offeredAdditional, ...offeredTravel }
: { type: 'dealOffer', targets: [...targets], terms: text, ...offeredPayment, ...offeredAdditional, ...offeredTravel };
? { type: 'dealOffer', target: targets[0], terms: text, ...offeredPayment, ...offeredAdditional, ...offeredImmediate, ...offeredTravel }
: { type: 'dealOffer', targets: [...targets], terms: text, ...offeredPayment, ...offeredAdditional, ...offeredImmediate, ...offeredTravel };
}
/** The whole table can read an offer and its history; only its parties act. */
@@ -127,6 +135,7 @@ export function PublicDealList({ game, act, disabled }: {
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 additionalImmediate = (deal as unknown as { additionalImmediatePayments?: ImmediateBribe[] }).additionalImmediatePayments ?? [];
const travel = (deal as TravelDeal).travel;
const travelActor = travel ? publicDealTravelActor(deal) : undefined;
const travelStatus = (game as TravelProjection).dealTravelStatus?.[deal.id];
@@ -136,7 +145,8 @@ export function PublicDealList({ game, act, disabled }: {
const finalAcceptance = recipient && !accepted.includes(game.me) && accepted.length === participants.length - 1;
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 paymentBlocked = finalAcceptance && (payment?.kind === 'immediateBribe' && payment.payer === game.me ||
additionalImmediate.some(term => term.payer === game.me)) ? game.bribeOptions?.blocked : null;
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];
@@ -146,6 +156,7 @@ export function PublicDealList({ game, act, disabled }: {
<p><strong>{name(deal.from)} → {participants.filter(id => id !== deal.from).map(name).join(', ')}</strong> · Turn {deal.turn} · {deal.status}</p>
<p>{deal.terms}</p>
{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>}
{additionalImmediate.map((term, index) => <p key={`immediate-${index}`}><strong>Additional immediate payment {index + 1}:</strong> {name(term.payer)} pays {term.amount} spice to {name(term.recipient)} on final acceptance. The recipient collects their share at the next Mentat opening; a Bureaucrat may redirect two spice to the bank.</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) => {
@@ -214,6 +225,8 @@ export function PublicDeals({ game, act, busy }: {
const [paymentAmount, setPaymentAmount] = useState('1');
const [additionalDrafts, setAdditionalDrafts] = useState<AdditionalPaymentDraft[]>([]);
const nextAdditionalKey = useRef(0);
const [additionalImmediateDrafts, setAdditionalImmediateDrafts] = useState<AdditionalImmediateDraft[]>([]);
const nextAdditionalImmediateKey = 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);
@@ -255,6 +268,9 @@ export function PublicDeals({ game, act, busy }: {
kind:'deferredBribe', payer:draft.payer, recipient:draft.recipient,
amount:Number(draft.amount), dueTurn:Number(draft.dueTurn),
}));
const additionalImmediatePayments: ImmediateBribe[] = additionalImmediateDrafts.map(draft => ({
kind:'immediateBribe', payer:draft.payer, recipient:draft.recipient, amount:Number(draft.amount),
}));
const travelTurn = Number(travelDueTurn);
const travelDueValid = travelDueTurn.trim() !== '' && Number.isSafeInteger(travelTurn) && travelTurn >= game.turn;
const travel: DealTravel | undefined = includeTravel ? {kind:travelKind, territory:travelTerritory,
@@ -262,7 +278,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, additionalPayments) : null;
? publicDealOfferAction(selected, terms, payment, me?.id, game.turn, travel, additionalPayments, additionalImmediatePayments) : 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">
@@ -332,6 +348,42 @@ 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>}
{additionalImmediateDrafts.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;
const update = (change: Partial<AdditionalImmediateDraft>) => setAdditionalImmediateDrafts(current =>
current.map(row => row.key === draft.key ? {...row,...change} : row));
return <fieldset key={draft.key}>
<legend>Additional immediate 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>
{legalSelection && !valid && <p>Choose two different participants and a positive whole spice amount.</p>}
<Button type="button" variant="outline" disabled={disabled}
onClick={() => setAdditionalImmediateDrafts(current => current.filter(row => row.key !== draft.key))}>Remove immediate payment {index + 1}</Button>
</fieldset>;
})}
<Button type="button" variant="outline" disabled={disabled || additionalImmediateDrafts.length >= 12 || selected.length === 0}
onClick={() => {
const key = nextAdditionalImmediateKey.current++;
setAdditionalImmediateDrafts(current => [...current, {key,payer:'',recipient:'',amount:'1'}]);
}}>Add immediate payment</Button>
{additionalImmediateDrafts.length > 0 && <p className="fine">Immediate payments are processed on final acceptance. A qualifying Bureaucrat may respond to each payment.</p>}
{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)) &&
+8
View File
@@ -17,6 +17,14 @@ open mode gates.
## Current checkpoint and work
**Multiple immediate deal payments — 16 November. Prototyped / Partial.**
Final consent preflights the complete ordered sequence; native Bureaucrat
decisions can pause it and a validated saved frame resumes the original remaining
payments. Forty-six related offline files pass 316 cases; the new authenticated
HTTP case, type checking, lint and production build pass. A staged recovery fixture now uses its
deterministic auction clock. Wider interactions and deployed acceptance remain
open. [Scope](PUBLIC_DEALS.md#multiple-immediate-payments--16-november-2026).
**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
+27
View File
@@ -1,5 +1,32 @@
# Public deal records
## Multiple immediate payments — 16 November 2026
**Prototyped / Partial.** A public offer may include up to twelve additional
immediate bribes, alongside its existing payment, deferred terms and supported
travel. Final consent first checks every original payment and both choices at
each possible Bureaucrat interruption against the native rules and due
commitments. If the sequence cannot be completed, consent and all payments
remain unchanged. Otherwise the original payment settles first, followed by
the additional payments in their listed order.
Each transfer uses the native bribe action. A qualifying Bureaucrat decision
pauses the sequence with a server-owned frame tied to the immutable deal and
the exact payment; after its choice the remaining payments resume once. The
completed receipt retains the original terms across later release. A payer's
spice and a recipient's separate Mentat bribe account keep their ordinary
timing. This bounded online settlement is a prototype, not a publisher limit
on the number of agreements or payments.
Evidence: [public gameplay](../tests/public-deals-multiple-immediate.test.ts),
[Bureaucrat continuation](../tests/public-deals-multiple-immediate-bureaucrat.test.ts),
[offer controls](../tests/public-deals-multiple-immediate-controls.test.tsx),
and the [authenticated boundary](../tests/public-deals-multiple-immediate-http.test.ts).
The Bureaucrat fixture uses genuine Skills setup and a labelled staged runtime
position. Wider interactions, full-game acceptance and deployed verification
remain open. This section supersedes the earlier immediate-payment boundary
recorded below.
## Multiple deferred payments — 16 November 2026
**Prototyped / Partial.** A two-party or group offer can include up to twelve
+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.',
],
+10 -5
View File
@@ -2,7 +2,7 @@ import assert from 'node:assert/strict';
import { createHash } from 'node:crypto';
import type { DatabaseSync } from 'node:sqlite';
import test from 'node:test';
import { applyAction, viewGame, type Game } from '../game/engine';
import { applyAction, synchronizeAuctionClock, viewGame, type Game } from '../game/engine';
import type * as Rooms from '../db/rooms';
import { unitStore } from './fixture-nexus-room-store';
import {
@@ -87,6 +87,11 @@ async function fixture(
allow: true,
});
assert.equal(game.decision?.kind, 'bureaucratPayment');
// Store the same paused native clock that an authenticated room read would
// initialize; the fixture is testing the payment continuation, not migration
// from an unclocked staged auction.
game = synchronizeAuctionClock(game, clock.now(), '0:0');
assert.equal(game.decision?.kind, 'bureaucratPayment');
game.version = 41;
const code = game.code,
event = game.decision!.event!;
@@ -126,8 +131,8 @@ async function views(f: Awaited<ReturnType<typeof fixture>>, game: Game) {
room = f.restart();
for (const player of game.players) {
const auth = await room.authenticate(f.code, f.tokens[player.id]);
const view = await room.readSeatView(f.code, auth);
assert.deepEqual(view, viewGame(game, player.id));
const view = await room.readSeatView(f.code, auth, clock);
assert.deepEqual(view, viewGame(game, player.id, clock.now()));
assert.equal('bureaucratPayments' in view, false);
assert.equal('bureaucratUseEvents' in view, false);
for (const rival of view.players.filter((p) => p.id !== player.id)) {
@@ -341,10 +346,10 @@ void test('saved normal, Richese cache and Black Market payments resume card cus
assert.ok(!JSON.stringify(viewGame(after, 'g')).includes(purchased));
const saved = rows(f.sqlite);
await assert.rejects(
f.restart().act(f.code, f.auths.b, 41, action),
f.restart().act(f.code, f.auths.b, 41, action, clock),
/table changed/,
);
await assert.rejects(f.restart().act(f.code, f.auths.b, 42, action));
await assert.rejects(f.restart().act(f.code, f.auths.b, 42, action, clock));
assert.deepEqual(rows(f.sqlite), saved);
assert.deepEqual(
f.writes.map((write) => write.changes),
@@ -0,0 +1,80 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { applyAction, normalizeAutomaticGame, viewGame, type Action, type Game } from '../game/engine';
import { bureaucratPaymentGame, bureaucratPlayer as player, bureaucratReload } from './bureaucrat-payment-fixture';
const payment = (amount: number) => ({ kind:'immediateBribe', payer:'p', recipient:'e', amount } as const);
function reject(game: Game, actor: string, action: Action) {
const before = structuredClone(game);
assert.throws(() => applyAction(game,actor,action));
assert.deepEqual(game,before,'Rejected actions cannot change the saved settlement.');
}
/** The shared fixture uses genuine Leader Skills setup, then stages a conserved
* quiet position and balances. All deal consent, native bribes, Bureaucrat
* decisions and continuation below use real actions. */
for (const trigger of ['first','second'] as const) for (const redirect of [false,true]) {
void test(`multiple immediate payments resume after the ${trigger} Bureaucrat opportunity (${redirect ? 'redirect' : 'pass'})`, () => {
const initial = bureaucratPaymentGame(), first = trigger === 'first' ? 5 : 1;
const second = trigger === 'second' ? 5 : 1;
let game = applyAction(initial,'p',{type:'dealOffer',target:'e',terms:'Two immediate bribes.',
payment:payment(first),additionalImmediatePayments:[payment(second)]});
const id = game.deals?.at(-1)?.id; assert.ok(id);
assert.equal(player(game,'p').spice,30); assert.equal(player(game,'e').bribes,0);
game = applyAction(game,'e',{type:'dealRespond',deal:id,accept:true});
assert.equal(game.deals?.find(deal => deal.id === id)?.status,'active');
assert.equal(game.decision?.kind,'bureaucratPayment');
const event = game.bureaucratPaymentEvent; assert.ok(event);
assert.equal(player(game,'p').spice,trigger === 'first' ? 25 : 24);
assert.equal(player(game,'e').bribes,trigger === 'first' ? 0 : 1);
assert.equal(viewGame(game,'b').bureaucrat.pending?.event,event);
reject(game,'p',{type:'bribe',target:'e',amount:1});
reject(game,'e',{type:'dealRelease',deal:id,agree:true});
const saved = bureaucratReload(game);
assert.deepEqual(viewGame(saved,'b').bureaucrat.pending,viewGame(game,'b').bureaucrat.pending);
assert.equal(normalizeAutomaticGame(saved).bureaucratPaymentEvent,event);
game = applyAction(saved,'b',{type:'decision',event,redirect});
assert.equal(game.bureaucratPayments?.pending,undefined);
assert.equal(player(game,'p').spice,24,'Both original gross payments are debited exactly once.');
assert.equal(player(game,'e').bribes,redirect ? 4 : 6,'Only the native redirect is withheld.');
assert.equal(viewGame(game,'b').bureaucrat.usedThisPhase,redirect);
reject(game,'b',{type:'decision',event,redirect});
reject(game,'e',{type:'dealRespond',deal:id,accept:true});
assert.equal(player(game,'p').spice,24);
assert.equal(player(game,'e').bribes,redirect ? 4 : 6);
});
}
void test('passing the first Bureaucrat opportunity preserves the second distinct payment and its decision', () => {
let game = applyAction(bureaucratPaymentGame(),'p',{type:'dealOffer',target:'e',terms:'Two five-spice bribes.',
payment:payment(5),additionalImmediatePayments:[payment(5)]});
const id = game.deals?.at(-1)?.id; assert.ok(id);
game = applyAction(game,'e',{type:'dealRespond',deal:id,accept:true});
const first = game.bureaucratPaymentEvent; assert.ok(first);
assert.equal(player(game,'p').spice,25); assert.equal(player(game,'e').bribes,0);
const forgedCursor = bureaucratReload(game);
assert.ok(forgedCursor.pendingPublicDealSettlement);
forgedCursor.pendingPublicDealSettlement.next = 2;
reject(forgedCursor,'b',{type:'decision',event:first,redirect:false});
const forgedTerms = bureaucratReload(game);
forgedTerms.deals!.find(deal => deal.id === id)!.additionalImmediatePayments![0].amount = 6;
reject(forgedTerms,'b',{type:'decision',event:first,redirect:false});
game = applyAction(bureaucratReload(game),'b',{type:'decision',event:first,redirect:false});
const second = game.bureaucratPaymentEvent; assert.ok(second); assert.notEqual(second,first);
assert.equal(game.decision?.kind,'bureaucratPayment');
assert.equal(player(game,'p').spice,20); assert.equal(player(game,'e').bribes,5);
assert.equal(viewGame(game,'b').bureaucrat.usedThisPhase,false);
reject(game,'b',{type:'decision',event:first,redirect:true});
reject(game,'e',{type:'dealRelease',deal:id,agree:true});
game = applyAction(bureaucratReload(game),'b',{type:'decision',event:second,redirect:true});
assert.equal(game.bureaucratPayments?.pending,undefined);
assert.equal(player(game,'p').spice,20); assert.equal(player(game,'e').bribes,8);
assert.equal(viewGame(game,'b').bureaucrat.usedThisPhase,true);
reject(game,'b',{type:'decision',event:second,redirect:true});
reject(game,'e',{type:'dealRespond',deal:id,accept:true});
assert.equal(player(game,'p').spice,20); assert.equal(player(game,'e').bribes,8);
});
@@ -0,0 +1,117 @@
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 } 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:'immediateBribe' as const,payer:'a',recipient:'b',amount:2};
const second = {kind:'immediateBribe' as const,payer:'b',recipient:'a',amount:3};
const deferred = {kind:'deferredBribe' as const,payer:'a',recipient:'b',amount:1,dueTurn:3};
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:[],deferredDealPaymentOptions:{}} as unknown as GameView;
void test('offer helper retains each immediate term alongside deferred and travel terms', () => {
const travel = {kind:'ship' as const,territory:'carthag',minimum:1,answer:true};
assert.deepEqual(publicDealOfferAction(['b'],' Terms ',first,'a',2,travel,[deferred],[second]),
{type:'dealOffer',target:'b',terms:'Terms',payment:first,travel,
additionalPayments:[deferred],additionalImmediatePayments:[second]});
assert.deepEqual(publicDealOfferAction(['b'],'Terms',undefined,'a',2,undefined,[],[first,second]),
{type:'dealOffer',target:'b',terms:'Terms',additionalImmediatePayments:[first,second]});
for (const terms of [[{...first,payer:'outsider'}],[{...first,recipient:'a'}],
[{...first,amount:0}],Array.from({length:13},() => first)])
assert.equal(publicDealOfferAction(['b'],'Terms',undefined,'a',2,undefined,[],terms),null);
});
void test('the offer displays all immediate terms to every participant', () => {
const deal = {id:'deal',from:'a',to:'b',terms:'Two immediate payments.',turn:2,status:'offered',releaseVotes:[],
additionalImmediatePayments:[first,second]};
for (const viewer of ['a','b']) {
const game = {...base,me:viewer,deals:[deal]} as unknown as GameView;
const html = renderToStaticMarkup(createElement(PublicDealList,{game,disabled:false,act() {}}));
assert.match(html,/Additional immediate payment 1/); assert.match(html,/Additional immediate payment 2/);
assert.match(html,/Alice \(Atreides\) pays 2 spice to Basil \(Harkonnen\)/);
assert.match(html,/Basil \(Harkonnen\) pays 3 spice to Alice \(Atreides\)/);
assert.match(html,/final acceptance/);
}
});
/** Exercise actual hook callbacks with a stateful React-compatible VM. This
* verifies the component controls, not a hydrated-browser session. */
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 render = () => {stateCursor = 0; refCursor = 0;
return elements(exported.PublicDeals!({game:base,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 immediate payment')));
assert.ok(sets[index]); return elements(sets[index]);
};
return {render,click,field,sent};
}
void test('authoring callbacks add, edit and remove immediate 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 immediate payment'); ui.click('Add immediate payment');
for (let index = 0; index < 2; index++) {
for (const [position,value] of [[0,index === 0 ? 'a' : 'b'],[1,index === 0 ? 'b' : 'a']] 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}});
}
const input = ui.field(index).find(node => node.type === 'input' && node.props.type === 'number'); assert.ok(input);
(input.props.onChange as (event:{target:{value:string}}) => void)({target:{value:String(index+2)}});
}
ui.click('Remove immediate 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 immediate payment'}});
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 immediate payment',
additionalImmediatePayments:[second]}]);
});
@@ -0,0 +1,65 @@
// @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}};
}
/** Create a fresh test room; do not use or remove pre-existing games. */
void test('authenticated final consent settles each immediate payment exactly once', async () => {
const host = await request('/api/rooms',undefined,{name:'Immediate 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:'Immediate 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 beforePayer = await request(path,payer.cookie), beforeRecipient = await request(path,host.cookie);
assert.equal(beforePayer.status,200); assert.equal(beforeRecipient.status,200); view = beforePayer.data;
const spice = beforePayer.data.players.find(player => player.id === payer.data.me)?.spice;
const incoming = beforeRecipient.data.bribeOptions.incoming;
assert.ok(typeof spice === 'number' && spice >= 5);
const terms = [2,3].map(amount => ({kind:'immediateBribe',payer:payer.data.me,recipient:host.data.me,amount}));
await act(host.cookie,{type:'dealOffer',target:payer.data.me,terms:'Pay two immediate amounts.',additionalImmediatePayments:terms});
const offered = view.deals.at(-1); assert.ok(offered);
assert.equal(offered.status,'offered'); assert.deepEqual(offered.additionalImmediatePayments,terms);
const acceptance = {type:'dealRespond',deal:offered.id,accept:true};
const wrongActor = await request(path,host.cookie,{version:view.version,action:acceptance});
assert.equal(wrongActor.status,409,JSON.stringify(wrongActor.data));
const forged = await request(path,host.cookie,{version:view.version,action:acceptance},payer.data.me);
assert.equal(forged.status,409,JSON.stringify(forged.data));
const beforeVersion = view.version;
await act(payer.cookie,acceptance);
assert.equal(view.deals.find(row => row.id === offered.id)?.status,'active');
const paidPayer = await request(path,payer.cookie), paidRecipient = await request(path,host.cookie);
assert.equal(paidPayer.status,200); assert.equal(paidRecipient.status,200);
assert.equal(paidPayer.data.players.find(player => player.id === payer.data.me)?.spice,spice-5);
assert.equal(paidRecipient.data.bribeOptions.incoming,incoming+5);
const stale = await request(path,payer.cookie,{version:beforeVersion,action:acceptance});
assert.equal(stale.status,409,JSON.stringify(stale.data));
const replay = await request(path,payer.cookie,{version:view.version,action:acceptance});
assert.equal(replay.status,409,JSON.stringify(replay.data));
assert.equal((await request(path,host.cookie)).data.bribeOptions.incoming,incoming+5);
});
@@ -0,0 +1,128 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { viewGame, type Action, type Game } from '../game/engine';
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';
const immediate = (payer: string, recipient: string, amount: number) =>
({kind:'immediateBribe', payer, recipient, amount} as const);
function reject(game: Game, actor: string, action: Action) {
const before = structuredClone(game);
assert.throws(() => act(game,actor,action));
assert.deepEqual(game,before,'Rejected consent or action leaves the original table untouched.');
}
/** Real public Basic H/A/E setup, auction and first Mentat. The inherited
* fixture orders unopened cards and Spice, without fabricating purses or
* commitments. Every offer and vote uses the normal public actions. */
void test('two immediate terms settle once at final consent in their stated order', () => {
const f = fixture(), original = f.game, originalCards = inventory(original);
const first = immediate(f.target,f.asker,2), second = immediate(f.target,f.asker,3);
const offered = act(original,f.asker,{type:'dealOffer',target:f.target,terms:'Two separate payments.',
payment:first,additionalImmediatePayments:[second]});
const id = offered.deals?.at(-1)?.id; assert.ok(id);
assert.equal(player(offered,f.target).spice,10);
assert.equal(player(offered,f.asker).bribes,0);
const logStart = offered.log.length;
let game = act(offered,f.target,{type:'dealRespond',deal:id,accept:true});
assert.equal(game.deals?.find(row => row.id === id)?.status,'active');
assert.equal(player(game,f.target).spice,5);
assert.equal(player(game,f.asker).bribes,5);
const payments = game.log.slice(logStart).map(row => row.text).filter(text => /paid a \d+-spice bribe/i.test(text));
assert.equal(payments.length,2);
assert.match(payments[0],/paid a 2-spice bribe/i);
assert.match(payments[1],/paid a 3-spice bribe/i);
reject(game,f.target,{type:'dealRespond',deal:id,accept:true});
game = act(game,f.asker,{type:'dealRelease',deal:id,agree:true});
game = act(game,f.target,{type:'dealRelease',deal:id,agree:true});
assert.equal(game.deals?.find(row => row.id === id)?.status,'released');
assert.equal(player(game,f.target).spice,5);
assert.equal(player(game,f.asker).bribes,5);
assert.deepEqual(inventory(game),originalCards);
});
void test('two additional immediate payments work without a legacy payment term', () => {
const f = fixture(), payments = [immediate(f.target,f.asker,2),immediate(f.target,f.asker,2)];
const offered = act(f.game,f.asker,{type:'dealOffer',target:f.target,terms:'Two matching payments.',
additionalImmediatePayments:payments});
const id = offered.deals?.at(-1)?.id; assert.ok(id);
const done = act(offered,f.target,{type:'dealRespond',deal:id,accept:true});
assert.equal(done.deals?.find(row => row.id === id)?.status,'active');
assert.equal(player(done,f.target).spice,6);
assert.equal(player(done,f.asker).bribes,4);
reject(done,f.target,{type:'dealRespond',deal:id,accept:true});
assert.deepEqual(inventory(done),f.originalCards);
});
void test('final consent atomically rejects two immediate terms that exceed the same purse', () => {
const f = fixture();
const offered = act(f.game,f.asker,{type:'dealOffer',target:f.target,terms:'An unfunded pair of payments.',
payment:immediate(f.target,f.asker,6),additionalImmediatePayments:[immediate(f.target,f.asker,5)]});
const id = offered.deals?.at(-1)?.id; assert.ok(id);
reject(offered,f.target,{type:'dealRespond',deal:id,accept:true});
assert.equal(offered.deals?.find(row => row.id === id)?.status,'offered');
assert.equal(player(offered,f.target).spice,10);
assert.equal(player(offered,f.asker).bribes,0);
assert.deepEqual(inventory(offered),f.originalCards);
});
void test('a group settles immediate terms from different payers only after all consent', () => {
const f = fixture(), start = f.game;
const targetBefore = player(start,f.target).spice, otherBefore = player(start,f.opponent).spice;
assert.ok(targetBefore >= 2 && otherBefore >= 1);
let game = act(start,f.asker,{type:'dealOffer',targets:[f.target,f.opponent],terms:'Two separate group payments.',
payment:immediate(f.target,f.asker,2),additionalImmediatePayments:[immediate(f.opponent,f.asker,1)]});
const id = game.deals?.at(-1)?.id; assert.ok(id);
game = act(game,f.target,{type:'dealRespond',deal:id,accept:true});
assert.equal(game.deals?.find(row => row.id === id)?.status,'offered');
assert.equal(player(game,f.target).spice,targetBefore);
assert.equal(player(game,f.opponent).spice,otherBefore);
assert.equal(player(game,f.asker).bribes,0);
game = act(game,f.opponent,{type:'dealRespond',deal:id,accept:true});
assert.equal(game.deals?.find(row => row.id === id)?.status,'active');
assert.equal(player(game,f.target).spice,targetBefore-2);
assert.equal(player(game,f.opponent).spice,otherBefore-1);
assert.equal(player(game,f.asker).bribes,3);
reject(game,f.opponent,{type:'dealRespond',deal:id,accept:true});
assert.deepEqual(inventory(game),f.originalCards);
});
void test('immediate payments, deferred payment and travel share actual resources', () => {
const f = createTruthTravelFixture(), initial = f.game, originalCards = truthTravelInventory(initial);
const cash = truthTravelPlayer(initial,f.target).spice, incoming = truthTravelPlayer(initial,f.asker).bribes;
assert.ok(cash >= f.shipmentCost+4);
let game = actTruthTravel(initial,f.asker,{type:'dealOffer',target:f.target,terms:'Pay and make the shipment.',
payment:immediate(f.target,f.asker,1),additionalImmediatePayments:[immediate(f.target,f.asker,2)],
additionalPayments:[{kind:'deferredBribe',payer:f.target,recipient:f.asker,amount:1,dueTurn:initial.turn}],
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(truthTravelPlayer(game,f.target).spice,cash-3);
assert.equal(truthTravelPlayer(game,f.asker).bribes,incoming+3);
assert.equal(viewGame(game,f.target).dealTravelStatus[id],'pending');
assert.equal(game.deals?.find(row => row.id === id)?.additionalPayments?.[0].paymentStatus,'pending');
game = settleTruthTravel(actTruthTravel(game,f.target,f.shipmentAction));
game = actTruthTravel(game,f.target,{type:'dealPay',deal:id,paymentIndex:0});
assert.equal(truthTravelPlayer(game,f.target).spice,cash-4-f.shipmentCost);
assert.equal(truthTravelPlayer(game,f.asker).bribes,incoming+4);
assert.equal(game.deals?.find(row => row.id === id)?.additionalPayments?.[0].paymentStatus,'paid');
assert.equal(viewGame(game,f.target).dealTravelStatus[id],'fulfilled');
assert.deepEqual(truthTravelInventory(game),originalCards);
});
void test('invalid additional immediate terms reject without creating a deal', () => {
const f = fixture(), good = immediate(f.target,f.asker,1);
const packet = {type:'dealOffer',target:f.target,terms:'Invalid payment.'};
for (const additionalImmediatePayments of [
[{...good,amount:0}], [{...good,payer:f.asker,recipient:f.asker}],
[{...good,payer:f.opponent}], [{...good,kind:'deferredBribe',dueTurn:f.game.turn}],
[{...good,extra:true}],
]) reject(f.game,f.asker,{...packet,additionalImmediatePayments});
});