@chrischall/warapp-mcp 0.0.0 → 0.1.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.
Files changed (177) hide show
  1. package/.claude-plugin/marketplace.json +4 -4
  2. package/.claude-plugin/plugin.json +2 -2
  3. package/README.md +199 -8
  4. package/dist/analysis/award.js +159 -0
  5. package/dist/analysis/bonuses.js +98 -0
  6. package/dist/analysis/breach.js +62 -0
  7. package/dist/analysis/card-support.js +329 -0
  8. package/dist/analysis/card-threats.js +234 -0
  9. package/dist/analysis/cards-in-effect.js +130 -0
  10. package/dist/analysis/chains.js +59 -0
  11. package/dist/analysis/chokepoints.js +140 -0
  12. package/dist/analysis/combat.js +231 -0
  13. package/dist/analysis/commander-safety.js +149 -0
  14. package/dist/analysis/commitments.js +338 -0
  15. package/dist/analysis/exchange.js +155 -0
  16. package/dist/analysis/graph.js +82 -0
  17. package/dist/analysis/guard-off.js +54 -0
  18. package/dist/analysis/guess.js +351 -0
  19. package/dist/analysis/headroom.js +241 -0
  20. package/dist/analysis/hold-diff.js +64 -0
  21. package/dist/analysis/how-lost.js +130 -0
  22. package/dist/analysis/index.js +14 -0
  23. package/dist/analysis/local-deploy.js +159 -0
  24. package/dist/analysis/lookahead.js +108 -0
  25. package/dist/analysis/opponent-profile.js +551 -0
  26. package/dist/analysis/opponents.js +1245 -0
  27. package/dist/analysis/outlook.js +633 -0
  28. package/dist/analysis/overrides.js +60 -0
  29. package/dist/analysis/picks.js +1879 -0
  30. package/dist/analysis/plan/after-leftover.js +140 -0
  31. package/dist/analysis/plan/cap-spend.js +242 -0
  32. package/dist/analysis/plan/captures.js +1195 -0
  33. package/dist/analysis/plan/commander.js +236 -0
  34. package/dist/analysis/plan/completed.js +29 -0
  35. package/dist/analysis/plan/conceded-out.js +131 -0
  36. package/dist/analysis/plan/estimates.js +715 -0
  37. package/dist/analysis/plan/guard-off.js +232 -0
  38. package/dist/analysis/plan/holds.js +1631 -0
  39. package/dist/analysis/plan/leftover.js +760 -0
  40. package/dist/analysis/plan/move-order.js +319 -0
  41. package/dist/analysis/plan/orders.js +317 -0
  42. package/dist/analysis/plan/relations.js +702 -0
  43. package/dist/analysis/plan/report.js +672 -0
  44. package/dist/analysis/plan/shared.js +1218 -0
  45. package/dist/analysis/plan/stand-still.js +823 -0
  46. package/dist/analysis/plan/state.js +44 -0
  47. package/dist/analysis/plan/strike.js +1416 -0
  48. package/dist/analysis/plan/targets.js +651 -0
  49. package/dist/analysis/plan/team.js +299 -0
  50. package/dist/analysis/plan/threats.js +927 -0
  51. package/dist/analysis/plan/transfers.js +328 -0
  52. package/dist/analysis/plan/util.js +5 -0
  53. package/dist/analysis/plan/vacated.js +285 -0
  54. package/dist/analysis/planner.js +2922 -0
  55. package/dist/analysis/player-record.js +144 -0
  56. package/dist/analysis/player.js +268 -0
  57. package/dist/analysis/profile.js +347 -0
  58. package/dist/analysis/relations.js +1030 -0
  59. package/dist/analysis/schedule.js +88 -0
  60. package/dist/analysis/since-last.js +50 -0
  61. package/dist/analysis/static-seats.js +71 -0
  62. package/dist/analysis/stress.js +577 -0
  63. package/dist/analysis/team-brief.js +151 -0
  64. package/dist/analysis/tripwire.js +644 -0
  65. package/dist/analysis/turn-sim.js +259 -0
  66. package/dist/analysis/whereabouts.js +1109 -0
  67. package/dist/board.js +105 -0
  68. package/dist/bundle.js +117959 -36172
  69. package/dist/cards.js +435 -0
  70. package/dist/chat-cursor.js +135 -0
  71. package/dist/chat.js +192 -0
  72. package/dist/client.js +361 -0
  73. package/dist/config.js +62 -0
  74. package/dist/direct/link.js +102 -0
  75. package/dist/direct/session.js +267 -0
  76. package/dist/direct/transport.js +424 -0
  77. package/dist/guess-salt.js +65 -0
  78. package/dist/hosted.js +24 -0
  79. package/dist/index.js +33 -0
  80. package/dist/join-color.js +140 -0
  81. package/dist/live.js +278 -0
  82. package/dist/map-stats.js +152 -0
  83. package/dist/map-store.js +204 -0
  84. package/dist/move-order.js +141 -0
  85. package/dist/my-games.js +180 -0
  86. package/dist/normalize.js +411 -0
  87. package/dist/open-games.js +537 -0
  88. package/dist/outlook-log.js +138 -0
  89. package/dist/path-lock.js +22 -0
  90. package/dist/pick-list.js +193 -0
  91. package/dist/player-record-store.js +229 -0
  92. package/dist/player-states.js +31 -0
  93. package/dist/profile-store.js +677 -0
  94. package/dist/protocol/bundle.js +375 -0
  95. package/dist/protocol/codec.js +556 -0
  96. package/dist/protocol/decoded.js +12 -0
  97. package/dist/protocol/interp.js +1904 -0
  98. package/dist/protocol/methods.js +531 -0
  99. package/dist/protocol/rpc.js +202 -0
  100. package/dist/push/listener.js +393 -0
  101. package/dist/push/packets.js +66 -0
  102. package/dist/push/socketio.js +333 -0
  103. package/dist/push/websocket.js +179 -0
  104. package/dist/redact.js +62 -0
  105. package/dist/relations-store.js +242 -0
  106. package/dist/replay.js +215 -0
  107. package/dist/scalars.js +28 -0
  108. package/dist/scout.js +346 -0
  109. package/dist/stats.js +269 -0
  110. package/dist/strategy/card-clock.js +185 -0
  111. package/dist/strategy/map-notes.js +128 -0
  112. package/dist/strategy/notes.js +2168 -0
  113. package/dist/team-cards.js +84 -0
  114. package/dist/team-orders.js +150 -0
  115. package/dist/teams.js +19 -0
  116. package/dist/tools/award.js +206 -0
  117. package/dist/tools/begin-turn.js +162 -0
  118. package/dist/tools/board.js +77 -0
  119. package/dist/tools/card-advice.js +256 -0
  120. package/dist/tools/card-effects.js +49 -0
  121. package/dist/tools/card-plays.js +434 -0
  122. package/dist/tools/card-support-advice.js +140 -0
  123. package/dist/tools/chat-inbox.js +146 -0
  124. package/dist/tools/chat.js +483 -0
  125. package/dist/tools/check-plan.js +688 -0
  126. package/dist/tools/commander-check.js +102 -0
  127. package/dist/tools/commitments.js +216 -0
  128. package/dist/tools/common.js +143 -0
  129. package/dist/tools/diplomacy.js +342 -0
  130. package/dist/tools/game.js +126 -0
  131. package/dist/tools/guess-view.js +56 -0
  132. package/dist/tools/healthcheck.js +90 -0
  133. package/dist/tools/hints.js +34 -0
  134. package/dist/tools/how-lost.js +154 -0
  135. package/dist/tools/index.js +142 -0
  136. package/dist/tools/join-game.js +327 -0
  137. package/dist/tools/leave-game.js +181 -0
  138. package/dist/tools/live-context.js +339 -0
  139. package/dist/tools/live.js +404 -0
  140. package/dist/tools/map-stats.js +117 -0
  141. package/dist/tools/map.js +133 -0
  142. package/dist/tools/my-games.js +123 -0
  143. package/dist/tools/open-games.js +104 -0
  144. package/dist/tools/opponents.js +151 -0
  145. package/dist/tools/order-options.js +135 -0
  146. package/dist/tools/picks.js +292 -0
  147. package/dist/tools/profile-hook.js +156 -0
  148. package/dist/tools/profile-opponents.js +121 -0
  149. package/dist/tools/profile-reads.js +99 -0
  150. package/dist/tools/push.js +385 -0
  151. package/dist/tools/relations.js +611 -0
  152. package/dist/tools/resolve.js +45 -0
  153. package/dist/tools/route.js +36 -0
  154. package/dist/tools/scout.js +87 -0
  155. package/dist/tools/session.js +163 -0
  156. package/dist/tools/strategy.js +200 -0
  157. package/dist/tools/stress-opponents.js +83 -0
  158. package/dist/tools/surrender.js +240 -0
  159. package/dist/tools/survival.js +189 -0
  160. package/dist/tools/team-brief.js +266 -0
  161. package/dist/tools/team-source.js +222 -0
  162. package/dist/tools/team.js +182 -0
  163. package/dist/tools/turn.js +2761 -0
  164. package/dist/tools/uncommit.js +160 -0
  165. package/dist/tools/where.js +275 -0
  166. package/dist/tools/write-kit.js +158 -0
  167. package/dist/transport-bridge.js +33 -0
  168. package/dist/trend.js +452 -0
  169. package/dist/version.js +4 -0
  170. package/manifest.json +174 -4
  171. package/mint.yaml +101 -14
  172. package/package.json +11 -6
  173. package/server.json +40 -3
  174. package/skills/warapp-api/SKILL.md +95 -4
  175. package/skills/warapp-api/references/scout.mjs +348 -0
  176. package/skills/warapp-api/scripts/warapp.sh +69 -8
  177. package/skills/warapp-mcp/SKILL.md +969 -21
