@chrischall/warapp-mcp 0.5.0 → 0.7.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 (125) hide show
  1. package/.claude-plugin/marketplace.json +3 -3
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/README.md +133 -8
  4. package/dist/analysis/accept-surrender.js +20 -2
  5. package/dist/analysis/calibrate.js +1 -0
  6. package/dist/analysis/card-support.js +177 -17
  7. package/dist/analysis/card-threats.js +126 -14
  8. package/dist/analysis/chat-advice.js +182 -0
  9. package/dist/analysis/chat-blocks.js +106 -0
  10. package/dist/analysis/chat-intent.js +559 -0
  11. package/dist/analysis/chat-read.js +159 -0
  12. package/dist/analysis/decision-replay.js +279 -0
  13. package/dist/analysis/decision-truth.js +146 -0
  14. package/dist/analysis/finished-game.js +62 -3
  15. package/dist/analysis/game-lessons.js +15 -10
  16. package/dist/analysis/hold-diff.js +3 -1
  17. package/dist/analysis/income-trend.js +38 -0
  18. package/dist/analysis/intel.js +75 -0
  19. package/dist/analysis/opens.js +64 -0
  20. package/dist/analysis/opponent-profile.js +121 -10
  21. package/dist/analysis/opponents.js +246 -20
  22. package/dist/analysis/outlook.js +360 -15
  23. package/dist/analysis/picks.js +91 -12
  24. package/dist/analysis/plan/after-leftover.js +4 -1
  25. package/dist/analysis/plan/bonus-attempts.js +105 -0
  26. package/dist/analysis/plan/capture-instead.js +116 -0
  27. package/dist/analysis/plan/captures.js +49 -7
  28. package/dist/analysis/plan/conceded-out.js +13 -2
  29. package/dist/analysis/plan/estimates.js +203 -30
  30. package/dist/analysis/plan/guard-off.js +2 -1
  31. package/dist/analysis/plan/holds.js +110 -9
  32. package/dist/analysis/plan/jabs.js +113 -0
  33. package/dist/analysis/plan/leftover.js +393 -8
  34. package/dist/analysis/plan/orders.js +76 -4
  35. package/dist/analysis/plan/relations.js +135 -2
  36. package/dist/analysis/plan/report.js +69 -3
  37. package/dist/analysis/plan/second-sizing.js +133 -0
  38. package/dist/analysis/plan/shared.js +279 -27
  39. package/dist/analysis/plan/siege.js +303 -0
  40. package/dist/analysis/plan/stand-still.js +9 -5
  41. package/dist/analysis/plan/state.js +8 -0
  42. package/dist/analysis/plan/stockpile.js +104 -0
  43. package/dist/analysis/plan/strike.js +39 -7
  44. package/dist/analysis/plan/targets.js +256 -110
  45. package/dist/analysis/plan/threats.js +148 -10
  46. package/dist/analysis/plan/transfers.js +57 -6
  47. package/dist/analysis/plan/two-move.js +70 -0
  48. package/dist/analysis/plan/vacated.js +124 -2
  49. package/dist/analysis/planner.js +527 -49
  50. package/dist/analysis/profile.js +13 -2
  51. package/dist/analysis/since-last.js +18 -5
  52. package/dist/analysis/stress.js +8 -2
  53. package/dist/board.js +36 -2
  54. package/dist/bonus-attempt-store.js +55 -0
  55. package/dist/build-id.js +106 -0
  56. package/dist/bundle.js +54138 -41059
  57. package/dist/cards.js +7 -5
  58. package/dist/chat-automation.js +22 -0
  59. package/dist/chat.js +35 -1
  60. package/dist/client.js +14 -0
  61. package/dist/commerce.js +111 -0
  62. package/dist/decision-log.js +1093 -0
  63. package/dist/finished-store.js +5 -1
  64. package/dist/index.js +9 -1
  65. package/dist/lessons-store.js +322 -21
  66. package/dist/live.js +43 -0
  67. package/dist/move-order.js +64 -3
  68. package/dist/normalize.js +17 -0
  69. package/dist/open-games.js +36 -16
  70. package/dist/outlook-log.js +42 -1
  71. package/dist/profile-store.js +12 -2
  72. package/dist/protocol/methods.js +62 -5
  73. package/dist/protocol/rpc.js +8 -0
  74. package/dist/relations-store.js +38 -4
  75. package/dist/review-export.js +198 -0
  76. package/dist/siege-store.js +49 -0
  77. package/dist/state-bundle.js +584 -0
  78. package/dist/state-cli.js +71 -0
  79. package/dist/strategy/notes.js +56 -0
  80. package/dist/team-cards.js +25 -0
  81. package/dist/tools/accept-surrender.js +23 -9
  82. package/dist/tools/award.js +20 -2
  83. package/dist/tools/card-advice.js +93 -28
  84. package/dist/tools/card-plays.js +2 -2
  85. package/dist/tools/card-support-advice.js +37 -7
  86. package/dist/tools/chat-advice.js +330 -0
  87. package/dist/tools/chat-inbox.js +19 -4
  88. package/dist/tools/chat.js +106 -17
  89. package/dist/tools/check-plan.js +68 -12
  90. package/dist/tools/commerce-deploy.js +33 -0
  91. package/dist/tools/common.js +31 -0
  92. package/dist/tools/decision-capture.js +459 -0
  93. package/dist/tools/end-of-game.js +151 -21
  94. package/dist/tools/game-kind.js +92 -0
  95. package/dist/tools/how-lost.js +7 -2
  96. package/dist/tools/index.js +10 -0
  97. package/dist/tools/join-game.js +10 -4
  98. package/dist/tools/live-context.js +6 -0
  99. package/dist/tools/live.js +10 -1
  100. package/dist/tools/map-curves.js +73 -0
  101. package/dist/tools/notifications.js +4 -3
  102. package/dist/tools/opponents.js +2 -0
  103. package/dist/tools/past-games.js +74 -8
  104. package/dist/tools/picks.js +61 -10
  105. package/dist/tools/profile-hook.js +62 -3
  106. package/dist/tools/profile-opponents.js +4 -0
  107. package/dist/tools/push.js +2 -2
  108. package/dist/tools/relations.js +139 -0
  109. package/dist/tools/scout.js +16 -2
  110. package/dist/tools/state.js +232 -0
  111. package/dist/tools/strategy.js +3 -3
  112. package/dist/tools/stress-opponents.js +7 -2
  113. package/dist/tools/surrender-pending.js +10 -1
  114. package/dist/tools/surrender.js +18 -3
  115. package/dist/tools/survival.js +11 -3
  116. package/dist/tools/team-brief.js +2 -2
  117. package/dist/tools/team.js +12 -3
  118. package/dist/tools/turn.js +643 -76
  119. package/dist/tools/where.js +3 -1
  120. package/dist/version.js +1 -1
  121. package/manifest.json +32 -3
  122. package/mint.yaml +37 -4
  123. package/package.json +4 -4
  124. package/server.json +20 -2
  125. package/skills/warapp-mcp/SKILL.md +73 -17
