@chrischall/warapp-mcp 0.13.1 → 0.15.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 (58) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/README.md +9 -6
  4. package/dist/analysis/airlift-plan.js +288 -0
  5. package/dist/analysis/blockade-plan.js +178 -0
  6. package/dist/analysis/bomb-plan.js +72 -0
  7. package/dist/analysis/card-threats.js +10 -9
  8. package/dist/analysis/cards-in-effect.js +20 -0
  9. package/dist/analysis/combat.js +5 -0
  10. package/dist/analysis/coordination.js +47 -0
  11. package/dist/analysis/income-calibration.js +280 -0
  12. package/dist/analysis/intel.js +1 -1
  13. package/dist/analysis/lookahead.js +4 -0
  14. package/dist/analysis/opponents.js +52 -3
  15. package/dist/analysis/plan/deploy-estimates.js +1 -1
  16. package/dist/analysis/plan/estimates.js +40 -6
  17. package/dist/analysis/plan/relations.js +57 -8
  18. package/dist/analysis/plan/threats.js +1 -1
  19. package/dist/analysis/player-record.js +1 -0
  20. package/dist/analysis/relations.js +40 -0
  21. package/dist/analysis/stress.js +42 -2
  22. package/dist/analysis/turn-sim.js +62 -0
  23. package/dist/bundle.js +24486 -21811
  24. package/dist/card-state.js +157 -0
  25. package/dist/decision-log.js +44 -5
  26. package/dist/local-time.js +142 -0
  27. package/dist/relations-store.js +30 -5
  28. package/dist/tools/airlift-readback.js +87 -0
  29. package/dist/tools/alternative-orders.js +21 -0
  30. package/dist/tools/begin-turn.js +19 -5
  31. package/dist/tools/calibration-harness.js +102 -0
  32. package/dist/tools/calibration.js +110 -0
  33. package/dist/tools/card-advice.js +5 -4
  34. package/dist/tools/card-plays.js +32 -20
  35. package/dist/tools/card-state-view.js +26 -0
  36. package/dist/tools/card-support-advice.js +25 -8
  37. package/dist/tools/chat-inbox.js +1 -1
  38. package/dist/tools/chat.js +1 -1
  39. package/dist/tools/check-plan.js +113 -9
  40. package/dist/tools/common.js +14 -0
  41. package/dist/tools/decision-capture.js +14 -1
  42. package/dist/tools/game.js +11 -2
  43. package/dist/tools/index.js +13 -1
  44. package/dist/tools/notifications.js +1 -1
  45. package/dist/tools/opponents.js +2 -0
  46. package/dist/tools/player-card-readback.js +45 -0
  47. package/dist/tools/relations.js +146 -14
  48. package/dist/tools/sanctions-played.js +51 -0
  49. package/dist/tools/stress-opponents.js +8 -4
  50. package/dist/tools/turn-history.js +214 -0
  51. package/dist/tools/turn.js +504 -20
  52. package/dist/turn-orders.js +64 -0
  53. package/dist/version.js +1 -1
  54. package/manifest.json +17 -2
  55. package/mint.yaml +7 -0
  56. package/package.json +1 -1
  57. package/server.json +8 -2
  58. package/skills/warapp-mcp/SKILL.md +9 -1
@@ -11,7 +11,7 @@ import { z } from 'zod';
11
11
  import { boardIncome, incomeRules, trackGame, trackOpponents } from '../analysis/index.js';
12
12
  import { agreementChange } from '../analysis/commitments.js';
13
13
  import { playerRecord, recordDelta, recordEntryFor } from '../analysis/player-record.js';
14
- import { AGREEMENT_STATUSES, agreementState, breachWatch, EXCEPTION_DIRECTIONS, MAX_EXCEPTION_NOTE, MAX_NOTICE_TURNS, newAgreement, OPENING_STATUSES, partyRefusal, scopeRefusal, tacitTruces, TERMINAL_STATUSES, transitionAgreement, TRUCE_OUTGROW_RATIO, trust, truceEndgame, withExceptions, } from '../analysis/relations.js';
14
+ import { AGREEMENT_STATUSES, agreementState, breachWatch, capSelfCheck, EXCEPTION_DIRECTIONS, MAX_CAPS, MAX_EXCEPTION_NOTE, MAX_NOTICE_TURNS, newAgreement, OPENING_STATUSES, partyRefusal, scopeRefusal, tacitTruces, TERMINAL_STATUSES, transitionAgreement, TRUCE_OUTGROW_RATIO, trust, truceEndgame, withCaps, withExceptions, } from '../analysis/relations.js';
15
15
  import { AVOID_REASONS, emptyIntel, INCOME_STALE_TURNS, intelIsEmpty } from '../analysis/intel.js';
16
16
  import { boardStateFromLive } from '../live.js';
17
17
  import { entryKey, legacyEntryKey, playerRecordEnabled, playerRecordState, readPlayerRecord, updatePlayerRecord } from '../player-record-store.js';
@@ -29,6 +29,7 @@ import { resolveBonus, resolvePlayer, resolveTerritory } from './resolve.js';
29
29
  import { boardHistory, plannerSettings } from './turn.js';
30
30
  import { captureObservation } from './decision-capture.js';
31
31
  import { scrubNames } from '../decision-log.js';
32
+ import { coordinationDue, MAX_COORDINATION_NOTE, nextCoordinationId } from '../analysis/coordination.js';
32
33
  import { resolveTeamsFor } from './team-source.js';
33
34
  const VIEWS = ['compact', 'full'];
34
35
  const MAX_SCOPE_ITEMS = 200;
@@ -180,9 +181,40 @@ function agreementView(a, game, map, turn, rung) {
180
181
  })),