@@ -0,0 +1,1030 @@
1
+ import { carriesTeam } from '../teams.js';
2
+ import { bonusTerritories } from './bonuses.js';
3
+ import { bfsDistances, neighborsOf } from './graph.js';
4
+ import { ownerShown, OWNERS_SHOWN_FOG, visibleState, } from './plan/shared.js';
5
+ import { planTurn } from './planner.js';
6
+ /** Every status an agreement can be recorded in. */
7
+ export const AGREEMENT_STATUSES = [
8
+ 'proposed-by-me',
9
+ 'proposed-by-them',
10
+ 'agreed',
11
+ 'notice-by-me',
12
+ 'notice-by-them',
13
+ 'ended',
14
+ 'broken-by-them',
15
+ 'broken-by-me',
16
+ ];
17
+ /** Statuses an agreement can be first recorded in. */
18
+ export const OPENING_STATUSES = ['proposed-by-me', 'proposed-by-them', 'agreed'];
19
+ /** Statuses after which nothing more is recorded on the agreement (a new one is recorded instead). */
20
+ export const TERMINAL_STATUSES = new Set(['ended', 'broken-by-them', 'broken-by-me']);
21
+ /** Which status may follow which ({@link transitionAgreement}). */
22
+ export const AGREEMENT_TRANSITIONS = {
23
+ 'proposed-by-me': ['proposed-by-them', 'agreed', 'ended'],
24
+ 'proposed-by-them': ['proposed-by-me', 'agreed', 'ended'],
25
+ agreed: ['notice-by-me', 'notice-by-them', 'ended', 'broken-by-them', 'broken-by-me'],
26
+ 'notice-by-me': ['agreed', 'ended', 'broken-by-them', 'broken-by-me'],
27
+ 'notice-by-them': ['agreed', 'ended', 'broken-by-them', 'broken-by-me'],
28
+ ended: [],
29
+ 'broken-by-them': [],
30
+ 'broken-by-me': [],
31
+ };
32
+ /** The most turns of notice a truce can carry. */
33
+ export const MAX_NOTICE_TURNS = 3;
34
+ /** Consecutive turns of growth near the covered border that read as `massing`. */
35
+ export const TRUCE_MASSING_TURNS = 2;
36
+ /** Steps from the covered border within which the partner's growth counts as massing. */
37
+ export const TRUCE_MASSING_REACH = 2;
38
+ /** The partner's tracked income above this × mine is `outgrowing`. */
39
+ export const TRUCE_OUTGROW_RATIO = 1.5;
40
+ /** Quiet turns on a shared border, with no agreement, that read as an unspoken truce. */
41
+ export const TACIT_QUIET_TURNS = 3;
42
+ /**
43
+ * The endgame of a truce: no other opponent's estimated income reaches this × the larger of mine
44
+ * and the partner's. The partner no longer needs me from there on.
45
+ */
46
+ export const TRUCE_ENDGAME_RATIO = 0.5;
47
+ const byNum = (a, b) => a - b;
48
+ const alive = (p) => p !== undefined && (p.state === undefined || p.state === 'Playing');
49
+ const turnedAI = (p) => p.isAI === true || p.humanTurnedIntoAI === true;
50
+ /** The terms' end condition, as a word. */
51
+ export function endCondition(terms) {
52
+ const t = terms.untilTurn !== undefined;
53
+ const p = terms.untilPlayerOut !== undefined;
54
+ return t && p ? 'turn-or-player-out' : t ? 'turn' : p ? 'player-out' : 'none';
55
+ }
56
+ /**
57
+ * Why `partner` cannot be a party to a truce with `me` in a game of `players`, or `undefined`
58
+ * when it can: it must be in the game, not me, human, still playing and not my teammate, and a
59
+ * truce needs a third player — none in a 1v1 or once only two players remain.
60
+ */
61
+ export function partyRefusal(players, me, partner) {
62
+ const p = players.find((x) => x.id === partner);
63
+ if (!p)
64
+ return `player ${partner} is not in this game`;
65
+ if (partner === me)
66
+ return 'that is you';
67
+ if (players.length <= 2)
68
+ return 'a 1v1 has no third player: there is nothing a truce could leave aside';
69
+ if (turnedAI(p))
70
+ return `player ${partner} is an AI${p.humanTurnedIntoAI ? ' (a human turned into one)' : ''}: it keeps no agreement`;
71
+ if (!alive(p))
72
+ return `player ${partner} is no longer playing (${p.state})`;
73
+ const mine = players.find((x) => x.id === me);
74
+ if (mine && carriesTeam(mine.team) && p.team === mine.team)
75
+ return `player ${partner} is your teammate`;
76
+ if (players.filter(alive).length <= 2)
77
+ return 'only two players remain: there is nothing a truce could leave aside';
78
+ // Someone must stand outside me, my team and the partner's team, or the truce leaves nothing aside.
79
+ const sameTeam = (x, y) => y !== undefined && carriesTeam(x.team) && x.team === y.team;
80
+ const third = players.some((x) => alive(x) && x.id !== me && x.id !== partner && !sameTeam(x, mine) && !sameTeam(x, p));
81
+ if (!third)
82
+ return "no third player or team remains outside you, your team and the partner's team: there is nothing a truce could leave aside";
83
+ return undefined;
84
+ }
85
+ /** Why `scope` names something not on the map, or `undefined` when every id exists. */
86
+ export function scopeRefusal(graph, scope) {
87
+ if (scope === 'all')
88
+ return undefined;
89
+ if ('territories' in scope) {
90
+ if (!scope.territories.length)
91
+ return 'the scope lists no territory';
92
+ const missing = scope.territories.filter((t) => !graph.territoryById.has(t));
93
+ return missing.length ? `territories ${missing.join(', ')} are not on this map` : undefined;
94
+ }
95
+ if (!scope.bonuses.length)
96
+ return 'the scope lists no bonus';
97
+ const missing = scope.bonuses.filter((b) => !graph.bonusById.has(b));
98
+ return missing.length ? `bonuses ${missing.join(', ')} are not on this map` : undefined;
99
+ }
100
+ /** A new agreement, first recorded on `turn` in `status` (one of {@link OPENING_STATUSES}). */
101
+ export function newAgreement(id, partner, status, turn, terms) {
102
+ return {
103
+ id,
104
+ with: partner,
105
+ kind: 'truce',
106
+ status,
107
+ createdTurn: turn,
108
+ ...(status === 'agreed' ? { agreedTurn: turn } : {}),
109
+ terms,
110
+ history: [{ turn, status }],
111
+ };
112
+ }
113
+ /**
114
+ * `agreement` moved to `status` on `turn`, or the reason it cannot be: a terminal agreement
115
+ * takes nothing more, and only the moves in {@link AGREEMENT_TRANSITIONS} are allowed. Notice
116
+ * stamps `noticeTurn`, agreeing stamps `agreedTurn` (the first time), a terminal status stamps
117
+ * `endedTurn`; withdrawing notice (back to `agreed`) clears `noticeTurn`.
118
+ */
119
+ export function transitionAgreement(agreement, status, turn) {
120
+ if (TERMINAL_STATUSES.has(agreement.status)) {
121
+ return { refused: `agreement ${agreement.id} is already ${agreement.status}: record a new one instead` };
122
+ }
123
+ if (!AGREEMENT_TRANSITIONS[agreement.status].includes(status)) {
124
+ return {
125
+ refused: `agreement ${agreement.id} cannot go from ${agreement.status} to ${status} (allowed: ${AGREEMENT_TRANSITIONS[agreement.status].join(', ')})`,
126
+ };
127
+ }
128
+ const next = { ...agreement, status, history: [...agreement.history, { turn, status }] };
129
+ if (status === 'agreed' && next.agreedTurn === undefined)
130
+ next.agreedTurn = turn;
131
+ if (status === 'agreed')
132
+ delete next.noticeTurn;
133
+ if (status === 'notice-by-me' || status === 'notice-by-them')
134
+ next.noticeTurn = turn;
135
+ if (TERMINAL_STATUSES.has(status))
136
+ next.endedTurn = turn;
137
+ return { agreement: next };
138
+ }
139
+ /**
140
+ * An agreement's state on `turn`: `proposed` (not agreed yet), `active`, in `notice` (with the
141
+ * first turn it no longer binds: the notice turn + its notice turns), or `over` — when recorded
142
+ * ended or broken, when the partner is eliminated (or otherwise no longer playing) or became an
143
+ * AI, when only two players remain, when its `untilPlayerOut` player is out, past its
144
+ * `untilTurn`, or once its notice has run.
145
+ */
146
+ export function agreementState(agreement, turn, players) {
147
+ const s = agreement.status;
148
+ if (s === 'ended' || s === 'broken-by-them' || s === 'broken-by-me')
149
+ return { phase: 'over', reason: s };
150
+ const partner = players.find((p) => p.id === agreement.with);
151
+ if (!partner || !alive(partner))
152
+ return { phase: 'over', reason: 'partner-out' };
153
+ if (turnedAI(partner))
154
+ return { phase: 'over', reason: 'partner-ai' };
155
+ if (players.filter(alive).length <= 2)
156
+ return { phase: 'over', reason: 'two-left' };
157
+ const out = agreement.terms.untilPlayerOut;
158
+ if (out !== undefined && !alive(players.find((p) => p.id === out)))
159
+ return { phase: 'over', reason: 'player-out' };
160
+ const until = agreement.terms.untilTurn;
161
+ if (until !== undefined && turn > until)
162
+ return { phase: 'over', reason: 'until-turn' };
163
+ if (s === 'proposed-by-me' || s === 'proposed-by-them')
164
+ return { phase: 'proposed' };
165
+ if ((s === 'notice-by-me' || s === 'notice-by-them') && agreement.noticeTurn !== undefined) {
166
+ const endsTurn = agreement.noticeTurn + agreement.terms.noticeTurns;
167
+ const capped = until !== undefined ? Math.min(endsTurn, until + 1) : endsTurn;
168
+ return turn >= capped ? { phase: 'over', reason: 'notice-served' } : { phase: 'notice', endsTurn: capped };
169
+ }
170
+ return { phase: 'active' };
171
+ }
172
+ /** My territories in `scope` among `mine`, ascending. */
173
+ export function coveredTerritories(graph, scope, mine) {
174
+ let ids;
175
+ if (scope === 'all')
176
+ ids = mine;
177
+ else if ('territories' in scope)
178
+ ids = scope.territories;
179
+ else
180
+ ids = scope.bonuses.flatMap((b) => [...bonusTerritories(graph, b)]);
181
+ return [...new Set(ids)].filter((t) => mine.has(t)).sort(byNum);
182
+ }
183
+ const ownerOn = (t) => t && t.owner.kind === 'player' ? t.owner.playerId : null;
184
+ function territoryMap(board) {
185
+ return new Map(board.territories.map((t) => [t.territoryId, t]));
186
+ }
187
+ function mineOn(board, me) {
188
+ return new Set(board.territories.filter((t) => ownerShown(t) && ownerOn(t) === me).map((t) => t.territoryId));
189
+ }
190
+ /** What my orders say should stand on `t` after the turn (deploys, moves out, moves in from mine). */
191
+ function expectedArmies(t, before, orders, mine) {
192
+ let n = before;
193
+ for (const d of orders.deploys)
194
+ if (d.territoryId === t)
195
+ n += d.armies;
196
+ for (const m of orders.moves) {
197
+ if (m.from === t)
198
+ n -= m.armies;
199
+ if (m.to === t && mine.has(m.from))
200
+ n += m.armies;
201
+ }
202
+ return n;
203
+ }
204
+ /**
205
+ * Whether a transfer of mine into `t` may not have arrived in full: its source is no longer shown
206
+ * as mine, or holds fewer armies than my orders leave there (it was hit, so the move may never have
207
+ * run). A shortfall on `t` is then not evidence against anyone.
208
+ */
209
+ function fedByHitSource(t, orders, mine, was, now, me) {
210
+ return orders.moves.some((m) => {
211
+ if (m.to !== t || !mine.has(m.from))
212
+ return false;
213
+ const after = ownerShown(now.get(m.from));
214
+ if (!after || ownerOn(after) !== me)
215
+ return true;
216
+ const before = visibleState(was.get(m.from))?.armies;
217
+ const nowArmies = visibleState(after)?.armies;
218
+ if (before == null || nowArmies == null)
219
+ return true;
220
+ return nowArmies < expectedArmies(m.from, before, orders, mine);
221
+ });
222
+ }
223
+ /**
224
+ * What my boards say about the partner keeping `agreement`, over the consecutive turns from the
225
+ * one it was agreed (and before it ended), as flags with their turn and evidence:
226
+ * - `broken`: the partner took a covered territory of mine, or attacked one (my orders known,
227
+ * armies lost there, only the partner — visibly — borders it, and no transfer of mine in came
228
+ * from a source taken or hit, which may never have arrived);
229
+ * - `cap-exceeded` (newest board): a visible partner territory beside a covered one holds more
230
+ * than the cap;
231
+ * - `massing`: the partner's visible armies within {@link TRUCE_MASSING_REACH} steps of the
232
+ * covered border grew for the last {@link TRUCE_MASSING_TURNS} turns up to the newest board
233
+ * (territories visible on both boards only: a fog reveal is no growth), or an event the fog
234
+ * leaves ambiguous;
235
+ * - `outgrowing`: its income passed {@link TRUCE_OUTGROW_RATIO} × mine;
236
+ * - `kept`: the consecutive quiet turns up to the newest board (when nothing broke).
237
+ * A proposal that was never agreed has no flags.
238
+ */
239
+ export function breachWatch(input) {
240
+ const { agreement: a, graph, me } = input;
241
+ if (a.agreedTurn === undefined)
242
+ return [];
243
+ const partner = a.with;
244
+ const byTurn = new Map();
245
+ for (const b of input.boards)
246
+ byTurn.set(b.turn, b);
247
+ const turns = [...byTurn.keys()].sort(byNum);
248
+ const flags = [];
249
+ const inWindow = (t) => t >= a.agreedTurn && (a.endedTurn === undefined || t < a.endedTurn);
250
+ // Consecutive pairs whose earlier board's orders fall within the agreement.
251
+ const pairs = turns
252
+ .filter((t) => byTurn.has(t + 1) && inWindow(t))
253
+ .map((t) => ({ from: byTurn.get(t), to: byTurn.get(t + 1) }));
254
+ const growthByTurn = new Map();
255
+ const eventTurns = new Set();
256
+ for (const { from, to } of pairs) {
257
+ const was = territoryMap(from.board);
258
+ const now = territoryMap(to.board);
259
+ const mine = mineOn(from.board, me);
260
+ const covered = coveredTerritories(graph, a.terms.scope, mine);
261
+ const taken = [];
262
+ const attacked = [];
263
+ const ambiguous = [];
264
+ for (const c of covered) {
265
+ const after = now.get(c);
266
+ const shown = ownerShown(after);
267
+ const neighbours = neighborsOf(graph, c);
268
+ const partnerNext = neighbours.some((n) => ownerOn(ownerShown(was.get(n))) === partner || ownerOn(ownerShown(now.get(n))) === partner);
269
+ if (shown && ownerOn(shown) === partner) {
270
+ taken.push(c);
271
+ continue;
272
+ }
273
+ if (!shown) {
274
+ // Lost to an owner I cannot see.
275
+ if (partnerNext)
276
+ ambiguous.push(c);
277
+ continue;
278
+ }
279
+ if (ownerOn(shown) !== me || !from.orders)
280
+ continue;
281
+ const before = visibleState(was.get(c))?.armies;
282
+ const nowArmies = visibleState(after)?.armies;
283
+ if (before == null || nowArmies == null)
284
+ continue;
285
+ if (expectedArmies(c, before, from.orders, mine) - nowArmies <= 0)
286
+ continue;
287
+ // Armies lost on a territory still mine: who could have hit it? Mine and visible neutrals
288
+ // cannot; a fogged neighbour or another player could.
289
+ if (!partnerNext)
290
+ continue;
291
+ // A transfer of mine in whose source was taken or hit may never have arrived: open, not a break.
292
+ if (fedByHitSource(c, from.orders, mine, was, now, me)) {
293
+ ambiguous.push(c);
294
+ continue;
295
+ }
296
+ const onlyPartner = neighbours.every((n) => {
297
+ const t = ownerShown(was.get(n));
298
+ if (t === undefined)
299
+ return false;
300
+ return t.owner.kind === 'neutral' || ownerOn(t) === me || ownerOn(t) === partner;
301
+ });
302
+ (onlyPartner ? attacked : ambiguous).push(c);
303
+ }
304
+ const turn = from.turn;
305
+ if (taken.length) {
306
+ flags.push({ kind: 'broken', turn, territories: taken, evidence: `took territories ${taken.join(', ')} on turn ${turn}` });
307
+ eventTurns.add(turn);
308
+ }
309
+ if (attacked.length) {
310
+ flags.push({
311
+ kind: 'broken',
312
+ turn,
313
+ territories: attacked,
314
+ evidence: `attacked territories ${attacked.join(', ')} on turn ${turn} (armies lost beyond my orders; only it borders them)`,
315
+ });
316
+ eventTurns.add(turn);
317
+ }
318
+ if (ambiguous.length) {
319
+ flags.push({
320
+ kind: 'massing',
321
+ turn,
322
+ territories: ambiguous,
323
+ ambiguous: true,
324
+ evidence: `territories ${ambiguous.join(', ')} were lost or hit on turn ${turn} beside it, but the fog or another player leaves who did it open`,
325
+ });
326
+ eventTurns.add(turn);
327
+ }
328
+ // Its visible armies near the covered border (both boards show them: no fog reveal counts).
329
+ const zone = bfsDistances(graph, covered);
330
+ let growth = 0;
331
+ for (const [t, d] of zone) {
332
+ if (d === 0 || d > TRUCE_MASSING_REACH)
333
+ continue;
334
+ const b = visibleState(was.get(t));
335
+ const n = visibleState(now.get(t));
336
+ if (!b || !n)
337
+ continue;
338
+ const armiesOf = (x) => (ownerOn(x) === partner ? (x.armies ?? 0) : 0);
339
+ growth += armiesOf(n) - armiesOf(b);
340
+ }
341
+ growthByTurn.set(turn, growth);
342
+ }
343
+ // Massing: growth on each of the last TRUCE_MASSING_TURNS consecutive pairs.
344
+ // The pairs must run up to the newest board: growth followed by a gap is old news.
345
+ const recent = pairs.slice(-TRUCE_MASSING_TURNS).map((p) => p.from.turn);
346
+ if (recent.length === TRUCE_MASSING_TURNS &&
347
+ recent.at(-1) + 1 === turns.at(-1) &&
348
+ recent.every((t, i) => i === 0 || t === recent[i - 1] + 1) &&
349
+ recent.every((t) => (growthByTurn.get(t) ?? 0) > 0)) {
350
+ const growth = recent.reduce((s, t) => s + growthByTurn.get(t), 0);
351
+ const last = recent.at(-1);
352
+ const covered = coveredTerritories(graph, a.terms.scope, mineOn(byTurn.get(last + 1).board, me));
353
+ flags.push({
354
+ kind: 'massing',
355
+ turn: last,
356
+ territories: covered,
357
+ growth,
358
+ evidence: `its visible armies within ${TRUCE_MASSING_REACH} steps of the covered border grew by ${growth} over turns ${recent[0]}–${last}`,
359
+ });
360
+ }
361
+ // The cap, on the newest board.
362
+ const newest = turns.at(-1);
363
+ if (a.terms.borderCap !== undefined && newest !== undefined && newest >= a.agreedTurn && (a.endedTurn === undefined || newest <= a.endedTurn)) {
364
+ const board = byTurn.get(newest).board;
365
+ const at = territoryMap(board);
366
+ const covered = coveredTerritories(graph, a.terms.scope, mineOn(board, me));
367
+ const over = new Map();
368
+ for (const c of covered)
369
+ for (const n of neighborsOf(graph, c)) {
370
+ const t = visibleState(at.get(n));
371
+ if (t && ownerOn(t) === partner && (t.armies ?? 0) > a.terms.borderCap)
372
+ over.set(n, t.armies ?? 0);
373
+ }
374
+ if (over.size) {
375
+ const ids = [...over.keys()].sort(byNum);
376
+ const armies = Math.max(...over.values());
377
+ flags.push({
378
+ kind: 'cap-exceeded',
379
+ turn: newest,
380
+ territories: ids,
381
+ armies,
382
+ cap: a.terms.borderCap,
383
+ evidence: `territories ${ids.join(', ')} on the covered border hold up to ${armies}, over the cap of ${a.terms.borderCap}`,
384
+ });
385
+ }
386
+ }
387
+ if (input.incomes && input.incomes.partner !== null && input.incomes.mine > 0) {
388
+ const ratio = Math.round((input.incomes.partner / input.incomes.mine) * 100) / 100;
389
+ if (input.incomes.partner > TRUCE_OUTGROW_RATIO * input.incomes.mine) {
390
+ flags.push({
391
+ kind: 'outgrowing',
392
+ turn: newest ?? a.agreedTurn,
393
+ territories: [],
394
+ ratio,
395
+ evidence: `its estimated income ${input.incomes.partner} is ${ratio}× mine (${input.incomes.mine}), above ${TRUCE_OUTGROW_RATIO}×`,
396
+ });
397
+ }
398
+ }
399
+ if (!flags.some((f) => f.kind === 'broken') && pairs.length) {
400
+ let quiet = 0;
401
+ for (let i = pairs.length - 1; i >= 0; i--) {
402
+ const t = pairs[i].from.turn;
403
+ if (eventTurns.has(t) || (i < pairs.length - 1 && pairs[i + 1].from.turn !== t + 1))
404
+ break;
405
+ quiet++;
406
+ }
407
+ if (quiet > 0) {
408
+ const last = pairs.at(-1).from.turn;
409
+ flags.push({ kind: 'kept', turn: last, territories: [], quietTurns: quiet, evidence: `${quiet} quiet turn${quiet === 1 ? '' : 's'} up to turn ${last}` });
410
+ }
411
+ }
412
+ return flags;
413
+ }
414
+ /**
415
+ * Neighbours with no agreement (`exclude` lists those with one) whose shared border with me saw
416
+ * no deploy from either side, no attack and no change of hands for at least
417
+ * {@link TACIT_QUIET_TURNS} consecutive turns up to the newest board. Reported, never planned on.
418
+ * Their side counts only where both boards showed it; a turn whose border it cannot see is not
419
+ * quiet. Without my orders, my side is quiet when its armies did not grow.
420
+ */
421
+ export function tacitTruces(input) {
422
+ const { graph, me } = input;
423
+ const byTurn = new Map();
424
+ for (const b of input.boards)
425
+ byTurn.set(b.turn, b);
426
+ const turns = [...byTurn.keys()].sort(byNum);
427
+ const newest = turns.at(-1);
428
+ if (newest === undefined)
429
+ return [];
430
+ const latest = territoryMap(byTurn.get(newest).board);
431
+ const latestMine = mineOn(byTurn.get(newest).board, me);
432
+ const players = new Set();
433
+ for (const m of latestMine)
434
+ for (const n of neighborsOf(graph, m)) {
435
+ const o = ownerOn(ownerShown(latest.get(n)));
436
+ if (o !== null && o !== me && !input.exclude?.has(o))
437
+ players.add(o);
438
+ }
439
+ const out = [];
440
+ for (const p of [...players].sort(byNum)) {
441
+ let quiet = 0;
442
+ for (let t = newest - 1; byTurn.has(t) && byTurn.has(t + 1); t--) {
443
+ if (!quietTurn(graph, byTurn.get(t), byTurn.get(t + 1), me, p))
444
+ break;
445
+ quiet++;
446
+ }
447
+ if (quiet < TACIT_QUIET_TURNS)
448
+ continue;
449
+ const border = [...latestMine].filter((m) => neighborsOf(graph, m).some((n) => ownerOn(ownerShown(latest.get(n))) === p)).sort(byNum);
450
+ out.push({ player: p, quietTurns: quiet, border });
451
+ }
452
+ return out;
453
+ }
454
+ function quietTurn(graph, from, to, me, p) {
455
+ const was = territoryMap(from.board);
456
+ const now = territoryMap(to.board);
457
+ const mine = mineOn(from.board, me);
458
+ let border = 0;
459
+ for (const m of [...mine].sort(byNum)) {
460
+ const theirs = neighborsOf(graph, m).filter((n) => ownerOn(ownerShown(was.get(n))) === p);
461
+ if (!theirs.length)
462
+ continue;
463
+ border++;
464
+ if (ownerOn(ownerShown(now.get(m))) !== me)
465
+ return false;
466
+ const mb = visibleState(was.get(m))?.armies;
467
+ const mn = visibleState(now.get(m))?.armies;
468
+ if (mb == null || mn == null)
469
+ return false;
470
+ if (from.orders) {
471
+ if (from.orders.deploys.some((d) => d.territoryId === m && d.armies > 0))
472
+ return false;
473
+ if (from.orders.moves.some((x) => x.from === m && theirs.includes(x.to)))
474
+ return false;
475
+ if (expectedArmies(m, mb, from.orders, mine) > mn)
476
+ return false;
477
+ }
478
+ else if (mn > mb)
479
+ return false;
480
+ for (const n of theirs) {
481
+ const b = visibleState(was.get(n));
482
+ const a = visibleState(now.get(n));
483
+ if (!b || !a || ownerOn(a) !== p)
484
+ return false;
485
+ if ((a.armies ?? 0) > (b.armies ?? 0))
486
+ return false;
487
+ }
488
+ }
489
+ return border > 0;
490
+ }
491
+ /**
492
+ * Whether a truce is in its endgame: no other opponent's estimated income reaches
493
+ * {@link TRUCE_ENDGAME_RATIO} × the larger of mine and the partner's (so the partner no longer
494
+ * needs me). With no other opponent left it is.
495
+ */
496
+ export function truceEndgame(input) {
497
+ const bar = TRUCE_ENDGAME_RATIO * Math.max(input.mine, input.partner);
498
+ return !input.others.some((o) => o >= bar);
499
+ }
500
+ /**
501
+ * Whether to rely on a live agreement now: `watch` on any flag but `kept`, on their notice, and in
502
+ * the endgame ({@link truceEndgame}); otherwise `clear`. Words in chat never move this — only the
503
+ * board does.
504
+ */
505
+ export function trust(agreement, flags, context) {
506
+ const reasons = [];
507
+ for (const kind of ['broken', 'cap-exceeded', 'massing', 'outgrowing'])
508
+ if (flags.some((f) => f.kind === kind))
509
+ reasons.push(`flag: ${kind}`);
510
+ if (agreement.status === 'notice-by-them')
511
+ reasons.push('they gave notice');
512
+ if (context.endgame)
513
+ reasons.push('endgame: no other opponent is still a match for either of us');
514
+ return { level: reasons.length ? 'watch' : 'clear', reasons };
515
+ }
516
+ /** The flag kinds that make the trust `watch`, as the planner names them. */
517
+ const WATCH_KINDS = ['broken', 'cap-exceeded', 'massing', 'outgrowing'];
518
+ /**
519
+ * B2 (warapp_submit_turn): the active or in-notice agreements that `moves` would break — an order that
520
+ * attacks a territory the partner holds on `board` and the terms cover (a transfer-only order attacks
521
+ * nothing), or a Bomb (`bombs`, the targets) on such a territory. By agreement id; empty when nothing binds. Pure; reads only the ledger's own agreements and
522
+ * the board (the breach watch is not consulted: a break by them is recorded as broken-by-them first).
523
+ */
524
+ export function truceBreaksIn(input) {
525
+ const out = [];
526
+ for (const a of [...input.agreements].sort((x, y) => x.id.localeCompare(y.id))) {
527
+ if (a.with === input.me)
528
+ continue;
529
+ const state = agreementState(a, input.turn, input.players);
530
+ if (state.phase !== 'active' && state.phase !== 'notice')
531
+ continue;
532
+ const held = new Set(input.board.territories.filter((t) => ownerShown(t) && ownerOn(t) === a.with).map((t) => t.territoryId));
533
+ const covered = new Set(coveredTerritories(input.graph, a.terms.scope, held));
534
+ const moves = input.moves.flatMap((m, index) => (m.mode !== 'transfer-only' && covered.has(m.to) ? [{ index, from: m.from, to: m.to }] : []));
535
+ const bombs = (input.bombs ?? []).flatMap((target, index) => (covered.has(target) ? [{ index, target }] : []));
536
+ if (moves.length || bombs.length)
537
+ out.push({ agreement: a.id, with: a.with, state: state.phase, moves, ...(bombs.length ? { bombs } : {}) });
538
+ }
539
+ return out;
540
+ }
541
+ export function planRelationsFrom(input) {
542
+ const { graph, board, me, turn, players, incomes } = input;
543
+ const holding = (p) => new Set(board.territories.filter((t) => ownerShown(t) && ownerOn(t) === p).map((t) => t.territoryId));
544
+ const mine = holding(me);
545
+ const relations = [];
546
+ for (const a of [...input.agreements].sort((x, y) => x.id.localeCompare(y.id))) {
547
+ const state = agreementState(a, turn, players);
548
+ if (state.phase !== 'active' && state.phase !== 'notice')
549
+ continue;
550
+ const partnerIncome = incomes.opponents.get(a.with);
551
+ const flags = breachWatch({
552
+ agreement: a,
553
+ graph,
554
+ boards: input.boards,
555
+ me,
556
+ ...(incomes.mine !== null ? { incomes: { mine: incomes.mine, partner: partnerIncome ?? null } } : {}),
557
+ });
558
+ const others = [...incomes.opponents].filter(([id]) => id !== a.with);
559
+ const endgame = incomes.mine !== null && partnerIncome !== null && partnerIncome !== undefined && others.every(([, v]) => v !== null)
560
+ ? truceEndgame({ mine: incomes.mine, partner: partnerIncome, others: others.map(([, v]) => v) })
561
+ : false;
562
+ const verdict = trust(a, flags, { endgame });
563
+ const watch = WATCH_KINDS.filter((k) => flags.some((f) => f.kind === k));
564
+ if (a.status === 'notice-by-them')
565
+ watch.push('their-notice');
566
+ if (endgame)
567
+ watch.push('endgame');
568
+ const broke = flags.find((f) => f.kind === 'broken' && !f.ambiguous);
569
+ relations.push({
570
+ player: a.with,
571
+ coveredMine: coveredTerritories(graph, a.terms.scope, mine),
572
+ coveredTheirs: coveredTerritories(graph, a.terms.scope, holding(a.with)),
573
+ state: broke ? 'broken' : state.phase,
574
+ ...(state.endsTurn !== undefined ? { endsTurn: state.endsTurn } : {}),
575
+ ...(a.terms.borderCap !== undefined ? { borderCap: a.terms.borderCap } : {}),
576
+ trust: verdict.level,
577
+ ...(watch.length ? { watch } : {}),
578
+ // T9: `a.enforced` is never read in. No tool writes it, and only a Diplomacy card the decoder is
579
+ // sure of (part D) may make a player no foe; a hand-edited ledger must not do it indefinitely.
580
+ agreement: a.id,
581
+ ...(a.status === 'notice-by-me' ? { noticeBy: 'me' } : a.status === 'notice-by-them' ? { noticeBy: 'them' } : {}),
582
+ ...(broke
583
+ ? { breach: { term: 'took or attacked a covered territory of mine', turn: broke.turn, evidence: broke.evidence, territories: [...broke.territories] } }
584
+ : {}),
585
+ });
586
+ }
587
+ // D3 (T9): the Diplomacy cards in effect. A card is a game rule, not a promise: it binds whatever the ledger says.
588
+ for (const d of [...(input.diplomacy ?? [])].sort((x, y) => x.player - y.player)) {
589
+ if (d.player === me || d.untilTurn <= turn)
590
+ continue;
591
+ const bound = relations.filter((r) => r.player === d.player && (r.state === 'active' || r.state === 'notice'));
592
+ for (const r of bound) {
593
+ r.enforced = true;
594
+ r.enforcedUntil = d.untilTurn;
595
+ }
596
+ if (bound.length)
597
+ continue;
598
+ relations.push({
599
+ player: d.player,
600
+ coveredMine: [...mine].sort((x, y) => x - y),
601
+ coveredTheirs: [...holding(d.player)].sort((x, y) => x - y),
602
+ state: 'active',
603
+ trust: 'clear',
604
+ enforced: true,
605
+ enforcedUntil: d.untilTurn,
606
+ card: 'Diplomacy',
607
+ });
608
+ }
609
+ const open = new Set(input.agreements.filter((a) => !TERMINAL_STATUSES.has(a.status)).map((a) => a.with));
610
+ return { relations, tacit: tacitTruces({ graph, boards: input.boards, me, exclude: open }) };
611
+ }
612
+ // ---------- B3: pricing a deal (docs/PLAN-TEAMS.md section 8 B3) ----------
613
+ //
614
+ // A truce is priced by planning the turn twice — without it and with it — on the same input, and
615
+ // comparing the plans. The planner is called, never changed. What the partner gains is read off the
616
+ // visible board only, and is an estimate. Words change no estimate: nothing here reads chat, and the
617
+ // partner's record (owner decision D5) is the board-derived history of what it did, never what it said.
618
+ /** The turns a suggested truce runs (its `untilTurn` is this turn + this). */
619
+ export const SUGGESTED_TRUCE_TURNS = 5;
620
+ /** The turns of notice a suggested truce carries. */
621
+ export const SUGGESTED_NOTICE_TURNS = 1;
622
+ /**
623
+ * Armies freed of at least this share of my income are worth a proposal on their own (B1's measure:
624
+ * a truce worth having frees a fifth of the turn's income).
625
+ */
626
+ export const TRUCE_MATERIAL_SHARE = 0.2;
627
+ /** A partner whose record keeps this share of its agreements or more reads as one who keeps them. */
628
+ export const RECORD_KEPT_RATE = 0.75;
629
+ /** A partner whose record keeps less than this share reads as one who breaks them. */
630
+ export const RECORD_BROKE_RATE = 0.5;
631
+ /** The record's reading: `unknown` with no finished agreement, else by its kept rate. */
632
+ export function reliabilityOf(record) {
633
+ if (!record || record.keptRate === null)
634
+ return 'unknown';
635
+ if (record.keptRate >= RECORD_KEPT_RATE)
636
+ return 'kept';
637
+ if (record.keptRate < RECORD_BROKE_RATE)
638
+ return 'broke';
639
+ return 'mixed';
640
+ }
641
+ const ownedBy = (t, p) => {
642
+ const s = ownerShown(t);
643
+ return s !== undefined && ownerOn(s) === p;
644
+ };
645
+ /** B3: the partner's side of a deal from the visible board (an estimate; see {@link PartnerReading}). */
646
+ export function partnerReading(graph, board, me, partner, coveredMine) {
647
+ const at = territoryMap(board);
648
+ const theirs = board.territories.filter((t) => ownedBy(t, partner)).map((t) => t.territoryId).sort(byNum);
649
+ const fronts = new Set();
650
+ const neutrals = new Set();
651
+ let fogBeside = false;
652
+ for (const t of theirs)
653
+ for (const n of neighborsOf(graph, t)) {
654
+ const s = ownerShown(at.get(n));
655
+ if (!s)
656
+ fogBeside = true;
657
+ else if (s.owner.kind === 'neutral')
658
+ neutrals.add(n);
659
+ else {
660
+ const o = ownerOn(s);
661
+ if (o !== null && o !== me && o !== partner)
662
+ fronts.add(o);
663
+ }
664
+ }
665
+ const covered = new Set(coveredMine);
666
+ let armiesOnBorder = 0;
667
+ for (const t of theirs)
668
+ if (neighborsOf(graph, t).some((n) => covered.has(n)))
669
+ armiesOnBorder += visibleState(at.get(t))?.armies ?? 0;
670
+ const roomToGrow = fronts.size > 0 || neutrals.size > 0 ? true : fogBeside ? null : false;
671
+ return { estimate: true, otherFronts: [...fronts].sort(byNum), neutralsBeside: neutrals.size, fogBeside, armiesOnBorder, roomToGrow };
672
+ }
673
+ const minus = (a, b) => {
674
+ const s = new Set(b);
675
+ return [...new Set(a)].filter((x) => !s.has(x)).sort(byNum);
676
+ };
677
+ /**
678
+ * B3: price a truce with `player` on `terms` — plan the turn without it (any other relation in
679
+ * `input` kept, a recorded one with this player taken out) and with it, and compare. The truce
680
+ * planned with is `active`, trust `clear` — unless `input` holds a relation with `player`, whose
681
+ * board reading it keeps (state, `broken` with its breach or `notice` with its end, trust and
682
+ * watch flags: so a recorded truce is priced on the plan warapp_plan_turn makes, and a partner the
683
+ * board flags is never priced as trusted) — with `opts.trust` / `opts.watch` (an endgame) added.
684
+ * Compared: the armies freed, the
685
+ * captures, bonuses and next income gained or lost, the borders no longer conceded, the partner's
686
+ * covered territories the no-deal plan attacks (what the truce gives up), and T6's `lossIfBroken`.
687
+ * Plus a rough reading of the partner's side from the visible board, marked as an estimate, and its
688
+ * record (D5) when given. Pure and deterministic: the planner is called, never changed, and `input`
689
+ * is not mutated. `opts.without` reuses a no-deal plan already made on the same input, and is
690
+ * ignored when `input` holds a relation with `player`: a plan on that input already carries the
691
+ * truce, so it is no no-deal plan (priced against it, every gain would read zero).
692
+ */
693
+ export function priceTruce(input, player, terms, opts = {}) {
694
+ const holding = (p) => new Set(input.board.territories.filter((t) => ownedBy(t, p)).map((t) => t.territoryId));
695
+ // D3: a Diplomacy card in effect with this player binds with or without the deal, so both plans keep it.
696
+ const enforcing = (input.relations ?? []).find((r) => r.player === player && r.enforced);
697
+ const card = enforcing
698
+ ? [
699
+ {
700
+ player,
701
+ coveredMine: [...holding(input.me)].sort(byNum),
702
+ coveredTheirs: [...holding(player)].sort(byNum),
703
+ state: 'active',
704
+ trust: 'clear',
705
+ enforced: true,
706
+ ...(enforcing.enforcedUntil !== undefined ? { enforcedUntil: enforcing.enforcedUntil } : {}),
707
+ card: 'Diplomacy',
708
+ },
709
+ ]
710
+ : [];
711
+ const others = [...(input.relations ?? []).filter((r) => r.player !== player), ...card];
712
+ const { relations: _given, ...rest } = input;
713
+ const base = others.length ? { ...rest, relations: others } : rest;
714
+ const reusable = !card.length && others.length === (input.relations ?? []).length;
715
+ const without = (reusable ? opts.without : undefined) ?? planTurn(base);
716
+ const coveredMine = coveredTerritories(input.graph, terms.scope, holding(input.me));
717
+ const coveredTheirs = coveredTerritories(input.graph, terms.scope, holding(player));
718
+ // The board's reading of a recorded truce with this player (planRelationsFrom) is kept: words
719
+ // never clear a flag, and a price never trusts more than warapp_plan_turn does (PLAN-TEAMS §4).
720
+ const standing = (input.relations ?? []).find((r) => r.player === player && !r.card);
721
+ const watch = [...new Set([...(standing?.watch ?? []), ...(opts.watch ?? [])])];
722
+ const trusted = standing?.trust === 'watch' || opts.trust === 'watch' ? 'watch' : 'clear';
723
+ const state = standing?.state ?? 'active';
724
+ const hypothetical = {
725
+ player,
726
+ coveredMine,
727
+ coveredTheirs,
728
+ state,
729
+ ...(state === 'notice' && standing?.endsTurn !== undefined ? { endsTurn: standing.endsTurn } : {}),
730
+ ...(state === 'notice' && standing?.noticeBy !== undefined ? { noticeBy: standing.noticeBy } : {}),
731
+ ...(state === 'broken' && standing?.breach ? { breach: standing.breach } : {}),
732
+ ...(terms.borderCap !== undefined ? { borderCap: terms.borderCap } : {}),
733
+ trust: trusted,
734
+ ...(watch.length ? { watch } : {}),
735
+ ...(opts.agreement !== undefined ? { agreement: opts.agreement } : standing?.agreement !== undefined ? { agreement: standing.agreement } : {}),
736
+ };
737
+ const withPlan = planTurn({ ...base, relations: [...others, hypothetical] });
738
+ const view = withPlan.relations?.find((r) => r.player === player && !r.card);
739
+ const theirCovered = new Set(coveredTheirs);
740
+ const attacksForgone = [...new Set(without.moves.filter((m) => m.kind === 'attack' && theirCovered.has(m.to)).map((m) => m.to))].sort(byNum);
741
+ const seen = new Set(without.warnings);
742
+ return {
743
+ player,
744
+ coveredMine,
745
+ coveredTheirs,
746
+ state,
747
+ ...(hypothetical.endsTurn !== undefined ? { endsTurn: hypothetical.endsTurn } : {}),
748
+ ...(hypothetical.noticeBy !== undefined ? { noticeBy: hypothetical.noticeBy } : {}),
749
+ trust: trusted,
750
+ watch,
751
+ ...(hypothetical.breach ? { breach: hypothetical.breach } : {}),
752
+ honoured: view?.honoured ?? false,
753
+ relaxed: view?.relaxed ?? [],
754
+ fullHold: view?.fullHold ?? [],
755
+ armiesFreed: view?.armiesFreed ?? 0,
756
+ capturesGained: minus(withPlan.expected.captures, without.expected.captures),
757
+ capturesLost: minus(without.expected.captures, withPlan.expected.captures),
758
+ bonusesGained: minus(withPlan.expected.bonusesCompleted, without.expected.bonusesCompleted),
759
+ bonusesLost: minus(without.expected.bonusesCompleted, withPlan.expected.bonusesCompleted),
760
+ incomeGained: withPlan.expected.nextIncome - without.expected.nextIncome,
761
+ concededAvoided: minus(without.conceded, withPlan.conceded),
762
+ concededAdded: minus(withPlan.conceded, without.conceded),
763
+ attacksForgone,
764
+ lossIfBroken: view?.lossIfBroken ?? null,
765
+ partner: partnerReading(input.graph, input.board, input.me, player, coveredMine),
766
+ record: opts.record ?? null,
767
+ reliability: reliabilityOf(opts.record),
768
+ warnings: withPlan.warnings.filter((w) => !seen.has(w)),
769
+ };
770
+ }
771
+ /** Whether a break this turn would cost me anything on the board (territory, armies, a bonus, my commander). */
772
+ const breakCosts = (l) => l !== null && (l.commanderLost || l.territories.length > 0 || l.bonusValue > 0 || l.armies > 0);
773
+ /** Each watch flag in plain words, for a verdict's reasons. */
774
+ const WATCH_WORDS = {
775
+ broken: 'a covered territory of mine was lost or hit beside it',
776
+ 'cap-exceeded': 'it keeps more than the cap on the covered border',
777
+ massing: 'it is massing armies beside the covered border',
778
+ outgrowing: 'its income has outgrown mine',
779
+ 'their-notice': 'it gave notice',
780
+ endgame: 'endgame: no other opponent is still a match for either of us, so the partner no longer needs me',
781
+ };
782
+ /**
783
+ * B3: the verdict on a priced truce. `no` when the partner broke it (`state: 'broken'`, T8: an
784
+ * ordinary opponent at once), when I already gave notice on it (it is ending: withdraw the notice or
785
+ * propose new terms), when the plan would not honour it, when the board puts it under
786
+ * watch (its flags, their notice, the endgame: every covered border keeps its full hold, so it
787
+ * frees nothing to rely on), when it gains nothing
788
+ * this turn (no armies freed, no income, no border kept), when a break would cost my commander, or
789
+ * when the partner's record reads `broke` and a break would cost me anything. `propose` when it gains
790
+ * something material (income, a border kept, or armies freed of at least {@link TRUCE_MATERIAL_SHARE}
791
+ * of my income), gives up no planned attack, a break would cost no more income than it gains, the
792
+ * partner has room to grow elsewhere (else it has little reason to keep it) and its record does not
793
+ * read `broke`; otherwise `accept-if-offered`.
794
+ */
795
+ export function truceVerdict(price, income) {
796
+ const reasons = [];
797
+ const p = price.player;
798
+ if (price.state === 'broken') {
799
+ const b = price.breach;
800
+ return {
801
+ verdict: 'no',
802
+ reasons: [
803
+ `player ${p} broke the truce${b ? `: ${b.term} on turn ${b.turn} (${b.evidence})` : ''}; it is an ordinary opponent now, and no truce is priced as trusted (T8)`,
804
+ ],
805
+ };
806
+ }
807
+ if (price.state === 'notice' && price.noticeBy === 'me')
808
+ return {
809
+ verdict: 'no',
810
+ reasons: [
811
+ `I already gave notice on this truce with player ${p}: it ${price.endsTurn !== undefined ? `no longer binds from turn ${price.endsTurn}` : 'is ending'}. ` +
812
+ 'To keep a truce, withdraw the notice or propose new terms',
813
+ ],
814
+ };
815
+ if (!price.honoured)
816
+ return { verdict: 'no', reasons: [`the plan would not honour a truce with player ${p} this turn (not a free-for-all, or nothing of it binds)`] };
817
+ if (price.lossIfBroken?.commanderLost)
818
+ return { verdict: 'no', reasons: [`a break this turn would take my commander (from ${price.lossIfBroken.from} on ${price.lossIfBroken.to})`] };
819
+ if (price.trust === 'watch') {
820
+ const flags = price.watch.map((w) => WATCH_WORDS[w]);
821
+ const holds = price.fullHold.length ? `; every covered border facing it keeps its full hold (${price.fullHold.map((f) => `${f.territory}: ${f.why}`).join(', ')})` : '';
822
+ return { verdict: 'no', reasons: [`under watch (${flags.length ? flags.join('; ') : 'the board flags it'}): nothing it frees can be relied on${holds}`] };
823
+ }
824
+ const gained = price.armiesFreed > 0 || price.incomeGained > 0 || price.concededAvoided.length > 0;
825
+ if (!gained) {
826
+ const why = price.fullHold.length
827
+ ? `every covered border facing it keeps its full hold (${price.fullHold.map((f) => `${f.territory}: ${f.why}`).join(', ')})`
828
+ : price.relaxed.length
829
+ ? 'the relaxed borders free no armies the plan would have spent'
830
+ : 'no covered border of mine faces only it';
831
+ return { verdict: 'no', reasons: [`it frees nothing this turn: ${why}`] };
832
+ }
833
+ if (price.reliability === 'broke' && breakCosts(price.lossIfBroken))
834
+ return { verdict: 'no', reasons: [`its record reads as one who breaks agreements (kept rate ${price.record?.keptRate}), and a break this turn would cost me`] };
835
+ const material = price.incomeGained > 0 || price.concededAvoided.length > 0 || price.armiesFreed >= Math.max(1, Math.ceil(TRUCE_MATERIAL_SHARE * income));
836
+ const bits = [];
837
+ if (price.armiesFreed > 0)
838
+ bits.push(`frees ${price.armiesFreed} armies`);
839
+ if (price.incomeGained > 0)
840
+ bits.push(`+${price.incomeGained} next income`);
841
+ if (price.capturesGained.length)
842
+ bits.push(`captures ${price.capturesGained.join(', ')}`);
843
+ if (price.concededAvoided.length)
844
+ bits.push(`holds ${price.concededAvoided.join(', ')}, conceded without it`);
845
+ reasons.push(`it ${bits.join('; ')}`);
846
+ let propose = material;
847
+ if (!material)
848
+ reasons.push(`the gain is small (under ${Math.round(TRUCE_MATERIAL_SHARE * 100)}% of my income ${income})`);
849
+ if (price.attacksForgone.length) {
850
+ propose = false;
851
+ reasons.push(`keeping it gives up the planned attack${price.attacksForgone.length === 1 ? '' : 's'} on ${price.attacksForgone.join(', ')}`);
852
+ }
853
+ const lossIncome = price.lossIfBroken?.bonusValue ?? 0;
854
+ if (lossIncome > Math.max(0, price.incomeGained)) {
855
+ propose = false;
856
+ reasons.push(`a break this turn would cost +${lossIncome} income, more than it gains`);
857
+ }
858
+ if (price.partner.roomToGrow === false) {
859
+ propose = false;
860
+ reasons.push('the partner has no other front and no neutral beside it in view: it gains little from a truce and may not keep it (an estimate)');
861
+ }
862
+ if (price.reliability === 'broke') {
863
+ propose = false;
864
+ reasons.push(`its record reads as one who breaks agreements (kept rate ${price.record?.keptRate})`);
865
+ }
866
+ else if (price.reliability === 'kept')
867
+ reasons.push(`its record reads as one who keeps agreements (kept rate ${price.record?.keptRate})`);
868
+ return { verdict: propose ? 'propose' : 'accept-if-offered', reasons };
869
+ }
870
+ export function offerChecks(price) {
871
+ const reasons = [];
872
+ const thinned = price.armiesFreed > 0 || price.concededAvoided.length > 0;
873
+ reasons.push(thinned
874
+ ? 'what it gains me comes from thinner holds on borders that face them'
875
+ : price.incomeGained > 0 || price.capturesGained.length > 0
876
+ ? 'what it gains me comes from armies kept from an attack on them, not from thinner holds: it survives a break'
877
+ : 'it gains me nothing this turn');
878
+ const lose = breakCosts(price.lossIfBroken);
879
+ const l = price.lossIfBroken;
880
+ reasons.push(lose && l
881
+ ? `a break this turn (from ${l.from} on ${l.to}) would cost ${l.territories.length} territor${l.territories.length === 1 ? 'y' : 'ies'}, ${l.armies} armies${l.bonusValue ? `, +${l.bonusValue} income` : ''}${l.commanderLost ? ', my commander' : ''}`
882
+ : 'a break this turn would cost me nothing on the board');
883
+ const r = price.partner;
884
+ const freesThem = r.armiesOnBorder > 0 && (r.otherFronts.length > 0 || r.neutralsBeside > 0);
885
+ const theirs = price.attacksForgone.length > 0 || freesThem;
886
+ reasons.push(price.attacksForgone.length
887
+ ? `it spares their ${price.attacksForgone.join(', ')} from my planned attack`
888
+ : freesThem
889
+ ? `it frees their ${r.armiesOnBorder} armies on the border for ${r.otherFronts.length ? 'another front' : 'the neutrals beside them'} (an estimate)`
890
+ : 'it frees nothing of theirs that shows');
891
+ return {
892
+ iGainOnlyIfTheyKeepIt: thinned,
893
+ iLoseIfIComplyAndTheyDoNot: lose,
894
+ theyGainFromMyCompliance: theirs,
895
+ stressTestFirst: thinned && lose && theirs,
896
+ reasons,
897
+ };
898
+ }
899
+ export function sharedBorder(graph, board, me, partner, chokepoints) {
900
+ const at = territoryMap(board);
901
+ const mineB = new Set();
902
+ const theirsB = new Set();
903
+ for (const t of board.territories) {
904
+ if (!ownedBy(t, me))
905
+ continue;
906
+ for (const n of neighborsOf(graph, t.territoryId))
907
+ if (ownedBy(at.get(n), partner)) {
908
+ mineB.add(t.territoryId);
909
+ theirsB.add(n);
910
+ }
911
+ }
912
+ const mine = [...mineB].sort(byNum);
913
+ const theirs = [...theirsB].sort(byNum);
914
+ const armies = (t) => visibleState(at.get(t))?.armies ?? null;
915
+ const myArmies = mine.reduce((s, t) => s + (armies(t) ?? 0), 0);
916
+ const theirArmies = theirs.reduce((s, t) => s + (armies(t) ?? 0), 0);
917
+ const theirHidden = theirs.filter((t) => armies(t) === null).length;
918
+ const largestStack = Math.max(0, ...[...mine, ...theirs].map((t) => armies(t) ?? 0));
919
+ return {
920
+ mine,
921
+ theirs,
922
+ chokepoints: [...mine, ...theirs].filter((t) => chokepoints.has(t)).sort(byNum),
923
+ myArmies,
924
+ theirArmies,
925
+ theirHidden,
926
+ largestStack,
927
+ };
928
+ }
929
+ /**
930
+ * B3: the terms suggested for a truce on `border`: scope by the named territories on both sides,
931
+ * {@link SUGGESTED_NOTICE_TURNS} turn of notice, a cap at the largest stack standing there now (so
932
+ * neither side has to move armies back, and any build-up shows as `cap-exceeded`), and an end
933
+ * {@link SUGGESTED_TRUCE_TURNS} turns on when the turn is known.
934
+ */
935
+ export function suggestedTerms(border, turn) {
936
+ return {
937
+ scope: { territories: [...new Set([...border.mine, ...border.theirs])].sort(byNum) },
938
+ noticeTurns: SUGGESTED_NOTICE_TURNS,
939
+ ...(border.largestStack > 0 ? { borderCap: border.largestStack } : {}),
940
+ ...(turn != null ? { untilTurn: turn + SUGGESTED_TRUCE_TURNS } : {}),
941
+ };
942
+ }
943
+ /**
944
+ * What a player sees under GameFeed's fog setting (the wiki's fog levels; UNVERIFIED live): every
945
+ * territory's owner under No, Light and Moderate fog (as {@link OWNERS_SHOWN_FOG}); the armies
946
+ * beside its own territories under No, Light and normal fog (`Foggy`), not under Very Foggy or
947
+ * Extreme fog.
948
+ */
949
+ export function seesUnderFog(fog, what) {
950
+ if (fog === undefined)
951
+ return 'unknown';
952
+ if (what === 'owners')
953
+ return OWNERS_SHOWN_FOG.has(fog) ? 'yes' : ['Foggy', 'VeryFoggy', 'ExtremeFog'].includes(fog) ? 'no' : 'unknown';
954
+ return ['NoFog', 'LightFog', 'Foggy'].includes(fog) ? 'yes' : ['VeryFoggy', 'ExtremeFog'].includes(fog) ? 'no' : 'unknown';
955
+ }
956
+ /**
957
+ * B3: true statements about third players (not me, not `recipient`) the agent may cite to
958
+ * `recipient`, from my board: the largest visible stack each has beside a territory of the
959
+ * recipient; how many territories each holds that I see (exact only when the fog shows every owner,
960
+ * else "at least"); and the bonuses each visibly holds in full. Each says whether the recipient can
961
+ * see it under `fog`. Nothing about me (withholding is free). Ascending by player, then kind.
962
+ */
963
+ export function diplomacyFacts(input) {
964
+ const { graph, board, me, recipient, fog } = input;
965
+ const at = territoryMap(board);
966
+ const byPlayer = new Map();
967
+ for (const t of board.territories) {
968
+ const s = ownerShown(t);
969
+ const o = s ? ownerOn(s) : null;
970
+ if (o === null || o === me || o === recipient)
971
+ continue;
972
+ byPlayer.set(o, [...(byPlayer.get(o) ?? []), t.territoryId]);
973
+ }
974
+ const ownersShown = seesUnderFog(fog, 'owners');
975
+ const besideShown = seesUnderFog(fog, 'armies-beside');
976
+ const besideRecipient = (t) => neighborsOf(graph, t).some((n) => ownedBy(at.get(n), recipient));
977
+ // Owners hidden by the fog: what lies wholly beside the recipient it may still see.
978
+ const sees = (ts) => ownersShown !== 'no' || !ts.length || !ts.every(besideRecipient) ? ownersShown : besideShown === 'yes' ? 'yes' : 'unknown';
979
+ const out = [];
980
+ for (const [p, ts] of [...byPlayer].sort(([a], [b]) => a - b)) {
981
+ let best;
982
+ for (const t of [...ts].sort(byNum)) {
983
+ const armies = visibleState(at.get(t))?.armies;
984
+ if (armies == null)
985
+ continue;
986
+ const beside = neighborsOf(graph, t).filter((n) => ownedBy(at.get(n), recipient)).sort(byNum)[0];
987
+ if (beside === undefined)
988
+ continue;
989
+ if (!best || armies > best.armies)
990
+ best = { territory: t, beside, armies };
991
+ }
992
+ if (best)
993
+ out.push({
994
+ kind: 'stack-beside-you',
995
+ about: p,
996
+ text: `player ${p} has ${best.armies} armies on territory ${best.territory}, beside your territory ${best.beside}`,
997
+ recipientSees: seesUnderFog(fog, 'armies-beside'),
998
+ ...best,
999
+ });
1000
+ const atLeast = ownersShown !== 'yes';
1001
+ out.push({
1002
+ kind: 'territories',
1003
+ about: p,
1004
+ text: `player ${p} holds ${atLeast ? 'at least ' : ''}${ts.length} territor${ts.length === 1 ? 'y' : 'ies'}`,
1005
+ recipientSees: sees(ts),
1006
+ count: ts.length,
1007
+ ...(atLeast ? { atLeast: true } : {}),
1008
+ });
1009
+ const held = new Set(ts);
1010
+ const full = [...graph.bonusById.keys()]
1011
+ .sort(byNum)
1012
+ .filter((b) => {
1013
+ const members = bonusTerritories(graph, b);
1014
+ return members.length > 0 && members.every((m) => held.has(m));
1015
+ })
1016
+ .filter((b) => (graph.bonusById.get(b)?.value ?? 0) > 0);
1017
+ if (full.length) {
1018
+ const value = full.reduce((s, b) => s + (graph.bonusById.get(b)?.value ?? 0), 0);
1019
+ out.push({
1020
+ kind: 'bonuses',
1021
+ about: p,
1022
+ text: `player ${p} holds bonus${full.length === 1 ? '' : 'es'} ${full.join(', ')} in full, worth +${value} a turn`,
1023
+ recipientSees: sees(full.flatMap((b) => bonusTerritories(graph, b))),
1024
+ bonuses: full,
1025
+ value,
1026
+ });
1027
+ }
1028
+ }
1029
+ return out;
1030
+ }