@@ -20,6 +20,8 @@ export function outcomeOf(players, me) {
20
20
  return players.some((p) => p.id !== me && p.state === 'Won') ? 'lost' : 'unknown';
21
21
  }
22
22
  const ownerOf = (t) => t?.owner.kind === 'player' ? t.owner.playerId : undefined;
23
+ /** A fog level that hides a territory's armies (fogged or owner-only, by word or number). */
24
+ const hidesArmies = (level) => level !== undefined && (/fog|owneronly/i.test(level) || level === '3' || level === '4');
23
25
  /**
24
26
  * Each of `players` on `board`: its income by THE income rule (`boardIncome`, src/analysis/player.ts:
25
27
  * base or per-territory income, plus every full bonus; the map's values with the game's overrides
@@ -29,12 +31,21 @@ const ownerOf = (t) => t?.owner.kind === 'player' ? t.owner.playerId : undefined
29
31
  export function turnIncomes(g, board, players, settings) {
30
32
  const held = new Map(players.map((p) => [p, new Set()]));
31
33
  const armies = new Map(players.map((p) => [p, 0]));
34
+ const unread = new Map();
35
+ const commanders = new Map();
32
36
  for (const t of board.territories) {
33
37
  const o = ownerOf(t);
34
38
  if (o === undefined || !held.has(o) || !g.territoryById.has(t.territoryId))
35
39
  continue;
36
40
  held.get(o).add(t.territoryId);
41
+ const own = t.specialUnits?.filter((u) => u.kind === 'commander' && u.playerId === o).length ?? 0;
42
+ if (own)
43
+ commanders.set(o, (commanders.get(o) ?? 0) + own);
37
44
  const a = armies.get(o);
45
+ if (t.armies === null && !hidesArmies(t.fogLevel)) {
46
+ unread.set(o, (unread.get(o) ?? 0) + 1);
47
+ continue;
48
+ }
38
49
  armies.set(o, a === null || t.armies === null ? null : a + t.armies);
39
50
  }
40
51
  const rules = incomeRules(settings);
@@ -46,11 +57,15 @@ export function turnIncomes(g, board, players, settings) {
46
57
  continue;
47
58
  }
48
59
  const inc = boardIncome(g, land, rules);
60
+ const u = unread.get(p);
61
+ const c = commanders.get(p);
49
62
  out.set(p, {
50
63
  income: inc.total,
51
64
  territories: land.size,
52
65
  armies: armies.get(p),
53
66
  bonuses: inc.bonuses.map((b) => b.bonusId).sort((a, b) => a - b),
67
+ ...(u ? { armiesUnread: u } : {}),
68
+ ...(c ? { commanders: c } : {}),
54
69
  });
55
70
  }
56
71
  return out;
@@ -118,19 +133,63 @@ export function failedAttacks(boards, orders, me) {
118
133
  }
119
134
  return out;
120
135
  }
136
+ /** Outcomes in which my seat left the game, so my orders of that turn never ran (#437). */
137
+ const LEFT = new Set(['surrendered', 'booted']);
138
+ /**
139
+ * The turn being played when my seat left (#437): for a surrender or a boot, `leftTurn` (the decision log's
140
+ * events), else my out turn on the history; for an elimination, my out turn; `null` otherwise or unknown. Pure.
141
+ */
142
+ export function leftTurnOf(result, outTurn, leftTurn) {
143
+ if (LEFT.has(result))
144
+ return leftTurn ?? outTurn;
145
+ return result === 'eliminated' ? outTurn : null;
146
+ }
121
147
  /** The whole capture of a finished game from its history boards and my orders. Pure. */
122
148
  export function captureFinished(input) {
123
149
  const ids = input.players.map((p) => p.id).sort((a, b) => a - b);
124
150
  const boards = ascending(input.boards);
151
+ const result = outcomeOf(input.players, input.me);
152
+ const outTurn = outTurnOf(boards, input.me);
153
+ const leftTurn = leftTurnOf(result, outTurn, input.leftTurn);
154
+ // #437: my orders of the turn my seat left (a surrender or a boot) never ran: no failed attack of theirs.
155
+ const ran = LEFT.has(result) && leftTurn !== null ? (f) => f.turn < leftTurn : () => true;
125
156
  return {
126
157
  outcome: {
127
- result: outcomeOf(input.players, input.me),
158
+ result,
128
159
  turn: input.numberOfTurns ?? null,
129
- outTurn: outTurnOf(boards, input.me),
160
+ outTurn,
161
+ leftTurn,
130
162
  winners: input.players.filter((p) => p.state === 'Won').map((p) => p.id).sort((a, b) => a - b),
131
163
  },
132
164
  starts: startsOf(boards, ids),
133
165
  turns: input.graph ? boards.map(({ turn, board }) => ({ afterTurn: turn, players: turnIncomes(input.graph, board, ids, input.settings) })) : [],
134
- failedAttacks: failedAttacks(boards, input.orders, input.me),
166
+ failedAttacks: failedAttacks(boards, input.orders, input.me).filter(ran),
135
167
  };
136
168
  }
