@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,127 @@
1
+ // A map's distribution modes and the territories each lets a player start on (#328): the GetMapDetails
2
+ // reply (method 73, no auth, the int32 map id), decoded by the client bundle's own readers by stable type
3
+ // name, like GetMyGames — fields by read order, checked by type, never by their minified names
4
+ // (docs/WEB-PROTOCOL.md, "Map details: distribution modes"). GameFeed's map names its modes but not their
5
+ // territories; the client's map preview reads them from here.
6
+ //
7
+ // `MapDetails` reads its modes fourth, an int32-count dict of mode id → `DistributionMode`, which the
8
+ // bundle reads by a byte tag: a `NormalDistribution` (its territory ids, then the description, the id and
9
+ // the name) or a `ScenarioDistribution` (its slot names, its territory → slot dict, then the same three).
10
+ // UNVERIFIED live beyond what #328's trace shows (a normal mode's bytes, and its ids against GameFeed's map).
11
+ import { McpToolError } from '@chrischall/mcp-utils';
12
+ import { fields, isObj } from './protocol/decoded.js';
13
+ export const MAP_DETAILS = 'warlight.shared.MapDetails';
14
+ export const NORMAL_DISTRIBUTION = 'warlight.shared.NormalDistribution';
15
+ export const SCENARIO_DISTRIBUTION = 'warlight.shared.ScenarioDistribution';
16
+ /** MapDetails: the position of its mode dict in read order, and its whole field count. */
17
+ const MD = { modes: 3 };
18
+ export const MAP_DETAILS_FIELDS = 14;
19
+ /** NormalDistribution: its territory list, then the base fields (description, id, name). */
20
+ const ND = { territories: 0, id: 2 };
21
+ export const NORMAL_DISTRIBUTION_FIELDS = 4;
22
+ /** ScenarioDistribution: its slot names, its territory → slot dict, then the base fields. */
23
+ const SD = { territories: 1, id: 3 };
24
+ export const SCENARIO_DISTRIBUTION_FIELDS = 5;
25
+ /** The GetMapDetails reply arrived in a shape this server does not understand. */
26
+ export class MapDetailsFormatError extends McpToolError {
27
+ constructor(detail) {
28
+ super(`war.app's map details arrived in an unexpected shape (${detail}).`, {
29
+ kind: 'unknown',
30
+ hint: "The war.app client may have changed; the distribution modes' territories stay unknown.",
31
+ });
32
+ this.name = 'MapDetailsFormatError';
33
+ }
34
+ }
35
+ const isInt = (v) => typeof v === 'number' && Number.isInteger(v);
36
+ const isIntList = (v) => Array.isArray(v) && v.every(isInt);
37
+ /** A decoded dict: `[key, value]` pairs. */
38
+ const isPairs = (v) => Array.isArray(v) && v.every((e) => Array.isArray(e) && e.length === 2);
39
+ /** One mode's territory ids (`null`: the reply lists none), checked against the dict's key. */
40
+ function territoriesOf(key, mode) {
41
+ if (mode === null)
42
+ return null;
43
+ if (!isObj(mode))
44
+ throw new MapDetailsFormatError(`mode ${key} is not a record`);
45
+ const f = fields(mode);
46
+ let id;
47
+ let ids;
48
+ if (mode.$type === NORMAL_DISTRIBUTION) {
49
+ if (f.length !== NORMAL_DISTRIBUTION_FIELDS)
50
+ throw new MapDetailsFormatError(`a NormalDistribution has ${f.length} fields`);
51
+ const list = f[ND.territories];
52
+ if (list !== null && !isIntList(list))
53
+ throw new MapDetailsFormatError(`mode ${key}'s territories are not ids`);
54
+ id = f[ND.id];
55
+ ids = list;
56
+ }
57
+ else if (mode.$type === SCENARIO_DISTRIBUTION) {
58
+ if (f.length !== SCENARIO_DISTRIBUTION_FIELDS)
59
+ throw new MapDetailsFormatError(`a ScenarioDistribution has ${f.length} fields`);
60
+ const dict = f[SD.territories];
61
+ if (dict !== null && !(isPairs(dict) && dict.every(([t, s]) => isInt(t) && isInt(s)))) {
62
+ throw new MapDetailsFormatError(`mode ${key}'s territories are not ids`);
63
+ }
64
+ id = f[SD.id];
65
+ ids = dict === null ? null : dict.map(([t]) => t);
66
+ }
67
+ else {
68
+ throw new MapDetailsFormatError(`mode ${key} is neither a normal nor a scenario distribution`);
69
+ }
70
+ if (id !== key)
71
+ throw new MapDetailsFormatError(`mode ${key} names itself ${String(id)}`);
72
+ return ids;
73
+ }
74
+ /**
75
+ * Read a GetMapDetails result (the body positioned at the result-present flag): mode id → its territory
76
+ * ids, `null` for a mode the reply lists none for. `null` when there is no result.
77
+ */
78
+ export function readMapDetailsModes(bundle, body) {
79
+ if (!body.bool())
80
+ return null;
81
+ const details = bundle.readClass(MAP_DETAILS, body);
82
+ if (!isObj(details) || details.$type !== MAP_DETAILS)
83
+ throw new MapDetailsFormatError('no MapDetails');
84
+ const f = fields(details);
85
+ if (f.length !== MAP_DETAILS_FIELDS)
86
+ throw new MapDetailsFormatError(`a MapDetails has ${f.length} fields, not ${MAP_DETAILS_FIELDS}`);
87
+ const modes = f[MD.modes];
88
+ const out = new Map();
89
+ if (modes === null)
90
+ return out;
91
+ if (!isPairs(modes))
92
+ throw new MapDetailsFormatError('no mode list');
93
+ for (const [key, mode] of modes) {
94
+ if (!isInt(key))
95
+ throw new MapDetailsFormatError('a mode id is not an integer');
96
+ out.set(key, territoriesOf(key, mode));
97
+ }
98
+ return out;
99
+ }
100
+ /**
101
+ * Lay the territories read (`byMode`) on `map`'s modes, a copy: each mode's ids that are territories of the
102
+ * map, in order, once each (an id the map lacks is dropped, with a warning); a mode the reply leaves out, or
103
+ * lists none for (or whose every id is dropped), is `null` — unknown, never empty. A mode the reply has but the map does not is ignored.
104
+ */
105
+ export function applyModeTerritories(map, byMode) {
106
+ const land = new Set(map.territories.map((t) => t.id));
107
+ const found = new Map();
108
+ const warnings = [];
109
+ const distributionModes = map.distributionModes.map((d) => {
110
+ const ids = byMode.get(d.id);
111
+ if (!ids)
112
+ return { ...d, territories: null };
113
+ const kept = [...new Set(ids.filter((id) => land.has(id)))];
114
+ const dropped = [...new Set(ids.filter((id) => !land.has(id)))];
115
+ if (dropped.length) {
116
+ const one = dropped.length === 1;
117
+ warnings.push(`Distribution mode ${d.id}: ${dropped.length} territory id${one ? '' : 's'} war.app listed ${one ? 'is' : 'are'} not ` +
118
+ `${one ? 'a territory' : 'territories'} of map ${map.id} and ${one ? 'was' : 'were'} dropped (${dropped.join(', ')}).`);
119
+ }
120
+ // Every id dropped (or none listed) says nothing about the mode: unknown, never known-empty.
121
+ if (!kept.length)
122
+ return { ...d, territories: null };
123
+ found.set(d.id, kept);
124
+ return { ...d, territories: kept };
125
+ });
126
+ return { map: { ...map, distributionModes }, found, warnings };
127
+ }
@@ -0,0 +1,160 @@
1
+ import { historyBoards, historyReport } from './trend.js';
2
+ /** Below this many games a rate is reported only with a warning. */
3
+ export const MIN_SAMPLE = 5;
4
+ /**
5
+ * Below this many players a bonus win rate is flagged as a small sample: at 5 players
6
+ * 4 wins (80%) is as consistent with a coin flip as with a strong start (#132).
7
+ */
8
+ export const MIN_RATE_SAMPLE = 10;
9
+ /**
10
+ * History layouts whose records are no longer trusted (#302): a record read under one is not
11
+ * readable, so it is never cached and a cached one is deleted and fetched again. Empty until the
12
+ * live check of GameFeed's finished-game history says which numbering is wrong.
13
+ */
14
+ export const RETIRED_LAYOUTS = new Set();
15
+ const byId = (a, b) => a - b;
16
+ const ownedBy = (board, playerId) => new Set(board.territories
17
+ .filter((t) => t.owner.kind === 'player' && t.owner.playerId === playerId)
18
+ .map((t) => t.territoryId));
19
+ /** Positive bonuses with territory members (superbonus members are not counted). */
20
+ const scoringBonuses = (map) => map.bonuses.filter((b) => b.value > 0 && b.territoryIds.length > 0).sort((a, b) => a.id - b.id);
21
+ /** Reduce a finished game (with `GetHistory`) to its stats record. Never throws on a bad history. */
22
+ export function recordFromGame(game, map) {
23
+ const boards = historyBoards(game.history, game.players, game.numberOfTurns !== undefined ? { numberOfTurns: game.numberOfTurns } : {});
24
+ const start = boards.find(({ board }) => board.territories.some((t) => t.owner.kind === 'player'));
25
+ const later = start ? boards.filter((b) => b.turn >= start.turn) : [];
26
+ const bonuses = scoringBonuses(map);
27
+ const players = [...game.players]
28
+ .sort((a, b) => a.id - b.id)
29
+ .map((p) => {
30
+ const starts = start ? [...ownedBy(start.board, p.id)].sort(byId) : [];
31
+ let anchorBonusId = null;
32
+ let best = 0;
33
+ const startBonusIds = [];
34
+ for (const b of bonuses) {
35
+ const n = b.territoryIds.filter((t) => starts.includes(t)).length;
36
+ if (n > 0)
37
+ startBonusIds.push(b.id);
38
+ if (n > best) {
39
+ best = n;
40
+ anchorBonusId = b.id;
41
+ }
42
+ }
43
+ let firstBonusTurn = null;
44
+ for (const { turn, board } of later) {
45
+ const owned = ownedBy(board, p.id);
46
+ if (bonuses.some((b) => b.territoryIds.every((t) => owned.has(t)))) {
47
+ firstBonusTurn = turn;
48
+ break;
49
+ }
50
+ }
51
+ return { playerId: p.id, won: p.state === 'Won', starts, anchorBonusId, startBonusIds, firstBonusTurn };
52
+ });
53
+ const report = boards.length ? historyReport(game) : undefined;
54
+ const layout = report && 'read' in report ? { layout: report.read.layout } : {};
55
+ return { gameId: game.id, mapId: map.id, turnsSeen: boards.length, ...layout, players };
56
+ }
57
+ const round2 = (n) => Math.round(n * 100) / 100;
58
+ function median(xs) {
59
+ if (xs.length === 0)
60
+ return null;
61
+ const s = [...xs].sort(byId);
62
+ const mid = Math.floor(s.length / 2);
63
+ return s.length % 2 ? s[mid] : (s[mid - 1] + s[mid]) / 2;
64
+ }
65
+ /** A record the stats can use: its history parsed, some player's starts were read, and its layout is not retired. */
66
+ export const readableRecord = (r, retired = RETIRED_LAYOUTS) => r.turnsSeen > 0 && r.players.some((p) => p.starts.length > 0) && (r.layout === undefined || !retired.has(r.layout));
67
+ function statsFor(mapId, all, top) {
68
+ const games = all.filter((r) => readableRecord(r));
69
+ const unreadable = all.length - games.length;
70
+ const picks = new Map();
71
+ const anchors = new Map();
72
+ const turns = [];
73
+ const winnerTurns = [];
74
+ let players = 0;
75
+ for (const g of games) {
76
+ for (const p of g.players) {
77
+ players++;
78
+ for (const t of new Set(p.starts)) {
79
+ const s = picks.get(t) ?? { picks: 0, winnerPicks: 0 };
80
+ s.picks++;
81
+ if (p.won)
82
+ s.winnerPicks++;
83
+ picks.set(t, s);
84
+ }
85
+ for (const id of p.startBonusIds ?? (p.anchorBonusId !== null ? [p.anchorBonusId] : [])) {
86
+ const a = anchors.get(id) ?? { players: 0, wins: 0 };
87
+ a.players++;
88
+ if (p.won)
89
+ a.wins++;
90
+ anchors.set(id, a);
91
+ }
92
+ if (p.firstBonusTurn !== null) {
93
+ turns.push(p.firstBonusTurn);
94
+ if (p.won)
95
+ winnerTurns.push(p.firstBonusTurn);
96
+ }
97
+ }
98
+ }
99
+ const n = games.length;
100
+ const lowSample = n < MIN_SAMPLE;
101
+ const byTurn = new Map();
102
+ for (const t of turns)
103
+ byTurn.set(t, (byTurn.get(t) ?? 0) + 1);
104
+ const out = {
105
+ mapId,
106
+ sampleSize: n,
107
+ unreadableGames: unreadable,
108
+ lowSample,
109
+ mostPicked: [...picks.entries()]
110
+ .sort(([ta, a], [tb, b]) => b.picks - a.picks || b.winnerPicks - a.winnerPicks || ta - tb)
111
+ .slice(0, top)
112
+ .map(([territoryId, s]) => ({ territoryId, picks: s.picks, pickRate: round2(s.picks / n), winnerPicks: s.winnerPicks })),
113
+ winRateByStartingBonus: [...anchors.entries()]
114
+ .sort(([ba, a], [bb, b]) => b.players - a.players || ba - bb)
115
+ .map(([bonusId, a]) => ({
116
+ bonusId,
117
+ players: a.players,
118
+ wins: a.wins,
119
+ winRate: round2(a.wins / a.players),
120
+ lowSample: a.players < MIN_RATE_SAMPLE,
121
+ })),
122
+ firstBonusTurn: {
123
+ players,
124
+ completed: turns.length,
125
+ neverCompleted: players - turns.length,
126
+ median: median(turns),
127
+ byTurn: [...byTurn.entries()].sort(([a], [b]) => a - b).map(([turn, c]) => ({ turn, players: c })),
128
+ winnersMedian: median(winnerTurns),
129
+ },
130
+ };
131
+ const left = unreadable > 0
132
+ ? ` ${unreadable} game${unreadable === 1 ? '' : 's'} whose history could not be read ${unreadable === 1 ? 'is' : 'are'} left out of every figure.`
133
+ : '';
134
+ if (lowSample) {
135
+ out.note =
136
+ `Only ${n} finished game${n === 1 ? '' : 's'} — fewer than ${MIN_SAMPLE}, so every rate here is ` +
137
+ `anecdotal, not a trend.${left}`;
138
+ }
139
+ else if (left)
140
+ out.note = left.trim();
141
+ return out;
142
+ }
143
+ /**
144
+ * Per-map statistics over finished-game records, ascending by map id. Duplicate
145
+ * game ids count once (the first record wins).
146
+ */
147
+ export function mapStats(games, opts = {}) {
148
+ const top = opts.top ?? 10;
149
+ const seen = new Set();
150
+ const byMap = new Map();
151
+ for (const g of [...games].sort((a, b) => a.gameId - b.gameId)) {
152
+ if (seen.has(g.gameId))
153
+ continue;
154
+ seen.add(g.gameId);
155
+ const list = byMap.get(g.mapId) ?? [];
156
+ list.push(g);
157
+ byMap.set(g.mapId, list);
158
+ }
159
+ return [...byMap.entries()].sort(([a], [b]) => a - b).map(([mapId, list]) => statsFor(mapId, list, top));
160
+ }
@@ -0,0 +1,242 @@
1
+ // The persistent map store: GameFeed maps by map id, so a known map is not downloaded again after a
2
+ // restart and the cached boards (`<dataDir>/boards/`) can be replayed offline (src/replay.ts).
3
+ //
4
+ // - `<dataDir>/maps/<mapId>.json`: `{ version: 1, storedAt, map }`, the map exactly as `MapCache` holds
5
+ // it (normalized: territories with adjacency, bonuses with their BASE values — overrides are per game
6
+ // and applied by `mapOf`). Maps are public data. At most MAX_STORED_MAPS files; the least recently
7
+ // used (file mtime, touched on every read and on every memory hit in `MapCache`) is evicted on a
8
+ // write.
9
+ // A mode may carry `territories` (#328: the ids war.app's map details list for it, src/map-details.ts),
10
+ // added by `writeStoredModeTerritories` with the map's `storedAt` unchanged; a mode without them reads
11
+ // as not read yet (never as empty), and a file written before them reads as it did (same version).
12
+ // `MapCache.store` carries them onto a fresh download of the map (src/client.ts) under the stored copy's
13
+ // `storedAt`, so ids read from war.app never gain a new 30 days; a mode whose ids are not all territories
14
+ // of the fresh map is not carried (it is read again).
15
+ // A map maker can publish an edit under the same map id and GameFeed sends no map version, so a
16
+ // stored map is trusted for MAX_MAP_AGE_MS after `storedAt` (the download time, epoch ms) and then
17
+ // reads as absent: the game is fetched with its map again and the fresh copy replaces it (sooner when
18
+ // a feed standing names land the map lacks: src/client.ts `getGame`). A file with
19
+ // no readable `storedAt` is stale. Offline replay (src/replay.ts) reads a map whatever its age.
20
+ // - `<dataDir>/maps/games.json`: `{ version: 1, games: [[gameId, mapId], …] }`, newest last, at most
21
+ // MAX_GAME_INDEX entries — which map a game is on, so a game seen before a restart is still asked
22
+ // `GetMap=false`.
23
+ //
24
+ // Files are 0600 in a 0700 folder and written atomically; every read is loose (a bad file is ignored,
25
+ // and replaced by the next write) and nothing here throws. Another process sharing the data directory
26
+ // may lose an index entry to a concurrent write, which only costs one map download.
27
+ import { randomBytes } from 'node:crypto';
28
+ import { mkdir, readdir, readFile, rename, stat, unlink, utimes, writeFile } from 'node:fs/promises';
29
+ import { join } from 'node:path';
30
+ import { withPathLock } from './path-lock.js';
31
+ /** Maps kept on disk; the least recently used goes first. */
32
+ export const MAX_STORED_MAPS = 40;
33
+ /** How long a stored map is trusted before it is downloaded again (30 days). */
34
+ export const MAX_MAP_AGE_MS = 30 * 24 * 60 * 60 * 1000;
35
+ /** Game → map entries kept in the index; the oldest goes first. */
36
+ export const MAX_GAME_INDEX = 500;
37
+ const VERSION = 1;
38
+ const MAP_FILE = /^\d+\.json$/;
39
+ const isRec = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
40
+ const isInt = (v) => typeof v === 'number' && Number.isInteger(v);
41
+ const isIntArray = (v) => Array.isArray(v) && v.every(isInt);
42
+ export const mapsDir = (dir) => join(dir, 'maps');
43
+ export const mapStorePath = (dir, mapId) => join(mapsDir(dir), `${mapId}.json`);
44
+ const indexPath = (dir) => join(mapsDir(dir), 'games.json');
45
+ /** Write `body` as JSON at `path` atomically (0600; folder 0700). */
46
+ export async function writeJsonAtomic(path, folder, body) {
47
+ await mkdir(folder, { recursive: true, mode: 0o700 });
48
+ const tmp = `${path}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`;
49
+ try {
50
+ await writeFile(tmp, JSON.stringify(body), { mode: 0o600 });
51
+ await rename(tmp, path);
52
+ }
53
+ catch (e) {
54
+ await unlink(tmp).catch(() => { });
55
+ throw e;
56
+ }
57
+ }
58
+ function territoryOf(t) {
59
+ if (!isRec(t) || !isInt(t.id) || typeof t.name !== 'string' || !isIntArray(t.connectedTo))
60
+ return undefined;
61
+ const out = { id: t.id, name: t.name, connectedTo: t.connectedTo };
62
+ if (isRec(t.coords) && typeof t.coords.x === 'number' && typeof t.coords.y === 'number')
63
+ out.coords = { x: t.coords.x, y: t.coords.y };
64
+ return out;
65
+ }
66
+ function bonusOf(b) {
67
+ if (!isRec(b) || !isInt(b.id) || typeof b.name !== 'string' || !isInt(b.value))
68
+ return undefined;
69
+ if (!isIntArray(b.territoryIds) || !isIntArray(b.bonusIds))
70
+ return undefined;
71
+ const out = { id: b.id, name: b.name, value: b.value, territoryIds: b.territoryIds, bonusIds: b.bonusIds };
72
+ if (isIntArray(b.unknownIds) && b.unknownIds.length)
73
+ out.unknownIds = b.unknownIds;
74
+ return out;
75
+ }
76
+ function modeOf(d) {
77
+ if (!isRec(d) || !isInt(d.id) || typeof d.name !== 'string')
78
+ return undefined;
79
+ const out = { id: d.id, name: d.name };
80
+ if (typeof d.type === 'string')
81
+ out.type = d.type;
82
+ // #328: only a non-empty list of ids is kept knowledge; anything else (absent, null, [], junk) reads as not read yet.
83
+ if (isIntArray(d.territories) && d.territories.length)
84
+ out.territories = d.territories;
85
+ return out;
86
+ }
87
+ /** Every element of `xs` read by `f`, or `undefined` when any is unreadable. */
88
+ function all(xs, f) {
89
+ if (!Array.isArray(xs))
90
+ return undefined;
91
+ const out = [];
92
+ for (const x of xs) {
93
+ const v = f(x);
94
+ if (v === undefined)
95
+ return undefined;
96
+ out.push(v);
97
+ }
98
+ return out;
99
+ }
100
+ /** A stored map, read strictly enough that the planner can trust it; `undefined` when anything is off or it is too old. */
101
+ function storedMapOf(raw, mapId, now, maxAgeMs) {
102
+ if (!isRec(raw) || raw.version !== VERSION || !isRec(raw.map))
103
+ return undefined;
104
+ if (maxAgeMs !== Number.POSITIVE_INFINITY) {
105
+ const at = raw.storedAt;
106
+ if (typeof at !== 'number' || !Number.isFinite(at) || now - at > maxAgeMs)
107
+ return undefined;
108
+ }
109
+ const m = raw.map;
110
+ if (m.id !== mapId || typeof m.name !== 'string')
111
+ return undefined;
112
+ const territories = all(m.territories, territoryOf);
113
+ const bonuses = all(m.bonuses, bonusOf);
114
+ const distributionModes = all(m.distributionModes, modeOf);
115
+ if (!territories || !bonuses || !distributionModes)
116
+ return undefined;
117
+ return { id: mapId, name: m.name, territories, bonuses, distributionModes };
118
+ }
119
+ /**
120
+ * The map stored for `mapId`, marking it recently used; `undefined` when absent, unusable or older
121
+ * than `maxAgeMs` ({@link MAX_MAP_AGE_MS} by default). Never throws.
122
+ */
123
+ export async function readStoredMap(dir, mapId, opts = {}) {
124
+ return (await readStoredMapEntry(dir, mapId, opts))?.map;
125
+ }
126
+ /** {@link readStoredMap} with the copy's `storedAt`. Never throws. */
127
+ export async function readStoredMapEntry(dir, mapId, opts = {}) {
128
+ const path = mapStorePath(dir, mapId);
129
+ try {
130
+ const raw = JSON.parse(await readFile(path, 'utf8'));
131
+ const map = storedMapOf(raw, mapId, opts.now ?? Date.now(), opts.maxAgeMs ?? MAX_MAP_AGE_MS);
132
+ if (!map)
133
+ return undefined;
134
+ const now = new Date();
135
+ await utimes(path, now, now).catch(() => { });
136
+ const at = isRec(raw) ? raw.storedAt : undefined;
137
+ return { map, storedAt: typeof at === 'number' && Number.isFinite(at) ? at : undefined };
138
+ }
139
+ catch {
140
+ return undefined;
141
+ }
142
+ }
143
+ /** Delete the least recently used maps beyond {@link MAX_STORED_MAPS}, keeping `keep`. Best effort. */
144
+ async function evictMaps(dir, keep) {
145
+ const folder = mapsDir(dir);
146
+ const files = [];
147
+ for (const name of await readdir(folder)) {
148
+ if (!MAP_FILE.test(name))
149
+ continue;
150
+ try {
151
+ files.push({ name, at: (await stat(join(folder, name))).mtimeMs });
152
+ }
153
+ catch {
154
+ // Gone already.
155
+ }
156
+ }
157
+ const excess = files.length - MAX_STORED_MAPS;
158
+ if (excess <= 0)
159
+ return;
160
+ const victims = files.filter((f) => f.name !== `${keep}.json`).sort((a, b) => a.at - b.at || a.name.localeCompare(b.name));
161
+ for (const f of victims.slice(0, excess))
162
+ await unlink(join(folder, f.name)).catch(() => { });
163
+ }
164
+ /** Store `map` (its base values) stamped `storedAt`, then evict beyond the cap. `true` when written; never throws. */
165
+ export async function writeStoredMap(dir, map, storedAt = Date.now()) {
166
+ try {
167
+ await writeJsonAtomic(mapStorePath(dir, map.id), mapsDir(dir), { version: VERSION, storedAt, map });
168
+ await evictMaps(dir, map.id).catch(() => { });
169
+ return true;
170
+ }
171
+ catch {
172
+ return false;
173
+ }
174
+ }
175
+ /**
176
+ * Keep the territories read for the stored map's distribution modes (#328, by mode id) in its file,
177
+ * leaving its `storedAt` alone: they came from war.app's map details for the same map, so they age out
178
+ * with the GameFeed copy (a fresh download replaces the file, and they are read again). Only a stored
179
+ * map still trusted is updated; a mode not in `byMode` keeps what it had. `true` when written; never throws.
180
+ */
181
+ export async function writeStoredModeTerritories(dir, mapId, byMode) {
182
+ const path = mapStorePath(dir, mapId);
183
+ try {
184
+ return await withPathLock(path, async () => {
185
+ const raw = JSON.parse(await readFile(path, 'utf8'));
186
+ if (!storedMapOf(raw, mapId, Date.now(), MAX_MAP_AGE_MS) || !isRec(raw) || !isRec(raw.map) || !Array.isArray(raw.map.distributionModes)) {
187
+ return false;
188
+ }
189
+ raw.map.distributionModes = raw.map.distributionModes.map((d) => isRec(d) && isInt(d.id) && byMode.get(d.id)?.length ? { ...d, territories: [...byMode.get(d.id)] } : d);
190
+ await writeJsonAtomic(path, mapsDir(dir), raw);
191
+ return true;
192
+ });
193
+ }
194
+ catch {
195
+ return false;
196
+ }
197
+ }
198
+ /**
199
+ * Mark the stored copy of `map` recently used, storing it when its file has gone. A map served from
200
+ * memory is otherwise never read from disk, so the map of a game played all session long would age
201
+ * out of the store and leave its replay without a map. Never throws.
202
+ */
203
+ export async function touchStoredMap(dir, map) {
204
+ const now = new Date();
205
+ try {
206
+ await utimes(mapStorePath(dir, map.id), now, now);
207
+ }
208
+ catch {
209
+ await writeStoredMap(dir, map);
210
+ }
211
+ }
212
+ /** The index entries, loosely: unusable entries are dropped. */
213
+ async function readIndex(dir) {
214
+ try {
215
+ const raw = JSON.parse(await readFile(indexPath(dir), 'utf8'));
216
+ if (!isRec(raw) || raw.version !== VERSION || !Array.isArray(raw.games))
217
+ return [];
218
+ return raw.games.filter((e) => Array.isArray(e) && e.length === 2 && isInt(e[0]) && isInt(e[1]));
219
+ }
220
+ catch {
221
+ return [];
222
+ }
223
+ }
224
+ /** The map id stored for `gameId`; `undefined` when not known. Never throws. */
225
+ export async function readGameMapId(dir, gameId) {
226
+ const hit = (await readIndex(dir)).reverse().find(([g]) => g === gameId);
227
+ return hit?.[1];
228
+ }
229
+ /** Remember that `gameId` is on `mapId` (newest kept, {@link MAX_GAME_INDEX} at most). `true` when written; never throws. */
230
+ export async function rememberGameMap(dir, gameId, mapId) {
231
+ try {
232
+ return await withPathLock(indexPath(dir), async () => {
233
+ const games = (await readIndex(dir)).filter(([g]) => g !== gameId);
234
+ games.push([gameId, mapId]);
235
+ await writeJsonAtomic(indexPath(dir), mapsDir(dir), { version: VERSION, games: games.slice(-MAX_GAME_INDEX) });
236
+ return true;
237
+ });
238
+ }
239
+ catch {
240
+ return false;
241
+ }
242
+ }
@@ -0,0 +1,141 @@
1
+ // Who moved first, kept between turns (#127). Under a cyclic move order (`Cycle`, `NoLuckCycle`)
2
+ // the order reverses every turn (the client's own help text: "ABCD becomes DCBA the next turn"),
3
+ // so in a two-player game one turn whose first mover is known gives every other turn's. The
4
+ // first mover of a turn is learnt from `first_mover` given to warapp_plan_turn (the user saw it)
5
+ // or from the award of picks (src/analysis/award.ts: the wiki's rule, not verified live), and is
6
+ // kept at `<dataDir>/move-order/<gameId>.json` so later turns default to it, alternated.
7
+ //
8
+ // The game history is not read for it: war.app does not say who moves first under a plain cycle
9
+ // ("you must deduce it by observing the sequence that orders happen"), and whether GameFeed's
10
+ // `GetHistory` carries a game in progress's orders, in the order they ran, is UNVERIFIED
11
+ // (docs/WARAPP-API.md "Move order"). The first mover kept is the cycle's: an Order Priority or
12
+ // Order Delay card played on a turn changes who moves first on that turn only.
13
+ //
14
+ // One record per game: the newest turn known, with where it came from. A first mover given
15
+ // explicitly outranks one read from the award. Turn number and the two words only: no names.
16
+ // Best effort and never throws; a game's file not written for 60 days is deleted on the first
17
+ // write of a process.
18
+ import { mkdir, readdir, readFile, rename, stat, unlink, writeFile } from 'node:fs/promises';
19
+ import { join } from 'node:path';
20
+ /** Where a game's first mover is kept. */
21
+ export const firstMoverPath = (dir, gameId) => join(dir, 'move-order', `${gameId}.json`);
22
+ /** A game's file not written for this long is deleted (finished or abandoned games). */
23
+ export const FIRST_MOVER_MAX_AGE_MS = 60 * 86_400_000;
24
+ const FILE = /^\d+\.json$/;
25
+ const pruned = new Set();
26
+ const other = (m) => (m === 'me' ? 'opponent' : 'me');
27
+ const isTurn = (v) => typeof v === 'number' && Number.isSafeInteger(v) && v >= 1;
28
+ const isMover = (v) => v === 'me' || v === 'opponent';
29
+ const isSource = (v) => v === 'explicit' || v === 'award';
30
+ /** The first mover on `turn`, from one known turn: the same every second turn, the other in between. */
31
+ export function projectFirstMover(seen, turn) {
32
+ return Math.abs(turn - seen.turn) % 2 === 0 ? seen.firstMover : other(seen.firstMover);
33
+ }
34
+ const RANK = { award: 0, explicit: 1 };
35
+ const said = (m, turn) => `${m === 'me' ? 'you move' : 'the opponent moves'} first on turn ${turn}`;
36
+ /**
37
+ * Who moves first on `turn` and how it is known, with the record to keep (absent when nothing new
38
+ * is known). An explicit first mover wins; then a remembered explicit turn, alternated; then the
39
+ * award; then a remembered award turn. Outside a two-player cyclic order (or without a turn) only
40
+ * an explicit first mover counts, for this turn alone, and nothing is kept. A source that
41
+ * disagrees with the one used is a warning. Pure.
42
+ */
43
+ export function resolveFirstMover(input) {
44
+ const { turn, explicit, award } = input;
45
+ if (turn === null || !input.cyclicDuel)
46
+ return { resolved: explicit ? { firstMover: explicit, source: 'explicit' } : null, warnings: [] };
47
+ const candidates = [];
48
+ const kept = input.remembered;
49
+ const fromKept = () => kept && {
50
+ firstMover: projectFirstMover(kept, turn),
51
+ label: kept.source === 'explicit' ? `the first_mover given on turn ${kept.turn}` : `the award of picks (kept on turn ${kept.turn})`,
52
+ resolved: { firstMover: projectFirstMover(kept, turn), source: 'remembered', from: { turn: kept.turn, source: kept.source } },
53
+ };
54
+ if (explicit)
55
+ candidates.push({ firstMover: explicit, label: 'first_mover', resolved: { firstMover: explicit, source: 'explicit' }, record: { turn, firstMover: explicit, source: 'explicit' } });
56
+ if (kept?.source === 'explicit')
57
+ candidates.push(fromKept());
58
+ if (award)
59
+ candidates.push({ firstMover: award, label: 'the award of picks', resolved: { firstMover: award, source: 'award' }, record: { turn, firstMover: award, source: 'award' } });
60
+ if (kept?.source === 'award')
61
+ candidates.push(fromKept());
62
+ const used = candidates[0];
63
+ if (!used)
64
+ return { resolved: null, warnings: [] };
65
+ const warnings = [];
66
+ const against = candidates.slice(1).filter((c) => c.firstMover !== used.firstMover);
67
+ if (against.length)
68
+ warnings.push(`Move order: the plan takes it that ${said(used.firstMover, turn)} (from ${used.label}), but ` +
69
+ against.map((c) => `${c.label} says ${said(c.firstMover, turn)}`).join(', and ') +
70
+ '. Give first_mover as the cycle has it, without an Order Priority or Order Delay card played this turn.');
71
+ // Keep what is newly known, unless a better-ranked turn is kept already.
72
+ const record = used.record && (!kept || RANK[used.record.source] >= RANK[kept.source]) && !same(used.record, kept) ? used.record : undefined;
73
+ return { resolved: used.resolved, ...(record ? { record } : {}), warnings };
74
+ }
75
+ /**
76
+ * #215 review: a first mover the user gave (`first_mover`, now or on a remembered turn, alternated)
77
+ * is verified; one read from the award of picks — the wiki's rule, not verified live — is not, and
78
+ * the planner's hold sizing treats it as unknown (`movesFirstUnverified`).
79
+ */
80
+ export function verifiedFirstMover(resolved) {
81
+ return resolved.source === 'explicit' || (resolved.source === 'remembered' && resolved.from?.source === 'explicit');
82
+ }
83
+ const same = (a, b) => b !== undefined && a.turn === b.turn && a.firstMover === b.firstMover && a.source === b.source;
84
+ /** The first mover kept for `gameId` when it is `playerId`'s; `undefined` when absent or unusable. Never throws. */
85
+ export async function readFirstMover(dir, gameId, playerId) {
86
+ try {
87
+ const c = JSON.parse(await readFile(firstMoverPath(dir, gameId), 'utf8'));
88
+ if (typeof c !== 'object' || c === null || Array.isArray(c))
89
+ return undefined;
90
+ const r = c;
91
+ if (r.gameId !== gameId || r.playerId !== playerId)
92
+ return undefined;
93
+ if (!isTurn(r.turn) || !isMover(r.firstMover) || !isSource(r.source))
94
+ return undefined;
95
+ return { turn: r.turn, firstMover: r.firstMover, source: r.source };
96
+ }
97
+ catch {
98
+ return undefined;
99
+ }
100
+ }
101
+ async function prune(dir) {
102
+ const base = join(dir, 'move-order');
103
+ if (pruned.has(base))
104
+ return;
105
+ pruned.add(base);
106
+ const cutoff = Date.now() - FIRST_MOVER_MAX_AGE_MS;
107
+ try {
108
+ for (const name of await readdir(base)) {
109
+ if (!FILE.test(name))
110
+ continue;
111
+ const file = join(base, name);
112
+ try {
113
+ if ((await stat(file)).mtimeMs < cutoff)
114
+ await unlink(file);
115
+ }
116
+ catch {
117
+ // Gone already, or unreadable: leave it.
118
+ }
119
+ }
120
+ }
121
+ catch {
122
+ // No directory yet.
123
+ }
124
+ }
125
+ /** Keep `seen` as `playerId`'s first mover for `gameId`, replacing what was kept. Never throws. */
126
+ export async function writeFirstMover(dir, gameId, playerId, seen) {
127
+ if (!isTurn(seen.turn) || !isMover(seen.firstMover) || !isSource(seen.source))
128
+ return false;
129
+ try {
130
+ const path = firstMoverPath(dir, gameId);
131
+ await mkdir(join(dir, 'move-order'), { recursive: true, mode: 0o700 });
132
+ const tmp = `${path}.${process.pid}.tmp`;
133
+ await writeFile(tmp, JSON.stringify({ gameId, playerId, turn: seen.turn, firstMover: seen.firstMover, source: seen.source }), { mode: 0o600 });
134
+ await rename(tmp, path);
135
+ await prune(dir);
136
+ return true;
137
+ }
138
+ catch {
139
+ return false;
140
+ }
141
+ }