@chrischall/warapp-mcp 0.24.0 → 0.26.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,327 @@
1
+ import { neighborsOf } from './graph.js';
2
+ import { ownerShown } from './plan/shared.js';
3
+ import { breachWatch } from './relations.js';
4
+ const byNum = (a, b) => a - b;
5
+ const alive = (p) => p !== undefined && (p.state === undefined || p.state === 'Playing');
6
+ const turnedAI = (p) => p.isAI === true || p.humanTurnedIntoAI === true;
7
+ const bound = (players, id) => {
8
+ const p = players.find((x) => x.id === id);
9
+ return alive(p) && !turnedAI(p);
10
+ };
11
+ /** Whether `a` is a pact (it carries `parties`), not a two-party agreement between me and `with`. */
12
+ export const isPact = (a) => a.parties !== undefined;
13
+ /** Every party of `a`, ascending: its `parties`, else me and `with`. */
14
+ export const partiesOf = (a, me) => a.parties ? [...a.parties] : [me, a.with].sort(byNum);
15
+ /** The first turn a party's notice on `a` no longer binds it: the notice turn + the notice turns, capped by `untilTurn` + 1. */
16
+ export function noticeEnds(a, n) {
17
+ const ends = n.turn + a.terms.noticeTurns;
18
+ return a.terms.untilTurn !== undefined ? Math.min(ends, a.terms.untilTurn + 1) : ends;
19
+ }
20
+ /** The first turn the whole pact no longer binds because a notice chose `rest: 'end'` (the earliest such); `undefined` with none. */
21
+ export function pactEndByNotice(a) {
22
+ const ends = (a.notices ?? []).filter((n) => n.rest === 'end').map((n) => noticeEnds(a, n));
23
+ return ends.length ? Math.min(...ends) : undefined;
24
+ }
25
+ /**
26
+ * A pact's state on `turn`: `over` when recorded ended or broken, once two players remain in the game, its
27
+ * `untilPlayerOut` player is out, past its `untilTurn`, once a notice whose `rest` is `end` has run
28
+ * (`notice-served`), or fewer than two parties are still bound (each party leaves once its own notice has run, or
29
+ * when it is out of the game or turned AI — automatically, the rest going on); else `proposed`, or `active` —
30
+ * `notice` when a notice running would end it, by `rest: 'end'` or by leaving fewer than two (`endsTurn`, the first
31
+ * turn that is so).
32
+ */
33
+ export function pactState(a, turn, players, me) {
34
+ const parties = partiesOf(a, me);
35
+ const over = (reason) => ({ phase: 'over', reason, remaining: [], leaving: [], left: parties, includesMe: false });
36
+ const s = a.status;
37
+ if (s === 'ended' || s === 'broken-by-them' || s === 'broken-by-me')
38
+ return over(s);
39
+ if (players.filter(alive).length <= 2)
40
+ return over('two-left');
41
+ const out = a.terms.untilPlayerOut;
42
+ if (out !== undefined && !alive(players.find((p) => p.id === out)))
43
+ return over('player-out');
44
+ if (a.terms.untilTurn !== undefined && turn > a.terms.untilTurn)
45
+ return over('until-turn');
46
+ const ends = new Map((a.notices ?? []).map((n) => [n.player, noticeEnds(a, n)]));
47
+ // A notice whose `rest` is `end` ends the whole pact once it has run (the owner's choice; never decided here).
48
+ const endAll = pactEndByNotice(a);
49
+ if (endAll !== undefined && turn >= endAll)
50
+ return over('notice-served');
51
+ const left = parties.filter((p) => !bound(players, p) || (ends.has(p) && turn >= ends.get(p)));
52
+ const remaining = parties.filter((p) => !left.includes(p));
53
+ if (remaining.length < 2)
54
+ return over('too-few-parties');
55
+ const includesMe = remaining.includes(me);
56
+ if (s === 'proposed-by-me' || s === 'proposed-by-them')
57
+ return { phase: 'proposed', remaining, leaving: [], left, includesMe };
58
+ const leaving = remaining
59
+ .filter((p) => ends.has(p))
60
+ .map((player) => ({ player, endsTurn: ends.get(player) }))
61
+ .sort((x, y) => x.endsTurn - y.endsTurn || x.player - y.player);
62
+ let count = remaining.length;
63
+ let endsTurn = endAll;
64
+ for (const l of leaving) {
65
+ count--;
66
+ if (count < 2) {
67
+ endsTurn = endsTurn === undefined ? l.endsTurn : Math.min(endsTurn, l.endsTurn);
68
+ break;
69
+ }
70
+ }
71
+ return { phase: endsTurn !== undefined ? 'notice' : 'active', ...(endsTurn !== undefined ? { endsTurn } : {}), remaining, leaving, left, includesMe };
72
+ }
73
+ /**
74
+ * The pairwise agreement between me and `partner` that a pact I am in amounts to — what a two-party truce with
75
+ * the same terms would be: `with` the partner; while agreed, in notice when either of us gave notice (the
76
+ * earlier, mine on a tie), `notice-by-me` or `notice-by-them` from that turn; the history without the other
77
+ * parties' notices. A third party's notice whose `rest` is `end` ends the truce with this partner too: its
78
+ * `terms.untilTurn` is capped at the turn before that notice runs, so it ends on its own (`until-turn`) without
79
+ * crediting the partner with a notice it never gave. Everything else (id, terms, exceptions, caps, turns) is the pact's.
80
+ */
81
+ export function pairwiseView(a, me, partner) {
82
+ const { parties: _p, notices, source: _s, ...rest } = a;
83
+ const history = a.history
84
+ .filter((h) => h.by === undefined || h.by === me || h.by === partner)
85
+ .map(({ by: _by, ...h }) => h);
86
+ const view = { ...rest, with: partner, history };
87
+ if (view.status === 'agreed') {
88
+ const mine = notices?.find((n) => n.player === me);
89
+ const theirs = notices?.find((n) => n.player === partner);
90
+ const pick = [mine, theirs].filter((n) => n !== undefined).sort((x, y) => x.turn - y.turn)[0];
91
+ if (pick) {
92
+ view.status = pick.player === me ? 'notice-by-me' : 'notice-by-them';
93
+ view.noticeTurn = pick.turn;
94
+ }
95
+ const end = pactEndByNotice({ terms: a.terms, notices: notices?.filter((n) => n.player !== me && n.player !== partner) });
96
+ if (end !== undefined && (view.terms.untilTurn === undefined || end - 1 < view.terms.untilTurn))
97
+ view.terms = { ...view.terms, untilTurn: end - 1 };
98
+ }
99
+ return view;
100
+ }
101
+ /** The pairwise views of a pact I am a party to, one per other party (ascending); `[]` when I am not one. */
102
+ export function pactViews(a, me) {
103
+ const parties = partiesOf(a, me);
104
+ if (!parties.includes(me))
105
+ return [];
106
+ return parties.filter((p) => p !== me).map((p) => pairwiseView(a, me, p));
107
+ }
108
+ /**
109
+ * Every truce with me as the planner, the submit refusal and the checks read it: the two-party agreements as they
110
+ * are, then each pact I am a party to as one pairwise agreement per partner. A pact without me is left out.
111
+ */
112
+ export function trucesWithMe(agreements, pacts, me) {
113
+ return [...agreements, ...(pacts ?? []).flatMap((p) => pactViews(p, me))];
114
+ }
115
+ const pairOf = (x, y) => (x < y ? [x, y] : [y, x]);
116
+ /** #686: whether parties `x` and `y` of `k` have broken with each other. */
117
+ export const pairBroken = (k, x, y) => {
118
+ const [a, b] = pairOf(x, y);
119
+ return (k.brokenPairs ?? []).some(([p, q]) => p === a && q === b);
120
+ };
121
+ /** #686: the watch's verdict on a pact's parties: its broken pairs, and `broken` once every pair is. */
122
+ function watched(parties, flags) {
123
+ const keys = new Map();
124
+ for (const f of flags)
125
+ if (f.kind === 'broken')
126
+ keys.set(pairOf(f.by, f.against).join(','), pairOf(f.by, f.against));
127
+ const brokenPairs = [...keys.values()].filter(([a, b]) => parties.includes(a) && parties.includes(b)).sort((x, y) => x[0] - y[0] || x[1] - y[1]);
128
+ const pairs = (parties.length * (parties.length - 1)) / 2;
129
+ return { flags: [...flags], ...(brokenPairs.length ? { brokenPairs } : {}), ...(pairs > 0 && brokenPairs.length >= pairs ? { broken: true } : {}) };
130
+ }
131
+ /** #686: whether a Gift may be in play (`cards` from the settings; unknown: any card may be). */
132
+ const giftPossible = (cards) => cards === undefined || cards.includes('Gift');
133
+ /**
134
+ * #686 (report only): what my boards show of the parties of `a` — a pact I am not in now — keeping it, over the turns it
135
+ * bound them: read exactly as my own truces (`breachWatch`, each party in turn as the one taken from): a party taking, in
136
+ * view, a territory another party held on the board before is `broken`; one lost into the fog beside the other party is
137
+ * `massing` (ambiguous), never `broken`, and a fog reveal is no event. With a Gift possibly in play (or the cards unknown)
138
+ * a take may be a gift: `massing`. A pair counts from the turn it was agreed until the pact ended, either party's own
139
+ * notice had run, or a `rest: 'end'` notice ended it. I am never a party watched here. Writes nothing: the ledger keeps a
140
+ * reported pact's status unless the owner records it.
141
+ */
142
+ export function pactBreachWatch(a, o) {
143
+ if (a.agreedTurn === undefined)
144
+ return [];
145
+ const parties = partiesOf(a, o.me).filter((p) => p !== o.me);
146
+ const leaves = new Map((a.notices ?? []).map((n) => [n.player, noticeEnds(a, n)]));
147
+ const endAll = pactEndByNotice(a);
148
+ const ends = [a.endedTurn, endAll].filter((t) => t !== undefined);
149
+ const out = [];
150
+ for (const against of parties)
151
+ for (const by of parties) {
152
+ if (by === against)
153
+ continue;
154
+ const until = [...ends, leaves.get(by), leaves.get(against)].filter((t) => t !== undefined);
155
+ const { parties: _p, notices: _n, exceptions: _e, caps: _c, source: _s, ...rest } = a;
156
+ // No cap: a border cap is a term of mine, never one between them.
157
+ const { borderCap: _b, ...terms } = a.terms;
158
+ const pair = { ...rest, with: by, terms, ...(until.length ? { endedTurn: Math.min(...until) } : {}) };
159
+ // The party taken from stands where I stand in breachWatch; its orders are never known.
160
+ const boards = o.boards.map(({ turn, board }) => ({ turn, board }));
161
+ for (const f of breachWatch({ agreement: pair, graph: o.graph, boards, me: against, ...(o.cards !== undefined ? { cards: o.cards } : {}) })) {
162
+ if (f.kind === 'broken') {
163
+ const ids = f.territories.join(', ');
164
+ out.push(giftPossible(o.cards)
165
+ ? { kind: 'massing', by, against, turn: f.turn, territories: f.territories, ambiguous: true, evidence: `player ${by} took territories ${ids} from player ${against} on turn ${f.turn}, but a Gift may have handed ${f.territories.length === 1 ? 'it' : 'them'} over` }
166
+ : { kind: 'broken', by, against, turn: f.turn, territories: f.territories, evidence: `player ${by} took territories ${ids} from player ${against} on turn ${f.turn}` });
167
+ }
168
+ else if (f.kind === 'massing' && f.ambiguous) {
169
+ out.push({
170
+ kind: 'massing',
171
+ by,
172
+ against,
173
+ turn: f.turn,
174
+ territories: f.territories,
175
+ ambiguous: true,
176
+ evidence: `player ${against}'s territories ${f.territories.join(', ')} were lost or hit on turn ${f.turn} beside player ${by}, but the fog or another player leaves who did it open`,
177
+ });
178
+ }
179
+ }
180
+ }
181
+ return out.sort((x, y) => x.turn - y.turn || x.by - y.by || x.against - y.against || (x.kind < y.kind ? -1 : x.kind > y.kind ? 1 : 0));
182
+ }
183
+ /**
184
+ * The pacts between other players that bind this turn, report only: the ledger's pacts that do not include me
185
+ * now (reported, or one whose notice of mine has run), the Diplomacy cards between two other players that the
186
+ * decoder is sure of (`diplomacy`, src/analysis/cards-in-effect.ts) and the Diplomacy 2 alliances between two
187
+ * other players (`mod`, GameFeed ids). A party out of the game is never named. Sorted by parties, then source.
188
+ */
189
+ export function pactsWithoutMe(input) {
190
+ const { me, turn, players } = input;
191
+ const out = [];
192
+ for (const a of input.pacts ?? []) {
193
+ const st = pactState(a, turn, players, me);
194
+ if ((st.phase !== 'active' && st.phase !== 'notice') || st.includesMe)
195
+ continue;
196
+ const flags = input.watch ? pactBreachWatch(a, { ...input.watch, me, turn, players }) : undefined;
197
+ out.push({
198
+ parties: st.remaining,
199
+ source: a.source ?? 'ledger',
200
+ agreement: a.id,
201
+ ...(st.endsTurn !== undefined ? { endsTurn: st.endsTurn } : {}),
202
+ ...(flags ? watched(st.remaining, flags) : {}),
203
+ });
204
+ }
205
+ const pair = (x, y) => (x === y || x === me || y === me || !bound(players, x) || !bound(players, y) ? undefined : [x, y].sort(byNum));
206
+ // #686, owner decision of 2026-12-01: a pact the game enforces is watched too, as one agreed from `from` (a card: the
207
+ // first turn it binds; the mod's alliance, whose start is not read: the turn just resolved only) until `until`.
208
+ const watchGame = (parties, from, until) => {
209
+ if (!input.watch)
210
+ return {};
211
+ const a = {
212
+ id: 'game',
213
+ with: parties[1],
214
+ parties,
215
+ kind: 'truce',
216
+ status: 'agreed',
217
+ createdTurn: from,
218
+ agreedTurn: from,
219
+ ...(until !== undefined ? { endedTurn: until } : {}),
220
+ terms: { scope: 'all', noticeTurns: 0 },
221
+ history: [],
222
+ };
223
+ return watched(parties, pactBreachWatch(a, { ...input.watch, me, turn, players }));
224
+ };
225
+ for (const d of input.diplomacy ?? []) {
226
+ const p = pair(d.players[0], d.players[1]);
227
+ if (p && d.untilTurn > turn)
228
+ out.push({ parties: p, source: 'card', untilTurn: d.untilTurn, ...watchGame(p, d.fromTurn ?? turn - 1, d.untilTurn) });
229
+ }
230
+ for (const m of input.mod ?? []) {
231
+ const p = pair(m[0], m[1]);
232
+ if (p)
233
+ out.push({ parties: p, source: 'mod', ...watchGame(p, turn - 1, undefined) });
234
+ }
235
+ const key = (k) => k.parties.join(',');
236
+ return out.sort((x, y) => (key(x) < key(y) ? -1 : key(x) > key(y) ? 1 : x.source.localeCompare(y.source)));
237
+ }
238
+ /** #686: the pacts that still count: one every pair of which has broken does not (a pact with some pairs broken does). */
239
+ export const pactsInForce = (pacts) => pacts.filter((k) => !k.broken);
240
+ /** The parties of `k` that `player` is still at peace with (its broken pairs aside), ascending. */
241
+ export const peersOf = (k, player) => k.parties.filter((p) => p !== player && !pairBroken(k, p, player)).sort(byNum);
242
+ /** The players `player` is at peace with by `pacts` (every other party of a pact naming it, a broken pair aside), ascending. */
243
+ export function atPeaceWith(pacts, player) {
244
+ return [...new Set(pactsInForce(pacts).filter((k) => k.parties.includes(player)).flatMap((k) => peersOf(k, player)))].sort(byNum);
245
+ }
246
+ /** Pairs of players at peace with each other by `pacts` (a broken pair aside), as `a,b` keys (a < b). */
247
+ export function pactPairs(pacts) {
248
+ const out = new Map();
249
+ for (const k of pactsInForce(pacts))
250
+ for (let i = 0; i < k.parties.length; i++)
251
+ for (let j = i + 1; j < k.parties.length; j++)
252
+ if (!pairBroken(k, k.parties[i], k.parties[j]))
253
+ out.set(`${k.parties[i]},${k.parties[j]}`, [k.parties[i], k.parties[j]]);
254
+ return [...out.values()].sort((x, y) => x[0] - y[0] || x[1] - y[1]);
255
+ }
256
+ /** A pact as a sentence names its source. */
257
+ export function pactLabel(k) {
258
+ switch (k.source) {
259
+ case 'reported':
260
+ return `a reported pact, ${k.agreement}`;
261
+ case 'ledger':
262
+ return `pact ${k.agreement}, which you left`;
263
+ case 'card':
264
+ return `a Diplomacy card${k.untilTurn !== undefined ? ` until turn ${k.untilTurn}` : ''}`;
265
+ case 'mod':
266
+ return 'a Diplomacy 2 alliance';
267
+ }
268
+ }
269
+ /**
270
+ * #680 (report only): each territory of mine on `board` beside which two or more parties of one pact each show a
271
+ * stack (a territory of theirs with 2 armies or more, owner and armies shown) — they may strike it together. By
272
+ * pact, then territory. Changes nothing.
273
+ */
274
+ export function pactJointThreats(graph, board, me, pacts) {
275
+ const at = new Map(board.territories.map((t) => [t.territoryId, t]));
276
+ const ownerOf = (id) => {
277
+ const t = at.get(id);
278
+ return t && ownerShown(t) && t.owner.kind === 'player' ? t.owner.playerId : undefined;
279
+ };
280
+ const mine = board.territories.filter((t) => ownerOf(t.territoryId) === me).map((t) => t.territoryId).sort(byNum);
281
+ const out = [];
282
+ // #686: a broken pact is no longer a reason to expect a joint strike.
283
+ for (const pact of pactsInForce(pacts)) {
284
+ const parties = new Set(pact.parties);
285
+ for (const t of mine) {
286
+ const best = new Map();
287
+ for (const n of [...neighborsOf(graph, t)].sort(byNum)) {
288
+ const owner = ownerOf(n);
289
+ const armies = at.get(n)?.armies;
290
+ if (owner === undefined || !parties.has(owner) || armies === null || armies === undefined || armies < 2)
291
+ continue;
292
+ const was = best.get(owner);
293
+ if (!was || armies > was.armies)
294
+ best.set(owner, { player: owner, from: n, armies });
295
+ }
296
+ // #686: only parties still at peace with another party beside it strike together.
297
+ const stacks = [...best.values()].filter((s) => [...best.keys()].some((q) => q !== s.player && !pairBroken(pact, s.player, q)));
298
+ if (stacks.length >= 2)
299
+ out.push({ territory: t, pact, stacks: stacks.sort((x, y) => x.player - y.player) });
300
+ }
301
+ }
302
+ return out;
303
+ }
304
+ /** #680: the warnings warapp_plan_turn adds for {@link pactJointThreats}, one per pact (report only). */
305
+ export function pactThreatWarnings(threats) {
306
+ const byPact = new Map();
307
+ for (const t of threats)
308
+ byPact.set(t.pact, [...(byPact.get(t.pact) ?? []), t]);
309
+ return [...byPact].map(([pact, ts]) => {
310
+ const who = pact.parties.length === 2 ? `Players ${pact.parties[0]} and ${pact.parties[1]}` : `Players ${pact.parties.join(', ')}`;
311
+ const where = ts
312
+ .map((t) => `territory ${t.territory} (${t.stacks.map((s) => `player ${s.player} from ${s.from} with ${s.armies}`).join(', ')})`)
313
+ .join('; ');
314
+ return (`${who} are at peace (${pactLabel(pact)}), and two or more of them each have a stack beside ${ts.length === 1 ? 'a territory' : `${ts.length} territories`} ` +
315
+ `of yours: ${where}. They may strike together (#680). Report only: the plan's orders do not change — warapp_check_plan tries their joint attack.`);
316
+ });
317
+ }
318
+ /** #680: the sentence the outlook's basis gains when pacts between other players are known; `''` with none. */
319
+ export function pactsBasis(all) {
320
+ const pacts = pactsInForce(all);
321
+ if (!pacts.length)
322
+ return '';
323
+ const list = pacts
324
+ .map((k) => `players ${k.parties.join(' and ')} (${pactLabel(k)}${k.brokenPairs?.length ? `; ${k.brokenPairs.map(([a, b]) => `${a} and ${b}`).join(', ')} broke with each other` : ''})`)
325
+ .join('; ');
326
+ return ` Known pacts between other players: ${list} — they may act together; each opponent's strength above is its own (report only, #680).`;
327
+ }
@@ -44,6 +44,16 @@ export const TACIT_QUIET_TURNS = 3;
44
44
  * and the partner's. The partner no longer needs me from there on.
