@chrischall/warapp-mcp 0.0.0-stage → 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 (179) hide show
  1. package/.claude-plugin/marketplace.json +34 -0
  2. package/.claude-plugin/plugin.json +21 -0
  3. package/.mcp.json +11 -0
  4. package/LICENSE +21 -0
  5. package/README.md +264 -2
  6. package/dist/analysis/award.js +159 -0
  7. package/dist/analysis/bonuses.js +98 -0
  8. package/dist/analysis/breach.js +62 -0
  9. package/dist/analysis/card-support.js +329 -0
  10. package/dist/analysis/card-threats.js +234 -0
  11. package/dist/analysis/cards-in-effect.js +130 -0
  12. package/dist/analysis/chains.js +59 -0
  13. package/dist/analysis/chokepoints.js +140 -0
  14. package/dist/analysis/combat.js +231 -0
  15. package/dist/analysis/commander-safety.js +149 -0
  16. package/dist/analysis/commitments.js +338 -0
  17. package/dist/analysis/exchange.js +155 -0
  18. package/dist/analysis/graph.js +82 -0
  19. package/dist/analysis/guard-off.js +54 -0
  20. package/dist/analysis/guess.js +351 -0
  21. package/dist/analysis/headroom.js +241 -0
  22. package/dist/analysis/hold-diff.js +64 -0
  23. package/dist/analysis/how-lost.js +130 -0
  24. package/dist/analysis/index.js +14 -0
  25. package/dist/analysis/local-deploy.js +159 -0
  26. package/dist/analysis/lookahead.js +108 -0
  27. package/dist/analysis/opponent-profile.js +551 -0
  28. package/dist/analysis/opponents.js +1245 -0
  29. package/dist/analysis/outlook.js +633 -0
  30. package/dist/analysis/overrides.js +60 -0
  31. package/dist/analysis/picks.js +1879 -0
  32. package/dist/analysis/plan/after-leftover.js +140 -0
  33. package/dist/analysis/plan/cap-spend.js +242 -0
  34. package/dist/analysis/plan/captures.js +1195 -0
  35. package/dist/analysis/plan/commander.js +236 -0
  36. package/dist/analysis/plan/completed.js +29 -0
  37. package/dist/analysis/plan/conceded-out.js +131 -0
  38. package/dist/analysis/plan/estimates.js +715 -0
  39. package/dist/analysis/plan/guard-off.js +232 -0
  40. package/dist/analysis/plan/holds.js +1631 -0
  41. package/dist/analysis/plan/leftover.js +760 -0
  42. package/dist/analysis/plan/move-order.js +319 -0
  43. package/dist/analysis/plan/orders.js +317 -0
  44. package/dist/analysis/plan/relations.js +702 -0
  45. package/dist/analysis/plan/report.js +672 -0
  46. package/dist/analysis/plan/shared.js +1218 -0
  47. package/dist/analysis/plan/stand-still.js +823 -0
  48. package/dist/analysis/plan/state.js +44 -0
  49. package/dist/analysis/plan/strike.js +1416 -0
  50. package/dist/analysis/plan/targets.js +651 -0
  51. package/dist/analysis/plan/team.js +299 -0
  52. package/dist/analysis/plan/threats.js +927 -0
  53. package/dist/analysis/plan/transfers.js +328 -0
  54. package/dist/analysis/plan/util.js +5 -0
  55. package/dist/analysis/plan/vacated.js +285 -0
  56. package/dist/analysis/planner.js +2922 -0
  57. package/dist/analysis/player-record.js +144 -0
  58. package/dist/analysis/player.js +268 -0
  59. package/dist/analysis/profile.js +347 -0
  60. package/dist/analysis/relations.js +1030 -0
  61. package/dist/analysis/schedule.js +88 -0
  62. package/dist/analysis/since-last.js +50 -0
  63. package/dist/analysis/static-seats.js +71 -0
  64. package/dist/analysis/stress.js +577 -0
  65. package/dist/analysis/team-brief.js +151 -0
  66. package/dist/analysis/tripwire.js +644 -0
  67. package/dist/analysis/turn-sim.js +259 -0
  68. package/dist/analysis/whereabouts.js +1109 -0
  69. package/dist/board.js +105 -0
  70. package/dist/bundle.js +143479 -0
  71. package/dist/cards.js +435 -0
  72. package/dist/chat-cursor.js +135 -0
  73. package/dist/chat.js +192 -0
  74. package/dist/client.js +361 -0
  75. package/dist/config.js +62 -0
  76. package/dist/direct/link.js +102 -0
  77. package/dist/direct/session.js +267 -0
  78. package/dist/direct/transport.js +424 -0
  79. package/dist/guess-salt.js +65 -0
  80. package/dist/hosted.js +24 -0
  81. package/dist/index.js +33 -0
  82. package/dist/join-color.js +140 -0
  83. package/dist/live.js +278 -0
  84. package/dist/map-stats.js +152 -0
  85. package/dist/map-store.js +204 -0
  86. package/dist/move-order.js +141 -0
  87. package/dist/my-games.js +180 -0
  88. package/dist/normalize.js +411 -0
  89. package/dist/open-games.js +537 -0
  90. package/dist/outlook-log.js +138 -0
  91. package/dist/path-lock.js +22 -0
  92. package/dist/pick-list.js +193 -0
  93. package/dist/player-record-store.js +229 -0
  94. package/dist/player-states.js +31 -0
  95. package/dist/profile-store.js +677 -0
  96. package/dist/protocol/bundle.js +375 -0
  97. package/dist/protocol/codec.js +556 -0
  98. package/dist/protocol/decoded.js +12 -0
  99. package/dist/protocol/interp.js +1904 -0
  100. package/dist/protocol/methods.js +531 -0
  101. package/dist/protocol/rpc.js +202 -0
  102. package/dist/push/listener.js +393 -0
  103. package/dist/push/packets.js +66 -0
  104. package/dist/push/socketio.js +333 -0
  105. package/dist/push/websocket.js +179 -0
  106. package/dist/redact.js +62 -0
  107. package/dist/relations-store.js +242 -0
  108. package/dist/replay.js +215 -0
  109. package/dist/scalars.js +28 -0
  110. package/dist/scout.js +346 -0
  111. package/dist/stats.js +269 -0
  112. package/dist/strategy/card-clock.js +185 -0
  113. package/dist/strategy/map-notes.js +128 -0
  114. package/dist/strategy/notes.js +2168 -0
  115. package/dist/team-cards.js +84 -0
  116. package/dist/team-orders.js +150 -0
  117. package/dist/teams.js +19 -0
  118. package/dist/tools/award.js +206 -0
  119. package/dist/tools/begin-turn.js +162 -0
  120. package/dist/tools/board.js +77 -0
  121. package/dist/tools/card-advice.js +256 -0
  122. package/dist/tools/card-effects.js +49 -0
  123. package/dist/tools/card-plays.js +434 -0
  124. package/dist/tools/card-support-advice.js +140 -0
  125. package/dist/tools/chat-inbox.js +146 -0
  126. package/dist/tools/chat.js +483 -0
  127. package/dist/tools/check-plan.js +688 -0
  128. package/dist/tools/commander-check.js +102 -0
  129. package/dist/tools/commitments.js +216 -0
  130. package/dist/tools/common.js +143 -0
  131. package/dist/tools/diplomacy.js +342 -0
  132. package/dist/tools/game.js +126 -0
  133. package/dist/tools/guess-view.js +56 -0
  134. package/dist/tools/healthcheck.js +90 -0
  135. package/dist/tools/hints.js +34 -0
  136. package/dist/tools/how-lost.js +154 -0
  137. package/dist/tools/index.js +142 -0
  138. package/dist/tools/join-game.js +327 -0
  139. package/dist/tools/leave-game.js +181 -0
  140. package/dist/tools/live-context.js +339 -0
  141. package/dist/tools/live.js +404 -0
  142. package/dist/tools/map-stats.js +117 -0
  143. package/dist/tools/map.js +133 -0
  144. package/dist/tools/my-games.js +123 -0
  145. package/dist/tools/open-games.js +104 -0
  146. package/dist/tools/opponents.js +151 -0
  147. package/dist/tools/order-options.js +135 -0
  148. package/dist/tools/picks.js +292 -0
  149. package/dist/tools/profile-hook.js +156 -0
  150. package/dist/tools/profile-opponents.js +121 -0
  151. package/dist/tools/profile-reads.js +99 -0
  152. package/dist/tools/push.js +385 -0
  153. package/dist/tools/relations.js +611 -0
  154. package/dist/tools/resolve.js +45 -0
  155. package/dist/tools/route.js +36 -0
  156. package/dist/tools/scout.js +87 -0
  157. package/dist/tools/session.js +163 -0
  158. package/dist/tools/strategy.js +200 -0
  159. package/dist/tools/stress-opponents.js +83 -0
  160. package/dist/tools/surrender.js +240 -0
  161. package/dist/tools/survival.js +189 -0
  162. package/dist/tools/team-brief.js +266 -0
  163. package/dist/tools/team-source.js +222 -0
  164. package/dist/tools/team.js +182 -0
  165. package/dist/tools/turn.js +2761 -0
  166. package/dist/tools/uncommit.js +160 -0
  167. package/dist/tools/where.js +275 -0
  168. package/dist/tools/write-kit.js +158 -0
  169. package/dist/transport-bridge.js +33 -0
  170. package/dist/trend.js +452 -0
  171. package/dist/version.js +4 -0
  172. package/manifest.json +247 -0
  173. package/mint.yaml +140 -0
  174. package/package.json +68 -4
  175. package/server.json +72 -0
  176. package/skills/warapp-api/SKILL.md +226 -0
  177. package/skills/warapp-api/references/scout.mjs +348 -0
  178. package/skills/warapp-api/scripts/warapp.sh +228 -0
  179. package/skills/warapp-mcp/SKILL.md +1011 -0
