@chrischall/warapp-mcp 0.23.2 → 0.25.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,285 @@
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
+ /** #686: whether a Gift may be in play (`cards` from the settings; unknown: any card may be). */
116
+ const giftPossible = (cards) => cards === undefined || cards.includes('Gift');
117
+ /**
118
+ * #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
119
+ * bound them: read exactly as my own truces (`breachWatch`, each party in turn as the one taken from): a party taking, in
120
+ * view, a territory another party held on the board before is `broken`; one lost into the fog beside the other party is
121
+ * `massing` (ambiguous), never `broken`, and a fog reveal is no event. With a Gift possibly in play (or the cards unknown)
122
+ * a take may be a gift: `massing`. A pair counts from the turn it was agreed until the pact ended, either party's own
123
+ * notice had run, or a `rest: 'end'` notice ended it. I am never a party watched here. Writes nothing: the ledger keeps a
124
+ * reported pact's status unless the owner records it.
125
+ */
126
+ export function pactBreachWatch(a, o) {
127
+ if (a.agreedTurn === undefined)
128
+ return [];
129
+ const parties = partiesOf(a, o.me).filter((p) => p !== o.me);
130
+ const leaves = new Map((a.notices ?? []).map((n) => [n.player, noticeEnds(a, n)]));
131
+ const endAll = pactEndByNotice(a);
132
+ const ends = [a.endedTurn, endAll].filter((t) => t !== undefined);
133
+ const out = [];
134
+ for (const against of parties)
135
+ for (const by of parties) {
136
+ if (by === against)
137
+ continue;
138
+ const until = [...ends, leaves.get(by), leaves.get(against)].filter((t) => t !== undefined);
139
+ const { parties: _p, notices: _n, exceptions: _e, caps: _c, source: _s, ...rest } = a;
140
+ // No cap: a border cap is a term of mine, never one between them.
141
+ const { borderCap: _b, ...terms } = a.terms;
142
+ const pair = { ...rest, with: by, terms, ...(until.length ? { endedTurn: Math.min(...until) } : {}) };
143
+ // The party taken from stands where I stand in breachWatch; its orders are never known.
144
+ const boards = o.boards.map(({ turn, board }) => ({ turn, board }));
145
+ for (const f of breachWatch({ agreement: pair, graph: o.graph, boards, me: against, ...(o.cards !== undefined ? { cards: o.cards } : {}) })) {
146
+ if (f.kind === 'broken') {
147
+ const ids = f.territories.join(', ');
148
+ out.push(giftPossible(o.cards)
149
+ ? { 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` }
150
+ : { kind: 'broken', by, against, turn: f.turn, territories: f.territories, evidence: `player ${by} took territories ${ids} from player ${against} on turn ${f.turn}` });
151
+ }
152
+ else if (f.kind === 'massing' && f.ambiguous) {
153
+ out.push({
154
+ kind: 'massing',
155
+ by,
156
+ against,
157
+ turn: f.turn,
158
+ territories: f.territories,
159
+ ambiguous: true,
160
+ 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`,
161
+ });
162
+ }
163
+ }
164
+ }
165
+ 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));
166
+ }
167
+ /**
168
+ * The pacts between other players that bind this turn, report only: the ledger's pacts that do not include me
169
+ * now (reported, or one whose notice of mine has run), the Diplomacy cards between two other players that the
170
+ * decoder is sure of (`diplomacy`, src/analysis/cards-in-effect.ts) and the Diplomacy 2 alliances between two
171
+ * other players (`mod`, GameFeed ids). A party out of the game is never named. Sorted by parties, then source.
172
+ */
173
+ export function pactsWithoutMe(input) {
174
+ const { me, turn, players } = input;
175
+ const out = [];
176
+ for (const a of input.pacts ?? []) {
177
+ const st = pactState(a, turn, players, me);
178
+ if ((st.phase !== 'active' && st.phase !== 'notice') || st.includesMe)
179
+ continue;
180
+ const flags = input.watch ? pactBreachWatch(a, { ...input.watch, me, turn, players }) : undefined;
181
+ out.push({
182
+ parties: st.remaining,
183
+ source: a.source ?? 'ledger',
184
+ agreement: a.id,
185
+ ...(st.endsTurn !== undefined ? { endsTurn: st.endsTurn } : {}),
186
+ ...(flags ? { flags, ...(flags.some((f) => f.kind === 'broken') ? { broken: true } : {}) } : {}),
187
+ });
188
+ }
189
+ const pair = (x, y) => (x === y || x === me || y === me || !bound(players, x) || !bound(players, y) ? undefined : [x, y].sort(byNum));
190
+ for (const d of input.diplomacy ?? []) {
191
+ const p = pair(d.players[0], d.players[1]);
192
+ if (p && d.untilTurn > turn)
193
+ out.push({ parties: p, source: 'card', untilTurn: d.untilTurn });
194
+ }
195
+ for (const m of input.mod ?? []) {
196
+ const p = pair(m[0], m[1]);
197
+ if (p)
198
+ out.push({ parties: p, source: 'mod' });
199
+ }
200
+ const key = (k) => k.parties.join(',');
201
+ return out.sort((x, y) => (key(x) < key(y) ? -1 : key(x) > key(y) ? 1 : x.source.localeCompare(y.source)));
202
+ }
203
+ /** #686: the pacts that still count: a broken one does not. */
204
+ export const pactsInForce = (pacts) => pacts.filter((k) => !k.broken);
205
+ /** The players `player` is at peace with by `pacts` (every other party of a pact naming it, a broken one aside), ascending. */
206
+ export function atPeaceWith(pacts, player) {
207
+ return [...new Set(pactsInForce(pacts).filter((k) => k.parties.includes(player)).flatMap((k) => k.parties.filter((p) => p !== player)))].sort(byNum);
208
+ }
209
+ /** Pairs of players at peace with each other by `pacts` (a broken one aside), as `a,b` keys (a < b). */
210
+ export function pactPairs(pacts) {
211
+ const out = new Map();
212
+ for (const k of pactsInForce(pacts))
213
+ for (let i = 0; i < k.parties.length; i++)
214
+ for (let j = i + 1; j < k.parties.length; j++)
215
+ out.set(`${k.parties[i]},${k.parties[j]}`, [k.parties[i], k.parties[j]]);
216
+ return [...out.values()].sort((x, y) => x[0] - y[0] || x[1] - y[1]);
217
+ }
218
+ /** A pact as a sentence names its source. */
219
+ export function pactLabel(k) {
220
+ switch (k.source) {
221
+ case 'reported':
222
+ return `a reported pact, ${k.agreement}`;
223
+ case 'ledger':
224
+ return `pact ${k.agreement}, which you left`;
225
+ case 'card':
226
+ return `a Diplomacy card${k.untilTurn !== undefined ? ` until turn ${k.untilTurn}` : ''}`;
227
+ case 'mod':
228
+ return 'a Diplomacy 2 alliance';
229
+ }
230
+ }
231
+ /**
232
+ * #680 (report only): each territory of mine on `board` beside which two or more parties of one pact each show a
233
+ * stack (a territory of theirs with 2 armies or more, owner and armies shown) — they may strike it together. By
234
+ * pact, then territory. Changes nothing.
235
+ */
236
+ export function pactJointThreats(graph, board, me, pacts) {
237
+ const at = new Map(board.territories.map((t) => [t.territoryId, t]));
238
+ const ownerOf = (id) => {
239
+ const t = at.get(id);
240
+ return t && ownerShown(t) && t.owner.kind === 'player' ? t.owner.playerId : undefined;
241
+ };
242
+ const mine = board.territories.filter((t) => ownerOf(t.territoryId) === me).map((t) => t.territoryId).sort(byNum);
243
+ const out = [];
244
+ // #686: a broken pact is no longer a reason to expect a joint strike.
245
+ for (const pact of pactsInForce(pacts)) {
246
+ const parties = new Set(pact.parties);
247
+ for (const t of mine) {
248
+ const best = new Map();
249
+ for (const n of [...neighborsOf(graph, t)].sort(byNum)) {
250
+ const owner = ownerOf(n);
251
+ const armies = at.get(n)?.armies;
252
+ if (owner === undefined || !parties.has(owner) || armies === null || armies === undefined || armies < 2)
253
+ continue;
254
+ const was = best.get(owner);
255
+ if (!was || armies > was.armies)
256
+ best.set(owner, { player: owner, from: n, armies });
257
+ }
258
+ if (best.size >= 2)
259
+ out.push({ territory: t, pact, stacks: [...best.values()].sort((x, y) => x.player - y.player) });
260
+ }
261
+ }
262
+ return out;
263
+ }
264
+ /** #680: the warnings warapp_plan_turn adds for {@link pactJointThreats}, one per pact (report only). */
265
+ export function pactThreatWarnings(threats) {
266
+ const byPact = new Map();
267
+ for (const t of threats)
268
+ byPact.set(t.pact, [...(byPact.get(t.pact) ?? []), t]);
269
+ return [...byPact].map(([pact, ts]) => {
270
+ const who = pact.parties.length === 2 ? `Players ${pact.parties[0]} and ${pact.parties[1]}` : `Players ${pact.parties.join(', ')}`;
271
+ const where = ts
272
+ .map((t) => `territory ${t.territory} (${t.stacks.map((s) => `player ${s.player} from ${s.from} with ${s.armies}`).join(', ')})`)
273
+ .join('; ');
274
+ 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`} ` +
275
+ `of yours: ${where}. They may strike together (#680). Report only: the plan's orders do not change — warapp_check_plan tries their joint attack.`);
276
+ });
277
+ }
278
+ /** #680: the sentence the outlook's basis gains when pacts between other players are known; `''` with none. */
279
+ export function pactsBasis(all) {
280
+ const pacts = pactsInForce(all);
281
+ if (!pacts.length)
282
+ return '';
283
+ const list = pacts.map((k) => `players ${k.parties.join(' and ')} (${pactLabel(k)})`).join('; ');
284
+ return ` Known pacts between other players: ${list} — they may act together; each opponent's strength above is its own (report only, #680).`;
285
+ }
@@ -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)