181
182
  }
182
183
  : {}),
184
+ ...(a.caps?.length
185
+ ? {
186
+ caps: a.caps.map((c) => ({
187
+ territory: name(c.territory),
188
+ max: c.max,
189
+ addedTurn: c.addedTurn,
190
+ ...(c.note !== undefined ? { note: untrustedText(c.note) } : {}),
191
+ })),
192
+ }
193
+ : {}),
183
194
  ...(rung === 'full' ? { history: a.history } : {}),
184
195
  };
185
196
  }
197
+ /** A coordination as a result shows it: players by id with a delimited name, territories by id and name. */
198
+ export function coordinationView(c, game, map, turn) {
199
+ const name = namer(map);
200
+ const player = (id) => {
201
+ const p = game.players.find((x) => x.id === id);
202
+ return { id, name: p ? untrustedText(p.name) : null };
203
+ };
204
+ return {
205
+ id: c.id,
206
+ with: player(c.with),
207
+ target: player(c.target),
208
+ mine: c.mine.map(name),
209
+ theirs: c.theirs.map(name),
210
+ ...(c.turn !== undefined ? { turn: c.turn } : {}),
211
+ open: c.doneTurn === undefined,
212
+ due: coordinationDue(c, turn),
213
+ recordedTurn: c.recordedTurn,
214
+ ...(c.doneTurn !== undefined ? { doneTurn: c.doneTurn } : {}),
215
+ ...(c.note !== undefined ? { note: untrustedText(c.note) } : {}),
216
+ };
217
+ }
186
218
  /** An exception's note as stored: trimmed, player names scrubbed (`Player <id>`), capped; absent when empty. */
187
219
  export function exceptionNote(note, game) {
188
220
  const t = note?.trim();
@@ -398,10 +430,11 @@ export function registerRelationsTools(server, ctx, opts = {}) {
398
430
  'its state this turn (`proposed`, `active`, in `notice` with the turn it ends, or `over` and why: ended, broken, ' +
399
431
  'the partner eliminated or turned AI, only two players left, its end condition met, its notice run), and for a ' +
400
432
  'live one: watch `flags` from your own board history — `broken` (the partner took or attacked a covered territory ' +
401
- 'of yours — not one a `theirs` exception you recorded allowed that turn), `cap-exceeded` (a partner stack on the covered border above the agreed cap), `massing` (its visible ' +
433
+ 'of yours — not one a `theirs` exception you recorded allowed that turn), `cap-exceeded` (a partner stack on the covered border above the agreed cap; with `by: "me"`, a stack of yours above a territory cap you promised — never counted in the trust), `massing` (its visible ' +
402
434
  'armies near the covered border grew two turns running, or an event the fog leaves ambiguous), `outgrowing` (its ' +
403
435
  `estimated income above ${TRUCE_OUTGROW_RATIO}× yours) and \`kept\` (quiet turns) — and \`trust\`: \`clear\`, or \`watch\` ` +
404
436
  'on any flag but kept, on their notice, and in the endgame (no other opponent still a match for either of you). ' +
437
+ 'Also `coordination`: the joint attacks recorded with warapp_record_agreement (open, due this turn, or done). ' +
405
438
  'Also `tacit`: neighbours with no agreement whose shared border stayed quiet three turns or more — reported, never ' +
406
439
  "relied on. The cross-game player record (on unless WARAPP_PLAYER_RECORD=off, local and hosted) gives each partner's " +
407
440
  '`record`: how it kept earlier agreements — tallies, a kept rate, its notices honoured or broken, its breaks in ' +
@@ -468,7 +501,8 @@ export function registerRelationsTools(server, ctx, opts = {}) {
468
501
  const endgame = live_ ? endgameOf(incomes, a.with) : null;
469
502
  agreements.push({
470
503
  agreement: a,
471
- flags,
504
+ // My own stack above a cap I promised: shown beside the partner's flags, never in its trust.
505
+ flags: live_ ? [...flags, ...capSelfCheck(a, boards, me.id)] : flags,
472
506
  ...(live_ ? { trust: trust(a, flags, { endgame: endgame === true }), endgame } : {}),
473
507
  ...(await recordFor(ctx.dataDir, a.with, env)),
474
508
  });
@@ -506,6 +540,7 @@ export function registerRelationsTools(server, ctx, opts = {}) {
506
540
  ...(rung === 'full' && x.entries ? { recordEntries: x.entries.map(entryView) } : {}),
507
541
  })),
508
542
  tacit: tacit.map((t) => ({ player: playerName(t.player), quietTurns: t.quietTurns, border: t.border.map(name) })),
543
+ ...(ledger.coordination?.length ? { coordination: ledger.coordination.map((c) => coordinationView(c, game, map, turn)) } : {}),
509
544
  ...(modView ? { modAlliances: modView } : {}),
510
545
  boards: { turns: boards.map((b) => b.turn).sort((a, b) => a - b), live },
511
546
  incomes: { mine: incomes.mine, opponents: Object.fromEntries(incomes.opponents) },
@@ -515,7 +550,7 @@ export function registerRelationsTools(server, ctx, opts = {}) {
515
550
  });