169
+ export const GAME_KINDS = ['lottery', 'no-show', 'legacy', 'team'];
170
+ /** The kinds kept out of the lessons, the map record and the profile folds. */
171
+ export const EXCLUDED_KINDS = ['lottery', 'no-show'];
172
+ /** The kinds of a finished game ({@link GameKind}), in {@link GAME_KINDS} order. Pure. */
173
+ export function gameKinds(k) {
174
+ const out = new Set();
175
+ const lottery = k.territories !== undefined ? k.territories <= k.lotteryMaxTerritories : k.joinLottery !== undefined || k.lotteryShape === true;
176
+ if (lottery)
177
+ out.add('lottery');
178
+ const legacy = !k.hasLog && !k.hasBoards;
179
+ // Never committed: only where this server kept the game (a legacy game's orders were never cached).
180
+ const neverCommitted = !legacy && k.committedTurns === 0 && k.result !== 'won';
181
+ // Booted before turn 2 was played: seen booted while turn 1 or 2 was being played (a boot at turn 1's
182
+ // deadline is first seen on turn 2), or the game ended with at most one turn completed.
183
+ const bootedEarly = k.result === 'booted' && ((k.leftTurn !== null && k.leftTurn <= 2) || (k.numberOfTurns !== null && k.numberOfTurns <= 1));
184
+ if (neverCommitted || bootedEarly)
185
+ out.add('no-show');
186
+ if (legacy)
187
+ out.add('legacy');
188
+ if (k.team)
189
+ out.add('team');
190
+ return GAME_KINDS.filter((x) => out.has(x));
191
+ }
192
+ /** The kind a game is kept apart for (lottery first), or `undefined` when it counts. Pure. */
193
+ export function excludedKind(kinds) {
194
+ return kinds.includes('lottery') ? 'lottery' : kinds.includes('no-show') ? 'no-show' : undefined;
195
+ }
@@ -52,10 +52,9 @@ export function incomeCurve(turns, player) {
52
52
  })
53
53
  .sort((a, b) => a.afterTurn - b.afterTurn);
54
54
  }
55
- /** The turns of no growth that make an income flat (#312: "slope ≈ 0 for 3+ turns"). */
56
- export const FLAT_TURNS = 3;
57
- /** What counts as no growth over those turns: at most this share of the income (and at least 1 army). */
58
- export const FLAT_TOLERANCE = 0.1;
55
+ // #303: one definition of "flat", shared with the planner's income trend.
56
+ import { FLAT_TOLERANCE, FLAT_TURNS } from './income-trend.js';
57
+ export { FLAT_TOLERANCE, FLAT_TURNS };
59
58
  /**
60
59
  * The first board (by completed turns, the opening's board 0 left out) from which my income stayed
61
60
  * within {@link FLAT_TOLERANCE} of it (at least 1) on each of the next {@link FLAT_TURNS} consecutive
@@ -88,19 +87,25 @@ export const MAX_CURVE_POINTS = 60;
88
87
  /** The boards the pace is read on: the income after these completed turns. */
89
88
  export const PACE_TURNS = [4, 8];
90
89
  const incomeAfter = (curve, n) => curve.find((c) => c.afterTurn === n)?.income ?? null;
90
+ /** A curve as a map record keeps it: index = completed turns up to its last board, `null` where none read, at most {@link MAX_CURVE_POINTS}. Pure. */
91
+ export function curvePoints(curve) {
92
+ const last = Math.min(MAX_CURVE_POINTS, curve.length ? curve.at(-1).afterTurn + 1 : 0);
93
+ return Array.from({ length: last }, (_, i) => incomeAfter(curve, i));
94
+ }
91
95
  /**
92
96
  * My start region and income curve (index = completed turns, `null` where no board read, at most
93
- * {@link MAX_CURVE_POINTS}), and each winner's start region and income after turns 4 and 8 (the pace
94
- * to beat). Pure.
97
+ * {@link MAX_CURVE_POINTS}), and each winner's start region, income curve (#419, the same shape) and
98
+ * income after turns 4 and 8 (the pace to beat). Pure.
95
99
  */
96
100
  export function mapFacts(g, me, winners, starts, turns) {
97
101
  const mine = incomeCurve(turns, me);
98
- const last = Math.min(MAX_CURVE_POINTS, mine.length ? mine.at(-1).afterTurn + 1 : 0);
99
- const income = Array.from({ length: last }, (_, i) => incomeAfter(mine, i));
100
102
  const pace = (curve) => ({ income4: incomeAfter(curve, PACE_TURNS[0]), income8: incomeAfter(curve, PACE_TURNS[1]) });
101
103
  return {
102
- me: { ...startRegion(g, starts.get(me) ?? []), income, ...pace(mine) },
103
- winners: [...winners].sort((a, b) => a - b).map((w) => ({ ...startRegion(g, starts.get(w) ?? []), ...pace(incomeCurve(turns, w)) })),
104
+ me: { ...startRegion(g, starts.get(me) ?? []), income: curvePoints(mine), ...pace(mine) },
105
+ winners: [...winners].sort((a, b) => a - b).map((w) => {
106
+ const curve = incomeCurve(turns, w);
107
+ return { ...startRegion(g, starts.get(w) ?? []), income: curvePoints(curve), ...pace(curve) };
108
+ }),
104
109
  };
105
110
  }
