Support multiple travel terms in public deals
Verify and publish checkpoint container / container (push) Canceled after 0s

This commit is contained in:
Quintine committed 2026-11-16 15:19:10 +11:00
1 parent 13c337a24a
commit d7d0f89625
13 files changed
+790 -51

No files matched your search

@@ -0,0 +1,82 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import {
createMultipartyPublicDeal, createPublicDeal, publicDealTravelTerms, PublicDealError,
releasePublicDeal, respondPublicDeal, setPublicDealAdditionalTravel, setPublicDealTravel,
validatePublicDeals, withdrawPublicDeal, type PublicDeal, type PublicDealSeat,
} from '../game/public-deals';
const seats: PublicDealSeat[] = ['a','b','c','d'].map(id => ({id}));
const original = {kind:'ship', territory:'polar_sink', minimum:1, answer:true} as const;
const extra = {kind:'move', territory:'imperial_basin', minimum:1, answer:true, actor:'a'} as const;
const pair = () => setPublicDealTravel(createPublicDeal(seats, 'a', 'b', 'Travel together', 3, 'pair'), original, seats);
const group = () => setPublicDealTravel(createMultipartyPublicDeal(seats, 'a', ['b','c','d'], 'Travel together', 3, 'group'),
{...original, actor:'b'}, seats);
void test('legacy, explicit and repeated additional travel terms retain stable indexes through the deal lifecycle', () => {
const source = pair();
assert.deepEqual(publicDealTravelTerms(source), [{travel:original}]);
const values = [extra, {...extra}, {...original, actor:'b', dueTurn:5}];
const offered = setPublicDealAdditionalTravel(source, values, seats);
assert.equal(source.additionalTravel, undefined);
assert.deepEqual(publicDealTravelTerms(offered), [
{travel:original}, {travel:extra,index:0}, {travel:extra,index:1},
{travel:{...original,actor:'b',dueTurn:5},index:2},
]);
assert.notEqual(offered.additionalTravel![0], values[0]);
const active = respondPublicDeal(offered, seats, 'b', true);
const released = releasePublicDeal(releasePublicDeal(active, seats, 'a', true), seats, 'b', true);
for (const saved of [offered,active,released]) {
const restored = JSON.parse(JSON.stringify(saved)) as PublicDeal;
validatePublicDeals([restored], seats);
assert.deepEqual(publicDealTravelTerms(restored), publicDealTravelTerms(offered));
}
});
void test('additional terms require a fresh original travel term, explicit participants and valid deadlines', () => {
const source = pair();
const withoutTravel = createPublicDeal(seats, 'a', 'b', 'Travel', 3, 'without');
assert.throws(() => setPublicDealAdditionalTravel(withoutTravel, [extra], seats), PublicDealError);
for (const bad of [null, undefined, [], Array(13).fill(extra), [original],
[{...extra,actor:'c'}], [{...extra,actor:''}], [{...extra,dueTurn:2}],
[{...extra,dueTurn:undefined}], [{...extra,sector:9}]])
assert.throws(() => setPublicDealAdditionalTravel(source, bad, seats), PublicDealError);
const twelve = setPublicDealAdditionalTravel(source, Array(12).fill(extra), seats);
assert.equal(publicDealTravelTerms(twelve).length, 13);
assert.throws(() => setPublicDealAdditionalTravel(twelve, [extra], seats), PublicDealError);
assert.throws(() => setPublicDealAdditionalTravel(respondPublicDeal(source,seats,'b',true), [extra], seats), PublicDealError);
for (const malformed of [
{...source, additionalTravel:[]}, {...source, additionalTravel:[original]},
{...withoutTravel, additionalTravel:[extra]}, {...source, additionalTravel:undefined},
]) assert.throws(() => validatePublicDeals([malformed], seats), PublicDealError);
});
void test('group non-travelers accept before any invited traveler, then travelers accept in either order', () => {
const offered = setPublicDealAdditionalTravel(group(), [{...extra,actor:'c'}], seats);
for (const actor of ['b','c'])
assert.throws(() => respondPublicDeal(offered,seats,actor,true), PublicDealError);
const beforeTravelers = respondPublicDeal(offered,seats,'d',true);
for (const [first,last] of [['b','c'],['c','b']]) {
const partial = respondPublicDeal(beforeTravelers,seats,first,true);
assert.equal(partial.status,'offered');
validatePublicDeals([JSON.parse(JSON.stringify(partial))],seats);
const active = respondPublicDeal(partial,seats,last,true);
assert.equal(active.status,'active');
assert.deepEqual(active.acceptVotes,['a','b','c','d']);
validatePublicDeals([active],seats);
}
assert.throws(() => validatePublicDeals([{...offered,acceptVotes:['a','b']}],seats), PublicDealError);
assert.equal(respondPublicDeal(offered,seats,'b',false).status,'declined');
assert.equal(withdrawPublicDeal(offered,seats,'a').status,'withdrawn');
});
void test('proposer consent is implicit and repeated traveler identities need only one vote', () => {
const self = setPublicDealTravel(createMultipartyPublicDeal(seats,'a',['b','c','d'],'I travel',3,'self'),
{...original,actor:'a'},seats);
const offered = setPublicDealAdditionalTravel(self, [extra,{...extra,actor:'b'},{...extra,actor:'b'}], seats);
assert.throws(() => respondPublicDeal(offered,seats,'b',true), PublicDealError);
const otherVotes = respondPublicDeal(respondPublicDeal(offered,seats,'c',true),seats,'d',true);
const active = respondPublicDeal(otherVotes,seats,'b',true);
assert.equal(active.status,'active');
assert.equal(publicDealTravelTerms(active).length,4);
});
@@ -0,0 +1,120 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { readFileSync } from 'node:fs';
import { runInNewContext } from 'node:vm';
import { createElement, isValidElement, type ReactElement, type ReactNode } from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
import * as jsxRuntime from 'react/jsx-runtime';
import ts from 'typescript';
import * as board from '../game/board';
import * as catalog from '../game/catalog';
import * as coalitionAlliance from '../game/coalition-alliance';
import * as publicDeals from '../game/public-deals';
import { PublicDealList, PublicDeals, publicDealOfferAction, publicDealRequests } from '../components/public-deals';
import { TravelPromises } from '../components/travel-promises';
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)];
}
const players = [
{id:'a',name:'Alice',faction:'atreides',ally:null},
{id:'b',name:'Basil',faction:'harkonnen',ally:null},
{id:'c',name:'Cora',faction:'emperor',ally:null},
{id:'d',name:'Dara',faction:'fremen',ally:null},
];
const base = {status:'playing',turn:2,me:'a',roomControl:null,coalitionState:null,
players,deals:[],dealTravelStatus:{},dealAdditionalTravelStatus:{}} as unknown as GameView;
const travel = {kind:'ship',territory:'carthag',minimum:1,answer:true} as const;
const extra = {actor:'a',kind:'move',territory:'imperial_basin',minimum:1,answer:true} as const;
void test('additional travel packets retain old defaults, validate actors and bound terms', () => {
assert.deepEqual(publicDealOfferAction(['b'],'Terms',undefined,'a',2,travel,[],[],[extra]),
{type:'dealOffer',target:'b',terms:'Terms',travel,additionalTravel:[extra]});
assert.deepEqual(publicDealOfferAction(['b'],'Terms',undefined,'a',2,travel,[],[],[{...extra,dueTurn:4}]),
{type:'dealOffer',target:'b',terms:'Terms',travel,additionalTravel:[{...extra,dueTurn:4}]});
assert.deepEqual(publicDealOfferAction(['b'],'Terms',undefined,'a',2,travel,[],[],[{...extra,dueTurn:2}]),
{type:'dealOffer',target:'b',terms:'Terms',travel,additionalTravel:[extra]});
assert.equal(publicDealOfferAction(['b'],'Terms',undefined,'a',2,undefined,[],[],[extra]),null);
assert.equal(publicDealOfferAction(['b'],'Terms',undefined,'a',2,travel,[],[],[{...extra,actor:'c'}]),null);
assert.equal(publicDealOfferAction(['b'],'Terms',undefined,'a',2,travel,[],[],[{...extra,dueTurn:1}]),null);
assert.equal(publicDealOfferAction(['b'],'Terms',undefined,'a',2,travel,[],[],Array(13).fill(extra)),null);
});
void test('travelers wait for nontravelers, then either can accept; individual statuses remain visible', () => {
const deal = {id:'deal',from:'a',to:'b',participants:['a','b','c','d'],acceptVotes:['a'],
terms:'Two journeys',turn:2,status:'offered',releaseVotes:[],travel:{...travel,actor:'b'},
additionalTravel:[{...extra,actor:'c'}]};
const game = {...base,me:'b',deals:[deal]} as unknown as GameView;
const button = (current:GameView) => elements(PublicDealList({game:current,disabled:false,act() {}}))
.find(row => row.props.children === 'Accept deal');
assert.equal(button(game)?.props.disabled,true);
assert.deepEqual(publicDealRequests(game),[['offer','deal','waiting']]);
const afterOther = {...game,deals:[{...deal,acceptVotes:['a','d']}]} as unknown as GameView;
assert.equal(button(afterOther)?.props.disabled,false);
assert.equal(button({...afterOther,me:'c'} as unknown as GameView)?.props.disabled,false);
assert.deepEqual(publicDealRequests({...afterOther,me:'c'} as unknown as GameView),[['offer','deal','ready']]);
const active = {...base,me:'c',deals:[{...deal,status:'active',acceptVotes:['a','b','c','d']}],
dealTravelStatus:{deal:'fulfilled'},dealAdditionalTravelStatus:{deal:['pending']}} as unknown as GameView;
const html = renderToStaticMarkup(createElement(PublicDealList,{game:active,disabled:false,act() {}}));
assert.match(html,/Additional travel 1:/); assert.match(html,/Travel status: fulfilled/); assert.match(html,/Travel status: pending/);
assert.deepEqual(publicDealRequests(active),[['travel','deal','0']]);
});
void test('own travel history uses the indexed term status for release explanations', () => {
const records = [0,1].map(index => ({event:`e${index}`,sourceDeal:'deal',sourceDealIndex:index,player:'a',
asker:'b',turn:2,mixed:{kind:'action',action:{kind:'ship',territory:'carthag',minimum:1}},
answer:true,fulfilled:false,released:true}));
const game = {...base,phase:6,active:null,travelPromises:records,allLeaders:[],combatLocations:[],
dealTravelStatus:{deal:'fulfilled'},dealAdditionalTravelStatus:{deal:['void','released']}} as unknown as GameView;
const html = renderToStaticMarkup(createElement(TravelPromises,{game,busy:false,act() {}}));
assert.match(html,/Void: this agreement is no longer possible/);
assert.match(html,/Released: this whole commitment is no longer binding/);
});
/** Exercise actual form state callbacks through an isolated React hook stub. */
void test('the form authors, validates and removes an additional term', () => {
const states:unknown[] = [], sent:Action[] = []; let cursor = 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 = cursor++; 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:() => ({current:null}),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 new Error(`Unexpected import ${name}`);
}});
assert.ok(exported.PublicDeals);
const render = () => {cursor=0; return elements(exported.PublicDeals!({game:base,busy:false,act(action) {sent.push(action);}}));};
const check = (index:number) => {const node=render().filter(row => row.type === 'input' && row.props.type === 'checkbox')[index];
assert.ok(node); (node.props.onChange as (event:{target:{checked:boolean}}) => void)({target:{checked:true}});};
const select = (index:number,value:string) => {const node=render().filter(row => row.type === 'select')[index]; assert.ok(node);
(node.props.onChange as (event:{target:{value:string}}) => void)({target:{value}});};
const click = (text:string) => {const node=render().find(row => row.type === 'button' &&
(Array.isArray(row.props.children) ? row.props.children.join('') : row.props.children) === text); assert.ok(node);
(node.props.onClick as () => void)();};
check(0); check(4); // Basil, then travel after four seats' recipient/payment checkboxes.
select(2,'carthag');
const textarea=render().find(row => row.type === 'textarea'); assert.ok(textarea);
(textarea.props.onChange as (event:{target:{value:string}}) => void)({target:{value:'Two journeys'}});
click('Add travel term');
const submit = () => render().find(row => row.type === 'button' && row.props.type === 'submit');
assert.equal(submit()?.props.disabled,true);
select(4,'a'); select(5,'move'); select(7,'imperial_basin');
assert.equal(submit()?.props.disabled,false);
const form = render().find(row => row.type === 'form'); assert.ok(form);
(form.props.onSubmit as (event:{preventDefault():void}) => void)({preventDefault() {}});
assert.deepEqual(JSON.parse(JSON.stringify(sent.at(-1))),
{type:'dealOffer',target:'b',terms:'Two journeys',travel,additionalTravel:[extra]});
click('Remove additional travel 1'); assert.equal(submit()?.props.disabled,false);
});
@@ -0,0 +1,70 @@
// @dune-suite integration
import assert from 'node:assert/strict';
import test from 'node:test';
import type { GameView } from '../game/engine';
import type { PublicDeal } from '../game/public-deals';
const base = process.env.DUNE_TEST_URL ?? 'http://localhost:3000';
async function request(path: string, cookie?: string, body?: unknown) {
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} : {}),
},
...(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 new two-seat room exercises the actual authenticated offer and consent;
* future terms need no staged counters, special cards, or existing saves. */
void test('authenticated multi-travel deal exposes each independently scheduled term', async () => {
const host = await request('/api/rooms',undefined,{
name:'Multiple journeys',faction:'harkonnen',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:'Other traveler',faction:'atreides'});
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 travel = {kind:'ship',territory:'polar_sink',minimum:1,answer:true,dueTurn:view.turn+1};
const additionalTravel = [
{actor:host.data.me,kind:'move',territory:'imperial_basin',minimum:1,answer:true,dueTurn:view.turn+1},
{actor:guest.data.me,kind:'move',territory:'polar_sink',minimum:1,answer:false,dueTurn:view.turn+2},
];
await act(host.cookie,{type:'dealOffer',target:guest.data.me,
terms:'We each agree to the listed future journeys.',travel,additionalTravel});
const offered = view.deals.at(-1); assert.ok(offered);
assert.equal(offered.status,'offered');
assert.deepEqual(offered.travel,travel);
assert.deepEqual(offered.additionalTravel,additionalTravel);
assert.equal(view.dealTravelStatus[offered.id],undefined);
assert.equal(view.dealAdditionalTravelStatus[offered.id],undefined);
await act(guest.cookie,{type:'dealRespond',deal:offered.id,accept:true});
for (const seat of seats) {
const read = await request(path,seat.cookie);
assert.equal(read.status,200,JSON.stringify(read.data));
const active: PublicDeal | undefined = read.data.deals.find(deal => deal.id === offered.id);
assert.ok(active); assert.equal(active.status,'active');
assert.deepEqual(active.travel,travel);
assert.deepEqual(active.additionalTravel,additionalTravel);
assert.equal(read.data.dealTravelStatus[offered.id],'scheduled');
assert.deepEqual(read.data.dealAdditionalTravelStatus[offered.id],['scheduled','scheduled']);
}
});
@@ -0,0 +1,95 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { viewGame, type Game } from '../game/engine';
import { actTruthTravel as act, createTruthTravelFixture as fixture, settleTruthTravel as settle } from './fixture-truth-travel';
/** Native public Basic setup and phase-five shipment; only unopened component
* order is selected by the shared fixture. All terms and actions are real. */
function accepted() {
const f = fixture(), dueTurn = f.game.turn+1;
let game = act(f.game,f.asker,{type:'dealOffer',target:f.target,terms:'Ship, move and ship next turn.',
travel:{kind:'ship',territory:f.shipmentTerritory,minimum:1,answer:true},
additionalTravel:[
{actor:f.target,kind:'move',territory:f.movementTerritory,minimum:1,answer:true},
{actor:f.target,kind:'ship',territory:f.shipmentTerritory,minimum:1,answer:true,dueTurn},
]});
const id = game.deals!.at(-1)!.id;
game = act(game,f.target,{type:'dealRespond',deal:id,accept:true});
return {f,game,id};
}
function linked(game: Game, id: string) {
return (game.travelPromises ?? []).filter(row => row.sourceDeal === id);
}
void test('primary and indexed additional terms project independent pending, scheduled, fulfilled and released statuses', () => {
const {f,id,game:initial} = accepted();
let game = initial;
assert.equal(viewGame(game,f.target).dealTravelStatus[id],'pending');
assert.deepEqual(viewGame(game,f.target).dealAdditionalTravelStatus[id],['pending','scheduled']);
game = settle(act(game,f.target,f.shipmentAction));
assert.equal(viewGame(game,f.asker).dealTravelStatus[id],'fulfilled');
assert.deepEqual(viewGame(game,f.asker).dealAdditionalTravelStatus[id],['pending','scheduled']);
game = settle(act(game,f.target,f.firstMove));
assert.deepEqual(viewGame(game,f.target).dealAdditionalTravelStatus[id],['fulfilled','scheduled']);
game = act(game,f.asker,{type:'dealRelease',deal:id,agree:true});
game = act(game,f.target,{type:'dealRelease',deal:id,agree:true});
assert.equal(viewGame(game,f.target).dealTravelStatus[id],'fulfilled');
assert.deepEqual(viewGame(game,f.target).dealAdditionalTravelStatus[id],['fulfilled','released']);
const rows = linked(game,id);
assert.equal(rows[0].fulfilled,true);
assert.equal(rows[1].fulfilled,true);
assert.equal(rows[2].releasedByDeal,true);
});
void test('missing, duplicated, misindexed and mismatched deal travel receipts are rejected without mutation', () => {
const {f,id,game} = accepted();
const variants: Array<(draft: Game) => void> = [
draft => { draft.travelPromises = draft.travelPromises!.filter(row => !(row.sourceDeal === id && row.sourceDealIndex === 0)); },
draft => { const row = linked(draft,id)[1]; draft.travelPromises!.push(structuredClone(row)); },
draft => { linked(draft,id)[1].sourceDealIndex = 1; },
draft => { linked(draft,id)[1].sourceDealIndex = 12; },
draft => { linked(draft,id)[1].player = f.asker; },
draft => { linked(draft,id)[1].turn += 1; },
draft => { linked(draft,id)[1].answer = false; },
];
for (const corrupt of variants) {
const draft = structuredClone(game); corrupt(draft);
const before = structuredClone(draft);
assert.throws(() => viewGame(draft,f.target));
assert.deepEqual(draft,before,'Rejecting a damaged source receipt does not mutate the game.');
}
});
void test('legacy immediate-settlement signatures stay identical when there are no additional travel terms', () => {
const f = fixture();
let game = act(f.game,f.asker,{type:'dealOffer',target:f.target,terms:'Two immediate payments.',
payment:{kind:'immediateBribe',payer:f.target,recipient:f.asker,amount:1},
additionalImmediatePayments:[{kind:'immediateBribe',payer:f.target,recipient:f.asker,amount:1}]});
const id = game.deals!.at(-1)!.id;
game = act(game,f.target,{type:'dealRespond',deal:id,accept:true});
const deal = game.deals!.find(row => row.id === id)!;
assert.equal(deal.additionalTravel,undefined);
const expected = 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]);
const receipt = game.publicDealSettlementHistory?.find(row => row.deal === id);
assert.equal(receipt?.signature,expected);
const restored = JSON.parse(JSON.stringify(game)) as Game;
assert.doesNotThrow(() => viewGame(restored,f.target));
});
void test('additional travel is included in new immediate-settlement signatures', () => {
const f = fixture();
let game = act(f.game,f.asker,{type:'dealOffer',target:f.target,terms:'Pay and travel twice.',
payment:{kind:'immediateBribe',payer:f.target,recipient:f.asker,amount:1},
additionalImmediatePayments:[{kind:'immediateBribe',payer:f.target,recipient:f.asker,amount:1}],
travel:{kind:'ship',territory:f.shipmentTerritory,minimum:1,answer:true},
additionalTravel:[{actor:f.target,kind:'move',territory:f.movementTerritory,minimum:1,answer:true}]});
const id = game.deals!.at(-1)!.id;
game = act(game,f.target,{type:'dealRespond',deal:id,accept:true});
assert.ok(game.publicDealSettlementHistory?.some(row => row.deal === id));
const changed = structuredClone(game), term = changed.deals!.find(row => row.id === id)!.additionalTravel![0];
term.minimum += 1;
const before = structuredClone(changed);
assert.throws(() => viewGame(changed,f.target));
assert.deepEqual(changed,before);
});
+153
View File
@@ -0,0 +1,153 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { createGame, joinGame, newPlayer, type Action, type Game } from '../game/engine';
import { actTruthTravel as act, createTruthTravelFixture as fixture, settleTruthTravel as settle,
truthTravelClean as clean, truthTravelInventory as inventory, truthTravelPlayer as player } from './fixture-truth-travel';
import { nextStrongholdFactionsNativeStep as next } 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 consent preserves every vote, commitment and resource.');
}
function receipts(game: Game, id: string) {
return (game.travelPromises ?? []).filter(row => row.sourceDeal === id);
}
function answer(game: Game, actor: string, id: string) {
return act(game, actor, {type:'dealRespond',deal:id,accept:true});
}
/** The original shared fixture reaches a real Basic shipment turn through
* public setup and native phase actions. No force, purse, promise or vote is
* assigned by these tests. */
void test('one deal binds and fulfills both a real shipment and a real move', () => {
const f = fixture(), originalCards = inventory(f.game), cash = player(f.game,f.target).spice;
let game = act(f.game,f.asker,{type:'dealOffer',target:f.target,terms:'Ship, then move.',
travel:{kind:'ship',territory:f.shipmentTerritory,minimum:1,answer:true},
additionalTravel:[{actor:f.target,kind:'move',territory:f.movementTerritory,minimum:1,answer:true}]});
const id = game.deals!.at(-1)!.id;
assert.equal(receipts(game,id).length,0);
game = answer(game,f.target,id);
const bound = receipts(game,id);
assert.equal(bound.length,2);
assert.equal(bound[0].sourceDealIndex,undefined);
assert.equal(bound[1].sourceDealIndex,0);
assert.ok(bound.every(row => row.player === f.target && !row.fulfilled && !row.released));
reject(game,f.target,f.currentEnd);
game = settle(act(game,f.target,f.shipmentAction));
assert.equal(receipts(game,id)[0].fulfilled,true);
assert.equal(receipts(game,id)[1].fulfilled,false);
reject(game,f.target,f.currentEnd);
game = settle(act(game,f.target,f.firstMove));
assert.ok(receipts(game,id).every(row => row.fulfilled));
assert.equal(player(game,f.target).spice,cash-f.shipmentCost);
assert.deepEqual(inventory(game),originalCards);
});
void test('a conflicting same-turn required and forbidden shipment rejects final consent', () => {
const f = fixture();
const offered = act(f.game,f.asker,{type:'dealOffer',target:f.target,terms:'Inconsistent shipment terms.',
travel:{kind:'ship',territory:f.shipmentTerritory,minimum:1,answer:true},
additionalTravel:[{actor:f.target,kind:'ship',territory:f.shipmentTerritory,minimum:1,answer:false}]});
const id = offered.deals!.at(-1)!.id;
reject(offered,f.target,{type:'dealRespond',deal:id,accept:true});
assert.equal(offered.deals!.at(-1)!.status,'offered');
assert.equal(receipts(offered,id).length,0);
});
void test('shipment, movement and a due payment cannot spend the same purse twice', () => {
const f = fixture(), cash = player(f.game,f.target).spice;
assert.ok(cash >= f.shipmentCost);
const offered = act(f.game,f.asker,{type:'dealOffer',target:f.target,terms:'Pay and travel.',
travel:{kind:'ship',territory:f.shipmentTerritory,minimum:1,answer:true},
additionalTravel:[{actor:f.target,kind:'move',territory:f.movementTerritory,minimum:1,answer:true}],
payment:{kind:'deferredBribe',payer:f.target,recipient:f.asker,amount:cash,dueTurn:f.game.turn}});
const id = offered.deals!.at(-1)!.id;
reject(offered,f.target,{type:'dealRespond',deal:id,accept:true});
assert.equal(offered.deals!.at(-1)!.status,'offered');
assert.equal(receipts(offered,id).length,0);
assert.equal(player(offered,f.target).spice,cash);
});
void test('future multi-travel contradictions reject atomically at final acceptance', () => {
const f = fixture(), dueTurn = f.game.turn+1;
const offered = act(f.game,f.asker,{type:'dealOffer',target:f.target,terms:'Contradictory future shipment.',
travel:{kind:'ship',territory:f.shipmentTerritory,minimum:1,answer:true,dueTurn},
additionalTravel:[{actor:f.target,kind:'ship',territory:f.shipmentTerritory,minimum:1,answer:false,dueTurn}]});
const id = offered.deals!.at(-1)!.id;
reject(offered,f.target,{type:'dealRespond',deal:id,accept:true});
assert.equal(receipts(offered,id).length,0);
});
void test('unanimous release cancels every unfinished term, including future travel for another participant', () => {
const f = fixture(), dueTurn = f.game.turn+1;
let game = act(f.game,f.asker,{type:'dealOffer',target:f.target,terms:'Both of us will ship next turn.',
travel:{kind:'ship',territory:f.shipmentTerritory,minimum:1,answer:true,dueTurn},
additionalTravel:[{actor:f.asker,kind:'ship',territory:'polar_sink',minimum:1,answer:true,dueTurn}]});
const id = game.deals!.at(-1)!.id;
game = answer(game,f.target,id);
assert.deepEqual(receipts(game,id).map(row => row.player),[f.target,f.asker]);
assert.ok(receipts(game,id).every(row => row.turn === dueTurn));
game = act(game,f.asker,{type:'dealRelease',deal:id,agree:true});
assert.ok(receipts(game,id).every(row => !row.released));
game = act(game,f.target,{type:'dealRelease',deal:id,agree:true});
assert.ok(receipts(game,id).every(row => row.released && row.releasedByDeal));
assert.equal(game.deals!.at(-1)!.status,'released');
});
const proposer = 'atreides', firstTraveler = 'emperor', secondTraveler = 'harkonnen', other = 'fremen';
function reach(game: Game, until: (state: Game) => boolean): Game {
for (let count = 0; count < 1200; count++) {
if (until(game)) return game;
assert.notEqual(game.status,'finished');
const step = next(game); assert.ok(step, `Native continuation needed at ${game.turn}/${game.phase}.`);
game = act(game,step.actor,step.action);
}
throw Error('The original group game did not reach the movement opportunity.');
}
/** Four actual human Basic seats, with only unopened cards and spice ordering
* selected, continued through native setup to the Emperor's real turn. */
function groupFixture(): Game {
let game = createGame('MULTITRAVEL',newPlayer(proposer,'Atreides','atreides'),false,[]);
for (const [id,faction] of [[firstTraveler,'emperor'],[secondTraveler,'harkonnen'],[other,'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,proposer,{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 = reach(game,state => state.status === 'playing');
const from = game.spiceDeck.findIndex(card => 'territory' in card && !card.discovery); assert.ok(from >= 0);
game.spiceDeck.unshift(game.spiceDeck.splice(from,1)[0]);
return reach(game,state => state.turn === 1 && state.phase === 5 && state.active === firstTraveler && clean(state));
}
let source: Game | undefined;
const group = () => structuredClone(source ??= groupFixture());
for (const voters of [[firstTraveler,secondTraveler],[secondTraveler,firstTraveler]]) void test(
`ordinary invitees consent before both travelers, who may accept in either order (${voters.join(' then ')})`, () => {
const initial = group(), dueTurn = initial.turn+1, cards = inventory(initial);
let game = act(initial,proposer,{type:'dealOffer',targets:[firstTraveler,secondTraveler,other],
terms:'Two players will ship on different turns.',
travel:{actor:firstTraveler,kind:'ship',territory:'polar_sink',minimum:1,answer:true},
additionalTravel:[{actor:secondTraveler,kind:'ship',territory:'polar_sink',minimum:1,answer:true,dueTurn}]});
const id = game.deals!.at(-1)!.id;
reject(game,voters[0],{type:'dealRespond',deal:id,accept:true});
game = answer(game,other,id);
game = answer(game,voters[0],id);
assert.equal(game.deals!.at(-1)!.status,'offered');
assert.equal(receipts(game,id).length,0);
game = answer(game,voters[1],id);
assert.equal(game.deals!.at(-1)!.status,'active');
assert.deepEqual(receipts(game,id).map(row => [row.player,row.turn]),
[[firstTraveler,initial.turn],[secondTraveler,dueTurn]]);
game = reach(act(game,firstTraveler,{type:'ship',territory:'polar_sink',sector:0,amount:1,elite:0,allyPayment:0}),
state => clean(state) && !state.pendingShipment);
assert.equal(receipts(game,id)[0].fulfilled,true);
assert.equal(receipts(game,id)[1].fulfilled,false);
assert.deepEqual(inventory(game),cards);
},
);