516
551
  server.registerTool('warapp_record_agreement', {
517
552
  title: 'Record an agreement in a war.app game',
518
- _meta: mintMeta('change', ['record a truce', 'we agreed a truce', 'they broke the truce', 'give notice', 'truce exception']),
553
+ _meta: mintMeta('change', ['record a truce', 'we agreed a truce', 'they broke the truce', 'give notice', 'truce exception', 'coordinated attack', 'promise a territory cap']),
519
554
  description: untrustedDescription('Record a truce you made, proposed or received in a war.app (Warzone) free-for-all, or a change to one, in this ' +
520
555
  "machine's agreement ledger. Nothing is sent to war.app or to any player (so there is no confirmation " +
521
556
  'step): it records what was agreed, so warapp_get_relations can watch the board for it. Create one with ' +
@@ -530,7 +565,15 @@ export function registerRelationsTools(server, ctx, opts = {}) {
530
565
  '(mine: the partner agreed I may attack its covered territories there — warapp_plan_turn targets them and ' +
531
566
  'warapp_submit_turn sends the attack without break_agreement; theirs: I agreed it may attack or take mine — ' +
532
567
  'warapp_get_relations raises no `broken` flag for it) and an optional `note` (player names scrubbed). The player ' +
533
- 'record counts exceptions apart from breaks. An agreement exists only because you record it here: chat is never read ' +
568
+ 'record counts exceptions apart from breaks. `caps` amends a proposed, agreed or in-notice truce without rewriting ' +
569
+ 'its terms: each `{territory, max, note?}` promises at most `max` of your armies on that territory (dated; again ' +
570
+ 'on the same territory replaces it), and `caps_remove` lifts one — warapp_plan_turn keeps it like the border cap ' +
571
+ '(the excess one step back, a warning when its hold needs more), warapp_check_plan warns when orders exceed it, ' +
572
+ 'and warapp_get_relations flags your own stack above it. ' +
573
+ '`coordination` records a joint attack agreed with the partner (`with`, ' +
574
+ 'or the partner of `agreement_id`; no agreement needed): each `{target, mine?, theirs?, turn?, note?}` gets an id ' +
575
+ '(k1, …), and `coordination_done` closes one; warapp_get_relations lists them and warapp_plan_turn tells one on ' +
576
+ 'its turn (any turn while open when it has none) — report only, never an order. An agreement exists only because you record it here: chat is never read ' +
534
577
  'into one. With the cross-game player record on (owner decision D5: on unless WARAPP_PLAYER_RECORD=off, local and ' +
535
578
  'hosted), each agreement is also kept per partner under a salted hash, name-free (no id, no name, no game, no ' +
536
579
  'message): the format, the turns agreed and ended, the shape of the terms, the outcome, a break\'s turn, flag and ' +
@@ -566,6 +609,28 @@ export function registerRelationsTools(server, ctx, opts = {}) {
566
609
  .max(10)
567
610
  .optional()
568
611
  .describe('Partner-approved exceptions to add: attacks the partner agreed to, which are no break. Any status.'),
612
+ coordination: z
613
+ .array(z.object({
614
+ target: playerRef.describe('The player (name or id) you attack together.'),
615
+ mine: z.array(playerRef).max(MAX_SCOPE_ITEMS).optional().describe('Territories (names or ids) you hit or follow on.'),
616
+ theirs: z.array(playerRef).max(MAX_SCOPE_ITEMS).optional().describe('Territories (names or ids) the partner hits.'),
617
+ turn: z.coerce.number().int().min(1).optional().describe('The turn agreed (omit: any turn while it is open).'),
618
+ note: z.string().max(MAX_COORDINATION_NOTE).optional().describe("The owner's own words on the plan (player names are scrubbed)."),
619
+ }))
620
+ .max(10)
621
+ .optional()
622
+ .describe('Joint attacks agreed with the partner (`with`, or the partner of `agreement_id`), kept per game and reported by warapp_get_relations and warapp_plan_turn: never an order. Needs no agreement.'),
623
+ coordination_done: z.array(z.string().trim().min(1).max(20)).max(10).optional().describe('Coordination ids (e.g. "k1") to close.'),
624
+ caps: z
625
+ .array(z.object({
626
+ territory: playerRef.describe('A territory (name or id) of yours.'),
627
+ max: z.coerce.number().int().min(0).describe('The most armies you keep on it.'),
628
+ note: z.string().max(MAX_EXCEPTION_NOTE).optional().describe("The owner's own words on what was agreed (player names are scrubbed)."),
629
+ }))
630
+ .max(MAX_CAPS)
631
+ .optional()
632
+ .describe('Territory caps you promised the partner, as a dated amendment (the terms are not rewritten): at most `max` of your armies on `territory`. A cap on a territory already capped replaces it. Proposed, agreed or in notice.'),
633
+ caps_remove: z.array(playerRef).max(MAX_CAPS).optional().describe('Territories (names or ids) whose cap is lifted.'),
569
634
  }),
570
635
  }, async (args) => {
571
636
  if (!ctx.dataDir) {
@@ -598,6 +663,7 @@ export function registerRelationsTools(server, ctx, opts = {}) {
598
663
  args.until_turn !== undefined ||
599
664
  args.until_player_out !== undefined ||
600
665
  args.against !== undefined;
666
+ const capsGiven = !!args.caps?.length || !!args.caps_remove?.length;
601
667
  const otherPlayer = (ref, what, partner) => {
602
668
  const p = resolvePlayer(game.players, ref);
603
669
  if (p.id === me.id || p.id === partner)
@@ -641,6 +707,43 @@ export function registerRelationsTools(server, ctx, opts = {}) {
641
707
  ...(note ? { note } : {}),
642
708
  };
643
709
  });
710
+ const coordGiven = !!args.coordination?.length || !!args.coordination_done?.length;
711
+ // Only coordination notes: no agreement is created or changed.
712
+ const coordOnly = coordGiven && args.agreement_id === undefined && args.status === undefined && !termsGiven && args.retaliated === undefined && !args.exceptions?.length;
713
+ /** `ledger`'s coordination with `args`' new notes (partner `partner`) added and `coordination_done` closed. */
714
+ const coordinationFrom = (ledger, partner) => {
715
+ let list = [...(ledger.coordination ?? [])];
716
+ for (const id of args.coordination_done ?? []) {
717
+ const c = list.find((x) => x.id === id);
718
+ if (!c)
719
+ refuse(`Game ${game.id} has no coordination ${JSON.stringify(id)}`, 'warapp_get_relations lists the coordination recorded.');
720
+ if (c.doneTurn !== undefined)
721
+ refuse(`Coordination ${id} is already done`, 'Nothing to close.');
722
+ list = list.map((x) => (x.id === id ? { ...x, doneTurn: turn } : x));
723
+ }
724
+ for (const x of args.coordination ?? []) {
725
+ if (partner === undefined)
726
+ refuse('A coordination needs `with` (the partner) or `agreement_id`', 'Name the partner you agreed the attack with.');
727
+ const target = resolvePlayer(game.players, x.target).id;
728
+ if (target === me.id || target === partner)
729
+ refuse('A coordination target must be a third player, not you or the partner', 'Name the player you attack together.');
730
+ if (x.turn !== undefined && x.turn < turn)
731
+ refuse(`A coordination turn ${x.turn} is before this turn (${turn})`, 'Give this turn or a later one, or omit it.');
732
+ const ids = (ts) => [...new Set((ts ?? []).map((t) => resolveTerritory(map, t).id))].sort((a, b) => a - b);
733
+ const note = exceptionNote(x.note, game)?.slice(0, MAX_COORDINATION_NOTE);
734
+ list.push({
735
+ id: nextCoordinationId(list),
736
+ with: partner,
737
+ target,
738
+ mine: ids(x.mine),
739
+ theirs: ids(x.theirs),
740
+ ...(x.turn !== undefined ? { turn: x.turn } : {}),
741
+ recordedTurn: turn,
742
+ ...(note ? { note } : {}),
743
+ });
744
+ }
745
+ return list;
746
+ };
644
747
  /** The change `args` make to `ledger`: the agreement after it, and as it stood. Refuses what cannot be recorded. */
645
748
  const change = (ledger) => {
646
749
  let agreement;
@@ -671,8 +774,8 @@ export function registerRelationsTools(server, ctx, opts = {}) {
671
774
  before = found;
672
775
  if (args.with !== undefined && resolvePlayer(game.players, args.with).id !== agreement.with)
673
776
  refuse(`Agreement ${agreement.id} is with player ${agreement.with}`, 'Omit `with` when updating, or record a new agreement.');
674
- if (args.status === undefined && !termsGiven && args.retaliated === undefined && !args.exceptions?.length)
675
- refuse('Nothing to record: give a new `status`, terms, `retaliated` or `exceptions`', 'Pass the status the agreement moved to.');
777
+ if (args.status === undefined && !termsGiven && args.retaliated === undefined && !args.exceptions?.length && !capsGiven && !coordGiven)
778
+ refuse('Nothing to record: give a new `status`, terms, `retaliated`, `exceptions`, `caps` or `coordination`', 'Pass the status the agreement moved to.');
676
779
  if (termsGiven) {
677
780
  if (agreement.status !== 'proposed-by-me' && agreement.status !== 'proposed-by-them')
678
781
  refuse(`The terms of agreement ${agreement.id} (${agreement.status}) can no longer change`, 'End it and record a new agreement with the new terms.');
@@ -698,11 +801,24 @@ export function registerRelationsTools(server, ctx, opts = {}) {
698
801
  }
699
802
  if (args.exceptions?.length)
700
803
  agreement = withExceptions(agreement, exceptionsFrom());
804
+ if (capsGiven) {
805
+ if (TERMINAL_STATUSES.has(agreement.status))
806
+ refuse(`Agreement ${agreement.id} is ${agreement.status}: caps apply only while it is proposed, agreed or in notice`, 'Record a new agreement to promise a cap.');
807
+ const remove = (args.caps_remove ?? []).map((t) => resolveTerritory(map, t).id);
808
+ for (const t of remove)
809
+ if (!agreement.caps?.some((c) => c.territory === t))
810
+ refuse(`Agreement ${agreement.id} has no cap on territory ${t}`, 'warapp_get_relations lists the caps recorded.');
811
+ const caps = (args.caps ?? []).map((c) => {
812
+ const note = exceptionNote(c.note, game);
813
+ return { territory: resolveTerritory(map, c.territory).id, max: c.max, addedTurn: turn, ...(note ? { note } : {}) };
814
+ });
815
+ agreement = withCaps(agreement, caps, remove);
816
+ }
701
817
  return { agreement, before, created };
702
818
  };
703
819
  const updateRecord = (agreement, before, created, others) => updateAgreementRecord({ dir, env, game, me, map, graph, agreement, before, created, others });
704
820
  // Read, change and write the ledger under its in-process lock: two calls never lose each other's change.
705
- const { agreement, created, recorded } = await withLedgerLock(dir, game.id, me.id, async () => {
821
+ const result = await withLedgerLock(dir, game.id, me.id, async () => {
706
822
  const read = await readLedgerForWrite(dir, game.id, me.id);
707
823
  if (read === 'unreadable') {
708
824
  throw new McpToolError(`The ledger for game ${game.id} exists but cannot be read: nothing was recorded, and the file was left as it is.`, {
@@ -710,19 +826,35 @@ export function registerRelationsTools(server, ctx, opts = {}) {
710
826
  });
711
827
  }
712
828
  const ledger = read ?? emptyLedger(game.id, me.id);
829
+ const unwritable = () => new McpToolError(`The ledger for game ${game.id} could not be written: nothing was recorded.`, {
830
+ hint: "Check that the server's data directory is writable.",
831
+ });
832
+ if (coordOnly) {
833
+ const partner = args.with !== undefined ? resolvePlayer(game.players, args.with).id : undefined;
834
+ if (partner === me.id)
835
+ refuse('A coordination partner must be another player', 'Name the partner you agreed the attack with.');
836
+ const coordination = coordinationFrom(ledger, partner);
837
+ if (!(await writeLedger(dir, { ...ledger, coordination })))
838
+ throw unwritable();
839
+ return { coordination };
840
+ }
713
841
  const c = change(ledger);
842
+ const coordination = coordGiven ? coordinationFrom(ledger, c.agreement.with) : ledger.coordination;
714
843
  const rest = ledger.agreements.filter((a) => a.id !== c.agreement.id);
715
- if (!(await writeLedger(dir, { ...ledger, agreements: [...rest, c.agreement] }))) {
716
- throw new McpToolError(`The ledger for game ${game.id} could not be written: nothing was recorded.`, {
717
- hint: "Check that the server's data directory is writable.",
718
- });
719
- }
720
- return { ...c, recorded: await updateRecord(c.agreement, c.before, c.created, rest) };
844
+ if (!(await writeLedger(dir, { ...ledger, agreements: [...rest, c.agreement], ...(coordination?.length ? { coordination } : {}) })))
845
+ throw unwritable();
846
+ return { ...c, coordination, recorded: await updateRecord(c.agreement, c.before, c.created, rest) };
721
847
  });
848
+ const coordView = result.coordination?.length && coordGiven ? { coordination: result.coordination.map((x) => coordinationView(x, game, map, turn)) } : {};
849
+ if (!('agreement' in result)) {
850
+ return respond(undefined, ['compact'], () => ({ game: { id: game.id, turn }, recorded: 'coordination', ...coordView, written: LEDGER_NOTE }));
851
+ }
852
+ const { agreement, created, recorded } = result;
722
853
  return respond(undefined, ['compact'], () => ({
723
854
  game: { id: game.id, turn },
724
855
  recorded: created ? 'created' : 'updated',
725
856
  agreement: agreementView(agreement, game, map, turn, 'full'),
857
+ ...coordView,
726
858
  playerRecord: recorded,
727
859
  written: LEDGER_NOTE,
728
860
  }));
@@ -0,0 +1,51 @@
1
+ // Owner request 2026-11-24: warapp_check_plan projects the Sanctions its orders play onto next turn's income. The
2
+ // card works from the turn after it is played (the bundle: an ActiveCard from the play, applied to the target's
3
+ // income per card as round((1 − Percentage) × income), capped at 10,000) for the game's Duration. A negative
4
+ // percentage raises the target's income: worth playing on myself, never on an opponent; a positive one the other way
5
+ // round (warapp_submit_turn refuses the wrong side; here it is a warning, since the test still runs). Pure.
6
+ import { percentText, sanctionedIncome, sanctionsSettings } from '../analysis/cards-in-effect.js';
7
+ /** The Sanctions card's type id. */
8
+ export const CARD_SANCTIONS = 9;
9
+ /** The Sanctions plays among the orders (targets by GameFeed id), each projected, with the warnings to show. */
10
+ export function sanctionsPlayed(targets, input) {
11
+ const san = sanctionsSettings(input.settings);
12
+ const pct = san?.percentage ?? null;
13
+ const turns = san?.duration ?? null;
14
+ const lasting = turns ? ` for ${turns} turn${turns === 1 ? '' : 's'}` : '';
15
+ const local = input.settings?.localDeployments === true;
16
+ const entries = [];
17
+ const warnings = [];
18
+ for (const player of targets) {
19
+ const mine = player === input.me;
20
+ const friendly = mine || input.friends.has(player);
21
+ const entry = { player, percentage: pct, turns };
22
+ entries.push(entry);
23
+ if (pct === null) {
24
+ warnings.push(`The Sanctions on player ${player}: this game's percentage could not be read, so the income it changes is not projected.`);
25
+ continue;
26
+ }
27
+ if (pct > 0 && friendly) {
28
+ warnings.push(`The Sanctions on ${mine ? 'yourself' : `your teammate ${player}`} would cut that income by ${percentText(pct)} (this game's percentage is positive): warapp_submit_turn refuses it. Sanction an opponent instead.`);
29
+ continue;
30
+ }
31
+ if (pct < 0 && !friendly) {
32
+ warnings.push(`The Sanctions on player ${player} would raise its income by ${percentText(-pct)} (this game's percentage is negative): warapp_submit_turn refuses it. Play it on yourself instead.`);
33
+ continue;
34
+ }
35
+ if (pct === 0)
36
+ continue;
37
+ if (local) {
38
+ warnings.push(`The Sanctions on ${mine ? 'yourself' : `player ${player}`}: under Local Deployment the change across the pools is not modelled, so next turn's income is not projected.`);
39
+ continue;
40
+ }
41
+ const before = mine ? input.myIncome : friendly ? undefined : input.estimateOf(player);
42
+ if (before === undefined)
43
+ continue;
44
+ const after = sanctionedIncome(before, [pct]);
45
+ entry.nextIncome = { before, after, change: after - before };
46
+ warnings.push(mine
47
+ ? `Your Sanctions on yourself (${percentText(pct)}) raise your income from next turn${lasting}: ${before} → ${after} (+${after - before}), on this turn's income.`
48
+ : `The Sanctions on player ${player} (${percentText(pct)}) cut its income from next turn${lasting}: its estimate ${before} → ${after}.`);
49
+ }
50
+ return { entries, warnings };
51
+ }
@@ -2,6 +2,7 @@
2
2
  // warapp_plan_turn works from. Shared by warapp_check_plan and warapp_submit_turn's commander
3
3
  // check (#274), so both size a reply alike.
4
4
  import { incomeDetail, planEnemyEstimates, symmetricStart, trackGame, trackOpponents, unevenStart } from '../analysis/index.js';
5
+ import { statedShifts } from '../analysis/plan/estimates.js';
5
6
  import { neutralizeSeats, seatEndRules, staticSeats } from '../analysis/static-seats.js';
6
7
  import { carriesTeam } from '../teams.js';
7
8
  import { opponentReinforcement } from './card-advice.js';
@@ -37,7 +38,7 @@ export function stressOpponents(input) {
37
38
  // PLAN-TEAMS D3: the cards in effect the decoder is sure of.
38
39
  const effect = boardCardsInEffect(game, me, turn, info);
39
40
  const previousOrders = previous && turn !== null ? input.boards.find((b) => b.turn === turn - 1)?.orders : undefined;
40
- const { estimates } = planEnemyEstimates({
41
+ const estimateArgs = {
41
42
  graph,
42
43
  board,
43
44
  me: me.id,
@@ -67,8 +68,11 @@ export function stressOpponents(input) {
67
68
  },
68
69
  turn,
69
70
  ...(effect.sanctionsOnOthers.length ? { sanctions: effect.sanctionsOnOthers } : {}),
70
- ...(input.known?.length && input.enemyDeploy === undefined ? { known: input.known } : {}),
71
- });
71
+ };
72
+ const known = input.known?.length && input.enemyDeploy === undefined ? input.known : undefined;
73
+ const { estimates, prior } = planEnemyEstimates({ ...estimateArgs, ...(known ? { known } : {}) });
74
+ // #567: the opponents a known income moved through #444's scale, against the estimates made without it.
75
+ const shifts = known ? statedShifts(planEnemyEstimates(estimateArgs).estimates, estimates, prior) : [];
72
76
  const myTeam = carriesTeam(me.team) ? me.team : undefined;
73
77
  const teamOf = new Map(game.players.map((p) => [p.id, p.team]));
74
78
  const friend = (id) => id === me.id || (myTeam !== undefined && teamOf.get(id) === myTeam);
@@ -107,5 +111,5 @@ export function stressOpponents(input) {
107
111
  // (two at least; enemy_deploy is a what-if, not the game's standing).
108
112
  const rivals = opponents.filter((o) => inView.has(o.id));
109
113
  const leader = teams.size === 0 && rivals.length >= 2 && rivals.every((o) => earnedIncome > estimateOf(o.id));
110
- return { board, seats, tracks, incomeOnBoard, income, earnedIncome, effect, estimates, estimateOf, friend, opponents, teams, inView, leader, commerce };
114
+ return { board, seats, tracks, incomeOnBoard, income, earnedIncome, effect, estimates, estimateOf, friend, opponents, teams, inView, leader, commerce, statedShifts: shifts };
111
115
  }
@@ -0,0 +1,214 @@
1
+ // warapp_turn_history (#570): a game turn by turn as this player saw it, beside what this server planned, sent
2
+ // and expected — read from the game's decision log (src/decision-log.ts), so an agent can plan from the turns
3
+ // before or compare an outcome with its plan. Per turn: the board seen (summary, or whole with `board: true`),
4
+ // what changed hands since the turn before among the territories in view both times, every player's visible
5
+ // orders on that turn (kept since #570, `seen`), the plan, the orders sent and whether they differ, the outcome
6
+ // next turn, cards, events, and once the game is finished its truth and accuracy. Ids and counts only (players
7
+ // by GameFeed id, territories and bonuses by id: warapp_get_map names them). Read-only; it makes no request,
8
+ // except `read_last_turn`, which reads the live board once to keep the turn just resolved first.
9
+ import { McpToolError } from '@chrischall/mcp-utils';
10
+ import { z } from 'zod';
11
+ import { parseGameId } from '../client.js';
12
+ import { boardAt, ordersDiffer, readDecisionLog } from '../decision-log.js';
13
+ import { currentTurn, gameIdArg, readAnnotations, respond, untrustedDescription } from './common.js';
14
+ import { captureSeenTurn } from './decision-capture.js';
15
+ import { lookupMeta } from './hints.js';
16
+ import { readLatestBoard } from './live-context.js';
17
+ import { BRIDGE_NOTE } from './live.js';
18
+ import { accountUnknown, refuse } from './write-kit.js';
19
+ /** Turns returned per call at most, and by default. */
20
+ export const MAX_HISTORY_TURNS = 20;
21
+ export const DEFAULT_HISTORY_TURNS = 5;
22
+ const ownerOf = (t) => (t.owner.kind === 'player' ? t.owner.playerId : t.owner.kind === 'neutral' ? 'neutral' : null);
23
+ /** A board's summary for `me`: my territories and armies, and each other player's in view. */
24
+ export function boardSummary(board, me) {
25
+ const players = new Map();
26
+ let neutral = 0;
27
+ let hidden = 0;
28
+ for (const t of board.territories) {
29
+ const o = ownerOf(t);
30
+ if (o === null)
31
+ hidden++;
32
+ else if (o === 'neutral')
33
+ neutral++;
34
+ else {
35
+ const p = players.get(o) ?? { territories: 0, armies: 0, hiddenArmies: 0 };
36
+ p.territories++;
37
+ if (t.armies === null)
38
+ p.hiddenArmies++;
39
+ else
40
+ p.armies += t.armies;
41
+ players.set(o, p);
42
+ }
43
+ }
44
+ const mine = players.get(me) ?? { territories: 0, armies: 0, hiddenArmies: 0 };
45
+ players.delete(me);
46
+ return {
47
+ mine: { territories: mine.territories, armies: mine.armies },
48
+ others: [...players]
49
+ .sort((a, b) => a[0] - b[0])
50
+ .map(([player, p]) => ({ player, territories: p.territories, armies: p.armies, ...(p.hiddenArmies ? { armiesHiddenOn: p.hiddenArmies } : {}) })),
51
+ neutral,
52
+ hidden,
53
+ };
54
+ }
55
+ /** Territories in view on both boards that changed owner, ascending: `[territory, from, to]`. Pure. */
56
+ export function ownerChanges(before, after) {
57
+ const was = new Map(before.territories.map((t) => [t.territoryId, ownerOf(t)]));
58
+ const out = [];
59
+ for (const t of after.territories) {
60
+ const now = ownerOf(t);
61
+ const prev = was.get(t.territoryId);
62
+ if (prev === undefined || prev === null || now === null || prev === now)
63
+ continue;
64
+ out.push([t.territoryId, prev, now]);
65
+ }
66
+ return out.sort((a, b) => a[0] - b[0]);
67
+ }
68
+ /** A turn's visible orders grouped by player (`unknown` for none read). */
69
+ export function seenByPlayer(orders) {
70
+ const out = {};
71
+ for (const o of orders) {
72
+ const k = o.player === null ? 'unknown' : String(o.player);
73
+ const p = (out[k] ??= { deploys: [], moves: [], cards: [], discards: 0, other: [] });
74
+ if (o.kind === 'deploy')
75
+ p.deploys.push([o.territoryId, o.armies]);
76
+ else if (o.kind === 'move')
77
+ p.moves.push({
78
+ from: o.from,
79
+ to: o.to,
80
+ armies: o.armies,
81
+ ...(o.mode && o.mode !== 'attack-transfer' ? { mode: o.mode } : {}),
82
+ ...(o.percent ? { percent: true } : {}),
83
+ ...(o.commander ? { commander: true } : {}),
84
+ });
85
+ else if (o.kind === 'card')
86
+ p.cards.push(o.card ?? 'card');
87
+ else if (o.kind === 'discard')
88
+ p.discards++;
89
+ else
90
+ p.other.push(o.cls ?? 'unknown');
91
+ }
92
+ return out;
93
+ }
94
+ const boardRows = (b) => [...b.territories].sort((x, y) => x.territoryId - y.territoryId).map((t) => [t.territoryId, ownerOf(t), t.armies]);
95
+ /** One turn as the tool shows it. Pure. */
96
+ export function historyTurn(log, turn, opts = {}) {
97
+ const e = log.turns[String(turn)] ?? {};
98
+ const me = log.playerId;
99
+ const board = e.board ? boardAt(log, turn) : undefined;
100
+ const prevBoard = log.turns[String(turn - 1)]?.board ? boardAt(log, turn - 1) : undefined;
101
+ const d = e.decision;
102
+ const events = (log.events ?? []).filter((x) => x.turn === turn);
103
+ return {
104
+ turn,
105
+ ...(e.kind ? { kind: e.kind } : {}),
106
+ ...(board ? { seen: boardSummary(board, me) } : e.board ? { seen: null, boardUnreadable: true } : {}),
107
+ ...(board && opts.board ? { board: boardRows(board) } : {}),
108
+ ...(board && prevBoard ? { changedHands: ownerChanges(prevBoard, board) } : {}),
109
+ ...(e.seen ? { orders: seenByPlayer(e.seen.orders), ...(e.seen.omitted ? { ordersOmitted: e.seen.omitted } : {}) } : {}),
110
+ ...(d
111
+ ? {
112
+ plan: {
113
+ goal: d.goal,
114
+ ...(d.income !== undefined ? { income: d.income } : {}),
115
+ deploys: d.deploys,
116
+ moves: d.moves,
117
+ expected: d.expected,
118
+ conceded: d.conceded,
119
+ ...(d.estimates ? { estimates: d.estimates } : {}),
120
+ outlook: d.outlook,
121
+ ...(d.outlookLean ? { outlookLean: d.outlookLean } : {}),
122
+ ...(opts.full ? { rationale: d.rationale, warnings: d.warnings } : { warnings: d.warnings.length }),
123
+ },
124
+ }
125
+ : {}),
126
+ ...(e.sent ? { sent: e.sent, ...(d ? { differsFromPlan: ordersDiffer(d, e.sent) } : {}) } : {}),
127
+ ...(e.override ? { override: e.override } : {}),
128
+ ...(e.next ? { outcome: e.next } : {}),
129
+ ...(e.cards ? { cards: e.cards } : {}),
130
+ ...(events.length ? { events } : {}),
131
+ ...(e.truth ? { truth: e.truth } : {}),
132
+ ...(e.accuracy ? { accuracy: e.accuracy } : {}),
133
+ ...(opts.full && e.checks ? { checks: e.checks } : {}),
134
+ ...(opts.full && e.times ? { times: e.times } : {}),
135
+ ...(opts.full && e.firstMover !== undefined ? { firstMover: e.firstMover } : {}),
136
+ };
137
+ }
138
+ const turnsOf = (log) => Object.keys(log.turns)
139
+ .filter((k) => /^\d+$/.test(k))
140
+ .map(Number)
141
+ .sort((a, b) => a - b);
142
+ export function registerTurnHistoryTool(server, ctx) {
143
+ server.registerTool('warapp_turn_history', {
144
+ title: 'A war.app game turn by turn, as I saw it',
145
+ description: untrustedDescription('A war.app (Warzone) game turn by turn as you saw it, beside what this server planned, sent and expected: ' +
146
+ 'per turn, the board in view (`seen`: your territories and armies, each other player\'s in view, neutral and ' +
147
+ 'hidden counts; whole with `board: true`, rows of [territory, owner, armies], owner a GameFeed id, "neutral" or ' +
148
+ 'null when fogged), `changedHands` since the turn before (territories in view both times: [territory, from, ' +
149
+ 'to]), every player\'s visible `orders` that turn (deploys [territory, armies], moves, card plays by name, ' +
150
+ 'discards; kept from the next turn\'s board since #570, so earlier turns have none), the `plan` (goal, income, ' +
151
+ 'deploys, moves, expected income and captures, conceded borders, the per-opponent income estimates, the outlook), ' +
152
+ 'the orders `sent` and `differsFromPlan`, any `override`, the `outcome` next turn (income, gained, lost, captures ' +
153
+ 'made and missed, bonuses held), cards, game events, and once the game is finished each turn\'s `truth` and ' +
154
+ '`accuracy`. Only turns this server saw are kept (planned, tracked or read). Turns `from_turn`..`to_turn` (default ' +
155
+ `the newest ${DEFAULT_HISTORY_TURNS}, at most ${MAX_HISTORY_TURNS} per call; \`next\` pages on); view "full" adds ` +
156
+ 'the plan\'s rationale and warnings, the checks run, times and the first mover. Ids only: name territories and ' +
157
+ 'bonuses with warapp_get_map, players with warapp_get_game. Attack results are not decoded: the next turn\'s board ' +
158
+ 'and `outcome` show what an attack achieved. `read_last_turn: true` first reads the live board once to keep the ' +
159
+ `turn just resolved (game being played, your seat). ${BRIDGE_NOTE} Read-only on war.app.`),
160
+ _meta: lookupMeta(['turn history', 'what happened last turn', 'past turns', 'replay my game', 'compare to the plan']),
161
+ annotations: readAnnotations('War.app game turn by turn'),
162
+ inputSchema: z.object({
163
+ game_id: gameIdArg,
164
+ from_turn: z.number().int().min(1).optional().describe('First turn to show (default: the newest turns).'),
165
+ to_turn: z.number().int().min(1).optional().describe('Last turn to show (default: the newest kept).'),
166
+ board: z.boolean().optional().describe('Include each turn\'s whole board as seen (default false: a summary).'),
167
+ read_last_turn: z.boolean().optional().describe('First read the live board once to keep the turn just resolved (default false).'),
168
+ view: z.enum(['compact', 'full']).optional().describe('"compact" (default) or "full" (adds rationale, warnings, checks, times, first mover).'),
169
+ }),
170
+ }, async ({ game_id, from_turn, to_turn, board, read_last_turn, view }) => {
171
+ const gameId = parseGameId(game_id);
172
+ if (!ctx.dataDir)
173
+ refuse('This server has no data directory, so no turn history is kept.', 'Nothing to read here.');
174
+ const warnings = [];
175
+ let me;
176
+ if (read_last_turn) {
177
+ const game = await ctx.client.getGame(gameId);
178
+ const token = await ctx.myInviteToken().catch(() => undefined);
179
+ if (token === undefined)
180
+ throw accountUnknown(ctx, 'the last turn cannot be read');
181
+ if (!game.players.some((p) => p.id === token))
182
+ throw new McpToolError(`The signed-in war.app account is not a player in game ${game.id}.`, { hint: 'Check the game id with warapp_my_games.' });
183
+ me = token;
184
+ try {
185
+ const { info } = await readLatestBoard(ctx, gameId);
186
+ if (!(await captureSeenTurn(ctx, game, token, info, currentTurn(game))))
187
+ warnings.push('The live board carried no resolved turn to keep (no turn resolved yet, or not this game\'s last one).');
188
+ }
189
+ catch (e) {
190
+ warnings.push(`The live board could not be read (${e instanceof Error ? e.message : String(e)}): showing what is kept.`);
191
+ }
192
+ }
193
+ const log = await readDecisionLog(ctx.dataDir, gameId, me);
194
+ if (!log)
195
+ refuse(`No turn history is kept for game ${gameId}${me !== undefined ? ' for the signed-in account' : ''}.`, 'History is kept from the turns this server sees: plan or track a turn (warapp_plan_turn, warapp_track_opponents) first.');
196
+ const kept = turnsOf(log);
197
+ if (!kept.length)
198
+ refuse(`No turn of game ${gameId} is kept yet.`, 'Plan or track a turn first.');
199
+ const hi = to_turn ?? kept.at(-1);
200
+ const lo = from_turn ?? Math.max(1, hi - DEFAULT_HISTORY_TURNS + 1);
201
+ const inRange = kept.filter((t) => t >= lo && t <= hi);
202
+ const shown = inRange.slice(0, MAX_HISTORY_TURNS);
203
+ const more = inRange.length > shown.length ? inRange[shown.length] : undefined;
204
+ return respond(undefined, ['compact'], () => ({
205
+ game: { id: gameId, status: log.status },
206
+ player: log.playerId,
207
+ keptTurns: { first: kept[0], last: kept.at(-1), count: kept.length },
208
+ turns: shown.map((t) => historyTurn(log, t, { board: board === true, full: view === 'full' })),
209
+ ...(more !== undefined ? { next: { from_turn: more, to_turn: hi } } : {}),
210
+ ...(log.accuracySummary ? { accuracySummary: log.accuracySummary } : {}),
211
+ ...(warnings.length ? { warnings } : {}),
212
+ }));
213
+ });
214
+ }