45
45
  */
46
46
  export const TRUCE_ENDGAME_RATIO = 0.5;
47
+ /** #680: the most parties a pact can have. */
48
+ export const MAX_PARTIES = 10;
49
+ /** #680: where a pact comes from: recorded by me, reported between others, a Diplomacy card, a Diplomacy 2 alliance. */
50
+ export const PACT_SOURCES = ['ledger', 'reported', 'card', 'mod'];
51
+ /**
52
+ * What becomes of the rest of a pact of three or more when one party gives notice — the owner's choice, never
53
+ * decided automatically: `continue` (the leaver leaves once its notice has run; the others stay bound while two or
54
+ * more remain) or `end` (the whole pact ends when that notice has run).
55
+ */
56
+ export const PACT_RESTS = ['continue', 'end'];
47
57
  /** Territory caps kept per agreement. */
48
58
  export const MAX_CAPS = 20;
49
59
  /** `a` with `caps` set (one per territory: a new one replaces the old) and `remove` lifted; `caps` absent when none is left. */
@@ -35,7 +35,8 @@
35
35
  // joint (#180) two opponents strike one territory of mine (now, or after my orders)
36
36
  // together, each from its largest stack beside it with its deploy: teammates
37
37
  // always, any two opponents in a free-for-all only when I lead (`leader`, the
