@chrischall/warapp-mcp 0.10.0 → 0.12.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 (65) hide show
  1. package/.claude-plugin/marketplace.json +3 -3
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/README.md +10 -8
  4. package/dist/analysis/cards-in-effect.js +10 -1
  5. package/dist/analysis/chat-mentions.js +17 -0
  6. package/dist/analysis/commander-fog.js +126 -0
  7. package/dist/analysis/end-game-stats.js +149 -0
  8. package/dist/analysis/local-deploy.js +3 -2
  9. package/dist/analysis/outlook.js +133 -55
  10. package/dist/analysis/picks.js +125 -0
  11. package/dist/analysis/plan/commander.js +3 -2
  12. package/dist/analysis/plan/deploy-estimates.js +11 -7
  13. package/dist/analysis/plan/estimates.js +63 -9
  14. package/dist/analysis/plan/relations.js +29 -14
  15. package/dist/analysis/plan/shared.js +21 -0
  16. package/dist/analysis/plan/threats.js +74 -5
  17. package/dist/analysis/player-record.js +31 -1
  18. package/dist/analysis/player.js +23 -10
  19. package/dist/analysis/relations.js +83 -9
  20. package/dist/analysis/scale.js +71 -0
  21. package/dist/analysis/single-pick.js +356 -0
  22. package/dist/bundle.js +3099 -809
  23. package/dist/chat-links.js +141 -0
  24. package/dist/finished-store.js +30 -0
  25. package/dist/index.js +1 -1
  26. package/dist/known-mods.js +33 -0
  27. package/dist/map-stats.js +24 -2
  28. package/dist/mod-alliances.js +217 -0
  29. package/dist/mod-data.js +160 -0
  30. package/dist/my-games.js +53 -2
  31. package/dist/normalize.js +7 -0
  32. package/dist/outlook-log.js +13 -0
  33. package/dist/player-record-store.js +5 -3
  34. package/dist/protocol/methods.js +14 -2
  35. package/dist/relations-store.js +29 -1
  36. package/dist/tools/card-advice.js +29 -9
  37. package/dist/tools/card-effects.js +3 -1
  38. package/dist/tools/card-support-advice.js +1 -1
  39. package/dist/tools/chat-advice.js +1 -1
  40. package/dist/tools/chat-inbox.js +67 -10
  41. package/dist/tools/chat.js +46 -8
  42. package/dist/tools/check-plan.js +115 -11
  43. package/dist/tools/close-finished-game.js +110 -0
  44. package/dist/tools/commander-check.js +80 -1
  45. package/dist/tools/diplomacy.js +11 -2
  46. package/dist/tools/end-of-game.js +57 -3
  47. package/dist/tools/game.js +7 -3
  48. package/dist/tools/how-lost.js +68 -5
  49. package/dist/tools/index.js +21 -1
  50. package/dist/tools/map.js +50 -1
  51. package/dist/tools/mod-alliances.js +191 -0
  52. package/dist/tools/my-games.js +12 -1
  53. package/dist/tools/pace.js +44 -0
  54. package/dist/tools/picks.js +41 -1
  55. package/dist/tools/relations.js +120 -7
  56. package/dist/tools/session.js +20 -6
  57. package/dist/tools/stress-opponents.js +25 -2
  58. package/dist/tools/turn.js +338 -42
  59. package/dist/tools/write-kit.js +1 -0
  60. package/dist/version.js +1 -1
  61. package/manifest.json +10 -2
  62. package/mint.yaml +3 -4
  63. package/package.json +1 -1
  64. package/server.json +2 -2
  65. package/skills/warapp-mcp/SKILL.md +73 -11
@@ -40,7 +40,7 @@ import { bonusTerritories } from '../bonuses.js';
40
40
  import { bfsDistances, neighborsOf } from '../graph.js';
41
41
  import { simTerritories, simulateTurn } from '../turn-sim.js';
42
42
  import { armiesToTake, DEFAULT_DEFENSIVE_KILL_RATE, straightKills } from '../combat.js';
43
- import { captureCost, CONCEDE_FACTOR, } from './shared.js';
43
+ import { captureCost, CONCEDE_FACTOR, ruleOnly, } from './shared.js';
44
44
  import { byNum } from './util.js';
45
45
  /** T3: a covered border protecting more than this share of my income keeps its full hold. */
46
46
  export const TRUCE_RELAX_VALUE = 0.25;