106
111
  /**
@@ -21,6 +21,8 @@ import { COMMANDER_STRENGTH } from './combat.js';
21
21
  import { neighborsOf } from './graph.js';
22
22
  import { neutralizeSeats } from './static-seats.js';
23
23
  import { simTerritories, simulateTurn } from './turn-sim.js';
24
+ /** #306: the least shortfall warapp_check_plan and warapp_submit_turn name; smaller ones are the plan's surplus. */
25
+ export const BELOW_PLAN_MIN_SHORT = 3;
24
26
  /** Every border the given orders leave below what the default plan leaves there, the largest shortfall first. */
25
27
  export function holdsBelowPlan(input) {
26
28
  const { graph, me, teams } = input;
@@ -57,7 +59,7 @@ export function holdsBelowPlan(input) {
57
59
  for (const id of borders) {
58
60
  const planLeaves = planned(id);
59
61
  const left = given(id);
60
- if (left < planLeaves)
62
+ if (planLeaves - left >= Math.max(1, input.minShort ?? 1))
61
63
  out.push({ territory: id, planLeaves, left, short: planLeaves - left });
62
64
  }
63
65
  return out.sort((a, b) => b.short - a.short || a.territory - b.territory);
@@ -0,0 +1,38 @@
1
+ // #303: my income over the last turns — the points, a least-squares slope and whether it is flat.
2
+ // Pure. The flat test is #312's (`flatTurn` in game-lessons.ts), on the turns that end at this one.
3
+ /** The turns of no growth that make an income flat (#312: "slope ≈ 0 for 3+ turns"). */
4
+ export const FLAT_TURNS = 3;
5
+ /** What counts as no growth over those turns: at most this share of the income (and at least 1 army). */
6
+ export const FLAT_TOLERANCE = 0.1;
7
+ /** The turns the trend reports, the current one included (#303: "the last five turns"). */
8
+ export const TREND_POINTS = 5;
9
+ /**
10
+ * The trend over `earlier` boards' incomes and `current` (later readings of a turn win; a turn at or after the
11
+ * current one is ignored). Absent with no earlier turn.
12
+ */
13
+ export function incomeTrend(earlier, current) {
14
+ const by = new Map();
15
+ for (const p of earlier)
16
+ if (p.turn < current.turn)
17
+ by.set(p.turn, p.income);
18
+ if (by.size === 0)
19
+ return undefined;
20
+ by.set(current.turn, current.income);
21
+ const turns = [...by.entries()]
22
+ .sort((a, b) => a[0] - b[0])
23
+ .slice(-TREND_POINTS)
24
+ .map(([turn, income]) => ({ turn, income }));
25
+ const n = turns.length;
26
+ const mx = turns.reduce((s, p) => s + p.turn, 0) / n;
27
+ const my = turns.reduce((s, p) => s + p.income, 0) / n;
28
+ const sxx = turns.reduce((s, p) => s + (p.turn - mx) ** 2, 0);
29
+ const sxy = turns.reduce((s, p) => s + (p.turn - mx) * (p.income - my), 0);
30
+ const slope = sxx > 0 ? Math.round((sxy / sxx) * 10) / 10 : 0;
31
+ const tail = turns.slice(-(FLAT_TURNS + 1));
32
+ const first = tail[0];
33
+ const tol = Math.max(1, FLAT_TOLERANCE * first.income);
34
+ const flat = tail.length === FLAT_TURNS + 1 &&
35
+ first.income > 0 &&
36
+ tail.every((p, i) => p.turn === first.turn + i && p.income > 0 && Math.abs(p.income - first.income) <= tol);
37
+ return { turns, slope: slope === 0 ? 0 : slope, flat };
38
+ }
@@ -0,0 +1,75 @@
1
+ // #386: what the player learnt in diplomacy and wants every plan to apply, kept per game in the agreement
2
+ // ledger (src/relations-store.ts) by `warapp_record_intel`: territories promised to someone, players I
3
+ // promised not to attack outside any truce (with a reason from a fixed list: the ledger is name-free, no
4
+ // message), and a player's stated income with the turn it was stated. `warapp_plan_turn` and
5
+ // `warapp_check_plan` apply them by default (`resolveIntel`); an explicit `avoid_territories`,
6
+ // `avoid_players` or `known_income` replaces the stored list of its kind for that call, and a stored
7
+ // income older than `INCOME_STALE_TURNS` turns is not applied (the estimate stands, with a warning). Pure.
8
+ /** Why a player is not to be attacked: a fixed list, so the ledger holds no free text. */
9
+ export const AVOID_REASONS = ['promised', 'asked-by-them', 'joint-enemy', 'kingmaker', 'other'];
10
+ /** A stored income is applied while `turn - statedTurn` is at most this; older, the estimate stands. */
11
+ export const INCOME_STALE_TURNS = 3;
12
+ export const emptyIntel = () => ({ avoidTerritories: [], avoidPlayers: [], incomes: [] });
13
+ export const intelIsEmpty = (i) => !i || (i.avoidTerritories.length === 0 && i.avoidPlayers.length === 0 && i.incomes.length === 0);
14
+ /**
15
+ * The arguments a plan uses: each kind given explicitly as it is, else the stored entries (incomes only
16
+ * while fresh on `turn`; `null` turn: every stored income applies, none can be judged stale).
17
+ */
18
+ export function resolveIntel(stored, turn, args) {
19
+ const out = {
20
+ ...(args.knownIncome !== undefined ? { knownIncome: [...args.knownIncome] } : {}),
21
+ ...(args.avoidTerritories !== undefined ? { avoidTerritories: [...args.avoidTerritories] } : {}),
22
+ ...(args.avoidPlayers !== undefined ? { avoidPlayers: [...args.avoidPlayers] } : {}),
23
+ warnings: [],
24
+ };
25
+ if (intelIsEmpty(stored))
26
+ return out;
27
+ const s = stored;
28
+ const report = { applied: { avoidTerritories: [], avoidPlayers: [], knownIncome: [] }, overridden: [], stale: [] };
29
+ if (s.avoidTerritories.length) {
30
+ if (args.avoidTerritories !== undefined)
31
+ report.overridden.push('avoid_territories');
32
+ else {
33
+ report.applied.avoidTerritories = s.avoidTerritories.map((a) => ({ territory: a.territory, ...(a.promisedTo !== undefined ? { promisedTo: a.promisedTo } : {}) }));
34
+ out.avoidTerritories = s.avoidTerritories.map((a) => a.territory);
35
+ }
36
+ }
37
+ if (s.avoidPlayers.length) {
38
+ if (args.avoidPlayers !== undefined)
39
+ report.overridden.push('avoid_players');
40
+ else {
41
+ report.applied.avoidPlayers = s.avoidPlayers.map((a) => ({ player: a.player, reason: a.reason }));
42
+ out.avoidPlayers = s.avoidPlayers.map((a) => a.player);
43
+ }
44
+ }
45
+ if (s.incomes.length) {
46
+ if (args.knownIncome !== undefined)
47
+ report.overridden.push('known_income');
48
+ else {
49
+ const fresh = [];
50
+ for (const i of s.incomes) {
51
+ const age = turn === null ? 0 : turn - i.turn;
52
+ if (age > INCOME_STALE_TURNS)
53
+ report.stale.push({ player: i.player, income: i.income, statedTurn: i.turn, turnsOld: age });
54
+ else
55
+ fresh.push(i);
56
+ }
57
+ report.applied.knownIncome = fresh.map((i) => ({ player: i.player, income: i.income, statedTurn: i.turn }));
58
+ if (fresh.length)
59
+ out.knownIncome = fresh.map((i) => ({ player: i.player, income: i.income }));
60
+ }
61
+ }
62
+ for (const st of report.stale)
63
+ out.warnings.push(`The income ${st.income} recorded for player ${st.player} (stated on turn ${st.statedTurn}) is ${st.turnsOld} turns old, past ` +
64
+ `${INCOME_STALE_TURNS}: it is not applied and the estimate stands. Record a fresh figure with warapp_record_intel, or forget it.`);
65
+ const a = report.applied;
66
+ const parts = [
67
+ ...(a.avoidTerritories.length ? [`avoids territor${a.avoidTerritories.length === 1 ? 'y' : 'ies'} ${a.avoidTerritories.map((t) => t.territory).join(', ')}`] : []),
68
+ ...(a.avoidPlayers.length ? [`avoids player${a.avoidPlayers.length === 1 ? '' : 's'} ${a.avoidPlayers.map((p) => p.player).join(', ')}`] : []),
69
+ ...(a.knownIncome.length ? [`takes the stated income of player${a.knownIncome.length === 1 ? '' : 's'} ${a.knownIncome.map((k) => `${k.player} (${k.income}, turn ${k.statedTurn})`).join(', ')}`] : []),
70
+ ];
71
+ if (parts.length)
72
+ out.warnings.push(`Recorded intel (warapp_record_intel) applied: the plan ${parts.join('; ')}. Pass the argument explicitly to override it for this call.`);
73
+ out.report = report;
74
+ return out;
75
+ }
@@ -0,0 +1,64 @@
1
+ // #291: what the loss of a territory of mine OPENS to the enemy. #235 counts what a loss cuts off from my own
2
+ // holdings; a gate cuts nothing off — it is the only way the enemy gets in. Its opened set is every territory of
3
+ // mine that every route from an enemy or the fog (a `source`) reaches only through it: with it taken out of the
4
+ // graph, no source reaches them, yet they lie behind it. Routes run through any territory (an enemy can take a
5
+ // neutral or one of mine on its way), so this is the map's own chokepoint, not a guess at the enemy's path.
6
+ // Pure and deterministic (neighbours as the graph lists them, ids ascending in the result).
7
+ import { bonusTerritories } from './bonuses.js';
8
+ import { neighborsOf } from './graph.js';
9
+ const byNum = (a, b) => a - b;
10
+ /**
11
+ * What losing my `t` opens (see the header). `holdings`: my territories; `isSource(x)`: `x` is an enemy's or
12
+ * hidden. A bonus already counted elsewhere — one with a member in `skip` (what losing `t` cuts off, #235; a
13
+ * guard-off breach, #275) — and one containing `t` (its own value already counts in full) are left out, so nothing
14
+ * is counted twice. Empty when `t` is no chokepoint.
15
+ */
16
+ export function opensBehind(g, holdings, isSource, t, skip) {
17
+ const empty = { ids: [], bonuses: [], income: 0 };
18
+ const ids = g.map.territories.map((x) => x.id);
19
+ const sources = ids.filter((x) => x !== t && isSource(x));
20
+ if (!sources.length)
21
+ return empty;
22
+ // Everything a source reaches with `t` taken out.
23
+ const reached = new Set(sources);
24
+ const queue = [...sources];
25
+ while (queue.length) {
26
+ const x = queue.shift();
27
+ for (const n of neighborsOf(g, x))
28
+ if (n !== t && !reached.has(n)) {
29
+ reached.add(n);
30
+ queue.push(n);
31
+ }
32
+ }
33
+ // Behind `t`: what it reaches through territories no source reaches. Mine among them are what it opens.
34
+ const behind = new Set();
35
+ const q2 = neighborsOf(g, t).filter((n) => !reached.has(n));
36
+ for (const n of q2)
37
+ behind.add(n);
38
+ while (q2.length) {
39
+ const x = q2.shift();
40
+ for (const n of neighborsOf(g, x))
41
+ if (n !== t && !reached.has(n) && !behind.has(n)) {
42
+ behind.add(n);
43
+ q2.push(n);
44
+ }
45
+ }
46
+ const opened = [...behind].filter((x) => holdings.has(x)).sort(byNum);
47
+ if (!opened.length)
48
+ return empty;
49
+ const set = new Set(opened);
50
+ const bonuses = [];
51
+ let income = 0;
52
+ for (const b of [...g.map.bonuses].sort((x, y) => x.id - y.id)) {
53
+ if (b.value <= 0)
54
+ continue;
55
+ const ts = bonusTerritories(g, b.id);
56
+ if (!ts.length || ts.includes(t) || !ts.every((x) => holdings.has(x)))
57
+ continue;
58
+ if (!ts.some((x) => set.has(x)) || ts.some((x) => skip.has(x)))
59
+ continue;
60
+ bonuses.push(b.id);
61
+ income += b.value;
62
+ }
63
+ return { ids: opened, bonuses, income };
64
+ }
@@ -70,7 +70,8 @@ function leastFailing(armies, from, off, def) {
70
70
  * My orders as cached (`MyOrders`): `moves` holds only plain orders; a percentage, Attack Only or
71
71
  * Transfer Only order is in `sent` alone, and card plays in `cards`. A territory such an order leaves
72
72
  * or enters, or one of my Airlifts touches, is never tested for `attackedMe` and gives no `reinforce`
73
- * reading (its armies are not known); `iAttacked` counts every non-transfer order of `sent`. When the
73
+ * reading (its armies are not known); `iAttacked` counts every non-transfer order of `sent` (#442: onto its
74
+ * territory on T, or onto one not mine on T that is its on T+1 — my attack ran into its fresh capture). When the
74
75
  * orders do not record card plays (`cards` absent: a cache written before they were) and the game may
75
76
  * have Airlift, nothing is tested from armies at all, and when it may have Gift — orders unknown
76
77
  * included — captures cannot be told (`tookFromMe: null`; it may have been my gift), so a game with
@@ -155,12 +156,21 @@ export function observeTurn(input) {
155
156
  const contact = ids.some((id) => ownsWas(id) && neighborsOf(graph, id).some(mineWas));
156
157
  const tookFromMe = giftUnknown ? null : ids.filter((id) => mineWas(id) && ownsNow(id) && !gifted.has(id));
157
158
  const lostToMe = ids.filter((id) => ownsWas(id) && mineNow(id));
158
- const iAttacked = moves.some((m) => ownsWas(m.to) && m.armies > 0 && !transferOnly.has(`${m.from}:${m.to}`)) ||
159
- sent.some((m) => ownsWas(m.to) && !m.transferOnly && sentCount(m) > plain(m));
159
+ // #442: or onto a territory not mine on T that is its on T+1 — its fresh capture my attack ran into.
160
+ const hit = (to) => ownsWas(to) || (!mineWas(to) && ownsNow(to));
161
+ const iAttacked = moves.some((m) => hit(m.to) && m.armies > 0 && !transferOnly.has(`${m.from}:${m.to}`)) ||
162
+ sent.some((m) => hit(m.to) && !m.transferOnly && sentCount(m) > plain(m));
160
163
  // attackedMe
161
164
  let attackedMe = tookFromMe?.length ? true : null;
162
- if (attackedMe === null && orders && !airliftUnknown) {
165
+ // #361: the borders read whose drop is exactly what one attacking army kills (a single-army jab);
166
+ // `null` unless combat is exact and at least one border was read.
167
+ let jabs = null;
168
+ if (orders && !airliftUnknown) {
163
169
  let tested = false;
170
+ let dropped = false;
171
+ let read = 0;
172
+ let jabbed = 0;
173
+ const oneKill = straightKills(1, off);
164
174
  for (const id of ids) {
165
175
  if (untested.has(id))
166
176
  continue;
@@ -190,9 +200,12 @@ export function observeTurn(input) {
190
200
  if (transfersIn.some((m) => enemiesNext(m.from).size > 0 || !allShown(m.from)))
191
201
  continue;
192
202
  const expected = a.armies + (deploys.get(id) ?? 0) - sum(outOf(id)) + sum(transfersIn);
203
+ read++;
193
204
  if (b.armies < expected) {
194
- attackedMe = true;
195
- break;
205
+ dropped = true;
206
+ if (oneKill >= 1 && expected - b.armies === oneKill)
207
+ jabbed++;
208
+ continue;
196
209
  }
197
210
  // A move out that did not surely land (a failed attack, a transfer that met a territory taken
198
211
  // first, or a move into a territory another order of mine also entered, which may have been
@@ -206,9 +219,13 @@ export function observeTurn(input) {
206
219
  if (!drained && !chainedIn && !outOf(id).some((m) => m.armies > 0 && !landed(m)))
207
220
  tested = true;
208
221
  }
222
+ if (attackedMe === null && dropped)
223
+ attackedMe = true;
209
224
  // A quiet border is a "no" only when captures can be told too (a capture elsewhere would be a yes).
210
225
  if (attackedMe === null && tested && tookFromMe !== null)
211
226
  attackedMe = false;
227
+ if (exact && read > 0)
228
+ jabs = jabbed;
212
229
  }
213
230
  // reinforce
214
231
  const reinforce = { n: 0, e: 0, extra: 0 };
@@ -279,6 +296,36 @@ export function observeTurn(input) {
279
296
  }
280
297
  }
281
298
  }
299
+ // #295: my biggest stack facing it, and whether its territories facing that stack were raised past
300
+ // what the stack's movable armies plus my income (my deploys this turn) could take.
301
+ let topUp = null;
302
+ if (orders && !airliftUnknown) {
303
+ let s = null;
304
+ for (const id of ids) {
305
+ const a = seen(was.get(id));
306
+ if (a?.owner !== me || !neighborsOf(graph, id).some((n) => seen(was.get(n))?.owner === p))
307
+ continue;
308
+ if (!s || a.armies > s.armies)
309
+ s = { id, armies: a.armies };
310
+ }
311
+ const facing = s ? neighborsOf(graph, s.id).filter((n) => ownsWas(n)) : [];
312
+ const readable = (x) => seen(was.get(x))?.owner === p &&
313
+ seen(now.get(x))?.owner === p &&
314
+ !untested.has(x) &&
315
+ !into(x).length &&
316
+ !sent.some((m) => m.to === x) &&
317
+ specialUnitStrength(visibleState(was.get(x))?.specialUnits) === 0 &&
318
+ specialUnitStrength(visibleState(now.get(x))?.specialUnits) === 0;
319
+ if (s && facing.length && facing.every(readable)) {
320
+ const capacity = Math.max(0, s.armies - guard) + sum(orders.deploys);
321
+ const takeable = (d) => {
322
+ const need = armiesToTake(d, { offensiveKillRate: off, defensiveKillRate: def });
323
+ return need !== null && need <= capacity;
324
+ };
325
+ if (facing.some((x) => takeable(seen(was.get(x)).armies)))
326
+ topUp = !facing.some((x) => takeable(seen(now.get(x)).armies));
327
+ }
328
+ }
282
329
  // stack
283
330
  let top = 0;
284
331
  let total = 0;
@@ -294,11 +341,11 @@ export function observeTurn(input) {
294
341
  top = Math.max(top, g);
295
342
  }
296
343
  const stack = both >= 2 && total >= 1 ? { top, total } : null;
297
- result.set(p, { contact, attackedMe, iAttacked, reinforce, stack, tookFromMe, lostToMe });
344
+ result.set(p, { contact, attackedMe, iAttacked, reinforce, stack, tookFromMe, lostToMe, jabs, topUp });
298
345
  }
299
346
  return result;
300
347
  }
301
- export const HABIT_NAMES = ['reinforce', 'attack', 'firstStrike', 'stacking', 'retaliate', 'retake'];
348
+ export const HABIT_NAMES = ['reinforce', 'attack', 'firstStrike', 'stacking', 'retaliate', 'retake', 'jab', 'capacityTopUp'];
302
349
  /**
303
350
  * The habits of one opponent from its observed turns (any order; each turn once). Habits that span
304
351
  * turns are recomputed from the whole list, so re-deriving never double-counts:
@@ -311,7 +358,11 @@ export const HABIT_NAMES = ['reinforce', 'attack', 'firstStrike', 'stacking', 'r
311
358
  * - `retaliate`: turns I attacked it, an event when it attacked me on one of the next two turns;
312
359
  * counted only when both are observed and told, or one says it did;
313
360
  * - `retake`: territories I took from it, an event when it took them back within two turns;
314
- * counted only when both turns are observed with their captures told, or it did.
361
+ * counted only when both turns are observed with their captures told, or it did;
362
+ * - `jab` (#361): turns in contact whose borders could be read for a single-army jab (exact combat), an
363
+ * event when one was;
364
+ * - `capacityTopUp` (#295): turns it had the chance to raise the territories facing my biggest stack past
365
+ * what that stack plus my income could take, an event when it did.
315
366
  */
316
367
  export function habitsOf(turns) {
317
368
  const by = new Map();
@@ -326,6 +377,8 @@ export function habitsOf(turns) {
326
377
  stacking: { n: 0, sum: 0, sq: 0 },
327
378
  retaliate: { e: 0, n: 0 },
328
379
  retake: { e: 0, n: 0 },
380
+ jab: { e: 0, n: 0 },
381
+ capacityTopUp: { e: 0, n: 0 },
329
382
  turns: order.length,
330
383
  };
331
384
  /** Whether either of the next two turns says yes (`true`), both say no (`false`), or it cannot be told (`null`). */
@@ -353,6 +406,10 @@ export function habitsOf(turns) {
353
406
  h.reinforceExtra.sum += p.reinforce.extra;
354
407
  if (p.contact && p.attackedMe !== null)
355
408
  count(h.attack, p.attackedMe);
409
+ if (p.contact && p.jabs != null)
410
+ count(h.jab, p.jabs > 0);
411
+ if (p.topUp != null)
412
+ count(h.capacityTopUp, p.topUp);
356
413
  if (p.stack && p.stack.total > 0) {
357
414
  const share = p.stack.top / p.stack.total;
358
415
  h.stacking.n++;
@@ -381,6 +438,46 @@ export function habitsOf(turns) {
381
438
  }
382
439
  return h;
383
440
  }
441
+ // ---- #420: the one profile read the planner may make (P1 amended, owner decision of 2026-11-20) ----
442
+ /** #420: the contact turns (each one whose attack on me could be told) a quiet neighbour needs. */
443
+ export const QUIET_CONTACT_TURNS = 10;
444
+ /** #420: the most attacks on me per contact turn a quiet neighbour may show. */
445
+ export const QUIET_ATTACK_RATE = 0.1;
446
+ /**
447
+ * #420 (owner decision of 2026-11-20): the one case P1 lets the planner read a profile. Over this
448
+ * game's observed turns in order, a contact turn whose attack on me could be told counts; once there are
449
+ * {@link QUIET_CONTACT_TURNS} or more at an attack rate of {@link QUIET_ATTACK_RATE} or less it is quiet,
450
+ * until its first attack on me after that, which ends it for the game (full sizing at once). Pure.
451
+ */
452
+ export function quietNeighbour(turns) {
453
+ const by = new Map();
454
+ for (const t of turns)
455
+ by.set(t.turn, t.primitives);
456
+ let n = 0;
457
+ let e = 0;
458
+ let since;
459
+ let attackedOn;
460
+ for (const t of [...by.keys()].sort(byNum)) {
461
+ const p = by.get(t);
462
+ if (!p.contact || p.attackedMe === null)
463
+ continue;
464
+ n++;
465
+ if (p.attackedMe) {
466
+ e++;
467
+ if (since !== undefined && attackedOn === undefined)
468
+ attackedOn = t;
469
+ }
470
+ if (since === undefined && n >= QUIET_CONTACT_TURNS && e <= QUIET_ATTACK_RATE * n)
471
+ since = t;
472
+ }
473
+ return {
474
+ contactTurns: n,
475
+ attacks: e,
476
+ quiet: since !== undefined && attackedOn === undefined,
477
+ ...(since !== undefined ? { since } : {}),
478
+ ...(attackedOn !== undefined ? { attackedOn } : {}),
479
+ };
480
+ }
384
481
  // ---- the estimate (B1): this game pooled with past games, shrunk toward the population or a default ----
385
482
  /** How many opportunities the prior weighs as (docs/PLAN-PROFILES.md B1). */
386
483
  export const PROFILE_PRIOR_WEIGHT = 4;
@@ -394,6 +491,8 @@ export const HABIT_DEFAULTS = {
394
491
  stacking: 0.7,
395
492
  retaliate: 0.5,
396
493
  retake: 0.4,
494
+ jab: 0.1,
495
+ capacityTopUp: 0.3,
397
496
  };
398
497
  /**
399
498
  * The least opportunities (readings, for a size) a population pool needs for one habit before its
@@ -421,6 +520,8 @@ export function emptyHabits() {
421
520
  stacking: { n: 0, sum: 0, sq: 0 },
422
521
  retaliate: { e: 0, n: 0 },
423
522
  retake: { e: 0, n: 0 },
523
+ jab: { e: 0, n: 0 },
524
+ capacityTopUp: { e: 0, n: 0 },
424
525
  turns: 0,
425
526
  };
426
527
  }
@@ -440,6 +541,8 @@ export function addHabits(a, b, scale = 1) {
440
541
  stacking: { n: tidy(a.stacking.n + scale * b.stacking.n), sum: tidy(a.stacking.sum + scale * b.stacking.sum), sq: tidy(a.stacking.sq + scale * b.stacking.sq) },
441
542
  retaliate: rate(a.retaliate, b.retaliate),
442
543
  retake: rate(a.retake, b.retake),
544
+ jab: rate(a.jab, b.jab),
545
+ capacityTopUp: rate(a.capacityTopUp, b.capacityTopUp),
443
546
  turns: tidy(a.turns + scale * b.turns),
444
547
  };
445
548
  }
@@ -494,9 +597,11 @@ export function estimateHabits(h, priors = {}) {
494
597
  stacking: blend(size(h), size(past), s.p0, s.from, PROFILE_PRIOR_WEIGHT, priors.pastHistory ? size(priors.pastHistory) : undefined),
495
598
  retaliate: rate('retaliate'),
496
599
  retake: rate('retake'),
600
+ jab: rate('jab'),
601
+ capacityTopUp: rate('capacityTopUp'),
497
602
  };
498
603
  }
499
- export const PROFILE_LABELS = ['reinforcer', 'rarely-reinforces', 'stacker', 'spreader', 'rusher', 'turtle', 'avenger', 'retakes'];
604
+ export const PROFILE_LABELS = ['reinforcer', 'rarely-reinforces', 'stacker', 'spreader', 'rusher', 'turtle', 'avenger', 'retakes', 'jabber', 'tops-up'];
500
605
  /** One fixed counter-play line per label the plan gives one (docs/PLAN-PROFILES.md B1; `spreader` has none). */
501
606
  export const COUNTER_PLAY = {
502
607
  reinforcer: 'Attack two of its territories in one turn (it deploys on one), or size for its deploy.',
@@ -506,6 +611,8 @@ export const COUNTER_PLAY = {
506
611
  turtle: 'Out-expand it; a quiet border with it tends to stay quiet.',
507
612
  avenger: 'Do not poke; strike only to cripple, and garrison the source.',
508
613
  retakes: 'A capture from it needs a garrison that survives its counter.',
614
+ jabber: 'It jabs a border with one army a turn (one for one at 0% luck): keep an army above the hold there to refill.',
615
+ 'tops-up': 'It raises the territory facing your biggest stack past what that stack plus your income can take: strike where it is not looking, or build past it first.',
509
616
  };
510
617
  /** Turns back from the one being played within which an attack on me withholds `turtle` (#264). */
511
618
  export const TURTLE_QUIET_TURNS = 2;
@@ -548,5 +655,9 @@ export function labelsOf(e, recent = {}) {
548
655
  out.push('avenger');
549
656
  if (sure(e.retake) && e.retake.value >= 0.6)
550
657
  out.push('retakes');
658
+ if (sure(e.jab) && e.jab.value >= 0.5)
659
+ out.push('jabber');
660
+ if (sure(e.capacityTopUp) && e.capacityTopUp.value >= 0.6)
661
+ out.push('tops-up');
551
662
  return out;
552
663
  }