Support deferred payments with travel deals
Verify and publish checkpoint container / container (push) Successful in 11m29s

This commit is contained in:
Quintine committed 2026-11-16 14:17:48 +11:00
1 parent 9536c77062
commit 5e294215be
16 files changed
+603 -100

No files matched your search

+4 -8
View File
@@ -69,10 +69,9 @@ export function publicDealOfferAction(targets: readonly string[], terms: string,
const travelKeys = travel ? Object.keys(travel).filter(key => key !== 'dueTurn').sort().join(',') : ''; const travelKeys = travel ? Object.keys(travel).filter(key => key !== 'dueTurn').sort().join(',') : '';
const travelDeadline = travel && Object.hasOwn(travel, 'dueTurn') ? travel.dueTurn : undefined; const travelDeadline = travel && Object.hasOwn(travel, 'dueTurn') ? travel.dueTurn : undefined;
if (travel && (!proposer || targets.includes(proposer) || if (travel && (!proposer || targets.includes(proposer) ||
(groupTravel ? !!payment && payment.kind !== 'immediateBribe' || travelKeys !== 'actor,answer,kind,minimum,territory' || (groupTravel ? travelKeys !== 'actor,answer,kind,minimum,territory' ||
typeof travel.actor !== 'string' || !targets.includes(travel.actor) : typeof travel.actor !== 'string' || !targets.includes(travel.actor) :
travelKeys !== 'answer,kind,minimum,territory' || travelKeys !== 'answer,kind,minimum,territory') ||
!!payment && payment.kind !== 'immediateBribe') ||
(Object.hasOwn(travel, 'dueTurn') && (!Number.isSafeInteger(travelDeadline) || (travelDeadline as number) < 1 || (Object.hasOwn(travel, 'dueTurn') && (!Number.isSafeInteger(travelDeadline) || (travelDeadline as number) < 1 ||
(currentTurn !== undefined && (!Number.isSafeInteger(currentTurn) || currentTurn < 1 || (travelDeadline as number) < currentTurn)))) || (currentTurn !== undefined && (!Number.isSafeInteger(currentTurn) || currentTurn < 1 || (travelDeadline as number) < currentTurn)))) ||
!['ship', 'move'].includes(travel.kind) || !TERRITORIES.some(territory => territory.id === travel.territory) || !['ship', 'move'].includes(travel.kind) || !TERRITORIES.some(territory => territory.id === travel.territory) ||
@@ -226,8 +225,6 @@ export function PublicDeals({ game, act, busy }: {
minimum:Number(travelMinimum), answer:travelAnswer, minimum:Number(travelMinimum), answer:travelAnswer,
...(selected.length > 1 ? {actor:travelActor} : {}), ...(selected.length > 1 ? {actor:travelActor} : {}),
...(travelTurn > game.turn ? {dueTurn:travelTurn} : {})} : undefined; ...(travelTurn > game.turn ? {dueTurn:travelTurn} : {})} : undefined;
const combinedPaymentValid = !includeTravel || !payment || payment.kind === 'immediateBribe' &&
paymentPeopleAndAmountValid;
const offer = legalSelection && paymentValid && (!includeTravel || travelDueValid) 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) : null;
const disabled = busy || !!game.roomControl?.paused || !!game.roomControl?.closed || !!me?.autopilot; const disabled = busy || !!game.roomControl?.paused || !!game.roomControl?.closed || !!me?.autopilot;
@@ -308,8 +305,7 @@ export function PublicDeals({ game, act, busy }: {
{includeTravel && <fieldset> {includeTravel && <fieldset>
<legend>Travel term</legend> <legend>Travel term</legend>
<p className="fine">This term concerns one physical action during the selected turn. The sole recipient commits to travel in a two-party deal. In a group deal, choose one recipient to commit; they accept last after all other recipients. Written terms remain player-managed.</p> <p className="fine">This term concerns one physical action during the selected turn. The sole recipient commits to travel in a two-party deal. In a group deal, choose one recipient to commit; they accept last after all other recipients. Written terms remain player-managed.</p>
<p className="fine">A travel term may include an immediate payment between two participants. The payment recipient collects their share at the next Mentat opening and can use it after collection. All invited parties accept before the traveler gives final consent.</p> <p className="fine">A travel term may include an immediate payment or a payment due by the end of a selected turn. Payment and travel may have different participants and turns. The payment recipient collects their share at the next Mentat opening and can use it after collection. All invited parties accept before the traveler gives final consent.</p>
{!combinedPaymentValid && <p role="alert">For travel, choose an immediate payment between two participants.</p>}
{selected.length > 1 && <label>Committed traveler {selected.length > 1 && <label>Committed traveler
<select value={selected.includes(travelActor) ? travelActor : ''} disabled={disabled} <select value={selected.includes(travelActor) ? travelActor : ''} disabled={disabled}
onChange={event => setTravelActor(event.target.value)}> onChange={event => setTravelActor(event.target.value)}>
@@ -317,7 +313,7 @@ export function PublicDeals({ game, act, busy }: {
{selectedPlayers.map(player => <option key={player.id} value={player.id}>{player.name} · {faction(player.faction).name}</option>)} {selectedPlayers.map(player => <option key={player.id} value={player.id}>{player.name} · {faction(player.faction).name}</option>)}
</select> </select>
</label>} </label>}
<p className="fine">This initial preview supports Basic games with classic factions and no expansions or optional modules. A current-turn term needs a quiet native window and a legal completion on final acceptance. A later-turn term reserves no forces or spice now. If the game finds no legal completion when the travel turn closes, it provisionally marks that term void.</p> <p className="fine">Travel terms are available in Basic games with classic factions and no expansions or optional modules. A current-turn term must be possible when accepted. A later-turn term reserves no forces or spice in advance; if no legal completion is found when the travel turn closes, the term may be marked void.</p>
<label>Travel action <label>Travel action
<select value={travelKind} disabled={disabled} onChange={event => setTravelKind(event.target.value === 'move' ? 'move' : 'ship')}> <select value={travelKind} disabled={disabled} onChange={event => setTravelKind(event.target.value === 'move' ? 'move' : 'ship')}>
<option value="ship">Reserve shipment</option> <option value="ship">Reserve shipment</option>
+10
View File
@@ -17,6 +17,16 @@ open mode gates.
## Current checkpoint and work ## Current checkpoint and work
**Public travel with deferred payment — 16 November. Prototyped / Partial.**
Two-party and group offers can pair a travel term with one deferred payment;
due-now acceptance checks a shared funded route, and participants can complete
the payment and travel in either order. Controls, release and scheduled terms
are connected. Bid/Revival bot guidance also retains its required bid. Thirty-one
related files pass 191 cases, the new authenticated HTTP case passes, and type
checking, lint and production build pass. Multiple payments in one offer, wider
rules/modules and deployed acceptance remain open.
[Scope](PUBLIC_DEALS.md#travel-with-a-deferred-payment--16-november-2026).
**Basic phase-bid, Revival and Shipment commitments — 16 November. Prototyped / **Basic phase-bid, Revival and Shipment commitments — 16 November. Prototyped /
Partial.** The owned-cash witness now composes supported leader and grouped Partial.** The owned-cash witness now composes supported leader and grouped
Revival with Shipment; planned returns use the same actual purse and physical Revival with Shipment; planned returns use the same actual purse and physical
+30
View File
@@ -1,5 +1,35 @@
# Public deal records # Public deal records
## Travel with a deferred payment — 16 November 2026
**Prototyped / Partial.** In supported Basic classic tables, a two-party or
group agreement can pair one structured travel term with one exact deferred
payment between participants. The traveler accepts last. The payment and
travel can have different actors or deadlines, and neither transfers spice
at acceptance. When due now, a detached native completion checks all the
payer's due payments together with their live travel, including a travel term
accepted immediately before a separate payment or vice versa. A failed final
acceptance leaves the offer and resources intact. Future obligations retain
the existing no-reservation policy and become enforceable in their due turn.
Payments still use the native bribe action and separate Mentat collection;
payment and travel can be completed in either order if both remain possible.
Unanimous release removes an unpaid payment and its unfinished travel; it does
not refund an already settled payment. The terms are a provisional structured
online representation of the public agreement rule, not a restriction imposed
by the publisher. This supersedes earlier statements below that the two terms
could not be combined. Multiple payments in one offer, Advanced, expansion
factions, arbitrary prose, wider interactions and deployed acceptance remain
open.
Evidence: [public gameplay](../tests/public-deals-deferred-travel.test.ts),
[separate future terms](../tests/public-deals-future-deferred-runtime.test.ts),
[deal controls](../tests/public-deals-travel-controls.test.tsx) and the
[authenticated boundary](../tests/public-deals-deferred-travel-http.test.ts).
Thirty-one related offline files pass 191 cases, and the new HTTP case passes
against a local server with a fresh test room. Type checking, lint and the
production build pass; build chunk-size warnings remain.
## Group travel with an immediate payment — 29 October 2026 ## Group travel with an immediate payment — 29 October 2026
**Prototyped / Partial.** A Basic classic group offer of three to six human **Prototyped / Partial.** A Basic classic group offer of three to six human
+11 -14
View File
@@ -6127,6 +6127,7 @@ function publicDealCompletion(g: Game, payer: Player): boolean {
!turnActionCompletion(trial,payer.id)) return false; !turnActionCompletion(trial,payer.id)) return false;
const voluntary = {actor:payer.id,action:{type:'bribe'}}; const voluntary = {actor:payer.id,action:{type:'bribe'}};
reconcileBattlePromises(trial,voluntary); reconcileBattlePromises(trial,voluntary);
reconcileTravelPromises(trial,payer.id,voluntary.action,g.phase);
reconcileShipmentPromises(trial,voluntary); reconcileShipmentPromises(trial,voluntary);
reconcileGroundMovementPromises(trial,payer.id,voluntary.action,g.phase); reconcileGroundMovementPromises(trial,payer.id,voluntary.action,g.phase);
reconcileBidPromises(trial,voluntary); reconcileBidPromises(trial,voluntary);
@@ -24323,9 +24324,6 @@ function bindPublicDealTravel(g: Game, deal: PublicDeal) {
const action = { kind: term.kind, territory: term.territory, minimum: term.minimum }; const action = { kind: term.kind, territory: term.territory, minimum: term.minimum };
const claim: TravelClaim = { turn: due, mixed: { kind: 'action', action } }; const claim: TravelClaim = { turn: due, mixed: { kind: 'action', action } };
if (due > g.turn) { if (due > g.turn) {
requireRule(!g.deals?.some(other => other.payment?.kind === 'deferredBribe' &&
other.paymentStatus === 'pending' && other.payment.payer === player.id && other.payment.dueTurn === due),
'This traveler already has a payment due in the same turn.');
// These are public, physical contradictions, not a forecast of future // These are public, physical contradictions, not a forecast of future
// funds: there is one shipment, and a required action cannot also be // funds: there is one shipment, and a required action cannot also be
// forbidden at an equal or lower threshold in that same territory. // forbidden at an equal or lower threshold in that same territory.
@@ -24342,8 +24340,7 @@ function bindPublicDealTravel(g: Game, deal: PublicDeal) {
requireRule(!conflicts, 'This future travel term conflicts with an already accepted public travel agreement.'); requireRule(!conflicts, 'This future travel term conflicts with an already accepted public travel agreement.');
} }
if (due === g.turn) { if (due === g.turn) {
requireRule(travelTargetAvailable(g, player.id) && !g.truthtrance && !hasBribePromises(g, player.id) && requireRule(travelTargetAvailable(g, player.id) && !g.truthtrance && !hasBribePromises(g, player.id),
!g.deals?.some(other => other.payment?.kind === 'deferredBribe' && other.paymentStatus === 'pending'),
'This travel agreement needs a supported quiet Basic opportunity in its due turn.'); 'This travel agreement needs a supported quiet Basic opportunity in its due turn.');
requireRule(travelTruthAnswers(g, player, claim).includes(term.answer ? 'yes' : 'no'), requireRule(travelTruthAnswers(g, player, claim).includes(term.answer ? 'yes' : 'no'),
'This travel agreement cannot be accepted at the current opportunity.'); 'This travel agreement cannot be accepted at the current opportunity.');
@@ -38349,7 +38346,7 @@ function projectedTypedRevivalPromiseGuide(g: Game, player: string, kind: 'force
// The separate bid guide owns a jointly binding Yes declaration. Passing // The separate bid guide owns a jointly binding Yes declaration. Passing
// cannot evade it merely because Revival comes later in this turn. // cannot evade it merely because Revival comes later in this turn.
const lot = g.phase === 3 && !ownPayment && !g.richeseAuction && !g.ixAuction ? bidOpportunity(g) : null; const lot = g.phase === 3 && !ownPayment && !g.richeseAuction && !g.ixAuction ? bidOpportunity(g) : null;
if (lot && bidRequired(g.bidPromises ?? [], player, lot)) return null; if (lot && (bidRequired(g.bidPromises ?? [], player, lot) || projectedPhaseBidGuide(g,player))) return null;
const grouped = liveRevivalExpressionPromises(g.revivalExpressionPromises ?? [], player, g.turn); const grouped = liveRevivalExpressionPromises(g.revivalExpressionPromises ?? [], player, g.turn);
const named = liveLeaderRevivalPromises(g.leaderRevivalPromises ?? [], player, g.turn); const named = liveLeaderRevivalPromises(g.leaderRevivalPromises ?? [], player, g.turn);
const promise = kind === 'expression' ? grouped[0] : grouped.length ? null : kind === 'leader' ? named[0] const promise = kind === 'expression' ? grouped[0] : grouped.length ? null : kind === 'leader' ? named[0]
@@ -43732,16 +43729,16 @@ function applyActionWithInitiator(state: Game, id: string, action: Action, initi
} }
} }
g.deals = deals.map((deal, position) => position === index ? next : deal); g.deals = deals.map((deal, position) => position === index ? next : deal);
if (current.status === 'offered' && next.status === 'active' && next.travel &&
publicDealTravelDueTurn(next) === g.turn) {
const traveler = getPlayer(g,publicDealTravelActor(next));
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') { if (current.status === 'offered' && next.status === 'active' && next.payment?.kind === 'deferredBribe') {
const payer = getPlayer(g,next.payment.payer), dueTurn = next.payment.dueTurn; const payer = getPlayer(g,next.payment.payer), dueTurn = next.payment.dueTurn;
requireRule(!(g.travelPromises ?? []).some(row => row.sourceDeal && row.player === payer.id && requireRule(dueTurn >= g.turn &&
row.turn === dueTurn && !row.fulfilled && !row.released), (dueTurn > g.turn || publicDealCompletion(g,payer)),
'The payer already has a public travel commitment in the payment’s due turn.');
requireRule(next.payment.dueTurn !== g.turn ||
!liveTravelPromises(g.travelPromises ?? [], payer.id, g.turn).some(row => !!row.sourceDeal),
'Finish the current public travel commitment before accepting a payment due this turn.');
requireRule(next.payment.dueTurn >= g.turn &&
(next.payment.dueTurn > g.turn || publicDealCompletion(g,payer)),
'The agreed payment needs an unexpired deadline and, when due now, a legal funded completion.'); 'The agreed payment needs an unexpired deadline and, when due now, a legal funded completion.');
if (next.payment.dueTurn === g.turn && if (next.payment.dueTurn === g.turn &&
(g.phase === 2 && !g.charityOrder || g.phase === 8 || g.phase === 7 && bribesCloseBeforeNextMentat(g)) && (g.phase === 2 && !g.charityOrder || g.phase === 8 || g.phase === 7 && bribesCloseBeforeNextMentat(g)) &&
+6 -8
View File
@@ -189,10 +189,10 @@ export function validatePublicDeals(value: unknown, players: readonly PublicDeal
const travel = parsePublicDealTravel(deal.travel); const travel = parsePublicDealTravel(deal.travel);
requireDeal(travel.dueTurn === undefined || travel.dueTurn >= (deal.turn as number), requireDeal(travel.dueTurn === undefined || travel.dueTurn >= (deal.turn as number),
'Choose a travel turn no earlier than the offer turn.'); 'Choose a travel turn no earlier than the offer turn.');
requireDeal(!Object.hasOwn(deal, 'paymentStatus') && (multi requireDeal(multi
? !!travel.actor && travel.actor !== deal.from && parties.includes(travel.actor) && (!payment || payment.kind === 'immediateBribe') ? !!travel.actor && travel.actor !== deal.from && parties.includes(travel.actor)
: !Object.hasOwn(travel, 'actor') && (!payment || payment.kind === 'immediateBribe')), : !Object.hasOwn(travel, 'actor'),
'Choose an invited traveler and an optional immediate bribe between participants.'); 'Choose an invited traveler and an optional bribe between participants.');
// The actor's final acceptance is checked privately. An unfinished offer // The actor's final acceptance is checked privately. An unfinished offer
// cannot already contain that vote, even after a decline or withdrawal. // cannot already contain that vote, even after a decline or withdrawal.
if (multi && deal.status !== 'active' && deal.status !== 'released') if (multi && deal.status !== 'active' && deal.status !== 'released')
@@ -253,10 +253,8 @@ export function setPublicDealTravel(deal: PublicDeal, value: unknown, players: r
validatePublicDeals([deal], players); validatePublicDeals([deal], players);
requireDeal(deal.status === 'offered' && !Object.hasOwn(deal, 'travel') && requireDeal(deal.status === 'offered' && !Object.hasOwn(deal, 'travel') &&
!Object.hasOwn(deal, 'paymentStatus') && (deal.participants !Object.hasOwn(deal, 'paymentStatus') && (deal.participants
? !!deal.acceptVotes && deal.acceptVotes.length === 1 && deal.acceptVotes[0] === deal.from && ? !!deal.acceptVotes && deal.acceptVotes.length === 1 && deal.acceptVotes[0] === deal.from
(!deal.payment || deal.payment.kind === 'immediateBribe') : !Object.hasOwn(deal, 'acceptVotes')),
: !Object.hasOwn(deal, 'acceptVotes') && (!deal.payment ||
deal.payment.kind === 'immediateBribe')),
'Only a fresh offer may add a travel term with a supported payment.'); 'Only a fresh offer may add a travel term with a supported payment.');
notAllied(participants(players, publicDealParticipants(deal))); notAllied(participants(players, publicDealParticipants(deal)));
const result = { ...deal, travel: parsePublicDealTravel(value) }; const result = { ...deal, travel: parsePublicDealTravel(value) };
+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 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 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.',
'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.', '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 payment between two participants. All parties accept, including the payer, and the traveler accepts last; only then does the payment settle. Final consent and payment are atomic, and current-turn travel must remain feasible after the payer spends. Deferred and multiple-payment travel remain unfinished.', '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.',
'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.', '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.', 'Minimal AI follows supported Truthtrance ordinary-payment answers and their legal guides. AI deal negotiation and automatic enforcement of prose remain unfinished.',
], ],
+22 -4
View File
@@ -118,7 +118,21 @@ void test('an optional gross bribe is bound to two distinct participants', () =>
assert.equal(publicDealOfferAction(['b'], 'Terms', payment), null); assert.equal(publicDealOfferAction(['b'], 'Terms', payment), null);
}); });
void test('all players can review the gross payment and only final acceptance is held at a blocked payment window', () => { void test('a deferred payment and travel show each participant and due turn in the deal history', () => {
const payment = {kind:'deferredBribe', payer:'a', recipient:'b', amount:3, dueTurn:4};
const travel = {kind:'ship', territory:'carthag', minimum:2, answer:true, actor:'e', dueTurn:3};
const combined = {...offer, participants:['a','b','e'], acceptVotes:['a','b','e'], status:'active',
payment, paymentStatus:'pending', travel};
const game = {...base, turn:2, players:base.players.map(player => ({...player, ally:null})),
deals:[combined], dealTravelStatus:{'deal-1':'scheduled'}} as unknown as GameView;
const html = render(game);
assert.match(html, /Alice \(Atreides\) pays exactly 3 spice to Basil \(Harkonnen\) on or before the end of turn 4/);
assert.match(html, /Emperor \(Emperor\) agrees to make a reserve shipment of at least 2 physical forces in one action to Carthag during turn 3/);
assert.match(html, /Payment status: pending/);
assert.match(html, /Travel status: scheduled/);
});
void test('the payer’s own blocked payment quote applies at final acceptance without using another seat’s quote', () => {
const payment = { kind: 'immediateBribe' as const, payer: 'b', recipient: 'a', amount: 3 }; const payment = { kind: 'immediateBribe' as const, payer: 'b', recipient: 'a', amount: 3 };
const multi = { ...offer, participants: ['a', 'b', 'e'], acceptVotes: ['a'], payment }; const multi = { ...offer, participants: ['a', 'b', 'e'], acceptVotes: ['a'], payment };
const game = { ...base, players: base.players.map(player => const game = { ...base, players: base.players.map(player =>
@@ -135,10 +149,14 @@ void test('all players can review the gross payment and only final acceptance is
assert.equal(first.find(node => node.props.children === 'Accept deal')?.props.disabled, false); assert.equal(first.find(node => node.props.children === 'Accept deal')?.props.disabled, false);
const lastGame = { ...game, me: 'e', deals: [{ ...multi, acceptVotes: ['a', 'b'] }] } as unknown as GameView; const lastGame = { ...game, me: 'e', deals: [{ ...multi, acceptVotes: ['a', 'b'] }] } as unknown as GameView;
const last = actions(lastGame, []); const last = actions(lastGame, []);
assert.equal(last.find(node => node.props.children === 'Accept deal')?.props.disabled, true); assert.equal(last.find(node => node.props.children === 'Accept deal')?.props.disabled, false,
'A final recipient cannot use their private quote to block another payer.');
assert.equal(last.find(node => node.props.children === 'Decline deal')?.props.disabled, false); assert.equal(last.find(node => node.props.children === 'Decline deal')?.props.disabled, false);
assert.match(render(lastGame), /Final acceptance must wait: Finish the current decision before paying a bribe/); assert.doesNotMatch(render(lastGame), /Final acceptance must wait:/);
const unblocked = { ...lastGame, bribeOptions: { ...lastGame.bribeOptions, blocked: null } } as GameView; const payerFinal = {...lastGame, deals:[{...multi, acceptVotes:['a','b'], payment:{...payment,payer:'e'}}]} as GameView;
assert.equal(actions(payerFinal, []).find(node => node.props.children === 'Accept deal')?.props.disabled, true);
assert.match(render(payerFinal), /Final acceptance must wait: Finish the current decision before paying a bribe/);
const unblocked = { ...payerFinal, bribeOptions: { ...payerFinal.bribeOptions, blocked: null } } as GameView;
assert.equal(actions(unblocked, []).find(node => node.props.children === 'Accept deal')?.props.disabled, false); assert.equal(actions(unblocked, []).find(node => node.props.children === 'Accept deal')?.props.disabled, false);
}); });
@@ -0,0 +1,81 @@
// @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 test room is created; no existing room is used or removed. Both
* terms retain the same original agreement identity. */
void test('authenticated players can consent to and pay a deferred travel agreement', async () => {
const host = await request('/api/rooms', undefined, {
name: 'Deferred travel 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 guest = await request(path, undefined, { type: 'join', name: 'Deferred traveler', faction: 'harkonnen' });
assert.equal(guest.status, 200, JSON.stringify(guest.data)); assert.ok(guest.cookie);
const seats = [{id:host.data.me,cookie:host.cookie}, {id:guest.data.me,cookie:guest.cookie}];
let view = guest.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, guest.cookie);
assert.equal(before.status, 200, JSON.stringify(before.data)); view = before.data;
const spice = before.data.players.find(player => player.id === guest.data.me)?.spice;
assert.ok(typeof spice === 'number' && spice >= 2);
const dueTurn = view.turn + 1;
const payment = {kind:'deferredBribe',payer:guest.data.me,recipient:host.data.me,amount:2,dueTurn};
const travel = {kind:'ship',territory:'polar_sink',minimum:1,answer:true,dueTurn};
await act(host.cookie, {type:'dealOffer',target:guest.data.me,
terms:'Ship to Polar Sink and pay two spice next turn.',payment,travel});
const offered = view.deals.at(-1); assert.ok(offered);
assert.equal(offered.status, 'offered'); assert.deepEqual(offered.payment, payment);
assert.deepEqual(offered.travel, travel);
const acceptance = {type:'dealRespond',deal:offered.id,accept:true};
const forged = await request(path, host.cookie, {version:view.version,action:acceptance}, guest.data.me);
assert.equal(forged.status, 409, JSON.stringify(forged.data));
await act(guest.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(deal => deal.id === offered.id); assert.ok(active);
assert.equal(active.status, 'active'); assert.equal(active.paymentStatus, 'pending');
assert.deepEqual(active.payment, payment); assert.deepEqual(active.travel, travel);
assert.equal(read.data.dealTravelStatus[offered.id], 'scheduled');
if (seat.id === guest.data.me)
assert.equal(read.data.players.find(player => player.id === guest.data.me)?.spice, spice);
}
const wrongPayer = await request(path, host.cookie,
{version:view.version,action:{type:'dealPay',deal:offered.id}});
assert.equal(wrongPayer.status, 409, JSON.stringify(wrongPayer.data));
await act(guest.cookie, {type:'dealPay',deal:offered.id});
const paid = await request(path, guest.cookie);
assert.equal(paid.status, 200, JSON.stringify(paid.data));
assert.equal(paid.data.deals.find(deal => deal.id === offered.id)?.paymentStatus, 'paid');
assert.equal(paid.data.dealTravelStatus[offered.id], 'scheduled');
assert.equal(paid.data.players.find(player => player.id === guest.data.me)?.spice, spice - 2);
});
+220
View File
@@ -0,0 +1,220 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { createGame, joinGame, newPlayer, viewGame, type Action, type Game } from '../game/engine';
import { actTruthTravel as act, advanceTruthTravel as advance, createTruthTravelFixture as fixture,
settleTruthTravel as settle, truthTravelClean as clean, truthTravelInventory as inventory,
truthTravelPlayer as player } from './fixture-truth-travel';
import { nextStrongholdFactionsNativeStep as nextNative } from './fixture-stronghold-factions';
function reject(game: Game, actor: string, action: Action) {
const before = structuredClone(game);
assert.throws(() => act(game, actor, action));
assert.deepEqual(game, before, 'Rejected action must not partially mutate the source game.');
}
function deal(game: Game, id: string) {
const found = game.deals?.find(row => row.id === id); assert.ok(found); return found;
}
function offer(game: Game, proposer: string, target: string, payer: string, recipient: string,
territory: string, amount: number, dueTurn: number, travelTurn?: number) {
const next = act(game, proposer, {type:'dealOffer', target, terms:'Pay the agreed amount and make the agreed shipment.',
payment:{kind:'deferredBribe', payer, recipient, amount, dueTurn},
travel:{kind:'ship', territory, minimum:1, answer:true, ...(travelTurn === undefined ? {} : {dueTurn:travelTurn})}});
const offered = next.deals?.at(-1); assert.ok(offered);
return {game:next, id:offered.id};
}
function accept(game: Game, target: string, id: string) {
return act(game, target, {type:'dealRespond', deal:id, accept:true});
}
function status(game: Game, viewer: string, id: string) {
return viewGame(game, viewer).dealTravelStatus[id];
}
/** Genuine public Basic two-seat setup and native phase-five window; the
* fixture stages only unopened cards/Spice. Every offer, vote, payment and
* shipment below is executed through public player actions. */
for (const payerRole of ['traveler','proposer'] as const) for (const order of ['pay-first','travel-first'] as const) {
void test(`current-turn deferred payment and shipment coexist with ${payerRole} paying (${order})`, () => {
const f = fixture(), before = f.game, payer = payerRole === 'traveler' ? f.target : f.asker;
const recipient = payerRole === 'traveler' ? f.asker : f.target;
const cash = player(before,payer).spice, travelCash = player(before,f.target).spice;
const escrow = player(before,recipient).bribes;
assert.ok(cash >= (payerRole === 'traveler' ? f.shipmentCost + 1 : 1));
const offered = offer(before,f.asker,f.target,payer,recipient,f.shipmentTerritory,1,before.turn);
assert.equal(deal(offered.game,offered.id).status,'offered');
assert.equal(player(offered.game,payer).spice,cash);
assert.equal(offered.game.travelPromises?.some(row => row.sourceDeal === offered.id) ?? false,false);
let game = accept(offered.game,f.target,offered.id);
assert.equal(deal(game,offered.id).status,'active');
assert.equal(deal(game,offered.id).paymentStatus,'pending');
assert.equal(status(game,f.target,offered.id),'pending');
assert.equal(player(game,payer).spice,cash);
assert.equal(game.travelPromises?.filter(row => row.sourceDeal === offered.id).length,1);
reject(game,f.asker,{type:'dealRespond',deal:offered.id,accept:true});
if (order === 'pay-first') {
game = act(game,payer,{type:'dealPay',deal:offered.id});
assert.equal(deal(game,offered.id).paymentStatus,'paid');
assert.equal(player(game,recipient).bribes,escrow+1);
game = settle(act(game,f.target,f.shipmentAction));
} else {
game = settle(act(game,f.target,f.shipmentAction));
assert.equal(deal(game,offered.id).paymentStatus,'pending');
game = act(game,payer,{type:'dealPay',deal:offered.id});
}
assert.equal(deal(game,offered.id).paymentStatus,'paid');
assert.equal(status(game,f.target,offered.id),'fulfilled');
assert.equal(player(game,f.target).forces['polar_sink:0'],1);
assert.equal(player(game,payer).spice,cash - 1 - (payerRole === 'traveler' ? f.shipmentCost : 0));
if (payerRole === 'proposer') assert.equal(player(game,f.target).spice,travelCash-f.shipmentCost);
assert.equal(player(game,recipient).bribes,escrow+1);
reject(game,payer,{type:'dealPay',deal:offered.id});
assert.deepEqual(inventory(game),f.originalCards);
});
}
void test('current-turn joint consent rejects an unaffordable payer-traveler without creating either obligation', () => {
const f = fixture(), cash = player(f.game,f.target).spice;
assert.ok(cash > 0 && f.shipmentCost > 0);
const offered = offer(f.game,f.asker,f.target,f.target,f.asker,f.shipmentTerritory,cash,f.game.turn);
const before = structuredClone(offered.game);
reject(offered.game,f.target,{type:'dealRespond',deal:offered.id,accept:true});
assert.deepEqual(offered.game,before);
assert.equal(deal(offered.game,offered.id).status,'offered');
assert.equal(offered.game.travelPromises?.some(row => row.sourceDeal === offered.id) ?? false,false);
assert.equal(player(offered.game,f.target).spice,cash);
});
void test('both participants must release the unpaid payment and matching travel together', () => {
const f = fixture();
const offered = offer(f.game,f.asker,f.target,f.target,f.asker,f.shipmentTerritory,1,f.game.turn);
let game = accept(offered.game,f.target,offered.id);
game = act(game,f.asker,{type:'dealRelease',deal:offered.id,agree:true});
assert.equal(status(game,f.target,offered.id),'pending');
assert.equal(deal(game,offered.id).paymentStatus,'pending');
reject(game,f.target,f.currentEnd);
game = act(game,f.target,{type:'dealRelease',deal:offered.id,agree:true});
assert.equal(status(game,f.target,offered.id),'released');
assert.equal(deal(game,offered.id).paymentStatus,'released');
reject(game,f.target,{type:'dealPay',deal:offered.id});
game = settle(act(game,f.target,f.currentEnd));
assert.equal(status(game,f.target,offered.id),'released');
assert.deepEqual(inventory(game),f.originalCards);
});
for (const payerRole of ['traveler','proposer'] as const) void test(
`future-due deferred payment and shipment survive rollover with ${payerRole} paying`, () => {
const f = fixture(), dueTurn = f.game.turn+1, payer = payerRole === 'traveler' ? f.target : f.asker;
const recipient = payerRole === 'traveler' ? f.asker : f.target;
const offered = offer(f.game,f.asker,f.target,payer,recipient,f.shipmentTerritory,1,dueTurn,dueTurn);
let game = accept(offered.game,f.target,offered.id);
assert.equal(status(game,f.target,offered.id),'scheduled');
assert.equal(deal(game,offered.id).paymentStatus,'pending');
game = settle(act(game,f.target,f.currentEnd));
game = advance(game,state => state.turn === dueTurn && state.phase === 2 && clean(state));
assert.equal(deal(game,offered.id).paymentStatus,'pending');
game = act(game,payer,{type:'dealPay',deal:offered.id});
assert.equal(deal(game,offered.id).paymentStatus,'paid');
game = advance(game,state => state.turn === dueTurn && state.phase === 5 && state.active === f.target && clean(state));
game = settle(act(game,f.target,f.shipmentAction));
assert.equal(status(game,f.target,offered.id),'fulfilled');
assert.equal(deal(game,offered.id).paymentStatus,'paid');
assert.equal(player(game,f.target).forces['polar_sink:0'],1);
assert.deepEqual(inventory(game),f.originalCards);
},
);
const groupProposer = 'atreides', groupTraveler = 'emperor', groupPayer = 'harkonnen', groupOther = 'fremen';
const groupShipment: Action = {type:'ship',territory:'polar_sink',sector:0,amount:1,elite:0,allyPayment:0};
function groupReach(game: Game, until: (state: Game) => boolean): Game {
for (let count = 0; count < 1600; count++) {
if (until(game)) return game;
assert.notEqual(game.status,'finished');
const step = nextNative(game); assert.ok(step, `Native continuation needed at ${game.turn}/${game.phase}`);
game = act(game,step.actor,step.action);
}
throw Error('The original group-deal programme did not reach its requested boundary.');
}
/** Four original human Basic seats. Only unopened starting cards and two land
* Spice cards are ordered; no resource, vote, promise, or force is fabricated. */
function groupFixture(): Game {
let game = createGame('GROUPDEFERTRAVEL',newPlayer(groupProposer,'Atreides','atreides'),false,[]);
for (const [id,faction] of [[groupTraveler,'emperor'],[groupPayer,'harkonnen'],[groupOther,'fremen']] as const)
joinGame(game,newPlayer(id,id,faction));
for (const seat of game.players) game = act(game,seat.id,{type:'ready'});
game = act(game,groupProposer,{type:'start'});
const cards = game.deck.filter(card => ['projectile','poison','shield','snooper'].includes(card.kind)).slice(0,4);
assert.equal(cards.length,4);
for (const [position,card] of cards.entries()) {
const from = game.deck.findIndex(row => row.id === card.id); assert.ok(from >= position);
[game.deck[position],game.deck[from]] = [game.deck[from],game.deck[position]];
}
game = groupReach(game,state => state.status === 'playing');
for (let position = 0; position < 2; position++) {
const from = game.spiceDeck.findIndex((card,index) => index >= position && 'territory' in card && !card.discovery);
assert.ok(from >= position);
game.spiceDeck.splice(position,0,game.spiceDeck.splice(from,1)[0]);
}
game = groupReach(game,state => state.turn === 1 && state.phase === 5 && state.active === groupTraveler && clean(state));
assert.ok(player(game,groupTraveler).spice >= 2);
return game;
}
function groupOffer(game: Game, payer: string, amount: number, dueTurn: number, travelTurn?: number) {
const next = act(game,groupProposer,{type:'dealOffer',targets:[groupPayer,groupTraveler],
terms:'Deferred payment and a shared journey.',
payment:{kind:'deferredBribe',payer,recipient:groupProposer,amount,dueTurn},
travel:{actor:groupTraveler,kind:'ship',territory:'polar_sink',minimum:1,answer:true,
...(travelTurn === undefined ? {} : {dueTurn:travelTurn})}});
const offered = next.deals?.at(-1); assert.ok(offered); return {game:next,id:offered.id};
}
for (const payer of [groupTraveler,groupPayer]) void test(
`three-party deferred travel requires the traveler last and retains ${payer}'s pending payment`, () => {
const initial = groupFixture(), cards = inventory(initial), cash = player(initial,payer).spice;
assert.ok(cash >= (payer === groupTraveler ? 3 : 1));
const offered = groupOffer(initial,payer,1,initial.turn);
let game = offered.game;
reject(game,groupTraveler,{type:'dealRespond',deal:offered.id,accept:true});
game = accept(game,groupPayer,offered.id);
assert.equal(deal(game,offered.id).status,'offered');
assert.equal(game.travelPromises?.some(row => row.sourceDeal === offered.id) ?? false,false);
assert.equal(player(game,payer).spice,cash);
game = accept(game,groupTraveler,offered.id);
assert.equal(deal(game,offered.id).status,'active');
assert.equal(deal(game,offered.id).paymentStatus,'pending');
assert.equal(status(game,groupTraveler,offered.id),'pending');
assert.equal(player(game,payer).spice,cash);
game = act(game,payer,{type:'dealPay',deal:offered.id});
assert.equal(deal(game,offered.id).paymentStatus,'paid');
game = groupReach(act(game,groupTraveler,groupShipment),state => clean(state) && !state.pendingShipment);
assert.equal(status(game,groupTraveler,offered.id),'fulfilled');
assert.equal(player(game,groupTraveler).forces['polar_sink:0'],1);
assert.equal(player(game,payer).spice,cash - 1 - (payer === groupTraveler ? 2 : 0));
assert.deepEqual(inventory(game),cards);
},
);
void test('final group consent rolls back when the traveling payer cannot fund both obligations', () => {
const initial = groupFixture(), cash = player(initial,groupTraveler).spice;
const offered = groupOffer(initial,groupTraveler,cash,initial.turn);
const waiting = accept(offered.game,groupPayer,offered.id);
reject(waiting,groupTraveler,{type:'dealRespond',deal:offered.id,accept:true});
assert.equal(deal(waiting,offered.id).status,'offered');
assert.equal(player(waiting,groupTraveler).spice,cash);
assert.equal(waiting.travelPromises?.some(row => row.sourceDeal === offered.id) ?? false,false);
});
void test('a third-party deferred payer and named traveler fulfill their actual next-turn group obligations', () => {
const initial = groupFixture(), cards = inventory(initial), dueTurn = initial.turn+1;
const offered = groupOffer(initial,groupPayer,1,dueTurn,dueTurn);
let game = accept(offered.game,groupPayer,offered.id);
game = accept(game,groupTraveler,offered.id);
assert.equal(status(game,groupTraveler,offered.id),'scheduled');
assert.equal(deal(game,offered.id).paymentStatus,'pending');
game = groupReach(act(game,groupTraveler,{type:'endMovement'}),state => state.turn === dueTurn && clean(state));
game = act(game,groupPayer,{type:'dealPay',deal:offered.id});
assert.equal(deal(game,offered.id).paymentStatus,'paid');
game = groupReach(game,state => state.turn === dueTurn && state.phase === 5 && state.active === groupTraveler && clean(state));
game = groupReach(act(game,groupTraveler,groupShipment),state => clean(state) && !state.pendingShipment);
assert.equal(status(game,groupTraveler,offered.id),'fulfilled');
assert.equal(deal(game,offered.id).paymentStatus,'paid');
assert.deepEqual(inventory(game),cards);
});
@@ -1,14 +1,9 @@
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
import test from 'node:test'; import test from 'node:test';
import { viewGame, type Action, type Game } from '../game/engine'; import { viewGame, type Game } from '../game/engine';
import { actTruthTravel as act, createTruthTravelFixture as fixture, import { actTruthTravel as act, advanceTruthTravel as advance, createTruthTravelFixture as fixture,
settleTruthTravel as settle, truthTravelClean as clean,
truthTravelInventory as inventory, truthTravelPlayer as player } from './fixture-truth-travel'; truthTravelInventory as inventory, truthTravelPlayer as player } from './fixture-truth-travel';
function reject(game: Game, actor: string, action: Action) {
const before = structuredClone(game);
assert.throws(() => act(game, actor, action));
assert.deepEqual(game, before, 'Conflicting consent must leave the source game unchanged.');
}
function travelOffer(game: Game, proposer: string, traveler: string, dueTurn: number) { function travelOffer(game: Game, proposer: string, traveler: string, dueTurn: number) {
const next = act(game, proposer, {type:'dealOffer', target:traveler, terms:'Travel in a future turn.', const next = act(game, proposer, {type:'dealOffer', target:traveler, terms:'Travel in a future turn.',
travel:{kind:'ship', territory:'polar_sink', minimum:1, answer:true, dueTurn}}); travel:{kind:'ship', territory:'polar_sink', minimum:1, answer:true, dueTurn}});
@@ -31,38 +26,45 @@ function deal(game: Game, id: string) {
/** Each case uses the genuine Basic Atreides/Emperor setup and actual native /** Each case uses the genuine Basic Atreides/Emperor setup and actual native
* first-turn pre-shipment window. These are independent two-party offers and * first-turn pre-shipment window. These are independent two-party offers and
* acceptances; no wallet, force, pending debt or travel receipt is staged. */ * acceptances; no wallet, force, pending debt or travel receipt is staged. */
void test('a same-turn deferred debt cannot be accepted after the payer schedules travel', () => { for (const order of ['travel-first', 'payment-first'] as const) void test(
const f = fixture(), dueTurn = f.game.turn + 1, originalCards = inventory(f.game); `the same future due turn retains travel and deferred payment when accepted ${order}`, () => {
const future = travelOffer(f.game, f.asker, f.target, dueTurn); const f = fixture(), dueTurn = f.game.turn + 1, originalCards = inventory(f.game);
let game = accept(future.game, f.target, future.id); let game = f.game, travelId: string, paymentId: string;
assert.equal(viewGame(game, f.target).dealTravelStatus[future.id], 'scheduled'); if (order === 'travel-first') {
const payment = paymentOffer(game, f.asker, f.target, f.target, f.asker, dueTurn); const future = travelOffer(game, f.asker, f.target, dueTurn); travelId = future.id;
game = payment.game; game = accept(future.game, f.target, travelId);
const purse = player(game, f.target).spice; const payment = paymentOffer(game, f.asker, f.target, f.target, f.asker, dueTurn); paymentId = payment.id;
reject(game, f.target, {type:'dealRespond', deal:payment.id, accept:true}); game = accept(payment.game, f.target, paymentId);
assert.equal(deal(game, future.id).status, 'active'); } else {
assert.equal(deal(game, payment.id).status, 'offered'); const payment = paymentOffer(game, f.asker, f.target, f.target, f.asker, dueTurn); paymentId = payment.id;
assert.equal(game.travelPromises?.filter(row => row.sourceDeal === future.id).length, 1); game = accept(payment.game, f.target, paymentId);
assert.equal(player(game, f.target).spice, purse); const future = travelOffer(game, f.asker, f.target, dueTurn); travelId = future.id;
assert.deepEqual(inventory(game), originalCards); game = accept(future.game, f.target, travelId);
}); }
assert.equal(deal(game, travelId).status, 'active');
assert.equal(viewGame(game, f.target).dealTravelStatus[travelId], 'scheduled');
assert.equal(game.travelPromises?.filter(row => row.sourceDeal === travelId).length, 1);
assert.equal(deal(game, paymentId).paymentStatus, 'pending');
assert.equal(player(game, f.target).spice, player(f.game, f.target).spice);
assert.deepEqual(inventory(game), originalCards);
void test('a same-turn scheduled journey cannot be accepted after the traveler owes a deferred debt', () => { // Finish the original current turn, then settle the actual separate
const f = fixture(), dueTurn = f.game.turn + 1, originalCards = inventory(f.game); // payment and shipment on their shared future due turn.
const payment = paymentOffer(f.game, f.asker, f.target, f.target, f.asker, dueTurn); game = settle(act(game, f.target, f.currentEnd));
let game = accept(payment.game, f.target, payment.id); game = advance(game, state => state.turn === dueTurn && state.phase === 2 && clean(state));
assert.equal(deal(game, payment.id).paymentStatus, 'pending'); assert.equal(viewGame(game, f.target).dealTravelStatus[travelId], 'pending');
const future = travelOffer(game, f.asker, f.target, dueTurn); const beforePayment = player(game, f.target).spice;
game = future.game; game = settle(act(game, f.target, {type:'dealPay', deal:paymentId}));
const purse = player(game, f.target).spice; assert.equal(deal(game, paymentId).paymentStatus, 'paid');
reject(game, f.target, {type:'dealRespond', deal:future.id, accept:true}); assert.equal(player(game, f.target).spice, beforePayment - 2);
assert.equal(deal(game, payment.id).status, 'active'); game = advance(game, state => state.turn === dueTurn && state.phase === 5 &&
assert.equal(deal(game, payment.id).paymentStatus, 'pending'); state.active === f.target && clean(state) && !state.pendingShipment);
assert.equal(deal(game, future.id).status, 'offered'); game = settle(act(game, f.target, f.shipmentAction));
assert.equal(game.travelPromises?.some(row => row.sourceDeal === future.id) ?? false, false); assert.equal(viewGame(game, f.target).dealTravelStatus[travelId], 'fulfilled');
assert.equal(player(game, f.target).spice, purse); assert.equal(deal(game, paymentId).paymentStatus, 'paid');
assert.deepEqual(inventory(game), originalCards); assert.deepEqual(inventory(game), originalCards);
}); },
);
for (const order of ['travel-first', 'payment-first'] as const) void test( for (const order of ['travel-first', 'payment-first'] as const) void test(
`different future due turns coexist when accepted ${order}`, () => { `different future due turns coexist when accepted ${order}`, () => {
@@ -166,18 +166,48 @@ for (const answer of [true, false]) void test(`group movement ${answer ? 'requir
assert.equal(status(game, first, offered.id), 'fulfilled'); assert.equal(status(game, first, offered.id), 'fulfilled');
}); });
void test('the traveler may decline early; malformed or uninvited actors and payment combinations reject', () => { void test('the traveler may decline early; malformed or uninvited actors and invalid payments reject', () => {
const initial = fixture(), term:Term = {actor:traveler, kind:'ship', territory:'polar_sink', minimum:1, answer:true}; const initial = fixture(), term:Term = {actor:traveler, kind:'ship', territory:'polar_sink', minimum:1, answer:true};
for (const bad of [proposer, second, 'unknown']) for (const bad of [proposer, second, 'unknown'])
reject(initial, proposer, {type:'dealOffer', targets:[first, traveler], terms:'Terms', travel:{...term, actor:bad}}); reject(initial, proposer, {type:'dealOffer', targets:[first, traveler], terms:'Terms', travel:{...term, actor:bad}});
reject(initial, proposer, {type:'dealOffer', targets:[first, traveler], terms:'Terms', travel:term, reject(initial, proposer, {type:'dealOffer', targets:[first, traveler], terms:'Terms', travel:term,
payment:{kind:'deferredBribe', payer:proposer, recipient:traveler, amount:1, dueTurn:initial.turn}}); payment:{kind:'deferredBribe', payer:proposer, recipient:proposer, amount:1, dueTurn:initial.turn}});
reject(initial, proposer, {type:'dealOffer', targets:[first, traveler], terms:'Terms', travel:term,
payment:{kind:'deferredBribe', payer:proposer, recipient:second, amount:1, dueTurn:initial.turn}});
reject(initial, proposer, {type:'dealOffer', targets:[first, traveler], terms:'Terms', travel:term,
payment:{kind:'deferredBribe', payer:proposer, recipient:traveler, amount:1, dueTurn:initial.turn - 1}});
const offered = offer(initial, [first, traveler], term); const offered = offer(initial, [first, traveler], term);
const declined = respond(offered.game, traveler, offered.id, false); const declined = respond(offered.game, traveler, offered.id, false);
assert.equal(declined.deals!.at(-1)!.status, 'declined'); assert.equal(declined.deals!.at(-1)!.status, 'declined');
assert.equal(declined.travelPromises?.some(row => row.sourceDeal === offered.id) ?? false, false); assert.equal(declined.travelPromises?.some(row => row.sourceDeal === offered.id) ?? false, false);
}); });
void test('a group offer combines deferred payment and travel through consent, payment and shipment', () => {
const initial = fixture(), originalCards = inventory(initial);
const payment = {kind:'deferredBribe', payer:first, recipient:proposer, amount:1, dueTurn:initial.turn};
const travel = {actor:traveler, kind:'ship', territory:'polar_sink', minimum:1, answer:true};
let game = act(initial, proposer, {type:'dealOffer', targets:[first,traveler],
terms:'Pay one spice and make the journey.', payment, travel});
const offered = game.deals!.at(-1)!;
assert.deepEqual(offered.payment, payment);
reject(game, traveler, {type:'dealRespond', deal:offered.id, accept:true});
game = respond(game, first, offered.id);
game = respond(game, traveler, offered.id);
const active = game.deals!.find(deal => deal.id === offered.id)!;
assert.equal(active.status, 'active');
assert.equal(active.paymentStatus, 'pending');
assert.equal(status(game, traveler, offered.id), 'pending');
const balance = player(game, first).spice, incoming = player(game, proposer).bribes;
reject(game, proposer, {type:'dealPay', deal:offered.id});
game = act(game, first, {type:'dealPay', deal:offered.id});
assert.equal(player(game, first).spice, balance - 1);
assert.equal(player(game, proposer).bribes, incoming + 1);
assert.equal(game.deals!.find(deal => deal.id === offered.id)!.paymentStatus, 'paid');
game = settle(act(game, traveler, shipment));
assert.equal(status(game, traveler, offered.id), 'fulfilled');
assert.deepEqual(inventory(game), originalCards);
});
void test('an unavailable journey rejects only the final traveler consent and leaves the group offer open', () => { void test('an unavailable journey rejects only the final traveler consent and leaves the group offer open', () => {
const alreadyShipped = settle(act(fixture(), traveler, shipment)); const alreadyShipped = settle(act(fixture(), traveler, shipment));
const offered = offer(alreadyShipped, [first, traveler], const offered = offer(alreadyShipped, [first, traveler],
+17 -2
View File
@@ -117,12 +117,27 @@ void test('unanimous release ends the pending travel obligation without refundin
assert.equal(player(game, f.target).bribes, escrow); assert.equal(player(game, f.target).bribes, escrow);
}); });
void test('paid travel excludes deferred and multiparty payment variants', () => { void test('travel can include a deferred payment while invalid participant lists still reject', () => {
const f = fixture(), travel = { kind: 'ship', territory: f.shipmentTerritory, minimum: 1, answer: true }; const f = fixture(), travel = { kind: 'ship', territory: f.shipmentTerritory, minimum: 1, answer: true };
const base = { type: 'dealOffer', target: f.target, terms: 'Travel.', travel } satisfies Action; const base = { type: 'dealOffer', target: f.target, terms: 'Travel.', travel } satisfies Action;
reject(f.game, f.asker, { ...base, payment: { kind: 'deferredBribe', payer: f.asker, recipient: f.target, amount: 1, dueTurn: f.game.turn } }); const payment = { kind: 'deferredBribe', payer: f.asker, recipient: f.target, amount: 1, dueTurn: f.game.turn };
const offered = act(f.game, f.asker, { ...base, payment });
const deal = offered.deals!.at(-1)!;
let game = accept(offered, f.target, deal.id);
assert.equal(game.deals!.find(row => row.id === deal.id)!.paymentStatus, 'pending');
assert.equal(status(game, f.target, deal.id), 'pending');
const payerBefore = player(game, f.asker).spice, recipientBefore = player(game, f.target).bribes;
game = act(game, f.asker, {type:'dealPay', deal:deal.id});
assert.equal(player(game, f.asker).spice, payerBefore - 1);
assert.equal(player(game, f.target).bribes, recipientBefore + 1);
assert.equal(game.deals!.find(row => row.id === deal.id)!.paymentStatus, 'paid');
game = settle(act(game, f.target, f.shipmentAction));
assert.equal(status(game, f.target, deal.id), 'fulfilled');
assert.deepEqual(inventory(game), f.originalCards);
reject(f.game, f.asker, { type: 'dealOffer', targets: [f.target, f.asker], terms: 'Travel.', travel, reject(f.game, f.asker, { type: 'dealOffer', targets: [f.target, f.asker], terms: 'Travel.', travel,
payment: { kind: 'immediateBribe', payer: f.asker, recipient: f.target, amount: 1 } }); payment: { kind: 'immediateBribe', payer: f.asker, recipient: f.target, amount: 1 } });
reject(f.game, f.asker, { ...base, payment: { ...payment, dueTurn: f.game.turn - 1 } });
reject(f.game, f.asker, { ...base, payment: { ...payment, recipient: f.asker } });
}); });
void test('the travelling recipient can pay the proposer at final consent and then complete shipment', () => { void test('the travelling recipient can pay the proposer at final consent and then complete shipment', () => {
+23 -6
View File
@@ -54,13 +54,18 @@ void test('the offer packet retains legacy two-party terms and validates an expl
{type:'dealOffer', targets:['b','c'], terms:'Terms', payment, travel:{...travel, actor:'c'}}); {type:'dealOffer', targets:['b','c'], terms:'Terms', payment, travel:{...travel, actor:'c'}});
assert.deepEqual(publicDealOfferAction(['b','c'], 'Terms', {...payment,payer:'b',recipient:'c'}, 'a', 2, {...travel, actor:'c'}), assert.deepEqual(publicDealOfferAction(['b','c'], 'Terms', {...payment,payer:'b',recipient:'c'}, 'a', 2, {...travel, actor:'c'}),
{type:'dealOffer', targets:['b','c'], terms:'Terms', payment:{...payment,payer:'b',recipient:'c'}, travel:{...travel, actor:'c'}}); {type:'dealOffer', targets:['b','c'], terms:'Terms', payment:{...payment,payer:'b',recipient:'c'}, travel:{...travel, actor:'c'}});
assert.equal(publicDealOfferAction(['b','c'], 'Terms', {kind:'deferredBribe',payer:'a',recipient:'b',amount:2,dueTurn:2}, 'a', 2, {...travel, actor:'c'}), null); const deferred = {kind:'deferredBribe' as const,payer:'a',recipient:'b',amount:2,dueTurn:2};
assert.deepEqual(publicDealOfferAction(['b','c'], 'Terms', deferred, 'a', 2, {...travel, actor:'c'}),
{type:'dealOffer', targets:['b','c'], terms:'Terms', payment:deferred, travel:{...travel, actor:'c'}});
assert.deepEqual(publicDealOfferAction(['b'], 'Terms', payment, 'a', 2, travel), assert.deepEqual(publicDealOfferAction(['b'], 'Terms', payment, 'a', 2, travel),
{type:'dealOffer', target:'b', terms:'Terms', payment, travel}); {type:'dealOffer', target:'b', terms:'Terms', payment, travel});
const reverse = {...payment,payer:'b',recipient:'a'}; const reverse = {...payment,payer:'b',recipient:'a'};
assert.deepEqual(publicDealOfferAction(['b'], 'Terms', reverse, 'a', 2, travel), assert.deepEqual(publicDealOfferAction(['b'], 'Terms', reverse, 'a', 2, travel),
{type:'dealOffer', target:'b', terms:'Terms', payment:reverse, travel}); {type:'dealOffer', target:'b', terms:'Terms', payment:reverse, travel});
assert.equal(publicDealOfferAction(['b'], 'Terms', {kind:'deferredBribe',payer:'a',recipient:'b',amount:2,dueTurn:2}, 'a', 2, travel), null); assert.deepEqual(publicDealOfferAction(['b'], 'Terms', deferred, 'a', 2, travel),
{type:'dealOffer', target:'b', terms:'Terms', payment:deferred, travel});
assert.equal(publicDealOfferAction(['b'], 'Terms', {...deferred,dueTurn:1}, 'a', 2, travel), null);
assert.equal(publicDealOfferAction(['b','c'], 'Terms', {...deferred,recipient:'outsider'}, 'a', 2, {...travel,actor:'c'}), null);
assert.equal(publicDealOfferAction(['b','c'], 'Terms', payment, 'a', 2, travel), null); assert.equal(publicDealOfferAction(['b','c'], 'Terms', payment, 'a', 2, travel), null);
assert.equal(publicDealOfferAction(['a'], 'Terms', undefined, 'a', 2, travel), null); assert.equal(publicDealOfferAction(['a'], 'Terms', undefined, 'a', 2, travel), null);
assert.equal(publicDealOfferAction(['b'], 'Terms', undefined, undefined, 2, travel), null); assert.equal(publicDealOfferAction(['b'], 'Terms', undefined, undefined, 2, travel), null);
@@ -130,7 +135,7 @@ function combinedForm(gameOverride?: GameView) {
return {render, check, select, sent}; return {render, check, select, sent};
} }
void test('the authoring controls compose a proposer payment with recipient travel and reject invalid combinations', () => { void test('the authoring controls compose immediate or deferred payment with recipient travel', () => {
const ui = combinedForm(); const ui = combinedForm();
ui.check(0); // Select recipient. ui.check(0); // Select recipient.
ui.check(1); // Include payment. ui.check(1); // Include payment.
@@ -146,12 +151,19 @@ void test('the authoring controls compose a proposer payment with recipient trav
assert.deepEqual(JSON.parse(JSON.stringify(ui.sent[0])), {type:'dealOffer',target:'b',terms:'Travel for spice', assert.deepEqual(JSON.parse(JSON.stringify(ui.sent[0])), {type:'dealOffer',target:'b',terms:'Travel for spice',
payment:{kind:'immediateBribe',payer:'a',recipient:'b',amount:1}, payment:{kind:'immediateBribe',payer:'a',recipient:'b',amount:1},
travel:{kind:'ship',territory:'carthag',minimum:1,answer:true}}); travel:{kind:'ship',territory:'carthag',minimum:1,answer:true}});
ui.select(0,'deferredBribe'); assert.equal(button()?.props.disabled,true); ui.select(0,'deferredBribe'); assert.equal(button()?.props.disabled,false);
assert.ok(ui.render().some(node => node.type === 'p' && typeof node.props.children === 'string' &&
node.props.children.includes('an immediate payment or a payment due by the end of a selected turn')));
const deferredForm = ui.render().find(node => node.type === 'form'); assert.ok(deferredForm);
(deferredForm.props.onSubmit as (event:{preventDefault():void}) => void)({preventDefault() {}});
assert.deepEqual(JSON.parse(JSON.stringify(ui.sent[1])), {type:'dealOffer',target:'b',terms:'Travel for spice',
payment:{kind:'deferredBribe',payer:'a',recipient:'b',amount:1,dueTurn:2},
travel:{kind:'ship',territory:'carthag',minimum:1,answer:true}});
ui.select(0,'immediateBribe'); ui.select(1,'b'); ui.select(2,'a'); ui.select(0,'immediateBribe'); ui.select(1,'b'); ui.select(2,'a');
assert.equal(button()?.props.disabled,false); assert.equal(button()?.props.disabled,false);
const reverseForm = ui.render().find(node => node.type === 'form'); assert.ok(reverseForm); const reverseForm = ui.render().find(node => node.type === 'form'); assert.ok(reverseForm);
(reverseForm.props.onSubmit as (event:{preventDefault():void}) => void)({preventDefault() {}}); (reverseForm.props.onSubmit as (event:{preventDefault():void}) => void)({preventDefault() {}});
assert.deepEqual(JSON.parse(JSON.stringify(ui.sent[1])), {type:'dealOffer',target:'b',terms:'Travel for spice', assert.deepEqual(JSON.parse(JSON.stringify(ui.sent[2])), {type:'dealOffer',target:'b',terms:'Travel for spice',
payment:{kind:'immediateBribe',payer:'b',recipient:'a',amount:1}, payment:{kind:'immediateBribe',payer:'b',recipient:'a',amount:1},
travel:{kind:'ship',territory:'carthag',minimum:1,answer:true}}); travel:{kind:'ship',territory:'carthag',minimum:1,answer:true}});
}); });
@@ -247,7 +259,12 @@ void test('the group offer form selects an invited traveler and revalidates part
assert.deepEqual(JSON.parse(JSON.stringify(ui.sent[1])), {type:'dealOffer',targets:['b','d'],terms:'Group travel', assert.deepEqual(JSON.parse(JSON.stringify(ui.sent[1])), {type:'dealOffer',targets:['b','d'],terms:'Group travel',
payment:{kind:'immediateBribe',payer:'b',recipient:'d',amount:1}, payment:{kind:'immediateBribe',payer:'b',recipient:'d',amount:1},
travel:{kind:'ship',territory:'carthag',minimum:1,answer:true,actor:'d'}}); travel:{kind:'ship',territory:'carthag',minimum:1,answer:true,actor:'d'}});
ui.select(0,'deferredBribe'); assert.equal(button()?.props.disabled,true, 'Deferred group payment remains unavailable.'); ui.select(0,'deferredBribe'); assert.equal(button()?.props.disabled,false);
const deferredForm = ui.render().find(node => node.type === 'form'); assert.ok(deferredForm);
(deferredForm.props.onSubmit as (event:{preventDefault():void}) => void)({preventDefault() {}});
assert.deepEqual(JSON.parse(JSON.stringify(ui.sent[2])), {type:'dealOffer',targets:['b','d'],terms:'Group travel',
payment:{kind:'deferredBribe',payer:'b',recipient:'d',amount:1,dueTurn:2},
travel:{kind:'ship',territory:'carthag',minimum:1,answer:true,actor:'d'}});
}); });
void test('the author chooses a future travel turn and can return to the legacy current-turn packet', () => { void test('the author chooses a future travel turn and can return to the legacy current-turn packet', () => {
+14 -7
View File
@@ -119,11 +119,11 @@ void test('a released deal cannot retain an unfulfilled live travel receipt', ()
reject(corrupted, f.target, f.currentEnd); reject(corrupted, f.target, f.currentEnd);
}); });
void test('travel terms reject payment combinations, multiparty packets and malformed claims', () => { void test('travel terms reject invalid payment, participant and malformed travel claims', () => {
const f = fixture(), term: Term = { kind: 'ship', territory: f.shipmentTerritory, minimum: 1, answer: true }; const f = fixture(), term: Term = { kind: 'ship', territory: f.shipmentTerritory, minimum: 1, answer: true };
const basic = { type: 'dealOffer', target: f.target, terms: 'Agreed travel.', travel: term } satisfies Action; const basic = { type: 'dealOffer', target: f.target, terms: 'Agreed travel.', travel: term } satisfies Action;
reject(f.game, f.asker, { ...basic, payment: { kind: 'deferredBribe', payer: f.target, reject(f.game, f.asker, { ...basic, payment: { kind: 'deferredBribe', payer: f.target,
recipient: f.asker, amount: 1, dueTurn: f.game.turn } }); recipient: f.asker, amount: 1, dueTurn: f.game.turn - 1 } });
reject(f.game, f.asker, { type: 'dealOffer', targets: [f.target, f.asker], terms: 'Travel.', travel: term }); reject(f.game, f.asker, { type: 'dealOffer', targets: [f.target, f.asker], terms: 'Travel.', travel: term });
reject(f.game, f.asker, { ...basic, travel: { ...term, minimum: 0 } }); reject(f.game, f.asker, { ...basic, travel: { ...term, minimum: 0 } });
reject(f.game, f.asker, { ...basic, travel: { ...term, answer: 'yes' } }); reject(f.game, f.asker, { ...basic, travel: { ...term, answer: 'yes' } });
@@ -162,7 +162,7 @@ void test('final consent to a conflicting obligation rolls back without disturbi
assert.equal(status(completed, f.target, first.id), 'fulfilled'); assert.equal(status(completed, f.target, first.id), 'fulfilled');
}); });
void test('a pending travel term prevents final consent to a separate current-turn deferred bribe', () => { void test('a pending travel term can coexist with a separately accepted current-turn deferred bribe', () => {
const f = fixture(), offered = offer(f.game, f.asker, f.target, const f = fixture(), offered = offer(f.game, f.asker, f.target,
{ kind: 'ship', territory: f.shipmentTerritory, minimum: 1, answer: true }); { kind: 'ship', territory: f.shipmentTerritory, minimum: 1, answer: true });
let game = accept(offered.game, f.target, offered.id); let game = accept(offered.game, f.target, offered.id);
@@ -171,15 +171,22 @@ void test('a pending travel term prevents final consent to a separate current-tu
const payment = game.deals!.at(-1)!; const payment = game.deals!.at(-1)!;
assert.notEqual(payment.id, offered.id); assert.notEqual(payment.id, offered.id);
assert.equal(payment.status, 'offered'); assert.equal(payment.status, 'offered');
const before = structuredClone(game); const cash = player(game, f.target).spice, incoming = player(game, f.asker).bribes;
reject(game, f.target, { type: 'dealRespond', deal: payment.id, accept: true }); assert.ok(cash >= f.shipmentCost + 1);
assert.deepEqual(game, before); game = accept(game, f.target, payment.id);
assert.equal(game.deals!.find(deal => deal.id === offered.id)!.status, 'active'); assert.equal(game.deals!.find(deal => deal.id === offered.id)!.status, 'active');
assert.equal(game.deals!.find(deal => deal.id === payment.id)!.status, 'offered'); assert.equal(game.deals!.find(deal => deal.id === payment.id)!.status, 'active');
assert.equal(game.deals!.find(deal => deal.id === payment.id)!.paymentStatus, 'pending');
assert.equal(status(game, f.target, offered.id), 'pending'); assert.equal(status(game, f.target, offered.id), 'pending');
assert.equal(receipt(game, offered.id).released, false); assert.equal(receipt(game, offered.id).released, false);
game = act(game, f.target, {type:'dealPay', deal:payment.id});
assert.equal(player(game, f.target).spice, cash - 1);
assert.equal(player(game, f.asker).bribes, incoming + 1);
assert.equal(game.deals!.find(deal => deal.id === payment.id)!.paymentStatus, 'paid');
const completed = settle(act(game, f.target, f.shipmentAction)); const completed = settle(act(game, f.target, f.shipmentAction));
assert.equal(status(completed, f.target, offered.id), 'fulfilled'); assert.equal(status(completed, f.target, offered.id), 'fulfilled');
assert.equal(player(completed, f.target).spice, cash - 1 - f.shipmentCost);
assert.deepEqual(inventory(completed), f.originalCards);
}); });
void test('final travel consent rejects a target with a live native Truthtrance bribe promise', () => { void test('final travel consent rejects a target with a live native Truthtrance bribe promise', () => {
+23 -9
View File
@@ -1,7 +1,7 @@
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
import test from 'node:test'; import test from 'node:test';
import { import {
createMultipartyPublicDeal, createPublicDeal, parsePublicDealTravel, PublicDealError, createMultipartyPublicDeal, createPublicDeal, markPublicDealPaid, parsePublicDealTravel, PublicDealError,
publicDealTravelActor, publicDealTravelDueTurn, publicDealTravelActor, publicDealTravelDueTurn,
releasePublicDeal, respondPublicDeal, setPublicDealTravel, validatePublicDeals, withdrawPublicDeal, releasePublicDeal, respondPublicDeal, setPublicDealTravel, validatePublicDeals, withdrawPublicDeal,
type PublicDeal, type PublicDealSeat, type PublicDeal, type PublicDealSeat,
@@ -195,13 +195,19 @@ for (const [payer, recipient] of [['a', 'b'], ['b', 'a']] as const) void test(`a
assert.equal(released.status, 'released'); assert.equal(released.status, 'released');
}); });
void test('paid travel rejects deferred and forged persisted payment shapes', () => { void test('deferred paid travel survives the two-party lifecycle and forged payment shapes reject', () => {
const deferred = { kind: 'deferredBribe', payer: 'a', recipient: 'b', amount: 1, dueTurn: 3 } as const; const deferred = { kind: 'deferredBribe', payer: 'a', recipient: 'b', amount: 1, dueTurn: 3 } as const;
const paid = { kind: 'immediateBribe', payer: 'a', recipient: 'b', amount: 1 } as const; const paid = { kind: 'immediateBribe', payer: 'a', recipient: 'b', amount: 1 } as const;
for (const payment of [deferred]) { const offer = setPublicDealTravel(createPublicDeal(seats, 'a', 'b', 'Terms', 3, 'deferred-travel', deferred), term, seats);
const offer = createPublicDeal(seats, 'a', 'b', 'Terms', 3, `invalid-${payment.kind}`, payment); const active = respondPublicDeal(offer, seats, 'b', true);
assert.throws(() => setPublicDealTravel(offer, term, seats), PublicDealError); assert.equal(active.paymentStatus, 'pending');
assert.throws(() => validatePublicDeals([{ ...offer, travel: term }], seats), PublicDealError); const paidDeal = markPublicDealPaid(active, seats, 'a');
assert.equal(paidDeal.paymentStatus, 'paid');
for (const deal of [offer,active,paidDeal]) {
const roundtrip = JSON.parse(JSON.stringify(deal)) as PublicDeal;
validatePublicDeals([roundtrip], seats);
assert.deepEqual(roundtrip.payment, deferred);
assert.deepEqual(roundtrip.travel, term);
} }
const multi = createMultipartyPublicDeal(seats, 'a', ['b', 'c'], 'Terms', 3, 'multi-paid', paid); const multi = createMultipartyPublicDeal(seats, 'a', ['b', 'c'], 'Terms', 3, 'multi-paid', paid);
for (const invalid of [ for (const invalid of [
@@ -247,11 +253,19 @@ for (const payer of ['a', 'b', 'c']) for (const recipient of ['a', 'b', 'c']) {
}); });
} }
void test('group travel still rejects deferred payments and forged party identities', () => { void test('group travel accepts deferred payments but rejects forged party identities', () => {
const deferred = { kind: 'deferredBribe', payer: 'a', recipient: 'b', amount: 1, dueTurn: 3 } as const; const deferred = { kind: 'deferredBribe', payer: 'a', recipient: 'b', amount: 1, dueTurn: 3 } as const;
const group = createMultipartyPublicDeal(seats, 'a', ['b', 'c'], 'Terms', 3, 'group-deferred', deferred); const group = createMultipartyPublicDeal(seats, 'a', ['b', 'c'], 'Terms', 3, 'group-deferred', deferred);
assert.throws(() => setPublicDealTravel(group, { ...term, actor: 'b' }, seats), PublicDealError); const offered = setPublicDealTravel(group, { ...term, actor: 'b' }, seats);
assert.throws(() => validatePublicDeals([{ ...group, travel: { ...term, actor: 'b' } }], seats), PublicDealError); assert.throws(() => respondPublicDeal(offered, seats, 'b', true), PublicDealError);
const active = respondPublicDeal(respondPublicDeal(offered, seats, 'c', true), seats, 'b', true);
assert.equal(active.paymentStatus, 'pending');
const settled = markPublicDealPaid(active, seats, 'a');
for (const deal of [offered,active,settled]) {
validatePublicDeals([JSON.parse(JSON.stringify(deal))], seats);
assert.deepEqual(deal.payment, deferred);
assert.deepEqual(deal.travel, { ...term, actor: 'b' });
}
const immediate = { kind: 'immediateBribe', payer: 'a', recipient: 'b', amount: 1 } as const; const immediate = { kind: 'immediateBribe', payer: 'a', recipient: 'b', amount: 1 } as const;
const paid = setPublicDealTravel(createMultipartyPublicDeal(seats, 'a', ['b', 'c'], 'Terms', 3, 'group-paid', immediate), const paid = setPublicDealTravel(createMultipartyPublicDeal(seats, 'a', ['b', 'c'], 'Terms', 3, 'group-paid', immediate),
{ ...term, actor: 'b' }, seats); { ...term, actor: 'b' }, seats);
@@ -0,0 +1,68 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { applyAction, viewGame, type Game } from '../game/engine';
import { botActions } from '../game/bots';
import { DIFFICULTIES } from '../game/bot-profiles';
import { actTruthBid as act, advanceTruthBid as advance, truthBidClean as clean,
truthBidInventory as inventory, truthBidPlayer as player } from './fixture-truth-bid';
import { createTruthTurnBidFixture } from './fixture-truth-turn-bid';
/** Real public Basic setup and Truthtrances. Stage unopened Spice order and
* move existing force/leader pieces into Tanks for the requested Revival. */
function fixture() {
const f = createTruthTurnBidFixture();
let game = structuredClone(f.afterSetup);
for (const {position, from, card} of f.spiceOrder) {
const [selected] = game.spiceDeck.splice(from, 1);
assert.deepEqual(selected, card);
game.spiceDeck.splice(position, 0, selected);
}
game = advance(game, state => state.turn === 1 && state.phase === 2 && clean(state));
const emperor = player(game, f.target);
assert.equal(emperor.spice, 10);
const leader = emperor.leaders.find(row => row.strength === 2); assert.ok(leader);
for (const disc of emperor.leaders) { disc.dead = true; disc.deaths = 1; }
emperor.reserves -= 3; emperor.tanks += 3;
assert.deepEqual(inventory(game), f.originalCards);
return {f, game, leader:leader.id};
}
function ask(game: Game, asker: string, card: string, question: object): Game {
game = act(game, asker, {type:'card', card});
for (let count = 0; game.truthtrance?.stage === 'priority' && count < game.players.length; count++) {
const seat = game.players.find(row => !game.truthtrance!.passed.includes(row.id)); assert.ok(seat);
game = act(game, seat.id, {type:'truthPass'});
}
assert.equal(game.truthtrance?.stage, 'ask');
return act(game, asker, {type:'truthAsk', question});
}
for (const mode of ['forces', 'leader', 'expression'] as const) {
for (const first of ['bid', 'revival'] as const) {
void test(`Basic ${mode} and phase-bid commitments give all bot difficulties a legal bid (${first} first)`, () => {
const {f, game:initial, leader} = fixture();
const bid = {kind:'phaseBid', target:f.target, turn:initial.turn, minimum:4};
const revival = mode === 'forces'
? {kind:'revival', target:f.target, turn:initial.turn, counter:'total', minimum:3}
: mode === 'leader'
? {kind:'leaderRevival', target:f.target, turn:initial.turn, leader}
: {kind:'revivalExpression', target:f.target, turn:initial.turn, claim:{kind:'and', terms:[
{kind:'forces', counter:'total', minimum:3}, {kind:'leader', leader},
]}};
const questions = first === 'bid' ? [bid, revival] : [revival, bid];
let game = ask(initial, f.asker, f.truths[0], questions[0]);
game = act(game, f.target, {type:'truthAnswer', answer:'yes'});
game = ask(game, f.asker, f.truths[1], questions[1]);
game = act(game, f.target, {type:'truthAnswer', answer:'yes'});
game = advance(game, state => clean(state) && state.phase === 3 && state.auction?.active === f.target);
assert.ok(viewGame(game, f.target).phaseBidPromiseGuide, 'The server has a legal qualifying bid guide');
for (const difficulty of DIFFICULTIES) {
const view = viewGame(game, f.target);
view.players.find(row => row.id === f.target)!.bot = difficulty;
const action = botActions(view)[0]; assert.ok(action);
assert.equal(action.type, 'bid', `${difficulty} must honor the outstanding phase bid`);
assert.doesNotThrow(() => applyAction(game, f.target, action));
}
});
}
}