@@ -0,0 +1,98 @@
1
+ // Per-bonus geometry: flattened membership, borders, entry points, and an
2
+ // "easiest bonus" ranking. Pure and deterministic.
3
+ import { neighborsOf } from './graph.js';
4
+ const byNum = (a, b) => a - b;
5
+ const flattened = new WeakMap();
6
+ /**
7
+ * All territories of a bonus, flattening member bonuses (cycle-safe). Unknown bonus → `[]`.
8
+ * Remembered per graph and frozen: the planner asks for the same bonus thousands of times in
9
+ * one plan (it was most of a plan's time on a large map), and a graph's bonuses never change.
10
+ */
11
+ export function bonusTerritories(g, bonusId) {
12
+ let cache = flattened.get(g);
13
+ if (!cache)
14
+ flattened.set(g, (cache = new Map()));
15
+ const hit = cache.get(bonusId);
16
+ if (hit)
17
+ return hit;
18
+ const out = new Set();
19
+ const seen = new Set();
20
+ const visit = (id) => {
21
+ const b = g.bonusById.get(id);
22
+ if (!b || seen.has(id))
23
+ return;
24
+ seen.add(id);
25
+ for (const t of b.territoryIds)
26
+ out.add(t);
27
+ for (const sub of b.bonusIds)
28
+ visit(sub);
29
+ };
30
+ visit(bonusId);
31
+ const ts = Object.freeze([...out].sort(byNum));
32
+ cache.set(bonusId, ts);
33
+ return ts;
34
+ }
35
+ export function analyzeBonus(g, bonusId) {
36
+ const b = g.bonusById.get(bonusId);
37
+ if (!b)
38
+ return undefined;
39
+ const territoryIds = [...bonusTerritories(g, bonusId)];
40
+ const inside = new Set(territoryIds);
41
+ const borders = [];
42
+ const entries = new Set();
43
+ for (const t of territoryIds) {
44
+ let border = false;
45
+ for (const n of neighborsOf(g, t)) {
46
+ if (inside.has(n))
47
+ continue;
48
+ border = true;
49
+ entries.add(n);
50
+ }
51
+ if (border)
52
+ borders.push(t);
53
+ }
54
+ const size = territoryIds.length;
55
+ return {
56
+ bonusId: b.id,
57
+ name: b.name,
58
+ value: b.value,
59
+ territoryIds,
60
+ memberBonusIds: [...b.bonusIds].sort(byNum),
61
+ isSuperbonus: b.bonusIds.length > 0,
62
+ borderTerritoryIds: borders,
63
+ entryPointIds: [...entries].sort(byNum),
64
+ valuePerTerritory: size ? b.value / size : 0,
65
+ valuePerBorder: borders.length ? b.value / borders.length : b.value,
66
+ score: size ? b.value / (size + borders.length) : 0,
67
+ };
68
+ }
69
+ /**
70
+ * Each entry point of a bonus (a territory outside it next to one of its territories) with
71
+ * the number of its territories that entry point borders, ascending by id. One that borders
72
+ * two or more is a double border: a single stack there threatens several members at once.
73
+ * Unknown bonus → empty.
74
+ */
75
+ export function entryTouches(g, bonusId) {
76
+ const inside = new Set(bonusTerritories(g, bonusId));
77
+ const touches = new Map();
78
+ for (const t of inside)
79
+ for (const n of neighborsOf(g, t))
80
+ if (!inside.has(n))
81
+ touches.set(n, (touches.get(n) ?? 0) + 1);
82
+ return new Map([...touches].sort((a, b) => a[0] - b[0]));
83
+ }
84
+ /** Every bonus on the map, in map order. */
85
+ export function analyzeBonuses(g) {
86
+ return g.map.bonuses.map((b) => analyzeBonus(g, b.id));
87
+ }
88
+ /** Bonuses ordered easiest first: score desc, then value desc, size asc, id asc. */
89
+ export function rankBonuses(g, opts = {}) {
90
+ const minValue = opts.minValue ?? 1;
91
+ const ranked = analyzeBonuses(g)
92
+ .filter((b) => b.value >= minValue)
93
+ .sort((a, b) => b.score - a.score ||
94
+ b.value - a.value ||
95
+ a.territoryIds.length - b.territoryIds.length ||
96
+ a.bonusId - b.bonusId);
97
+ return opts.limit !== undefined ? ranked.slice(0, opts.limit) : ranked;
98
+ }
@@ -0,0 +1,62 @@
1
+ // The breach cost of a border (#275, pattern 2): with the guard off every interior territory may
2
+ // hold 0, so one breach by a large stack puts everything behind the border one move away. Pure and
3
+ // deterministic; ties resolve on ascending ids.
4
+ //
5
+ // The territories a border `t` alone shields are my territories within BREACH_DEPTH (2) steps of it
6
+ // through my holdings that face no enemy themselves (no neighbour of a foe, none in the fog), and
7
+ // whose only front within BREACH_DEPTH steps (through my holdings) is `t`: a territory a second front
8
+ // also reaches is that front's too, so no breach cost is counted twice. Only a hollow territory
9
+ // counts (`hollow`, the caller's test: in the planner, none of my territories beside it, itself
10
+ // included, holds the stack that would come through; a 120-army stack one step behind answers a
11
+ // breach, #214's boards). The cost is the positive
12
+ // bonuses I hold in full with a member among them, leaving out every bonus `t` itself is in (losing
13
+ // `t` breaks those already). The planner adds per-territory income itself.
14
+ import { bonusTerritories } from './bonuses.js';
15
+ import { neighborsOf } from './graph.js';
16
+ /** How far behind a border a breach reaches: the stack takes the border, then walks on. */
17
+ export const BREACH_DEPTH = 2;
18
+ const byNum = (a, b) => a - b;
19
+ /** My territories within `depth` steps of `from` through `holdings` (`from` itself left out). */
20
+ function within(graph, holdings, from, depth) {
21
+ const dist = new Map([[from, 0]]);
22
+ let frontier = [from];
23
+ for (let d = 1; d <= depth; d++) {
24
+ const next = [];
25
+ for (const x of frontier)
26
+ for (const n of neighborsOf(graph, x))
27
+ if (holdings.has(n) && !dist.has(n)) {
28
+ dist.set(n, d);
29
+ next.push(n);
30
+ }
31
+ frontier = next;
32
+ }
33
+ dist.delete(from);
34
+ return dist;
35
+ }
36
+ /**
37
+ * What a breach of my border `t` opens (see the header). `front(x)`: my `x` faces an enemy or the
38
+ * fog. `skip`: territories already counted elsewhere (what losing `t` cuts off, #235). `hollow(x)`:
39
+ * a breach walks into `x` (default: always). Empty when `t` is not mine or not a front.
40
+ */
41
+ export function breachBehind(graph, holdings, front, t, skip = new Set(), hollow = () => true) {
42
+ const none = { ids: [], bonuses: [], income: 0 };
43
+ if (!holdings.has(t) || !front(t))
44
+ return none;
45
+ const ids = [...within(graph, holdings, t, BREACH_DEPTH).keys()]
46
+ .filter((x) => !skip.has(x) && !front(x) && hollow(x))
47
+ .filter((x) => [...within(graph, holdings, x, BREACH_DEPTH).keys()].filter(front).every((y) => y === t))
48
+ .sort(byNum);
49
+ if (!ids.length)
50
+ return none;
51
+ const inside = new Set(ids);
52
+ const bonuses = [];
53
+ for (const b of [...graph.bonusById.values()].sort((a, c) => a.id - c.id)) {
54
+ if (b.value <= 0)
55
+ continue;
56
+ const ts = bonusTerritories(graph, b.id);
57
+ if (!ts.length || ts.includes(t) || !ts.every((x) => holdings.has(x)) || !ts.some((x) => inside.has(x)))
58
+ continue;
59
+ bonuses.push({ id: b.id, value: b.value });
60
+ }
61
+ return { ids, bonuses, income: bonuses.reduce((n, b) => n + b.value, 0) };
62
+ }
@@ -0,0 +1,329 @@
1
+ // Where to play the cards warapp_submit_turn can play but the planner never does (PLAN-TEAMS part D2):
2
+ // Diplomacy on the opponent pressing me hardest when two or more are, Sanctions on the leader, Airlift
3
+ // onto a border of mine or a teammate's that falls without it, and Gift as team support (a territory
4
+ // that completes a teammate's bonus); and (G2) Spy, Reconnaissance and Surveillance only where the fog
5
+ // hides what the plan needs. Advice only: nothing here changes the plan or its orders. Pure and
6
+ // deterministic (ties on ascending id); no I/O.
7
+ //
8
+ // Rules (docs/STRATEGY.md, the wiki's card pages): a Diplomacy card stops attacks between its two
9
+ // players from the turn after it is played; Sanctions cut the target's income from its next turn (a
10
+ // negative percentage raises it); an Airlift lands after the deploys and before every attack, and armies
11
+ // landing on a teammate's territory become the teammate's; a Gift moves a territory and its armies after
12
+ // the airlifts and before the attacks. The card plays' encodings are UNVERIFIED live (V9).
13
+ import { bonusTerritories } from './bonuses.js';
14
+ import { COMMANDER_STRENGTH } from './combat.js';
15
+ import { reader } from './card-threats.js';
16
+ import { neighborsOf } from './graph.js';
17
+ import { ownerShown, visibleState } from './plan/shared.js';
18
+ /**
19
+ * Each opponent in contact with me (a visible stack beside a territory of mine), with the armies my
20
+ * borders must keep against it alone: what a Diplomacy card with it frees. Strongest pressure first
21
+ * (then ascending id).
22
+ */
23
+ export function pressures(cb) {
24
+ const r = reader(cb);
25
+ const by = new Map();
26
+ for (const b of r.ids) {
27
+ if (!r.isMine(b))
28
+ continue;
29
+ const cmd = r.commanderOf(b, (q) => q === cb.me);
30
+ for (const [player, reach] of r.reachByPlayer(b)) {
31
+ const p = by.get(player) ?? { player, armies: 0, takes: [], borders: [] };
32
+ p.borders.push(b);
33
+ p.armies += r.holdNeed(reach, cmd) + (cmd ? COMMANDER_STRENGTH : 0);
34
+ if (r.toTake(r.after(b) + (cmd ? COMMANDER_STRENGTH : 0)) <= reach)
35
+ p.takes.push(b);
36
+ by.set(player, p);
37
+ }
38
+ }
39
+ return [...by.values()].sort((a, b) => b.armies - a.armies || a.player - b.player);
40
+ }
41
+ /**
42
+ * Diplomacy on the opponent pressing me hardest, when two or more opponents are in contact (with
43
+ * one, peace with it is peace with everyone: the card is a truce for nothing). An opponent already at
44
+ * peace with me by a Diplomacy card in force is passed over, and so is a truce partner whose truce
45
+ * already covers every border it touches — unless the card adds protection: the truce is in notice
46
+ * (it ends), or the partner presses a border the truce does not cover. Either way it is said.
47
+ * `undefined` with fewer than two opponents in contact.
48
+ */
49
+ export function diplomacyAdvice(cb, opts = {}) {
50
+ const all = pressures(cb);
51
+ if (all.length < 2)
52
+ return undefined;
53
+ const skipped = [];
54
+ for (const p of all) {
55
+ if (opts.atPeace?.has(p.player)) {
56
+ skipped.push(`player ${p.player}: a Diplomacy card between you is already in force`);
57
+ continue;
58
+ }
59
+ const truce = opts.truces?.find((t) => t.player === p.player);
60
+ let overTruce;
61
+ if (truce) {
62
+ const covered = new Set(truce.coveredMine);
63
+ const open = p.borders.filter((b) => !covered.has(b));
64
+ if (truce.state === 'notice') {
65
+ overTruce = `your truce with player ${p.player} is in notice${truce.endsTurn !== undefined ? ` (it ends turn ${truce.endsTurn})` : ''}, and a Diplomacy card is enforced by the game`;
66
+ }
67
+ else if (open.length) {
68
+ overTruce = `your truce with player ${p.player} does not cover ${open.join(', ')}, which it presses`;
69
+ }
70
+ else {
71
+ skipped.push(`player ${p.player}: your truce already covers every border it presses, so the card adds nothing the truce does not`);
72
+ continue;
73
+ }
74
+ }
75
+ if (p.armies <= 0)
76
+ break;
77
+ const takes = p.takes.length ? `; as the plan leaves them it can take ${p.takes.join(', ')}` : '';
78
+ return {
79
+ player: p.player,
80
+ pressure: p,
81
+ ...(overTruce ? { overTruce } : {}),
82
+ why: `Diplomacy with player ${p.player}: of the ${all.length} opponents beside you it presses hardest — your borders ${p.borders.join(', ')} ` +
83
+ `keep ${p.armies} armies against it alone${takes}.${overTruce ? ` Played on a truce partner because ${overTruce}.` : ''}`,
84
+ skipped,
85
+ };
86
+ }
87
+ return { why: 'Hold the Diplomacy card: no opponent beside you is worth it this turn.', skipped };
88
+ }
89
+ /**
90
+ * Sanctions on the strongest opponent (the leader, or the strongest other player when I lead); with a
91
+ * negative percentage the card raises income, so on me. G2: an opponent in `pass` (a truce partner, a
92
+ * player a Diplomacy card keeps at peace with me) is passed over, its reason stated. `undefined` with no
93
+ * opponent in sight.
94
+ */
95
+ export function sanctionsAdvice(input) {
96
+ const { me, players, percentage } = input;
97
+ if (percentage !== undefined && percentage < 0) {
98
+ return { player: me, why: `Sanctions on yourself: this game's percentage is negative (${Math.round(percentage * 100)}%), so the card raises the target's income.` };
99
+ }
100
+ const ranked = [...players].sort((a, b) => b.strength - a.strength || a.playerId - b.playerId);
101
+ const opponents = ranked.filter((p) => p.playerId !== me);
102
+ if (!opponents.length)
103
+ return undefined;
104
+ const skipped = opponents.flatMap((p) => (input.pass?.has(p.playerId) ? [`player ${p.playerId}: ${input.pass.get(p.playerId)}`] : []));
105
+ const passed = skipped.length ? ` Passed over: ${skipped.join('; ')}.` : '';
106
+ const top = opponents.find((p) => !input.pass?.has(p.playerId));
107
+ if (!top)
108
+ return { why: `Hold the Sanctions card: no opponent in sight is one to sanction.${passed}`, skipped };
109
+ const lead = ranked[0].playerId === me;
110
+ const pct = percentage !== undefined ? ` by ${Math.round(percentage * 100)}%` : '';
111
+ const strongest = top === opponents[0];
112
+ return {
113
+ player: top.playerId,
114
+ why: `Sanctions on player ${top.playerId}: ${lead ? `you lead, and it is the strongest opponent${strongest ? '' : ' left'}` : strongest ? 'it leads' : 'it is the strongest opponent left'} on strength (visible armies + ` +
115
+ `income: ${top.strength}). A sanction cuts its income${pct} from its next turn, so a cut costs the largest player most; play it the turn before you attack.${passed}`,
116
+ ...(skipped.length ? { skipped } : {}),
117
+ };
118
+ }
119
+ /**
120
+ * An Airlift onto a territory that falls this turn without it — mine as the plan leaves it, or (in a
121
+ * team game) a teammate's with the deploys it has entered; never one the plan moves armies out of — from a territory of mine with armies to
122
+ * spare (what stands there after the deploys, less what the plan moves out of it and what it must
123
+ * keep to hold). A commander's territory first, then the most armies at stake, then ascending id; the
124
+ * first one a source can save. `undefined` when none.
125
+ */
126
+ export function airliftAdvice(cb) {
127
+ const r = reader(cb);
128
+ const teammateDeploy = (t) => (cb.board.teammateOrders ?? []).reduce((a, e) => a + (e.orders?.deploys ?? []).filter((d) => d.territoryId === t).reduce((x, d) => x + d.armies, 0), 0);
129
+ const friendOf = (t) => {
130
+ const p = r.ownerOf(t);
131
+ return p !== undefined && cb.friends?.has(p) ? p : undefined;
132
+ };
133
+ const targets = [];
134
+ for (const t of r.ids) {
135
+ const teammate = friendOf(t);
136
+ if (!r.isMine(t) && teammate === undefined)
137
+ continue;
138
+ // A border the plan withdraws from is given up on purpose: no airlift into it.
139
+ if (teammate === undefined && r.outOf(t) > 0)
140
+ continue;
141
+ if (r.state.get(t)?.armies === null)
142
+ continue;
143
+ const reach = r.reachOf(t);
144
+ if (!reach)
145
+ continue;
146
+ const owner = teammate ?? cb.me;
147
+ const commander = r.commanderOf(t, (q) => q === owner);
148
+ const armies = teammate === undefined ? r.after(t) : r.armiesOf(t) + teammateDeploy(t);
149
+ const need = r.holdNeed(reach.reach, commander) - armies;
150
+ if (need <= 0)
151
+ continue;
152
+ targets.push({ id: t, ...(teammate !== undefined ? { teammate } : {}), armies, commander, player: reach.player, reach: reach.reach, need });
153
+ }
154
+ targets.sort((a, b) => Number(b.commander) - Number(a.commander) || b.armies - a.armies || a.id - b.id);
155
+ // What each territory of mine can spare: after the deploys, less the plan's moves out of it, less what it
156
+ // keeps to hold (a commander's own territory keeps its hold too).
157
+ const spare = new Map();
158
+ for (const s of r.ids) {
159
+ if (!r.isMine(s))
160
+ continue;
161
+ const reach = r.reachOf(s)?.reach;
162
+ const keep = Math.max(r.guard, reach === undefined ? 0 : r.holdNeed(reach, r.commanderOf(s, (q) => q === cb.me)));
163
+ const can = Math.min(r.armiesOf(s) + r.deployAt(s) - r.outOf(s), r.after(s)) - keep;
164
+ if (can > 0)
165
+ spare.set(s, can);
166
+ }
167
+ for (const t of targets) {
168
+ let best;
169
+ for (const [s, can] of spare) {
170
+ if (s === t.id || can < t.need)
171
+ continue;
172
+ if (best === undefined || can > spare.get(best) || (can === spare.get(best) && s < best))
173
+ best = s;
174
+ }
175
+ if (best === undefined)
176
+ continue;
177
+ const where = t.teammate !== undefined ? `your teammate ${t.teammate}'s ${t.id}` : `${t.id}`;
178
+ return {
179
+ from: best,
180
+ to: t.id,
181
+ armies: t.need,
182
+ ...(t.teammate !== undefined ? { teammate: t.teammate } : {}),
183
+ player: t.player,
184
+ reach: t.reach,
185
+ commander: t.commander,
186
+ why: `Airlift ${t.need} from ${best} to ${where}${t.commander ? ' (a commander stands there)' : ''}: its ${t.armies} fall to player ${t.player}'s ~${t.reach}, ` +
187
+ `and ${t.armies + t.need} hold; the airlift lands before any attack.` +
188
+ (t.teammate !== undefined ? " The armies become your teammate's, and hold only if your teammate keeps them there: say so in team chat." : ''),
189
+ };
190
+ }
191
+ return undefined;
192
+ }
193
+ /**
194
+ * A Gift as team support: my members of a bonus a teammate is nearer to holding, when giving them
195
+ * completes it (every other member is the teammate's) and I hold enough Gift cards — never a territory
196
+ * with a special unit on it (war.app refuses it) or one the plan moves armies out of. The most valuable
197
+ * bonus first, then ascending id. `undefined` when none.
198
+ */
199
+ export function giftAdvice(cb, shared, gifts) {
200
+ if (gifts <= 0)
201
+ return undefined;
202
+ const r = reader(cb);
203
+ const ok = (t) => !(r.state.get(t)?.specialUnits ?? []).length && r.outOf(t) === 0;
204
+ const best = [...shared]
205
+ .filter((b) => b.nearer !== null && b.nearer !== cb.me && !b.others.length && b.teammates.length === 1 && b.mine.length <= gifts && b.mine.every(ok))
206
+ .sort((a, b) => b.value - a.value || a.bonusId - b.bonusId)[0];
207
+ if (!best)
208
+ return undefined;
209
+ const mate = best.teammates[0].player;
210
+ const borders = best.mine.filter((t) => r.reachOf(t) !== undefined);
211
+ return {
212
+ player: mate,
213
+ bonus: best.bonusId,
214
+ value: best.value,
215
+ territories: [...best.mine],
216
+ why: `Gift ${best.mine.join(', ')} to your teammate ${mate}: it holds every other member of bonus ${best.bonusId}, so the gift completes it ` +
217
+ `(+${best.value} a turn for the team; a bonus pays only the player who holds all of it).` +
218
+ (borders.length ? ` ${borders.join(', ')} ${borders.length === 1 ? 'faces' : 'face'} an opponent: your teammate must hold ${borders.length === 1 ? 'it' : 'them'}.` : ''),
219
+ };
220
+ }
221
+ /**
222
+ * G2: where an information card reveals something the plan needs — never with fog off, and never just
223
+ * to see more. Three needs, read off the board: a border of mine whose neighbour the fog hides (its
224
+ * armies unknown: an opponent may stand there), a bonus I am completing (I hold half its members or more, not all) with
225
+ * a member the fog hides, and an opponent with no territory in view. Spy goes on an unseen opponent, else
226
+ * on the owner shown beside the most hidden stacks next to me; Surveillance on the bonus I am completing
227
+ * that is nearest done (then the most valuable, then ascending id), else the bonus worth the most with a
228
+ * hidden border of mine in it; Reconnaissance on the hidden territory next to the most of mine (then the
229
+ * most armies of mine beside it, then ascending id), else a hidden member of the bonus I am completing.
230
+ * `hold` says, for a card held with nothing to reveal, why it is kept. Pure; ties on ascending id.
231
+ */
232
+ export function intelAdvice(cb, opts) {
233
+ if (opts.fog === 'NoFog' || !opts.held.size)
234
+ return { advice: [], hold: [] };
235
+ const r = reader(cb);
236
+ const hidden = (t) => !visibleState(r.state.get(t));
237
+ const mineNext = (t) => neighborsOf(cb.graph, t).filter((n) => r.isMine(n));
238
+ // A border of mine whose neighbour the fog hides.
239
+ const blind = r.ids
240
+ .filter((t) => !r.isMine(t) && hidden(t) && mineNext(t).length)
241
+ .map((t) => ({ t, next: mineNext(t).length, armies: mineNext(t).reduce((a, n) => a + r.armiesOf(n), 0) }))
242
+ .sort((a, b) => b.next - a.next || b.armies - a.armies || a.t - b.t);
243
+ // A bonus I am completing with a member the fog hides.
244
+ const building = cb.graph.map.bonuses
245
+ .filter((b) => b.value > 0)
246
+ .map((b) => {
247
+ const ts = bonusTerritories(cb.graph, b.id);
248
+ const held = ts.filter((t) => r.isMine(t)).length;
249
+ return { id: b.id, value: b.value, size: ts.length, held, fogged: ts.filter((t) => !r.isMine(t) && hidden(t)) };
250
+ })
251
+ .filter((b) => b.size > 0 && 2 * b.held >= b.size && b.held < b.size && b.fogged.length)
252
+ .sort((a, b) => b.held / b.size - a.held / a.size || b.value - a.value || a.id - b.id);
253
+ // An opponent with no territory in view.
254
+ const inView = new Set(r.ids.flatMap((t) => {
255
+ const s = ownerShown(r.state.get(t));
256
+ return s?.owner.kind === 'player' ? [s.owner.playerId] : [];
257
+ }));
258
+ const unseen = [...opts.opponents].filter((p) => p !== cb.me && !cb.friends?.has(p) && !inView.has(p)).sort((a, b) => a - b);
259
+ // An owner shown beside me whose stack the fog hides (owner-only fog).
260
+ const shownBeside = new Map();
261
+ for (const { t } of blind) {
262
+ const s = ownerShown(r.state.get(t));
263
+ if (s?.owner.kind === 'player' && r.foe(s.owner.playerId))
264
+ shownBeside.set(s.owner.playerId, (shownBeside.get(s.owner.playerId) ?? 0) + 1);
265
+ }
266
+ const hiddenStacks = [...shownBeside].sort((a, b) => b[1] - a[1] || a[0] - b[0])[0];
267
+ const advice = [];
268
+ const hold = [];
269
+ const nothing = (card) => hold.push(`Hold the ${card} card: the fog hides nothing the plan needs this turn (no hidden border of yours, no bonus you are completing with a fogged member, no opponent out of view).`);
270
+ if (opts.held.has('Spy')) {
271
+ if (unseen.length) {
272
+ const p = unseen[0];
273
+ advice.push({ card: 'Spy', player: p, why: `Spy on player ${p}: none of its territories is in view, so its income and stacks are unknown to the plan.` });
274
+ }
275
+ else if (hiddenStacks) {
276
+ const [p, n] = hiddenStacks;
277
+ advice.push({
278
+ card: 'Spy',
279
+ player: p,
280
+ why: `Spy on player ${p}: the fog hides the armies on ${n === 1 ? 'its territory' : `${n} of its territories`} beside yours, so the threat there is a guess.`,
281
+ });
282
+ }
283
+ else
284
+ nothing('Spy');
285
+ }
286
+ if (opts.held.has('Surveillance')) {
287
+ const b = building[0];
288
+ if (b) {
289
+ advice.push({
290
+ card: 'Surveillance',
291
+ bonus: b.id,
292
+ why: `Surveillance on bonus ${b.id}: you hold ${b.held} of its ${b.size} territories and the fog hides ${b.fogged.join(', ')}, so what finishing it costs is a guess.`,
293
+ });
294
+ }
295
+ else {
296
+ const blindSet = new Set(blind.map((x) => x.t));
297
+ const best = cb.graph.map.bonuses
298
+ .filter((x) => x.value > 0)
299
+ .map((x) => ({ id: x.id, value: x.value, n: bonusTerritories(cb.graph, x.id).filter((t) => blindSet.has(t)).length }))
300
+ .filter((x) => x.n > 0)
301
+ .sort((a, c) => c.value - a.value || c.n - a.n || a.id - c.id)[0];
302
+ if (best)
303
+ advice.push({
304
+ card: 'Surveillance',
305
+ bonus: best.id,
306
+ why: `Surveillance on bonus ${best.id} (+${best.value}): the fog hides ${best.n} of its territories beside yours, so who holds it, and what they earn, is a guess.`,
307
+ });
308
+ else
309
+ nothing('Surveillance');
310
+ }
311
+ }
312
+ if (opts.held.has('Reconnaissance')) {
313
+ const x = blind[0];
314
+ if (x) {
315
+ advice.push({
316
+ card: 'Reconnaissance',
317
+ target: x.t,
318
+ why: `Reconnaissance on ${x.t}: it borders ${x.next} of your territories (${x.armies} armies) and the fog hides what stands there.`,
319
+ });
320
+ }
321
+ else if (building[0]) {
322
+ const t = building[0].fogged[0];
323
+ advice.push({ card: 'Reconnaissance', target: t, why: `Reconnaissance on ${t}: a member of bonus ${building[0].id}, which you are completing, hidden by the fog.` });
324
+ }
325
+ else
326
+ nothing('Reconnaissance');
327
+ }
328
+ return { advice, hold };
329
+ }