38
- // caller's call: they gang up on the leader). Both relative orders are tried, with
38
+ // caller's call: they gang up on the leader), and #680 any two at peace by a pact I am not
39
+ // in (`pacts`, marked `pact`: counted in `safe` as teammates are). Both relative orders are tried, with
39
40
  // me first and with me last. `jointFalls` lists the territories that fall to some
40
41
  // pair, with the armies they would need to hold (luck-free: one more than the two
41
42
  // attacks together kill; armies alone, a commander of mine there not counted).
@@ -344,13 +345,15 @@ export function stressPlan(input) {
344
345
  }
345
346
  }
346
347
  // Joint (#180): two opponents on one territory of mine.
348
+ const pactKeys = new Set((input.pacts ?? []).map(([x, y]) => `${Math.min(x, y)},${Math.max(x, y)}`));
347
349
  const largestBeside = (id, t) => stacksOf(id)
348
350
  .filter((s) => neighborsOf(graph, s).includes(t))
349
351
  .sort((x, y) => (start.get(y)?.armies ?? 0) - (start.get(x)?.armies ?? 0) || x - y)[0];
350
352
  for (let i = 0; i < opponents.length; i++) {
351
353
  for (let j = i + 1; j < opponents.length; j++) {
352
354
  const [a, b] = [opponents[i], opponents[j]];
353
- if (!sameTeam(a.id, b.id) && !input.leader)
355
+ const atPeace = !sameTeam(a.id, b.id) && pactKeys.has(`${Math.min(a.id, b.id)},${Math.max(a.id, b.id)}`);
356
+ if (!sameTeam(a.id, b.id) && !input.leader && !atPeace)
354
357
  continue;
355
358
  for (const t of [...mineEither].sort(byNum)) {
356
359
  const [sa, sb] = [largestBeside(a.id, t), largestBeside(b.id, t)];
@@ -360,7 +363,7 @@ export function stressPlan(input) {
360
363
  const dep = deployOn(o, s);
361
364
  return { player: o.id, deployTo: s, deploy: dep, orders: [{ from: s, to: t, armies: allOf(s, dep), withCommander: true }] };
362
365
  };
363
- candidates.push({ ...side(a, sa), kind: 'joint', partner: side(b, sb) });
366
+ candidates.push({ ...side(a, sa), kind: 'joint', partner: side(b, sb), ...(atPeace ? { pact: true } : {}) });
364
367
  }
365
368
  }
366
369
  }