@@ -167,14 +167,14 @@ function truceFrom(input, o) {
167
167
  else if (r.state === 'broken')
168
168
  st = 'broken';
169
169
  // D3: a relation that is only a card ends with it.
170
- else if (r.card && !enforcedNow[i])
170
+ else if (ruleOnly(r) && !enforcedNow[i])
171
171
  st = 'over';
172
172
  else if (r.state === 'notice' && r.endsTurn !== undefined && o.turnNow !== null && o.turnNow >= r.endsTurn)
173
173
  st = 'over';
174
174
  else
175
175
  st = r.state;
176
176
  kept.push(st === 'active' || st === 'notice');
177
- if (!ffa && !r.card && !(enforcedNow[i] && kept[i]))
177
+ if (!ffa && !ruleOnly(r) && !(enforcedNow[i] && kept[i]))
178
178
  st = 'ignored';
179
179
  status.push(st);
180
180
  binds.push(st === 'active' || st === 'notice');
@@ -193,7 +193,7 @@ function truceFrom(input, o) {
193
193
  given.forEach((r, i) => {
194
194
  if (!kept[i])
195
195
  return;
196
- if (!r.card)
196
+ if (!ruleOnly(r))
197
197
  keptWith.add(r.player);
198
198
  // T2–T5 and T9 only in a free-for-all; T1 (never a surprise break, D3) wherever the agreement binds.
199
199
  if (binds[i]) {
@@ -620,7 +620,13 @@ export function reportTruce(pc, ps, tp, freedOn) {
620
620
  const relations = truce.given.map((r, i) => {
621
621
  const st = truce.status[i];
622
622
  const flags = [...(r.watch ?? [])];
623
- const name = r.card ? `Diplomacy card with player ${r.player}` : `Truce with player ${r.player}${r.agreement ? ` (agreement ${r.agreement})` : ''}`;
623
+ const name = r.card
624
+ ? `Diplomacy card with player ${r.player}`
625
+ : ruleOnly(r)
626
+ ? `Diplomacy 2 alliance with player ${r.player}`
627
+ : `Truce with player ${r.player}${r.agreement ? ` (agreement ${r.agreement})` : ''}`;
628
+ // What enforces it: the Diplomacy 2 mod's alliance (a card enforcing it too lasts longer and is named instead).
629
+ const byMod = r.mod !== undefined && !r.card && !(r.enforcedUntil !== undefined && turnNow !== null && r.enforcedUntil > turnNow + 1);
624
630
  const mineRelaxed = tp ? [...tp.relaxed].filter(([t, p]) => p === r.player && r.coveredMine.includes(t)).map(([t]) => t).sort(byNum) : [];
625
631
  const fullHold = tp
626
632
  ? [...tp.fullHold]
@@ -633,7 +639,7 @@ export function reportTruce(pc, ps, tp, freedOn) {
633
639
  warnings.push(`${name} is broken by them: ${r.breach.term} on turn ${r.breach.turn}${r.breach.territories.length ? ` (${r.breach.territories.map(label).join(', ')})` : ''} — ${r.breach.evidence}. Player ${r.player} is planned as an ordinary opponent from this turn (T8). ${RECORD_BROKEN(r)}`);
634
640
  else if (st === 'broken')
635
641
  warnings.push(`${name} is broken by them: player ${r.player} is planned as an ordinary opponent from this turn (T8). ${RECORD_BROKEN(r)}`);
636
- else if (st === 'over' && r.card)
642
+ else if (st === 'over' && ruleOnly(r))
637
643
  rationale.push(`${name}: it is gone by this turn, so player ${r.player} is an ordinary opponent (T9).`);
638
644
  else if (st === 'over')
639
645
  rationale.push(`${name}: its notice ran out on turn ${r.endsTurn}, so player ${r.player} is an ordinary opponent this turn (T7).`);
@@ -642,14 +648,21 @@ export function reportTruce(pc, ps, tp, freedOn) {
642
648
  else if (st === 'active' || st === 'notice') {
643
649
  const enforced = truce.enforced.has(r.player);
644
650
  const notice = st === 'notice' && r.endsTurn !== undefined ? ` (in notice${r.noticeBy ? ` given by ${r.noticeBy === 'me' ? 'me' : 'them'}` : ''}: binding until turn ${r.endsTurn})` : '';
645
- rationale.push(enforced
646
- ? `${name}${notice}: a Diplomacy card is in effect, so player ${r.player}'s attacks on me do nothing this turn — its threat is 0 and no attack on it is planned (T9)` +
647
- (truce.lookAheadFoes.has(r.player)
648
- ? `; the card is gone by turn ${r.enforcedUntil}, so its stacks still count for next turn's look-ahead.`
649
- : r.enforcedUntil !== undefined
650
- ? `; the card lasts until turn ${r.enforcedUntil}.`
651
- : '.')
652
- : `${name}${notice}: none of its ${r.coveredTheirs.length} covered ${r.coveredTheirs.length === 1 ? 'territory is' : 'territories are'} a target this turn (T1), and player ${r.player} is no front for the no-second-front rule or the idle armies (T4).`);
651
+ rationale.push(enforced && byMod
652
+ ? `${name}${notice}: the Diplomacy 2 mod's alliance is in effect, so the game skips every attack between player ${r.player} and me this turn — its threat is 0 and no attack on it is planned (T9); ` +
653
+ 'either side may enter a break this turn, unseen, that applies at its end, so its stacks still count for next turn\'s look-ahead.'
654
+ : enforced
655
+ ? `${name}${notice}: a Diplomacy card is in effect, so player ${r.player}'s attacks on me do nothing this turn — its threat is 0 and no attack on it is planned (T9)` +
656
+ (truce.lookAheadFoes.has(r.player)
657
+ ? `; the card is gone by turn ${r.enforcedUntil}, so its stacks still count for next turn's look-ahead.`
658
+ : r.enforcedUntil !== undefined
659
+ ? `; the card lasts until turn ${r.enforcedUntil}.`
660
+ : '.')
661
+ : `${name}${notice}: none of its ${r.coveredTheirs.length} covered ${r.coveredTheirs.length === 1 ? 'territory is' : 'territories are'} a target this turn (T1), and player ${r.player} is no front for the no-second-front rule or the idle armies (T4).`);
662
+ for (const e of r.exceptions ?? [])
663
+ rationale.push(e.direction === 'mine'
664
+ ? `${name}: player ${r.player} agreed to an exception this turn, so ${e.territories.map(label).join(', ')} ${e.territories.length === 1 ? 'is a normal target' : 'are normal targets'} — no break.`
665
+ : `${name}: I agreed to an exception this turn, so player ${r.player} may attack ${e.territories.map(label).join(', ')}: ${e.territories.length === 1 ? 'it is' : 'they are'} held as against any opponent.`);
653
666
  if (mineRelaxed.length)
654
667
  rationale.push(`${name}: ${mineRelaxed.map(label).join(', ')} ${mineRelaxed.length === 1 ? 'faces' : 'face'} only player ${r.player}, so ${mineRelaxed.length === 1 ? 'it is' : 'they are'} held against its visible stacks there attacking with no deploy (T2) — a break needs a visible build-up first; ${freed} ${freed === 1 ? 'army' : 'armies'} freed this turn.`);
655
668
  const why = { commander: 'my commander stands there', value: `it protects more than ${TRUCE_RELAX_VALUE} × my income`, watch: `the trust is watch (${flags.join(', ') || 'a flag'})` };
@@ -669,6 +682,7 @@ export function reportTruce(pc, ps, tp, freedOn) {
669
682
  enforced: truce.binds[i] && truce.enforced.has(r.player),
670
683
  ...(r.enforcedUntil !== undefined ? { enforcedUntil: r.enforcedUntil } : {}),
671
684
  ...(r.card ? { card: r.card } : {}),
685
+ ...(r.mod ? { mod: r.mod } : {}),
672
686
  trust: r.trust,
673
687
  flags,
674
688
  ...(r.endsTurn !== undefined ? { endsTurn: r.endsTurn } : {}),
@@ -677,6 +691,7 @@ export function reportTruce(pc, ps, tp, freedOn) {
677
691
  armiesFreed: freed,
678
692
  ...(tp?.capMoved.get(i)?.length ? { capMoved: tp.capMoved.get(i) } : {}),
679
693
  ...(r.breach ? { breach: r.breach } : {}),
694
+ ...(r.exceptions?.length ? { exceptions: r.exceptions } : {}),
680
695
  // T6: filled in once the plan's orders are final (truceBreakLosses).
681
696
  lossIfBroken: null,
682
697
  };
@@ -157,8 +157,29 @@ export function localFreeOn(base, floor, clock, turn) {
157
157
  export function bombPossibleOn(settings, turn) {
158
158
  return settings.bombFrom !== undefined && (turn === null || turn === undefined || turn >= settings.bombFrom);
159
159
  }
160
+ /** Round to the nearest, .5 down: the client's rounding of a progressive card (`Round(x, false)`). */
161
+ const roundHalfDown = (x) => {
162
+ const whole = Math.floor(x);
163
+ return x - whole > 0.5 + 1e-9 ? whole + 1 : whole;
164
+ };
165
+ /**
166
+ * An opponent's Reinforcement card under `r`: a flat card's armies, or a progressive one by the client's formula.
167
+ * `territories` is every territory a player (any player, me included) holds in view: under fog only a floor of
168
+ * the count the game uses, so a Reinforcement card in my hand worth more (`r.armies`: the client's figure for
169
+ * the same formula in the same game) is taken instead, labelled "my card's value". `turn` is the turn being
170
+ * played: the latest card was earned on the turn before it.
171
+ */
172
+ export function reinforcementArmiesFor(r, opts) {
173
+ if (!r.progressive)
174
+ return { armies: r.armies };
175
+ const basis = r.progressive.by === 'territories' ? opts.territories : Math.max(0, opts.turn - 1);
176
+ const formula = Math.max(1, roundHalfDown(r.progressive.percentage * basis));
177
+ return r.armies > formula ? { armies: r.armies, basis: "my card's value" } : { armies: formula, basis: 'client formula' };
178
+ }
160
179
  /** #164: GameFeed fog levels that show every territory's owner (No, Light and Dense fog): income is exact. */
161
180
  export const OWNERS_SHOWN_FOG = new Set(['NoFog', 'LightFog', 'ModerateFog']);
181
+ /** A relation that is only a game rule — a Diplomacy card, or a Diplomacy 2 alliance with no agreement recorded. */
182
+ export const ruleOnly = (r) => r.card !== undefined || (r.mod !== undefined && r.agreement === undefined);
162
183
  /** An opponent with at most this many visible territories has its exits listed (#179). */
163
184
  export const FEW_TERRITORIES = 3;
164
185
  /** The most turns {@link EliminateEta} looks ahead. */
@@ -6,18 +6,20 @@
6
6
  import { carriesTeam } from '../../teams.js';
7
7
  import { searchChains } from '../chains.js';
8
8
  import { guaranteedKills } from '../combat.js';
9
+ import { FOG_PLAYER, foggedAttacks, foggedTakes, likelyStackAt } from '../commander-fog.js';
9
10
  import { bfsDistances, neighborsOf } from '../graph.js';
10
11
  import { couldHoldBonusPools, enemyDeployReaching, freeIncome } from '../local-deploy.js';
11
12
  import { incomeBasis, LOST_STACK_TURNS } from '../opponents.js';
12
13
  import { HIDDEN_POOL_INCOMES, MAX_NAMED_REVEALS, coverageText, LOW_COVERAGE, MIN_ENEMY_DEPLOY, openingArmies, ownerShown, visibleState, } from './shared.js';
13
14
  import { gameBaseIncome, territoryIncome } from '../player.js';
14
15
  import { simTerritories } from '../turn-sim.js';
16
+ import { VACATED_FOG_ARMIES } from './vacated.js';
15
17
  import { byNum } from './util.js';
16
18
  /** Read the threats against my territories, and state them. */
17
19
  export function threatsPhase(pc, ps, input, valueOf) {
18
20
  const src = threatSources(pc, ps, input);
19
21
  const forces = threatForces(pc, ps, src, valueOf);
20
- const { borders, facing, borderAt, safeAtStart } = borderThreats(pc, ps, input, src, forces);
22
+ const { borders, facing, borderAt, visibleBorderAt, safeAtStart } = borderThreats(pc, ps, input, src, forces);
21
23
  const { growthOf, deployReaching, reinforcementAt, holdArmies, bombSized, hiddenFoe, hiddenMovable, hiddenPool, } = src;
22
24
  const { chainAt, stacksAt, forceAt, threatAt, nextTurnAt, expectedAt, exposure } = forces;
23
25
  const seen = visibleOpponents(pc, input);
@@ -53,6 +55,7 @@ export function threatsPhase(pc, ps, input, valueOf) {
53
55
  borders,
54
56
  facing,
55
57
  borderAt,
58
+ visibleBorderAt,
56
59
  safeAtStart,
57
60
  };
58
61
  }
@@ -724,7 +727,7 @@ export function threatForces(pc, ps, src, valueOf) {
724
727
  export function borderThreats(pc, ps, input, src, forces) {
725
728
  const { g, board, game: ctx, foe, custom, estimates, incomePrior, incomePriorSkipped, enemyDeploy, territories: state, label, mine, mineSet, armiesOf, unitsAt, uncounted, uncountedKind, bombOn, toTake, turnNow, holdPasses, myCommanders, s, baseIncome, rates, } = pc;
726
729
  const { warnings, rationale } = ps;
727
- const { growthOf, holdArmies, hiddenFoe, lostAt, teamOf, deployReaching, bombSized } = src;
730
+ const { growthOf, holdArmies, hiddenFoe, lostAt, teamOf, deployReaching, bombSized, killsOf, takesAlone } = src;
728
731
  /** #226: the game pays per territory (BonusArmyPer). */
729
732
  const perTerritory = (s.bonusArmyPer ?? 0) > 0;
730
733
  /** #226: what the bonuses it could still hold add to what it could earn (its territories' pay aside). */
@@ -778,7 +781,67 @@ export function borderThreats(pc, ps, input, src, forces) {
778
781
  }
779
782
  return worst;
780
783
  };
784
+ /**
785
+ * Part 5 (mega game, `PlanOptions.foggedAttackers`): my commander's territory `t` against the fog's
786
+ * attackers ({@link foggedAttacks}): the `count` strongest fogged territories within two moves of it, each
787
+ * hiding a player with `stack` armies and my whole income (a what-if `enemyDeploy` as given), striking in
788
+ * turn (#201's separate-attack arithmetic). `undefined` when off or with no fogged territory in reach.
789
+ */
790
+ const fogWorstAt = (t, gone) => {
791
+ const fa = pc.opts.foggedAttackers;
792
+ if (!fa || fa.count <= 0)
793
+ return undefined;
794
+ const view = {
795
+ mine: (x) => mineSet.has(x),
796
+ fogged: (x) => {
797
+ const st = state.get(x);
798
+ if (!st || st.owner.kind === 'unknown')
799
+ return true;
800
+ if (st.armies !== null)
801
+ return false;
802
+ return st.owner.kind !== 'player' || foe(st.owner.playerId);
803
+ },
804
+ armies: (x) => {
805
+ const st = state.get(x);
806
+ return st && st.owner.kind !== 'unknown' ? st.armies : null;
807
+ },
808
+ };
809
+ const deploy = custom ? (enemyDeploy ?? 0) : Math.max(0, pc.income - pc.cardArmies);
810
+ /** #529: a start's armies only on a likely holder; elsewhere the fogged territory's usual estimate. */
811
+ const stackAt = likelyStackAt({
812
+ stack: fa.stack,
813
+ me: pc.me,
814
+ starts: new Set(fa.starts ?? []),
815
+ shownPlayer: (x) => {
816
+ const o = state.get(x)?.owner;
817
+ return o?.kind === 'player' ? o.playerId : undefined;
818
+ },
819
+ lastSeen: pc.opts.lastSeen,
820
+ vacated: pc.vacated,
821
+ vacatedArmies: VACATED_FOG_ARMIES,
822
+ rememberedNeutrals: pc.opts.rememberedNeutrals,
823
+ neutralArmies: s.neutralArmies,
824
+ });
825
+ const all = foggedAttacks(g, view, t, { stack: stackAt, deploy, defensiveKillRate: rates.defensiveKillRate }, gone);
826
+ if (!all.length)
827
+ return undefined;
828
+ const used = all.slice(0, fa.count);
829
+ const joint = used.length > 1 ? (toTake(foggedTakes(used.map((a) => a.armies), used.length, killsOf, takesAlone)) ?? used[0].armies) : used[0].armies;
830
+ const threat = bombSized(t, Math.max(used[0].armies, joint));
831
+ return { threat, fog: { attackers: used.length, territories: used.map((a) => a.territory), stacks: used.map((a) => stackAt(a.territory)), stack: fa.stack, deploy } };
832
+ };
781
833
  const borderAt = (t, gone) => {
834
+ const b = visibleBorderAt(t, gone);
835
+ if (!myCommanders.has(t))
836
+ return b;
837
+ const fw = fogWorstAt(t, gone);
838
+ if (!fw || (b && b.threat >= fw.threat))
839
+ return b;
840
+ if (b)
841
+ return { ...b, threat: fw.threat, fogWorst: fw.fog };
842
+ return { id: t, player: FOG_PLAYER, movable: 0, growth: 0, deploy: fw.fog.deploy, threat: fw.threat, fogWorst: fw.fog };
843
+ };
844
+ const visibleBorderAt = (t, gone) => {
782
845
  // #235: a leader's border whose joint hold does not pay is sized for each opponent alone.
783
846
  const solo = ps.soloHeld.has(t);
784
847
  const f = forceAt(t, gone, { trend: true, allPlayers: true, solo });
@@ -838,6 +901,10 @@ export function borderThreats(pc, ps, input, src, forces) {
838
901
  const b = borderAt(t, () => false);
839
902
  if (b)
840
903
  borders.set(t, b);
904
+ if (b?.fogWorst) {
905
+ const w = b.fogWorst;
906
+ rationale.push(`My commander's territory ${label(t)} is held against the fog too (mega game, part 5), ~${b.threat}: ${w.attackers} unknown opponent${w.attackers === 1 ? '' : 's'} the fog may hide on ${w.territories.map((x, i) => `${label(x)} (${w.stacks[i]})`).join(', ')} (within two moves of it; in brackets the armies each may hold — a start's ${w.stack} only where a start could be or a player was last seen, #529) striking ${w.attackers === 1 ? 'it' : 'it together'}, each plus a whole deploy of ~${w.deploy}.`);
907
+ }
841
908
  if (b?.commanderWorst) {
842
909
  const w = b.commanderWorst;
843
910
  rationale.push(`My commander's territory ${label(t)} is held against the worst case (#274), ~${b.threat}: ${w.players.length > 1 ? `players ${w.players.join(' and ')}` : `player ${w.players[0]}`}'s whole deploy, ~${w.deploy} (never below my own income), plus the ${w.stacks} movable armies ${w.players.length > 1 ? 'they have' : 'it has'} within two moves of it.`);
@@ -1015,13 +1082,14 @@ export function borderThreats(pc, ps, input, src, forces) {
1015
1082
  : `Player ${p}'s Reinforcement card is taken as played on turn ${e.cardPlayed} (a deployment of a card's armies over its visible income), so none is added until the next can be due; income the fog hides can look the same, so it may still hold one and the estimate errs low.`);
1016
1083
  // #164: the income behind the estimate; a card the clock adds is named on top of it.
1017
1084
  const income = e.estimate - (e.card?.armies ?? 0);
1018
- // G2 (D3): Sanctions on it the decoder is sure of — applied to a figure read off the board only.
1085
+ // G2 (D3): Sanctions on it the decoder is sure of — every income figure cut, unless read from deploys under the card.
1019
1086
  if (e.sanctioned) {
1020
1087
  const z = e.sanctioned;
1021
1088
  const pct = z.percentages.map((x) => `${Math.round(x * 100)}%`).join(' then ');
1089
+ const range = z.applied && e.thinEvidence ? ` (its range ~${e.thinEvidence.lower}–${e.thinEvidence.upper})` : '';
1022
1090
  warnings.push(z.applied
1023
- ? `Player ${p} is under Sanctions (${pct}, until turn ${z.untilTurn}, read from the board by an unverified decoder): its estimate is cut from ~${z.before} to ~${income} by the client's rule.`
1024
- : `Player ${p} is under Sanctions (${pct}, until turn ${z.untilTurn}, read from the board by an unverified decoder), but its estimate ~${income} is not cut: ${e.source === 'prior' ? 'it is a prior, a floor guessed from what it could earn, not its income' : `it is ${e.source} from its deploys, which may already carry the cut`}.`);
1091
+ ? `Player ${p} is under Sanctions (${pct}, until turn ${z.untilTurn}, read from the board by an unverified decoder): its estimate is cut from ~${z.before} to ~${income}${range} by the client's rule.`
1092
+ : `Player ${p} is under Sanctions (${pct}, until turn ${z.untilTurn}, read from the board by an unverified decoder): its estimate ~${income} is not cut again, since it was read from deploys made under the card${z.fromTurn !== undefined ? ` (from turn ${z.fromTurn})` : ''}, which already carry the cut.`);
1025
1093
  }
1026
1094
  // #332: a commerce game's rising army price, applied to a figure read off the board.
1027
1095
  if (e.armyPrice)
@@ -1111,6 +1179,7 @@ export function borderThreats(pc, ps, input, src, forces) {
1111
1179
  borders,
1112
1180
  facing,
1113
1181
  borderAt,
1182
+ visibleBorderAt,
1114
1183
  safeAtStart,
1115
1184
  };
1116
1185
  }
@@ -8,6 +8,8 @@
8
8
  // terms, the outcome (kept, ended with notice and whether it was honoured, broken by them or by
9
9
  // me), the break turn and the strongest breach flag my boards showed, the context at the break
10
10
  // (endgame, who led, outgrowing), whether they retaliated and whether they proposed again;
11
+ // - partner-approved exceptions (attacks the partner agreed to, either way) are no break: counted apart
12
+ // (`exceptionsMine` / `exceptionsTheirs`, and per entry), never in the outcome;
11
13
  // - tallies (`RecordCounts`), each moved once by the recorded transition that earns it
12
14
  // (`recordDelta`), so recording the same agreement again never counts it twice, and an entry
13
15
  // dropped past the bound still counts.
@@ -59,6 +61,7 @@ export function recordEntryFor(a, input, previous) {
59
61
  ...outcomeOf(a),
60
62
  ...(previous?.proposedAgain ? { proposedAgain: true } : {}),
61
63
  ...(a.retaliated !== undefined ? { retaliated: a.retaliated } : {}),
64
+ ...(a.exceptions?.length ? { exceptions: exceptionCounts(a) } : {}),
62
65
  updated: input.now,
63
66
  };
64
67
  if (a.status === 'broken-by-them' || a.status === 'broken-by-me') {
@@ -76,8 +79,23 @@ export function upsertEntry(entries, entry) {
76
79
  const rest = entries.filter((e) => e.key !== entry.key);
77
80
  return [...rest, entry].sort(byUpdated).slice(-MAX_RECORD_ENTRIES);
78
81
  }
79
- export const ZERO_COUNTS = Object.freeze({ made: 0, kept: 0, endedWithNotice: 0, brokenByThem: 0, brokenByMe: 0 });
82
+ export const ZERO_COUNTS = Object.freeze({
83
+ made: 0,
84
+ kept: 0,
85
+ endedWithNotice: 0,
86
+ brokenByThem: 0,
87
+ brokenByMe: 0,
88
+ exceptionsMine: 0,
89
+ exceptionsTheirs: 0,
90
+ });
80
91
  export const COUNT_KEYS = Object.keys(ZERO_COUNTS);
92
+ /** The tallies every stored version carries; the exception tallies came later and read as 0 when absent. */
93
+ export const CORE_COUNT_KEYS = ['made', 'kept', 'endedWithNotice', 'brokenByThem', 'brokenByMe'];
94
+ /** `a`'s exceptions counted by direction. */
95
+ function exceptionCounts(a) {
96
+ const list = a.exceptions ?? [];
97
+ return { mine: list.filter((e) => e.direction === 'mine').length, theirs: list.filter((e) => e.direction === 'theirs').length };
98
+ }
81
99
  const OUTCOME_COUNT = {
82
100
  kept: 'kept',
83
101
  'ended-with-notice': 'endedWithNotice',
@@ -98,6 +116,16 @@ export function recordDelta(before, after) {
98
116
  if (key)
99
117
  delta[key] = 1;
100
118
  }
119
+ // Each exception once, by its id: one already on `before` is not counted again.
120
+ const had = new Set((before?.exceptions ?? []).map((e) => e.id));
121
+ for (const e of after.exceptions ?? []) {
122
+ if (had.has(e.id))
123
+ continue;
124
+ if (e.direction === 'mine')
125
+ delta.exceptionsMine++;
126
+ else
127
+ delta.exceptionsTheirs++;
128
+ }
101
129
  return delta;
102
130
  }
103
131
  export const isZero = (c) => COUNT_KEYS.every((k) => c[k] === 0);
@@ -116,6 +144,8 @@ export function talliesOf(entries) {
116
144
  const key = OUTCOME_COUNT[e.outcome];
117
145
  if (key)
118
146
  out[key]++;
147
+ out.exceptionsMine += e.exceptions?.mine ?? 0;
148
+ out.exceptionsTheirs += e.exceptions?.theirs ?? 0;
119
149
  }
120
150
  return out;
121
151
  }
@@ -112,11 +112,10 @@ export function incomeRules(settings) {
112
112
  * the game uses is modelled (base, BonusArmyPer, held bonuses, card armies,
113
113
  * overridden bonus values once read — only unreadable overrides are listed).
114
114
  * Cities and per-player income mods have no known settings key, so they are
115
- * not detected: those games still get the hard deploy-total check. Sanctions is
116
- * flagged when the card is merely enabled: the live board's active-card decoder is
117
- * unverified (#163), so the model cannot be sure whether I am sanctioned this turn
118
- * (docs/WARAPP-API.md, the trade-off). With `sanctionsApplied` (PLAN-TEAMS D3: the
119
- * income already carries the Sanctions read on me) the reason says so instead. An army cap is
115
+ * not detected: those games still get the hard deploy-total check. Sanctions are a reason only
116
+ * when they are on me and their cut is not modelled (`sanctionsUnmodelled`: under Local Deployment,
117
+ * where the pools the cut comes from are unknown); an enabled card nobody played on me, or Sanctions
118
+ * on me that the income already carries (PLAN-TEAMS D3), are none. An army cap is
120
119
  * modelled ({@link armyCapIncome}, #253) and verified by six live cases, yet stays listed (where the
121
120
  * card armies and Local Deployment's pools fall is not verified): with
122
121
  * `armyCap` (the figure the caller applied) the reason states its arithmetic.
@@ -134,15 +133,29 @@ export function incomeUncertainties(settings, opts = {}) {
134
133
  // Overrides that were read are applied to the map (applyBonusOverrides), so only unreadable ones make income uncertain.
135
134
  if (settings?.overriddenBonusesUnparsed)
136
135
  out.push(OVERRIDES_UNPARSED);
137
- if (settings?.cards.includes('Sanctions')) {
138
- const pct = settings.raw?.SanctionsCard;
136
+ // Owner spec 2026-11-23: the Sanctions on me are modelled (the income carries the cut), so the card is no
137
+ // reason to doubt the income — only Sanctions on me whose cut the model could not apply are.
138
+ if (opts.sanctionsUnmodelled) {
139
+ const pct = settings?.raw?.SanctionsCard;
139
140
  const p = isRecord(pct) && typeof pct.Percentage === 'number' ? ` by ${Math.round(pct.Percentage * 100)}%` : '';
140
- out.push(opts.sanctionsApplied
141
- ? `the Sanctions on you${p} are applied as read from the board by an unverified decoder (#163).`
142
- : `This game has the Sanctions card, which cuts a sanctioned player's income${p}; the model does not apply it.`);
141
+ out.push(`Sanctions are on you, which cut your income${p}; the model does not apply the cut here (Local Deployment).`);
143
142
  }
144
143
  return out;
145
144
  }
145
+ /**
146
+ * warapp_submit_turn only: a game with the Sanctions card and none read on me this turn. The board's
147
+ * active-card reader is unverified (#163), so a deploy total below the model still warns there rather
148
+ * than refuses. Not an income doubt for warapp_plan_turn (it plans on the Sanctions it reads).
149
+ */
150
+ export function unreadSanctionsUncertainty(settings, opts) {
151
+ if (!settings?.cards.includes('Sanctions') || opts.sanctionsOnMe)
152
+ return [];
153
+ const pct = settings.raw?.SanctionsCard;
154
+ const p = isRecord(pct) && typeof pct.Percentage === 'number' ? ` by ${Math.round(pct.Percentage * 100)}%` : '';
155
+ return [
156
+ `This game has the Sanctions card, which cuts a sanctioned player's income${p}; none is read on you this turn, but the board's active-card reader is unverified, so a lower total is not refused.`,
157
+ ];
158
+ }
146
159
  /**
147
160
  * Why warapp_submit_turn's deploy-total check must warn rather than refuse: the income
148
161
  * uncertainties plus, while the overrides' shape is unverified, a game's overrides.
@@ -1,7 +1,7 @@
1
1
  import { carriesTeam, teammatesOf } from '../teams.js';
2
2
  import { bonusTerritories } from './bonuses.js';
3
3
  import { bfsDistances, neighborsOf } from './graph.js';
4
- import { ownerShown, OWNERS_SHOWN_FOG, visibleState, } from './plan/shared.js';
4
+ import { ownerShown, OWNERS_SHOWN_FOG, visibleState, ruleOnly, } from './plan/shared.js';
5
5
  import { planTurn } from './planner.js';
6
6
  /** Every status an agreement can be recorded in. */
7
7
  export const AGREEMENT_STATUSES = [
@@ -44,6 +44,36 @@ export const TACIT_QUIET_TURNS = 3;
44
44
  * and the partner's. The partner no longer needs me from there on.
45
45
  */
46
46
  export const TRUCE_ENDGAME_RATIO = 0.5;
47
+ /**
48
+ * Who an exception lets attack: `mine` — the partner agreed I may attack its covered territories;
49
+ * `theirs` — I agreed the partner may attack (or take) covered territories of mine.
50
+ */
51
+ export const EXCEPTION_DIRECTIONS = ['mine', 'theirs'];
52
+ /** Exceptions kept per agreement (the newest). */
53
+ export const MAX_EXCEPTIONS = 50;
54
+ /** The longest note an exception keeps (the owner's own words, names scrubbed). */
55
+ export const MAX_EXCEPTION_NOTE = 200;
56
+ /** The next exception id on `a`: `e1`, `e2`, … */
57
+ export function nextExceptionId(a) {
58
+ const n = (a.exceptions ?? []).reduce((m, e) => Math.max(m, Number(/^e(\d+)$/.exec(e.id)?.[1] ?? 0)), 0);
59
+ return `e${n + 1}`;
60
+ }
61
+ /** `a` with `exceptions` appended (fresh ids), at most {@link MAX_EXCEPTIONS} kept (the newest). */
62
+ export function withExceptions(a, exceptions) {
63
+ let next = a;
64
+ for (const e of exceptions)
65
+ next = { ...next, exceptions: [...(next.exceptions ?? []), { id: nextExceptionId(next), ...e }] };
66
+ return next.exceptions && next.exceptions.length > MAX_EXCEPTIONS ? { ...next, exceptions: next.exceptions.slice(-MAX_EXCEPTIONS) } : next;
67
+ }
68
+ /** The territories `a`'s exceptions in `direction` open on `turn` (the turn's orders), ascending. */
69
+ export function exceptedOn(a, turn, direction) {
70
+ const out = new Set();
71
+ for (const e of a.exceptions ?? [])
72
+ if (e.direction === direction && e.fromTurn <= turn && turn <= e.toTurn)
73
+ for (const t of e.territories)
74
+ out.add(t);
75
+ return out;
76
+ }
47
77
  const byNum = (a, b) => a - b;
48
78
  const alive = (p) => p !== undefined && (p.state === undefined || p.state === 'Playing');
49
79
  const turnedAI = (p) => p.isAI === true || p.humanTurnedIntoAI === true;
@@ -234,7 +264,8 @@ function fedByHitSource(t, orders, mine, was, now, me) {
234
264
  * leaves ambiguous;
235
265
  * - `outgrowing`: its income passed {@link TRUCE_OUTGROW_RATIO} × mine;
236
266
  * - `kept`: the consecutive quiet turns up to the newest board (when nothing broke).
237
- * A proposal that was never agreed has no flags.
267
+ * A covered territory under a `theirs` exception on a turn (the partner may attack it by agreement) raises
268
+ * nothing that turn. A proposal that was never agreed has no flags.
238
269
  */
239
270
  export function breachWatch(input) {
240
271
  const { agreement: a, graph, me } = input;
@@ -261,7 +292,11 @@ export function breachWatch(input) {
261
292
  const taken = [];
262
293
  const attacked = [];
263
294
  const ambiguous = [];
295
+ // A `theirs` exception on this turn: the partner may attack or take these by agreement — no event.
296
+ const allowed = exceptedOn(a, from.turn, 'theirs');
264
297
  for (const c of covered) {
298
+ if (allowed.has(c))
299
+ continue;
265
300
  const after = now.get(c);
266
301
  const shown = ownerShown(after);
267
302
  const neighbours = neighborsOf(graph, c);
@@ -518,7 +553,8 @@ const WATCH_KINDS = ['broken', 'cap-exceeded', 'massing', 'outgrowing'];
518
553
  /**
519
554
  * B2 (warapp_submit_turn): the active or in-notice agreements that `moves` would break — an order that
520
555
  * attacks a territory the partner holds on `board` and the terms cover (a transfer-only order attacks
521
- * nothing), or a Bomb (`bombs`, the targets) on such a territory. By agreement id; empty when nothing binds. Pure; reads only the ledger's own agreements and
556
+ * nothing), or a Bomb (`bombs`, the targets) on such a territory — except one a `mine` exception opens on `turn`
557
+ * (the partner agreed to it). By agreement id; empty when nothing binds. Pure; reads only the ledger's own agreements and
522
558
  * the board (the breach watch is not consulted: a break by them is recorded as broken-by-them first).
523
559
  */
524
560
  export function truceBreaksIn(input) {
@@ -530,7 +566,9 @@ export function truceBreaksIn(input) {
530
566
  if (state.phase !== 'active' && state.phase !== 'notice')
531
567
  continue;
532
568
  const held = new Set(input.board.territories.filter((t) => ownerShown(t) && ownerOn(t) === a.with).map((t) => t.territoryId));
533
- const covered = new Set(coveredTerritories(input.graph, a.terms.scope, held));
569
+ // A `mine` exception on this turn: the partner agreed to these attacks — no break.
570
+ const allowed = exceptedOn(a, input.turn, 'mine');
571
+ const covered = new Set(coveredTerritories(input.graph, a.terms.scope, held).filter((t) => !allowed.has(t)));
534
572
  const moves = input.moves.flatMap((m, index) => (m.mode !== 'transfer-only' && covered.has(m.to) ? [{ index, from: m.from, to: m.to }] : []));
535
573
  const bombs = (input.bombs ?? []).flatMap((target, index) => (covered.has(target) ? [{ index, target }] : []));
536
574
  if (moves.length || bombs.length)
@@ -566,10 +604,21 @@ export function planRelationsFrom(input) {
566
604
  if (endgame)
567
605
  watch.push('endgame');
568
606
  const broke = flags.find((f) => f.kind === 'broken' && !f.ambiguous);
607
+ // Partner-approved exceptions on this turn: those territories are no longer covered (normal targets
608
+ // for me, or open to the partner), and the plan lists them.
609
+ const exceptMine = exceptedOn(a, turn, 'mine');
610
+ const exceptTheirs = exceptedOn(a, turn, 'theirs');
611
+ const coveredMine = coveredTerritories(graph, a.terms.scope, mine);
612
+ const coveredTheirs = coveredTerritories(graph, a.terms.scope, holding(a.with));
613
+ const exceptions = [
614
+ { direction: 'mine', territories: coveredTheirs.filter((t) => exceptMine.has(t)) },
615
+ { direction: 'theirs', territories: coveredMine.filter((t) => exceptTheirs.has(t)) },
616
+ ].filter((e) => e.territories.length);
569
617
  relations.push({
570
618
  player: a.with,
571
- coveredMine: coveredTerritories(graph, a.terms.scope, mine),
572
- coveredTheirs: coveredTerritories(graph, a.terms.scope, holding(a.with)),
619
+ coveredMine: coveredMine.filter((t) => !exceptTheirs.has(t)),
620
+ coveredTheirs: coveredTheirs.filter((t) => !exceptMine.has(t)),
621
+ ...(exceptions.length ? { exceptions } : {}),
573
622
  state: broke ? 'broken' : state.phase,
574
623
  ...(state.endsTurn !== undefined ? { endsTurn: state.endsTurn } : {}),
575
624
  ...(a.terms.borderCap !== undefined ? { borderCap: a.terms.borderCap } : {}),
@@ -584,6 +633,29 @@ export function planRelationsFrom(input) {
584
633
  : {}),
585
634
  });
586
635
  }
636
+ // T9: the Diplomacy 2 mod's alliances, a game rule like a card: enforced this turn whatever the ledger says.
637
+ for (const player of [...new Set(input.modAllies ?? [])].sort((x, y) => x - y)) {
638
+ if (player === me)
639
+ continue;
640
+ const bound = relations.filter((r) => r.player === player && (r.state === 'active' || r.state === 'notice'));
641
+ for (const r of bound) {
642
+ r.enforced = true;
643
+ r.enforcedUntil = turn + 1;
644
+ r.mod = 'Diplomacy 2';
645
+ }
646
+ if (bound.length)
647
+ continue;
648
+ relations.push({
649
+ player,
650
+ coveredMine: [...mine].sort((x, y) => x - y),
651
+ coveredTheirs: [...holding(player)].sort((x, y) => x - y),
652
+ state: 'active',
653
+ trust: 'clear',
654
+ enforced: true,
655
+ enforcedUntil: turn + 1,
656
+ mod: 'Diplomacy 2',
657
+ });
658
+ }
587
659
  // D3 (T9): the Diplomacy cards in effect. A card is a game rule, not a promise: it binds whatever the ledger says.
588
660
  for (const d of [...(input.diplomacy ?? [])].sort((x, y) => x.player - y.player)) {
589
661
  if (d.player === me || d.untilTurn <= turn)
@@ -591,7 +663,8 @@ export function planRelationsFrom(input) {
591
663
  const bound = relations.filter((r) => r.player === d.player && (r.state === 'active' || r.state === 'notice'));
592
664
  for (const r of bound) {
593
665
  r.enforced = true;
594
- r.enforcedUntil = d.untilTurn;
666
+ // A mod alliance enforcing it already: the card keeps it at least as long.
667
+ r.enforcedUntil = r.enforcedUntil !== undefined ? Math.max(r.enforcedUntil, d.untilTurn) : d.untilTurn;
595
668
  }
596
669
  if (bound.length)
597
670
  continue;
@@ -710,7 +783,8 @@ export function priceTruce(input, player, terms, opts = {}) {
710
783
  trust: 'clear',
711
784
  enforced: true,
712
785
  ...(enforcing.enforcedUntil !== undefined ? { enforcedUntil: enforcing.enforcedUntil } : {}),
713
- card: 'Diplomacy',
786
+ // A Diplomacy 2 alliance binds like a card, with or without the deal.
787
+ ...(enforcing.mod && !enforcing.card ? { mod: enforcing.mod } : { card: 'Diplomacy' }),
714
788
  },
715
789
  ]
716
790
  : [];
@@ -723,7 +797,7 @@ export function priceTruce(input, player, terms, opts = {}) {
723
797
  const coveredTheirs = coveredTerritories(input.graph, terms.scope, holding(player));
724
798
  // The board's reading of a recorded truce with this player (planRelationsFrom) is kept: words
725
799
  // never clear a flag, and a price never trusts more than warapp_plan_turn does (PLAN-TEAMS §4).
726
- const standing = (input.relations ?? []).find((r) => r.player === player && !r.card);
800
+ const standing = (input.relations ?? []).find((r) => r.player === player && !ruleOnly(r));
727
801
  const watch = [...new Set([...(standing?.watch ?? []), ...(opts.watch ?? [])])];
728
802
  const trusted = standing?.trust === 'watch' || opts.trust === 'watch' ? 'watch' : 'clear';
729
803
  const state = standing?.state ?? 'active';
@@ -0,0 +1,71 @@
1
+ // Scale (mega games, ~100 players): which opponents a tool estimates one by one, and a summary of the rest.
2
+ // A game with more than LARGE_GAME_OPPONENTS opponents still playing is "large": its per-opponent estimates,
3
+ // rows and lists keep only the players near me — in view (fog shows their land) or holding land within
4
+ // NEAR_STEPS steps of mine — and the others are counted. Every other game is unchanged (no scope at all).
5
+ // Pure and deterministic.
6
+ import { neighborsOf } from './graph.js';
7
+ /** More opponents still playing than this makes a game large (a 1v1, a team game or an ordinary free-for-all never is). */
8
+ export const LARGE_GAME_OPPONENTS = 16;
9
+ /** A player holding land this many steps from mine, or fewer, is near. */
10
+ export const NEAR_STEPS = 2;
11
+ /**
12
+ * The players (never `me`) near my land on `board`: each holding a territory within `steps` steps of one of
13
+ * mine, and, under fog (some territory's owner hidden), each whose land is in view anywhere (a card's vision,
14
+ * say). Without fog every owner is in view, so only the steps count.
15
+ */
16
+ export function nearPlayers(g, board, me, steps = NEAR_STEPS) {
17
+ const owner = new Map();
18
+ let fogged = false;
19
+ for (const t of board.territories) {
20
+ if (t.owner.kind === 'player')
21
+ owner.set(t.territoryId, t.owner.playerId);
22
+ else if (t.owner.kind === 'unknown')
23
+ fogged = true;
24
+ }
25
+ const out = new Set();
26
+ let frontier = [...owner].filter(([, p]) => p === me).map(([t]) => t);
27
+ const seen = new Set(frontier);
28
+ for (let d = 0; d < steps && frontier.length; d++) {
29
+ const next = [];
30
+ for (const t of frontier)
31
+ for (const n of neighborsOf(g, t)) {
32
+ if (seen.has(n))
33
+ continue;
34
+ seen.add(n);
35
+ next.push(n);
36
+ const p = owner.get(n);
37
+ if (p !== undefined && p !== me)
38
+ out.add(p);
39
+ }
40
+ frontier = next;
41
+ }
42
+ if (fogged)
43
+ for (const p of owner.values())
44
+ if (p !== me)
45
+ out.add(p);
46
+ return out;
47
+ }
48
+ /** The scope over `opponents` (teammates and me already left out): every one unless the game is large. */
49
+ export function opponentScope(g, board, me, opponents) {
50
+ const ids = [...new Set(opponents)].filter((p) => p !== me).sort((a, b) => a - b);
51
+ if (ids.length <= LARGE_GAME_OPPONENTS)
52
+ return { large: false, near: ids, far: [] };
53
+ const near = nearPlayers(g, board, me);
54
+ return { large: true, near: ids.filter((p) => near.has(p)), far: ids.filter((p) => !near.has(p)) };
55
+ }
56
+ export const FAR_NOTE = `A large game (more than ${LARGE_GAME_OPPONENTS} opponents): only the opponents in view or holding land within ` +
57
+ `${NEAR_STEPS} steps of yours are estimated one by one; the rest are summed here. Their estimates are priors (the fog ` +
58
+ 'hides them), so the sum is a scale, not a threat: none of them can reach your land this turn.';
59
+ export function farSummary(far, estimateOf) {
60
+ let sum = null;
61
+ let biggest = null;
62
+ for (const p of far) {
63
+ const e = estimateOf(p);
64
+ if (e === undefined)
65
+ continue;
66
+ sum = (sum ?? 0) + e;
67
+ if (!biggest || e > biggest.deploy)
68
+ biggest = { player: p, deploy: e };
69
+ }
70
+ return { count: far.length, estimatedDeploy: sum, biggest, note: FAR_NOTE };
71
+ }