@chrischall/warapp-mcp 0.0.0 → 0.2.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 (194) hide show
  1. package/.claude-plugin/marketplace.json +4 -4
  2. package/.claude-plugin/plugin.json +2 -2
  3. package/README.md +211 -9
  4. package/dist/analysis/accept-surrender.js +56 -0
  5. package/dist/analysis/award.js +159 -0
  6. package/dist/analysis/bonuses.js +98 -0
  7. package/dist/analysis/breach.js +62 -0
  8. package/dist/analysis/calibrate.js +239 -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/finished-game.js +136 -0
  19. package/dist/analysis/game-lessons.js +217 -0
  20. package/dist/analysis/graph.js +82 -0
  21. package/dist/analysis/guard-off.js +54 -0
  22. package/dist/analysis/guess.js +351 -0
  23. package/dist/analysis/headroom.js +241 -0
  24. package/dist/analysis/hold-diff.js +64 -0
  25. package/dist/analysis/how-lost.js +130 -0
  26. package/dist/analysis/index.js +14 -0
  27. package/dist/analysis/local-deploy.js +179 -0
  28. package/dist/analysis/lookahead.js +108 -0
  29. package/dist/analysis/opponent-profile.js +552 -0
  30. package/dist/analysis/opponents.js +1253 -0
  31. package/dist/analysis/outlook.js +695 -0
  32. package/dist/analysis/overrides.js +60 -0
  33. package/dist/analysis/picks.js +1879 -0
  34. package/dist/analysis/plan/after-leftover.js +140 -0
  35. package/dist/analysis/plan/cap-spend.js +242 -0
  36. package/dist/analysis/plan/captures.js +1195 -0
  37. package/dist/analysis/plan/commander.js +236 -0
  38. package/dist/analysis/plan/completed.js +29 -0
  39. package/dist/analysis/plan/conceded-out.js +131 -0
  40. package/dist/analysis/plan/estimates.js +715 -0
  41. package/dist/analysis/plan/guard-off.js +232 -0
  42. package/dist/analysis/plan/holds.js +1631 -0
  43. package/dist/analysis/plan/leftover.js +760 -0
  44. package/dist/analysis/plan/move-order.js +319 -0
  45. package/dist/analysis/plan/orders.js +317 -0
  46. package/dist/analysis/plan/relations.js +702 -0
  47. package/dist/analysis/plan/report.js +672 -0
  48. package/dist/analysis/plan/shared.js +1405 -0
  49. package/dist/analysis/plan/stand-still.js +823 -0
  50. package/dist/analysis/plan/state.js +44 -0
  51. package/dist/analysis/plan/strike.js +1416 -0
  52. package/dist/analysis/plan/targets.js +651 -0
  53. package/dist/analysis/plan/team.js +299 -0
  54. package/dist/analysis/plan/threats.js +1001 -0
  55. package/dist/analysis/plan/transfers.js +328 -0
  56. package/dist/analysis/plan/util.js +5 -0
  57. package/dist/analysis/plan/vacated.js +285 -0
  58. package/dist/analysis/planner.js +2927 -0
  59. package/dist/analysis/player-record.js +144 -0
  60. package/dist/analysis/player.js +268 -0
  61. package/dist/analysis/profile.js +347 -0
  62. package/dist/analysis/relations.js +1030 -0
  63. package/dist/analysis/schedule.js +88 -0
  64. package/dist/analysis/since-last.js +50 -0
  65. package/dist/analysis/static-seats.js +71 -0
  66. package/dist/analysis/stress.js +584 -0
  67. package/dist/analysis/team-brief.js +151 -0
  68. package/dist/analysis/tripwire.js +644 -0
  69. package/dist/analysis/turn-sim.js +259 -0
  70. package/dist/analysis/whereabouts.js +1112 -0
  71. package/dist/board.js +105 -0
  72. package/dist/bundle.js +121082 -36148
  73. package/dist/calibration-source.js +75 -0
  74. package/dist/cards.js +435 -0
  75. package/dist/chat-cursor.js +135 -0
  76. package/dist/chat.js +265 -0
  77. package/dist/client.js +439 -0
  78. package/dist/config.js +62 -0
  79. package/dist/direct/link.js +102 -0
  80. package/dist/direct/session.js +267 -0
  81. package/dist/direct/transport.js +424 -0
  82. package/dist/finished-store.js +357 -0
  83. package/dist/guess-salt.js +65 -0
  84. package/dist/hosted.js +24 -0
  85. package/dist/index.js +33 -0
  86. package/dist/join-color.js +140 -0
  87. package/dist/lessons-store.js +356 -0
  88. package/dist/live.js +287 -0
  89. package/dist/map-details.js +127 -0
  90. package/dist/map-stats.js +160 -0
  91. package/dist/map-store.js +242 -0
  92. package/dist/move-order.js +141 -0
  93. package/dist/my-games.js +218 -0
  94. package/dist/normalize.js +443 -0
  95. package/dist/notifications.js +143 -0
  96. package/dist/open-games.js +537 -0
  97. package/dist/outlook-log.js +165 -0
  98. package/dist/path-lock.js +22 -0
  99. package/dist/pick-list.js +193 -0
  100. package/dist/player-record-store.js +231 -0
  101. package/dist/player-states.js +31 -0
  102. package/dist/profile-store.js +727 -0
  103. package/dist/protocol/bundle.js +375 -0
  104. package/dist/protocol/codec.js +556 -0
  105. package/dist/protocol/decoded.js +12 -0
  106. package/dist/protocol/interp.js +1904 -0
  107. package/dist/protocol/methods.js +615 -0
  108. package/dist/protocol/rpc.js +202 -0
  109. package/dist/push/listener.js +393 -0
  110. package/dist/push/packets.js +66 -0
  111. package/dist/push/socketio.js +333 -0
  112. package/dist/push/websocket.js +179 -0
  113. package/dist/redact.js +62 -0
  114. package/dist/relations-store.js +242 -0
  115. package/dist/replay.js +227 -0
  116. package/dist/scalars.js +28 -0
  117. package/dist/scout.js +346 -0
  118. package/dist/stats.js +291 -0
  119. package/dist/strategy/card-clock.js +185 -0
  120. package/dist/strategy/map-notes.js +128 -0
  121. package/dist/strategy/notes.js +2223 -0
  122. package/dist/surrender-pending.js +126 -0
  123. package/dist/team-cards.js +84 -0
  124. package/dist/team-orders.js +150 -0
  125. package/dist/teams.js +19 -0
  126. package/dist/tools/accept-surrender.js +311 -0
  127. package/dist/tools/award.js +206 -0
  128. package/dist/tools/begin-turn.js +162 -0
  129. package/dist/tools/board.js +77 -0
  130. package/dist/tools/card-advice.js +256 -0
  131. package/dist/tools/card-effects.js +49 -0
  132. package/dist/tools/card-plays.js +434 -0
  133. package/dist/tools/card-support-advice.js +140 -0
  134. package/dist/tools/chat-inbox.js +158 -0
  135. package/dist/tools/chat-read-mark.js +179 -0
  136. package/dist/tools/chat.js +525 -0
  137. package/dist/tools/check-plan.js +689 -0
  138. package/dist/tools/commander-check.js +103 -0
  139. package/dist/tools/commitments.js +216 -0
  140. package/dist/tools/common.js +143 -0
  141. package/dist/tools/diplomacy.js +342 -0
  142. package/dist/tools/end-of-game.js +384 -0
  143. package/dist/tools/game.js +151 -0
  144. package/dist/tools/guess-view.js +56 -0
  145. package/dist/tools/healthcheck.js +90 -0
  146. package/dist/tools/hints.js +34 -0
  147. package/dist/tools/how-lost.js +154 -0
  148. package/dist/tools/index.js +152 -0
  149. package/dist/tools/join-game.js +327 -0
  150. package/dist/tools/leave-game.js +181 -0
  151. package/dist/tools/live-context.js +339 -0
  152. package/dist/tools/live.js +404 -0
  153. package/dist/tools/map-details.js +88 -0
  154. package/dist/tools/map-stats.js +130 -0
  155. package/dist/tools/map.js +141 -0
  156. package/dist/tools/my-games.js +193 -0
  157. package/dist/tools/notifications.js +484 -0
  158. package/dist/tools/open-games.js +104 -0
  159. package/dist/tools/opponents.js +163 -0
  160. package/dist/tools/order-options.js +135 -0
  161. package/dist/tools/past-games.js +94 -0
  162. package/dist/tools/picks.js +305 -0
  163. package/dist/tools/profile-hook.js +156 -0
  164. package/dist/tools/profile-opponents.js +121 -0
  165. package/dist/tools/profile-reads.js +99 -0
  166. package/dist/tools/push.js +445 -0
  167. package/dist/tools/relations.js +611 -0
  168. package/dist/tools/resolve.js +45 -0
  169. package/dist/tools/route.js +36 -0
  170. package/dist/tools/scout.js +87 -0
  171. package/dist/tools/session.js +163 -0
  172. package/dist/tools/strategy.js +257 -0
  173. package/dist/tools/stress-opponents.js +83 -0
  174. package/dist/tools/surrender-pending.js +74 -0
  175. package/dist/tools/surrender.js +247 -0
  176. package/dist/tools/survival.js +189 -0
  177. package/dist/tools/team-brief.js +266 -0
  178. package/dist/tools/team-source.js +222 -0
  179. package/dist/tools/team.js +178 -0
  180. package/dist/tools/turn.js +2825 -0
  181. package/dist/tools/uncommit.js +160 -0
  182. package/dist/tools/where.js +300 -0
  183. package/dist/tools/write-kit.js +164 -0
  184. package/dist/transport-bridge.js +33 -0
  185. package/dist/trend.js +577 -0
  186. package/dist/version.js +4 -0
  187. package/manifest.json +194 -4
  188. package/mint.yaml +106 -14
  189. package/package.json +11 -6
  190. package/server.json +40 -3
  191. package/skills/warapp-api/SKILL.md +95 -4
  192. package/skills/warapp-api/references/scout.mjs +348 -0
  193. package/skills/warapp-api/scripts/warapp.sh +69 -8
  194. package/skills/warapp-mcp/SKILL.md +1096 -21