@@ -434,6 +437,7 @@ export function stressPlan(input) {
434
437
  ...(c.kind === 'all-attack' || c.kind === 'joint' ? { attacks: sides.flatMap((x) => x.orders.map((o) => ({ from: o.from, to: o.to }))) } : {}),
435
438
  ...(c.partner ? { partner: c.partner.player, partnerDeployTo: c.partner.deployTo, partnerDeploy: c.partner.deploy } : {}),
436
439
  ...(run.firstOpponent !== undefined ? { firstOpponent: run.firstOpponent } : {}),
440
+ ...(c.pact ? { pact: true } : {}),
437
441
  ...(c.path ? { path: c.path } : {}),
438
442
  firstMover: run.firstMover,
439
443
  lost,
@@ -541,6 +545,7 @@ export function stressPlan(input) {
541
545
  needs: straightKills(pa.power, off) + straightKills(pb.power, off) + 1,
542
546
  bonusesLost,
543
547
  incomeLost: bonusesLost.reduce((n, b) => n + b.value, 0),
548
+ ...(c.pact ? { pact: true } : {}),
544
549
  };
545
550
  const known = joints.get(t);
546
551
  if (!known || j.needs > known.needs)
@@ -0,0 +1,145 @@
1
+ // Turn order (#693): who moves before whom, this turn and the next few, from the turns this server saw. Pure.
2
+ //
3
+ // The rule, read from the client bundle's ServerGame (the server code ships in it): a game keeps one fixed
4
+ // `CyclicMoveOrder` (a list of player ids, random at the start, or by first-turn speed under NoLuckCycle); each turn
5
+ // the players still playing take it forward on an even turn count and REVERSED on an odd one (the client's help:
6
+ // "ABCD becomes DCBA"), then the turn's Order Priority / Order Delay plays re-sort it for that turn only. So whoever
7
+ // moved first moves last on the next turn, in a free-for-all as in a 1v1, and a seat that leaves drops out without
8
+ // changing the others' order. Under `Random` every turn is drawn afresh. Not yet seen live: a projection is the rule's.
9
+ //
10
+ // What is known of a past turn (an `OrderFact`):
11
+ // - `move-order`: the turn's own MoveOrder, when war.app sent it (src/turn-orders.ts; null on every live read so far);
12
+ // - `orders`: inferred from the order the turn's visible moves ran in. Moves run in rounds — one attack/transfer per
13
+ // player per round — and the client REVERSES the player order after every round (A B C, C B A, A B C, …: the
14
+ // turn's order on odd rounds, reversed on even ones; read from the client bundle, and every live turn read so far
15
+ // fits it, war.app's own MoveOrder included). A player's j-th visible move ran in round j or later (fog may hide
16
+ // earlier ones; an order that cannot run is skipped within its slot, so each round runs one per player). When it ran
17
+ // before my j-th move (all of mine are visible, and in round j when every move I sent ran), that player moved before
18
+ // me in round j: before me in the turn's order when j is odd, AFTER me when j is even. A player read both ways in one
19
+ // turn is dropped. The converse (a move after mine) is never sound under fog.
20
+ // A turn with a visible Order Priority or Order Delay play is not used (it re-sorts that turn); one not visible (card
21
+ // plays fogged) can still skew a fact, so facts that disagree are reported as a conflict, never resolved.
22
+ /** The cards that re-sort a turn's move order. */
23
+ const RESORTING_CARDS = new Set(['Order Priority', 'Order Delay']);
24
+ /**
25
+ * What one resolved turn says about the move order relative to me (`null`: nothing). `sentMoves`: how many moves I
26
+ * sent that turn, when known — fewer of mine in the list means one did not run, and my rounds are then unknown.
27
+ */
28
+ export function factOfTurn(seen, me, o = {}) {
29
+ if (seen.orders.some((x) => x.kind === 'card' && x.card !== undefined && RESORTING_CARDS.has(x.card)))
30
+ return null;
31
+ if (seen.moveOrder && seen.moveOrder.length >= 2 && seen.moveOrder.includes(me))
32
+ return { turn: seen.turn, source: 'move-order', full: [...seen.moveOrder] };
33
+ // A move that moved nothing (`actual` 0: no armies left on its source) shares its slot with the player's next order,
34
+ // which war.app runs in it and lists right after it (finished games' histories, 2026-12-01: 34 of 41; the other 7
35
+ // were the player's last order). Counted apart, the pair would shift the player's later rounds by one. One not
36
+ // followed by its player's move keeps its place: under fog the order that ran in that slot may be out of view.
37
+ const moves = seen.orders.map((x, i) => [x, i]).filter(([x]) => x.kind === 'move' && x.player !== null);
38
+ const at = new Map();
39
+ let listedMine = 0;
40
+ moves.forEach(([x, i], k) => {
41
+ if (x.player === me)
42
+ listedMine++;
43
+ if (x.actual === 0 && moves[k + 1]?.[0].player === x.player)
44
+ return;
45
+ const list = at.get(x.player) ?? [];
46
+ list.push(i);
47
+ at.set(x.player, list);
48
+ });
49
+ const mine = at.get(me) ?? [];
50
+ if (!mine.length || (o.sentMoves !== undefined && listedMine < o.sentMoves))
51
+ return null;
52
+ const before = [];
53
+ const after = [];
54
+ for (const [player, idx] of at) {
55
+ if (player === me)
56
+ continue;
57
+ // The rounds (1-based) where this player's move ran before mine: odd → before me, even → after me (snake).
58
+ const rounds = idx.map((pos, j) => (j < mine.length && pos < mine[j] ? j + 1 : 0)).filter((r) => r > 0);
59
+ const inOdd = rounds.some((r) => r % 2 === 1);
60
+ const inEven = rounds.some((r) => r % 2 === 0);
61
+ if (inOdd && !inEven)
62
+ before.push(player);
63
+ else if (inEven && !inOdd)
64
+ after.push(player);
65
+ }
66
+ if (!before.length && !after.length)
67
+ return null;
68
+ return { turn: seen.turn, source: 'orders', ...(before.length ? { before } : {}), ...(after.length ? { after } : {}) };
69
+ }
70
+ const flip = (r) => (r === 'before' ? 'after' : 'before');
71
+ const odd = (n) => Math.abs(n) % 2 === 1;
72
+ const at = (r, from, to) => (odd(to - from) ? flip(r) : r);
73
+ /** A fact's relations at its own turn: every player it places against me. */
74
+ function relationsOf(f, me) {
75
+ const out = new Map();
76
+ if (f.full) {
77
+ const mine = f.full.indexOf(me);
78
+ f.full.forEach((p, i) => p !== me && out.set(p, i < mine ? 'before' : 'after'));
79
+ }
80
+ for (const p of f.before ?? [])
81
+ out.set(p, 'before');
82
+ for (const p of f.after ?? [])
83
+ out.set(p, 'after');
84
+ return out;
85
+ }
86
+ function rowOf(turn, status, rel, playing, order) {
87
+ const pick = (r) => (order ? order.filter((p) => rel.get(p) === r) : playing.filter((p) => rel.get(p) === r));
88
+ return { turn, status, order, beforeMe: pick('before'), afterMe: pick('after'), unknown: playing.filter((p) => !rel.has(p)) };
89
+ }
90
+ export function readTurnOrder(a) {
91
+ const { turn, me, playing } = a;
92
+ const cyclic = a.moveOrder === 'Cycle' || a.moveOrder === 'NoLuckCycle';
93
+ const facts = [...a.facts].filter((f) => f.turn < turn).sort((x, y) => x.turn - y.turn);
94
+ const past = facts.slice(-(a.pastTurns ?? 5)).map((f) => {
95
+ const rel = relationsOf(f, me);
96
+ return { ...rowOf(f.turn, 'known', rel, f.full ? f.full.filter((p) => p !== me) : [...rel.keys()].filter((p) => p !== me), f.full ?? null), basis: f.source };
97
+ });
98
+ // Past rows list every seat the fact placed; the unknown are the players still playing it did not place.
99
+ for (const r of past)
100
+ r.unknown = playing.filter((p) => !r.beforeMe.includes(p) && !r.afterMe.includes(p));
101
+ const perOpponent = playing.map((player) => {
102
+ if (!cyclic)
103
+ return { player, thisTurn: null, basis: null };
104
+ let seen;
105
+ let conflict = false;
106
+ for (const f of facts) {
107
+ const r = relationsOf(f, me).get(player);
108
+ if (!r)
109
+ continue;
110
+ const now = at(r, f.turn, turn);
111
+ if (seen && seen.rel !== now)
112
+ conflict = true;
113
+ seen = { rel: now, basis: f.source, from: f.turn };
114
+ }
115
+ if (conflict)
116
+ return { player, thisTurn: null, basis: null, conflict: true };
117
+ return seen ? { player, thisTurn: seen.rel, basis: seen.basis, fromTurn: seen.from } : { player, thisTurn: null, basis: null };
118
+ });
119
+ const ahead = [];
120
+ const whole = cyclic ? [...facts].reverse().find((f) => f.full) : undefined;
121
+ for (let t = turn; t <= turn + (a.horizon ?? 5); t++) {
122
+ if (!cyclic) {
123
+ ahead.push(rowOf(t, 'unknown', new Map(), playing, null));
124
+ continue;
125
+ }
126
+ const rel = new Map();
127
+ for (const p of perOpponent)
128
+ if (p.thisTurn)
129
+ rel.set(p.player, at(p.thisTurn, turn, t));
130
+ let order = null;
131
+ if (whole && playing.every((p) => whole.full.includes(p) && rel.has(p))) {
132
+ const kept = whole.full.filter((p) => p === me || playing.includes(p));
133
+ order = odd(t - whole.turn) ? kept.reverse() : kept;
134
+ }
135
+ ahead.push(rowOf(t, rel.size ? 'projected' : 'unknown', rel, playing, order));
136
+ }
137
+ const now = perOpponent.map((p) => p.thisTurn);
138
+ const basisNow = perOpponent.some((p) => p.basis === 'orders') ? 'orders' : 'move-order';
139
+ const firstMover = playing.length && now.every((r) => r === 'after')
140
+ ? { who: 'me', turn, basis: basisNow }
141
+ : playing.length && now.every((r) => r === 'before')
142
+ ? { who: 'opponent', turn, basis: basisNow }
143
+ : null;
144
+ return { moveOrder: a.moveOrder ?? null, cyclic, turns: [...past, ...ahead], perOpponent, firstMover };
145
+ }