@@ -0,0 +1,144 @@
1
+ // The cross-game record of how a player kept agreements (docs/PLAN-TEAMS.md A2, owner decision D5 of
2
+ // 2026-11-14: ON, local and hosted — a hosted child keeps it in its per-user data dir — keyed by a
3
+ // salted hash of the player's GameFeed id; see src/player-record-store.ts). Pure.
4
+ //
5
+ // Per player it keeps two things:
6
+ // - one entry per agreement, name-free (no player id, no game id, no name, no message: the entry's
7
+ // key is itself a salted hash): the game's format, the turns agreed and ended, the shape of the
8
+ // terms, the outcome (kept, ended with notice and whether it was honoured, broken by them or by
9
+ // me), the break turn and the strongest breach flag my boards showed, the context at the break
10
+ // (endgame, who led, outgrowing), whether they retaliated and whether they proposed again;
11
+ // - tallies (`RecordCounts`), each moved once by the recorded transition that earns it
12
+ // (`recordDelta`), so recording the same agreement again never counts it twice, and an entry
13
+ // dropped past the bound still counts.
14
+ // Words never enter it: only what the player recorded with `warapp_record_agreement` and what the
15
+ // boards showed.
16
+ import { endCondition, TERMINAL_STATUSES } from './relations.js';
17
+ /** Entries kept per player (the least recently updated dropped first). */
18
+ export const MAX_RECORD_ENTRIES = 30;
19
+ /** Players kept (the least recently updated dropped first). */
20
+ export const MAX_RECORD_PLAYERS = 300;
21
+ /** What the agreement's outcome is so far, from its status history. */
22
+ export function outcomeOf(a) {
23
+ const statuses = a.history.map((h) => h.status);
24
+ // Notice counts only when it was still standing at the end (withdrawn notice goes back to `agreed`).
25
+ const standing = a.status === 'ended' || a.status === 'broken-by-me' || a.status === 'broken-by-them' ? statuses.at(-2) : a.status;
26
+ const noticeBy = standing === 'notice-by-me' ? 'me' : standing === 'notice-by-them' ? 'them' : undefined;
27
+ if (!TERMINAL_STATUSES.has(a.status))
28
+ return { outcome: 'open', ...(noticeBy ? { noticeBy } : {}) };
29
+ if (a.status === 'ended') {
30
+ if (noticeBy)
31
+ return { outcome: 'ended-with-notice', noticeBy, noticeHonoured: true };
32
+ return { outcome: a.agreedTurn === undefined ? 'not-agreed' : 'kept' };
33
+ }
34
+ const outcome = a.status === 'broken-by-me' ? 'broken-by-me' : 'broken-by-them';
35
+ if (!noticeBy)
36
+ return { outcome };
37
+ // Broken during notice: the breaker's notice was not honoured when it was theirs to keep.
38
+ const breaker = a.status === 'broken-by-me' ? 'me' : 'them';
39
+ return { outcome, noticeBy, noticeHonoured: noticeBy !== breaker };
40
+ }
41
+ /** The entry for `a` (name-free), merged over `previous` when it exists. */
42
+ export function recordEntryFor(a, input, previous) {
43
+ const first = a.history[0]?.status;
44
+ const scope = a.terms.scope;
45
+ const entry = {
46
+ key: input.key,
47
+ format: previous?.format ?? input.format,
48
+ proposedBy: first === 'proposed-by-me' ? 'me' : first === 'proposed-by-them' ? 'them' : null,
49
+ agreedTurn: a.agreedTurn ?? null,
50
+ endedTurn: a.endedTurn ?? null,
51
+ terms: {
52
+ scope: scope === 'all' ? 'all' : 'territories' in scope ? 'territories' : 'bonuses',
53
+ scopeSize: scope === 'all' ? null : 'territories' in scope ? scope.territories.length : scope.bonuses.length,
54
+ noticeTurns: a.terms.noticeTurns,
55
+ cap: a.terms.borderCap ?? null,
56
+ endCondition: endCondition(a.terms),
57
+ against: a.terms.against !== undefined,
58
+ },
59
+ ...outcomeOf(a),
60
+ ...(previous?.proposedAgain ? { proposedAgain: true } : {}),
61
+ ...(a.retaliated !== undefined ? { retaliated: a.retaliated } : {}),
62
+ updated: input.now,
63
+ };
64
+ if (a.status === 'broken-by-them' || a.status === 'broken-by-me') {
65
+ entry.breakTurn = a.endedTurn ?? previous?.breakTurn ?? 0;
66
+ entry.breachFlag = input.breachFlag !== undefined ? input.breachFlag : (previous?.breachFlag ?? null);
67
+ const context = input.context ?? previous?.context;
68
+ if (context)
69
+ entry.context = context;
70
+ }
71
+ return entry;
72
+ }
73
+ const byUpdated = (a, b) => a.updated - b.updated || (a.key < b.key ? -1 : 1);
74
+ /** `entries` with `entry` in place of the one with its key, capped at {@link MAX_RECORD_ENTRIES}. */
75
+ export function upsertEntry(entries, entry) {
76
+ const rest = entries.filter((e) => e.key !== entry.key);
77
+ return [...rest, entry].sort(byUpdated).slice(-MAX_RECORD_ENTRIES);
78
+ }
79
+ export const ZERO_COUNTS = Object.freeze({ made: 0, kept: 0, endedWithNotice: 0, brokenByThem: 0, brokenByMe: 0 });
80
+ export const COUNT_KEYS = Object.keys(ZERO_COUNTS);
81
+ const OUTCOME_COUNT = {
82
+ kept: 'kept',
83
+ 'ended-with-notice': 'endedWithNotice',
84
+ 'broken-by-them': 'brokenByThem',
85
+ 'broken-by-me': 'brokenByMe',
86
+ };
87
+ /**
88
+ * What one recorded change adds to the partner's tallies: `made` the first time it is agreed, and its
89
+ * outcome when it becomes over. `before` is the agreement as it stood (`undefined` for a new one).
90
+ */
91
+ export function recordDelta(before, after) {
92
+ const delta = { ...ZERO_COUNTS };
93
+ if (before?.agreedTurn === undefined && after.agreedTurn !== undefined)
94
+ delta.made = 1;
95
+ const wasOver = before !== undefined && TERMINAL_STATUSES.has(before.status);
96
+ if (!wasOver && TERMINAL_STATUSES.has(after.status)) {
97
+ const key = OUTCOME_COUNT[outcomeOf(after).outcome];
98
+ if (key)
99
+ delta[key] = 1;
100
+ }
101
+ return delta;
102
+ }
103
+ export const isZero = (c) => COUNT_KEYS.every((k) => c[k] === 0);
104
+ export function addCounts(a, b) {
105
+ const out = { ...ZERO_COUNTS };
106
+ for (const k of COUNT_KEYS)
107
+ out[k] = a[k] + b[k];
108
+ return out;
109
+ }
110
+ /** Tallies rebuilt from entries alone (a file written before tallies were kept). */
111
+ export function talliesOf(entries) {
112
+ const out = { ...ZERO_COUNTS };
113
+ for (const e of entries) {
114
+ if (e.agreedTurn !== null)
115
+ out.made++;
116
+ const key = OUTCOME_COUNT[e.outcome];
117
+ if (key)
118
+ out[key]++;
119
+ }
120
+ return out;
121
+ }
122
+ export function playerRecord(tallies, entries = []) {
123
+ const sorted = [...entries].sort(byUpdated);
124
+ const count = (f) => sorted.filter(f).length;
125
+ const over = tallies.kept + tallies.endedWithNotice + tallies.brokenByThem;
126
+ const theirBreak = (e) => e.outcome === 'broken-by-them';
127
+ return {
128
+ ...tallies,
129
+ keptRate: over ? Math.round(((tallies.kept + tallies.endedWithNotice) / over) * 100) / 100 : null,
130
+ entries: sorted.length,
131
+ proposals: { byMe: count((e) => e.proposedBy === 'me'), byThem: count((e) => e.proposedBy === 'them') },
132
+ open: count((e) => e.outcome === 'open'),
133
+ theirNotice: {
134
+ honoured: count((e) => e.noticeBy === 'them' && e.noticeHonoured === true),
135
+ broken: count((e) => e.noticeBy === 'them' && e.noticeHonoured === false),
136
+ },
137
+ brokenByThemInEndgame: count((e) => theirBreak(e) && e.context?.endgame === true),
138
+ brokenByThemLeading: count((e) => theirBreak(e) && e.context?.leader === 'partner'),
139
+ retaliated: count((e) => e.retaliated === true),
140
+ proposedAgain: count((e) => e.proposedAgain === true),
141
+ turnsToBreak: sorted.filter((e) => theirBreak(e) && e.agreedTurn !== null && e.breakTurn !== undefined).map((e) => e.breakTurn - e.agreedTurn),
142
+ last: sorted.at(-1)?.outcome ?? null,
143
+ };
144
+ }
@@ -0,0 +1,268 @@
1
+ // One player's view of a board: income, bonuses closest to completion, and
2
+ // visible threats. Pure: consumes a source-agnostic BoardState only.
3
+ import { bonusTerritories } from './bonuses.js';
4
+ import { armiesToTake, DEFAULT_DEFENSIVE_KILL_RATE, DEFAULT_OFFENSIVE_KILL_RATE } from './combat.js';
5
+ import { neighborsOf } from './graph.js';
6
+ import { OVERRIDES_UNPARSED, overrideUncertainties } from './overrides.js';
7
+ /** Warzone's default base income when the settings do not say. */
8
+ export const DEFAULT_BASE_INCOME = 5;
9
+ /**
10
+ * Income before bonuses: the base, or floor(territories / per) when that is
11
+ * larger ("Extra Armies for Territories", BonusArmyPer). Read from war.app's
12
+ * client income code, which adds floor(territories / BonusArmyPer) and then tops
13
+ * it up to MinimumArmyBonus when smaller ("Bonus armies for N territories (if
14
+ * more than base armies)"); live (#38): base 4, per 1, 1 territory paid 4, and
15
+ * base 20, per 1, 164 territories paid 164; base 2, per 1, 3 territories
16
+ * refused 5 and accepted 3. `per` 0 (or less) is off.
17
+ */
18
+ export function territoryIncome(territories, base, per) {
19
+ return per > 0 ? Math.max(base, Math.floor(territories / per)) : base;
20
+ }
21
+ const inIdOrder = new WeakMap();
22
+ /**
23
+ * A graph's bonuses in id order, each with its territories, remembered per graph: the pick
24
+ * advisor asks for the income thousands of times in one plan, and sorting a large map's bonuses
25
+ * and looking each one's territories up every time was a quarter of it. Built again when the
26
+ * map's bonus list is replaced or changes length.
27
+ */
28
+ function bonusesInIdOrder(g) {
29
+ const from = g.map.bonuses;
30
+ const hit = inIdOrder.get(g);
31
+ if (hit && hit.from === from && hit.count === from.length)
32
+ return hit.sorted;
33
+ const sorted = [...from]
34
+ .sort((x, y) => x.id - y.id)
35
+ .map((bonus) => ({ bonus, territories: bonusTerritories(g, bonus.id) }));
36
+ inIdOrder.set(g, { from, count: from.length, sorted });
37
+ return sorted;
38
+ }
39
+ /**
40
+ * THE income rule (#85): every income figure — warapp_plan_turn's income, warapp_submit_turn's
41
+ * deploy check, warapp_analyze_board, the planner's next income and per-opponent estimate, the
42
+ * picks budget — comes from here, so they cannot disagree. War.app's client income code
43
+ * (docs/WARAPP-API.md, verified from the bundle): max(base, floor(territories / per)), plus the
44
+ * value of EVERY bonus all of whose territories are held — each counted once, whatever it
45
+ * overlaps; a superbonus is one more bonus over all its member territories (flattened, a member
46
+ * id read as a territory first); 0-value bonuses add nothing; negative ones subtract — and never
47
+ * below 0 (the client zeroes the income when the negatives reach it). Card armies come on top
48
+ * (not modelled here: a play is a choice, see `incomeFor` callers). Bonus values are the map's
49
+ * as given: the tools' `mapOf` has already applied the game's `OverriddenBonuses`.
50
+ */
51
+ export function boardIncome(g, held, rules) {
52
+ let territories = 0;
53
+ for (const t of held)
54
+ if (g.territoryById.has(t))
55
+ territories++;
56
+ const perTerritory = rules.per > 0 ? Math.floor(territories / rules.per) : 0;
57
+ const bonuses = [];
58
+ for (const { bonus: b, territories: ts } of bonusesInIdOrder(g)) {
59
+ // The first territory settles most bonuses without walking the rest.
60
+ if (ts.length && held.has(ts[0]) && ts.every((t) => held.has(t)))
61
+ bonuses.push({ bonusId: b.id, name: b.name, value: b.value });
62
+ }
63
+ const total = Math.max(0, territoryIncome(territories, rules.base, rules.per) + bonuses.reduce((s, b) => s + b.value, 0));
64
+ return { base: rules.base, perTerritory, bonuses, total };
65
+ }
66
+ /** To the nearest integer, a half rounded down (the client's round for the cap; x ≥ 0 here). */
67
+ function roundHalfDown(x) {
68
+ return Math.ceil(x - 0.5);
69
+ }
70
+ /** {@link ArmyCapIncome} for an income, a game's cap and my armies on the board; `undefined` with no cap. */
71
+ export function armyCapIncome(income, cap, armies) {
72
+ if (cap === null || cap === undefined || !(cap > 0))
73
+ return undefined;
74
+ const limit = roundHalfDown(cap * income);
75
+ const received = Math.min(income, Math.max(0, limit - armies));
76
+ return { uncapped: income, cap, armies, limit, received, cut: received < income };
77
+ }
78
+ /**
79
+ * The army cap's arithmetic in one clause, e.g. "8 × 52 = 416, less your 375 armies on the board, is 41";
80
+ * over the cap, floored like the income: "…, is 0 (over the cap by 4)".
81
+ */
82
+ export function armyCapText(c) {
83
+ const room = c.limit - c.armies;
84
+ return `${c.cap} × ${c.uncapped} = ${c.limit}, less your ${c.armies} armies on the board, is ${Math.max(0, room)}${room < 0 ? ` (over the cap by ${-room})` : ''}`;
85
+ }
86
+ /**
87
+ * J1 review: under Local Deployment, why the bonus pools are a guess when the army cap cuts my income.
88
+ * The cut total is modelled, but how war.app takes it out of the pools is not known: the pool model
89
+ * (`deployPools`, local-deploy.ts) trims the outermost pools first, an assumption. So the pool check only warns
90
+ * and the plan says so, as for Sanctions under Local Deployment. `undefined` without a cut.
91
+ */
92
+ export function armyCapPoolsUncertainty(c, localDeployments) {
93
+ if (!localDeployments || !c?.cut)
94
+ return undefined;
95
+ return (`Local Deployment: the army cap cuts your income from ${c.uncapped} to ${c.received}, and which bonus pools the ` +
96
+ `${c.uncapped - c.received} come out of is not known (the model takes them from the outermost pools first, a guess): ` +
97
+ "deploy as the game's deploy panel shows.");
98
+ }
99
+ /** What the army cap's figure rests on: six live cases, and the card armies' place (from the client's guide, unverified). */
100
+ export const ARMY_CAP_BASIS = "the formula is verified by six live cases (2026-11-15: received 41, 49, 25, 27 and 71 where the cap bit, among them the binding case sent through warapp_submit_turn, and a room of 61 it did not bind), the cap taken on this turn's income; Reinforcement card armies are outside it (the client's guide: they are not income and always pay in full, unverified live)";
101
+ /** {@link IncomeRules} from a game's settings (the defaults when it does not say). */
102
+ export function incomeRules(settings) {
103
+ return { base: settings?.minimumArmyBonus ?? DEFAULT_BASE_INCOME, per: settings?.bonusArmyPer ?? 0 };
104
+ }
105
+ /**
106
+ * Settings that make the income model uncertain, each as a reason: war.app's
107
+ * income has a term the model does not compute. Empty when every income rule
108
+ * the game uses is modelled (base, BonusArmyPer, held bonuses, card armies,
109
+ * overridden bonus values once read — only unreadable overrides are listed).
110
+ * Cities and per-player income mods have no known settings key, so they are
111
+ * not detected: those games still get the hard deploy-total check. Sanctions is
112
+ * flagged when the card is merely enabled: the live board's active-card decoder is
113
+ * unverified (#163), so the model cannot be sure whether I am sanctioned this turn
114
+ * (docs/WARAPP-API.md, the trade-off). With `sanctionsApplied` (PLAN-TEAMS D3: the
115
+ * income already carries the Sanctions read on me) the reason says so instead. An army cap is
116
+ * modelled ({@link armyCapIncome}, #253) and verified by six live cases, yet stays listed (where the
117
+ * card armies and Local Deployment's pools fall is not verified): with
118
+ * `armyCap` (the figure the caller applied) the reason states its arithmetic.
119
+ */
120
+ export function incomeUncertainties(settings, opts = {}) {
121
+ const out = [];
122
+ if (settings?.minimumArmyBonus === undefined)
123
+ out.push(`The game's base income is missing from its settings; the model assumes ${DEFAULT_BASE_INCOME}.`);
124
+ if (settings?.armyCap !== undefined && settings.armyCap !== null) {
125
+ const c = opts.armyCap;
126
+ out.push(c
127
+ ? `This game has an army cap (${c.cap}× income): ${armyCapText(c)}: ${c.cut ? `income ${c.received}, not ${c.uncapped}` : `no cut, income ${c.received}`}; ${ARMY_CAP_BASIS}.`
128
+ : `This game has an army cap (${settings.armyCap}× income): the income received is min(income, ${settings.armyCap} × income − your armies on the board) at the start of the turn; ${ARMY_CAP_BASIS}.`);
129
+ }
130
+ // Overrides that were read are applied to the map (applyBonusOverrides), so only unreadable ones make income uncertain.
131
+ if (settings?.overriddenBonusesUnparsed)
132
+ out.push(OVERRIDES_UNPARSED);
133
+ if (settings?.cards.includes('Sanctions')) {
134
+ const pct = settings.raw?.SanctionsCard;
135
+ const p = isRecord(pct) && typeof pct.Percentage === 'number' ? ` by ${Math.round(pct.Percentage * 100)}%` : '';
136
+ out.push(opts.sanctionsApplied
137
+ ? `the Sanctions on you${p} are applied as read from the board by an unverified decoder (#163).`
138
+ : `This game has the Sanctions card, which cuts a sanctioned player's income${p}; the model does not apply it.`);
139
+ }
140
+ return out;
141
+ }
142
+ /**
143
+ * Why warapp_submit_turn's deploy-total check must warn rather than refuse: the income
144
+ * uncertainties plus, while the overrides' shape is unverified, a game's overrides.
145
+ */
146
+ export function deployCheckUncertainties(settings, opts = {}) {
147
+ return [...new Set([...incomeUncertainties(settings, opts), ...overrideUncertainties(settings)])];
148
+ }
149
+ function isRecord(v) {
150
+ return typeof v === 'object' && v !== null && !Array.isArray(v);
151
+ }
152
+ const UNKNOWN = { kind: 'unknown' };
153
+ export function analyzePlayer(g, board, playerId, settings, opts = {}) {
154
+ const limit = opts.limit ?? 10;
155
+ const byId = new Map(board.territories.map((t) => [t.territoryId, t]));
156
+ const isMine = (id) => {
157
+ const o = byId.get(id)?.owner;
158
+ return o?.kind === 'player' && o.playerId === playerId;
159
+ };
160
+ const mineIds = board.territories
161
+ .filter((t) => g.territoryById.has(t.territoryId) && isMine(t.territoryId))
162
+ .map((t) => t.territoryId)
163
+ .sort((a, b) => a - b);
164
+ const mineSet = new Set(mineIds);
165
+ const armies = mineIds.reduce((s, id) => s + (byId.get(id).armies ?? 0), 0);
166
+ const rates = {
167
+ offensiveKillRate: settings?.offensiveKillRate ?? DEFAULT_OFFENSIVE_KILL_RATE,
168
+ defensiveKillRate: settings?.defensiveKillRate ?? DEFAULT_DEFENSIVE_KILL_RATE,
169
+ };
170
+ // ---- income ----
171
+ const income = boardIncome(g, mineSet, incomeRules(settings));
172
+ const progress = [];
173
+ for (const b of [...g.map.bonuses].sort((x, y) => x.id - y.id)) {
174
+ const ts = bonusTerritories(g, b.id);
175
+ if (!ts.length)
176
+ continue;
177
+ const owned = ts.filter((t) => mineSet.has(t)).length;
178
+ if (owned === ts.length)
179
+ continue;
180
+ if (b.value <= 0)
181
+ continue;
182
+ const missingIds = ts.filter((t) => !mineSet.has(t));
183
+ const reachable = owned > 0 || missingIds.some((t) => neighborsOf(g, t).some((n) => mineSet.has(n)));
184
+ if (!reachable)
185
+ continue;
186
+ const counts = { neutral: 0, enemy: 0, unknown: 0 };
187
+ let needed = 0;
188
+ let complete = true;
189
+ const missing = missingIds.map((t) => {
190
+ const st = byId.get(t);
191
+ const owner = st?.owner ?? UNKNOWN;
192
+ const visible = st?.armies ?? null;
193
+ if (owner.kind === 'player')
194
+ counts.enemy++;
195
+ else if (owner.kind === 'unknown')
196
+ counts.unknown++;
197
+ else
198
+ counts.neutral++;
199
+ const known = owner.kind === 'unknown' ? null : visible;
200
+ const take = known === null ? null : armiesToTake(known, rates);
201
+ if (take === null)
202
+ complete = false;
203
+ else
204
+ needed += take;
205
+ return { territoryId: t, name: g.territoryById.get(t).name, owner, armies: known, armiesToTake: take };
206
+ });
207
+ progress.push({
208
+ bonusId: b.id,
209
+ name: b.name,
210
+ value: b.value,
211
+ territoryCount: ts.length,
212
+ ownedCount: owned,
213
+ missing,
214
+ missingCounts: counts,
215
+ armiesNeeded: needed,
216
+ armiesNeededComplete: complete,
217
+ });
218
+ }
219
+ progress.sort((a, b) => a.missing.length - b.missing.length ||
220
+ Number(b.armiesNeededComplete) - Number(a.armiesNeededComplete) ||
221
+ a.armiesNeeded - b.armiesNeeded ||
222
+ b.value - a.value ||
223
+ a.bonusId - b.bonusId);
224
+ // ---- threats ----
225
+ const threats = [];
226
+ for (const t of board.territories) {
227
+ if (t.owner.kind !== 'player' || t.owner.playerId === playerId || t.armies === null)
228
+ continue;
229
+ if (!g.territoryById.has(t.territoryId))
230
+ continue;
231
+ const adjacentTo = neighborsOf(g, t.territoryId).filter((n) => mineSet.has(n));
232
+ if (!adjacentTo.length)
233
+ continue;
234
+ threats.push({
235
+ territoryId: t.territoryId,
236
+ name: g.territoryById.get(t.territoryId).name,
237
+ playerId: t.owner.playerId,
238
+ armies: t.armies,
239
+ adjacentTo,
240
+ });
241
+ }
242
+ threats.sort((a, b) => b.armies - a.armies || a.territoryId - b.territoryId);
243
+ // ---- assumptions ----
244
+ const assumptions = [];
245
+ if (!board.verified)
246
+ assumptions.push('Board state comes from an unverified parser of the GameFeed standing; check it against the game.');
247
+ if (settings?.offensiveKillRate === undefined || settings?.defensiveKillRate === undefined)
248
+ assumptions.push(`Kill rates missing from settings; using the defaults (${DEFAULT_OFFENSIVE_KILL_RATE}% offense, ${DEFAULT_DEFENSIVE_KILL_RATE}% defense).`);
249
+ if (settings?.minimumArmyBonus === undefined)
250
+ assumptions.push(`Base income missing from settings; using the default of ${DEFAULT_BASE_INCOME}.`);
251
+ if (settings?.roundingMode !== undefined && settings.roundingMode !== 'StraightRound')
252
+ assumptions.push(`Armies needed assume straight rounding; this game uses ${settings.roundingMode}.`);
253
+ if (settings?.overriddenBonusesUnparsed)
254
+ assumptions.push(OVERRIDES_UNPARSED);
255
+ if ((settings?.luckModifier ?? 0) > 0)
256
+ assumptions.push('Armies needed assume 0% luck; this game has luck, so outcomes can vary.');
257
+ return {
258
+ playerId,
259
+ boardVerified: board.verified,
260
+ territoryCount: mineIds.length,
261
+ armies,
262
+ heldBonusIds: income.bonuses.map((b) => b.bonusId),
263
+ income,
264
+ closestBonuses: progress.slice(0, limit),
265
+ threats,
266
+ assumptions,
267
+ };
268
+ }