@chrischall/warapp-mcp 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/.claude-plugin/marketplace.json +3 -3
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/README.md +28 -17
  4. package/dist/analysis/accept-surrender.js +56 -0
  5. package/dist/analysis/calibrate.js +239 -0
  6. package/dist/analysis/finished-game.js +136 -0
  7. package/dist/analysis/game-lessons.js +217 -0
  8. package/dist/analysis/local-deploy.js +37 -17
  9. package/dist/analysis/opponent-profile.js +6 -5
  10. package/dist/analysis/opponents.js +10 -2
  11. package/dist/analysis/outlook.js +63 -1
  12. package/dist/analysis/plan/shared.js +194 -7
  13. package/dist/analysis/plan/threats.js +103 -29
  14. package/dist/analysis/planner.js +10 -5
  15. package/dist/analysis/stress.js +14 -7
  16. package/dist/analysis/whereabouts.js +3 -0
  17. package/dist/bundle.js +12392 -9245
  18. package/dist/calibration-source.js +75 -0
  19. package/dist/chat.js +73 -0
  20. package/dist/client.js +85 -7
  21. package/dist/finished-store.js +357 -0
  22. package/dist/index.js +1 -1
  23. package/dist/lessons-store.js +356 -0
  24. package/dist/live.js +9 -0
  25. package/dist/map-details.js +127 -0
  26. package/dist/map-stats.js +14 -6
  27. package/dist/map-store.js +44 -6
  28. package/dist/my-games.js +44 -6
  29. package/dist/normalize.js +34 -2
  30. package/dist/notifications.js +143 -0
  31. package/dist/outlook-log.js +28 -1
  32. package/dist/player-record-store.js +2 -0
  33. package/dist/profile-store.js +61 -11
  34. package/dist/protocol/methods.js +86 -2
  35. package/dist/replay.js +16 -4
  36. package/dist/stats.js +26 -4
  37. package/dist/strategy/notes.js +64 -9
  38. package/dist/surrender-pending.js +126 -0
  39. package/dist/tools/accept-surrender.js +311 -0
  40. package/dist/tools/chat-inbox.js +17 -5
  41. package/dist/tools/chat-read-mark.js +179 -0
  42. package/dist/tools/chat.js +50 -8
  43. package/dist/tools/check-plan.js +1 -0
  44. package/dist/tools/commander-check.js +1 -0
  45. package/dist/tools/end-of-game.js +384 -0
  46. package/dist/tools/game.js +31 -6
  47. package/dist/tools/index.js +15 -5
  48. package/dist/tools/live-context.js +1 -1
  49. package/dist/tools/map-details.js +88 -0
  50. package/dist/tools/map-stats.js +15 -2
  51. package/dist/tools/map.js +10 -2
  52. package/dist/tools/my-games.js +77 -7
  53. package/dist/tools/notifications.js +484 -0
  54. package/dist/tools/opponents.js +14 -2
  55. package/dist/tools/past-games.js +94 -0
  56. package/dist/tools/picks.js +15 -2
  57. package/dist/tools/profile-opponents.js +1 -1
  58. package/dist/tools/profile-reads.js +3 -3
  59. package/dist/tools/push.js +72 -12
  60. package/dist/tools/strategy.js +65 -8
  61. package/dist/tools/stress-opponents.js +1 -1
  62. package/dist/tools/surrender-pending.js +74 -0
  63. package/dist/tools/surrender.js +10 -3
  64. package/dist/tools/team.js +1 -5
  65. package/dist/tools/turn.js +79 -15
  66. package/dist/tools/where.js +42 -17
  67. package/dist/tools/write-kit.js +6 -0
  68. package/dist/trend.js +145 -20
  69. package/dist/version.js +1 -1
  70. package/manifest.json +22 -2
  71. package/mint.yaml +14 -9
  72. package/package.json +1 -1
  73. package/server.json +2 -2
  74. package/skills/warapp-mcp/SKILL.md +141 -14
@@ -12,14 +12,15 @@ import { holdsBelowPlan } from '../analysis/hold-diff.js';
12
12
  import { guardCase } from '../analysis/profile.js';
13
13
  import { boardStateFromLive, inGameId, playersByInGameId } from '../live.js';
14
14
  import { checkMoveOptions, MOVE_MODES } from './order-options.js';
15
- import { AttackTransferMode, Method, UNVERIFIED_CARD_PLAYS, writeSendOrdersParams, } from '../protocol/methods.js';
15
+ import { AttackTransferMode, Method, TARGETED_CARD_PLAYS, UNVERIFIED_CARD_PLAYS, writeSendOrdersParams, } from '../protocol/methods.js';
16
16
  import { SERVER_ERROR_MESSAGES } from '../protocol/rpc.js';
17
17
  import { assumedWarning, awardView, firstMoverFor, loadAward, openingThreat } from './award.js';
18
18
  import { boardCardsInEffect, CARDS_IN_EFFECT_UNVERIFIED, sanctionMyIncome } from './card-effects.js';
19
19
  import { adviseCards, cardGame, cardPieceOption, handOwners, opponentCanHold, opponentReinforcement, TEAM_HAND } from './card-advice.js';
20
- import { currentTurn, gameIdArg, graphOf, namer, readAnnotations, respond, shownAccount, UNTRUSTED_PREVIEW_NOTE, untrustedDescription, untrustedText, viewArg, } from './common.js';
20
+ import { currentTurn, turnsCompleted, gameIdArg, graphOf, namer, readAnnotations, respond, shownAccount, UNTRUSTED_PREVIEW_NOTE, untrustedDescription, untrustedText, viewArg, } from './common.js';
21
21
  import { lookupMeta, mintMeta } from './hints.js';
22
22
  import { chatSummary } from './chat.js';
23
+ import { readPendingSurrenders, surrenderOwedLine } from './surrender-pending.js';
23
24
  import { failureText, loadLiveGame, requireApprovedAccount, writeAccount } from './live-context.js';
24
25
  import { BRIDGE_NOTE, playerArg, resolveMe } from './live.js';
25
26
  import { guessOrdersOf, guessView } from './guess-view.js';
@@ -27,6 +28,8 @@ import { guessSalt, peekGuessSalt } from '../guess-salt.js';
27
28
  import { recordProfile } from './profile-hook.js';
28
29
  import { confidentHabits, counterOf, neighboursOf, readOpponents } from './profile-reads.js';
29
30
  import { mapOf } from './map.js';
31
+ import { PACE_TURNS } from '../analysis/game-lessons.js';
32
+ import { mapRecordFor, paceView } from './past-games.js';
30
33
  import { defineGatedWrite, requireMySeat, sendAndVerify } from './write-kit.js';
31
34
  import { resolveBonus, resolveTerritory } from './resolve.js';
32
35
  import { checkCardFields, newCardPlaySeen, resolveCardTargets, } from './card-plays.js';
@@ -35,6 +38,7 @@ import { writeGameRecord } from '../replay.js';
35
38
  import { gameOutlook } from '../analysis/outlook.js';
36
39
  import { neutralizeSeats, seatEndRules, staticSeats } from '../analysis/static-seats.js';
37
40
  import { cardArmyCeiling, cardClock } from '../strategy/card-clock.js';
41
+ import { hasCostlyBonus, noteContext, notesFor } from '../strategy/notes.js';
38
42
  import { sinceLastTurn } from '../analysis/since-last.js';
39
43
  import { recordOutlook } from '../outlook-log.js';
40
44
  import { readPickRecord } from '../pick-list.js';
@@ -205,6 +209,11 @@ export function plannerSettings(s) {
205
209
  const bombFrom = cardClock(s)?.cards.find((c) => c.card === 'Bomb')?.firstPlayableTurn.fastest;
206
210
  if (bombFrom !== undefined && bombFrom !== null)
207
211
  out.bombFrom = bombFrom;
212
+ // #293 review: an opponent's fixed Reinforcement card on the clock (no hand here: a progressive one
213
+ // is unknown), which the observed deploy counts in its free income under Local Deployment.
214
+ const reinforcement = opponentReinforcement(s, []);
215
+ if (reinforcement)
216
+ out.opponentReinforcement = reinforcement;
208
217
  // AllowTransferOnly is deliberately not mapped: it toggles the per-order
209
218
  // "transfer only" mode, while every planned move is sent as AttackTransfer
210
219
  // (mode 3), which transfers between my own territories in any game. The
@@ -401,6 +410,12 @@ export function validateTurn(args) {
401
410
  const t = standing.get(id);
402
411
  return t !== undefined && !t.fogged && t.owner === myInGameId;
403
412
  };
413
+ // #292: whether a move's armies arrive at its target, given the territories moves earlier in the
414
+ // list went into: Attack Only between my own territories and Transfer Only into one not mine move nothing.
415
+ const lands = (m, entered) => {
416
+ const ours = mine(m.to.id) || entered.has(m.to.id);
417
+ return m.mode === 'attack-only' ? !ours : m.mode === 'transfer-only' ? ours : true;
418
+ };
404
419
  // Under Multi-Attack a territory not mine at the start may move on once a move earlier in the list went in.
405
420
  const chained = new Set();
406
421
  if (args.multiAttack) {
@@ -410,7 +425,8 @@ export function validateTurn(args) {
410
425
  if (!mine(m.from.id) && !movedOut.has(m.from.id) && reached.has(m.from.id))
411
426
  chained.add(m.from.id);
412
427
  movedOut.add(m.from.id);
413
- reached.add(m.to.id);
428
+ if (lands(m, reached))
429
+ reached.add(m.to.id);
414
430
  }
415
431
  }
416
432
  // Deploys land before any attack, so only a move's source may be a territory captured earlier in the list.
@@ -505,32 +521,51 @@ export function validateTurn(args) {
505
521
  }
506
522
  // Walk the moves in order: each source's total sent so far against its armies, its deploys and,
507
523
  // under Multi-Attack, every army moved in earlier in the list (an attack, a transfer in, then
508
- // another attack is fine). Without Multi-Attack, armies moved in do not move on this turn.
524
+ // another attack is fine). Without Multi-Attack, armies moved in do not move on this turn, but
525
+ // one of them can stand guard (#292: the wiki's guard, turn-sim and the bundle's validator), so a
526
+ // source with an arrival earlier in the list may send all of its own — a warning, since whether
527
+ // war.app accepts it live is unverified.
509
528
  const sent = new Map();
510
529
  const inflow = new Map();
530
+ const arrived = new Map();
531
+ const guardedByArrival = new Map();
511
532
  let over;
533
+ const entered = new Set();
512
534
  for (const m of moves) {
513
535
  const start = chained.has(m.from.id) ? 0 : atMoves(m.from.id);
514
- const max = start + (inflow.get(m.from.id) ?? 0) - (args.guard ? 1 : 0);
536
+ const strict = start + (inflow.get(m.from.id) ?? 0) - (args.guard ? 1 : 0);
537
+ const arrivalGuard = args.guard && !args.multiAttack && (arrived.get(m.from.id) ?? 0) > 0;
538
+ const max = arrivalGuard ? start : strict;
515
539
  // A percentage order takes a share of what is left when it runs: it never over-sends, and what
516
540
  // it moves on is at most what the source could move (#165).
517
- const moved = m.percent ? Math.max(0, max - (sent.get(m.from.id) ?? 0)) : m.armies;
541
+ const moved = m.percent ? Math.max(0, strict - (sent.get(m.from.id) ?? 0)) : m.armies;
518
542
  if (!m.percent) {
519
543
  const armies = (sent.get(m.from.id) ?? 0) + m.armies;
520
544
  sent.set(m.from.id, armies);
521
545
  if (armies > max && !over)
522
- over = { from: m.from, armies, max };
546
+ over = { from: m.from, armies, max, arrivalGuard };
547
+ else if (armies > strict)
548
+ guardedByArrival.set(m.from.id, armies);
523
549
  }
550
+ if (!lands(m, entered))
551
+ continue;
552
+ entered.add(m.to.id);
524
553
  if (args.multiAttack)
525
554
  inflow.set(m.to.id, (inflow.get(m.to.id) ?? 0) + moved);
555
+ else if (moved > 0)
556
+ arrived.set(m.to.id, (arrived.get(m.to.id) ?? 0) + moved);
526
557
  }
527
558
  if (over) {
528
- const { from, armies, max } = over;
559
+ const { from, armies, max, arrivalGuard } = over;
529
560
  throw new McpToolError(`These orders send ${armies} armies from ${label(from)}, which can send at most ${max} this turn` +
530
- `${args.guard ? ' (one army stands guard)' : ''}` +
561
+ `${arrivalGuard ? ' (an army moved in earlier in the list may stand guard)' : args.guard ? ' (one army stands guard)' : ''}` +
531
562
  `${airlifted.has(from.id) ? ', counting this turn\'s Airlift' : ''}` +
532
563
  `${inflow.has(from.id) ? '; that counts every army moved in earlier in the list, an upper bound: an attack\'s survivors are fewer' : ''}.`, { hint: 'A territory sends at most its armies plus what is deployed there this turn.' });
533
564
  }
565
+ for (const [id, armies] of guardedByArrival)
566
+ warnings.push(`Territory ${id} sends all ${armies} of its own armies: this relies on an army moved in earlier in the list ` +
567
+ 'standing guard there, as the game rules allow (unverified live). If war.app keeps one of its own armies back, ' +
568
+ 'it may refuse the orders or send one fewer.');
534
569
  // No-Split moves the whole stack (#124: the wiki, and a live turn that left every source at 0):
535
570
  // an order for fewer armies still sends them all, so say what will actually move. A source captured
536
571
  // earlier in the list (Multi-Attack) is left out: the armies standing there at the start were the
@@ -889,7 +924,7 @@ export async function boardHistory(ctx, game, me, turn, opts = {}) {
889
924
  for (let k = Math.max(1, turn - CACHED_TURNS); k < turn; k++) {
890
925
  if (byTurn.has(k))
891
926
  continue;
892
- const board = boardFromHistory(withHistory.history, k - 1, game.players);
927
+ const board = boardFromHistory(withHistory.history, k - 1, game.players, withHistory.numberOfTurns !== undefined ? { numberOfTurns: withHistory.numberOfTurns } : {});
893
928
  if (board)
894
929
  byTurn.set(k, { source: 'history', board });
895
930
  }
@@ -1443,7 +1478,7 @@ export function registerTurnTools(server, ctx, opts = {}) {
1443
1478
  'warnings and the reasoning. Its `orders` array is exactly what warapp_submit_turn takes — review it with ' +
1444
1479
  'the user first. Every plan reads the game profile (`profile`: format 1v1/ffa/teams, phase, standing ' +
1445
1480
  'ahead/even/behind/unknown on income) and returns the `outlook` (winning/losing/even/stalemate from ' +
1446
- 'armies + 3 × income held over 3 turns of boards, with its `basis`; thresholds unmeasured, so advice, not a verdict; ' +
1481
+ 'armies + 3 × income held over 3 turns of boards, with its `basis` and `evidence`: the two incomes compared and how much of each opponent\'s frontier was read, `thin` when under half, so even is not safe; thresholds unmeasured, so advice, not a verdict; ' +
1447
1482
  'an opponent is bounded above by all it can have received (its start, or an even share of the map; each turn\'s most it could earn; ' +
1448
1483
  'a fixed Reinforcement card by the card clock) — a scenario\'s starts, a Gift card or a progressive Reinforcement card leave it unbounded, and then `winning` is never read; ' +
1449
1484
  'once winning or losing, payback tests count the turns the game has left instead of 10). With no `goal` the profile picks and tunes it (`goalSource` ' +
@@ -1518,6 +1553,11 @@ export function registerTurnTools(server, ctx, opts = {}) {
1518
1553
  '`reads` (opponent profiles, as warapp_profile_opponents reads them; reported only, the plan never uses them): ' +
1519
1554
  'each opponent in contact with a habit at the confidence bar or a label — its labels, `lastAttackTurn` (the last turn it attacked you), those habits with `n` and ' +
1520
1555
  '`basis`, `gamesMet` — a likelihood, never a certainty, and never to be quoted to another player. ' +
1556
+ '`surrenderPending` lists the surrenders other players asked for that are still pending (from the game details, ' +
1557
+ 'unverified live; null when they could not be read, never "none"), each with `owedByMe`; when one waits on your ' +
1558
+ 'acceptance the first warning says so. ' +
1559
+ '`pace` (after turns 4 and 8, when you have finished games on this map; reported only): your income beside the median ' +
1560
+ "winner's and your own past median there. " +
1521
1561
  `Refuses outside a turn phase. ${BRIDGE_NOTE} Read-only on war.app; it never submits orders.`),
1522
1562
  _meta: lookupMeta(['plan my turn', 'warzone turn plan', 'what should i deploy', 'suggest my orders']),
1523
1563
  annotations: readAnnotations('Plan a war.app turn'),
@@ -1594,11 +1634,13 @@ export function registerTurnTools(server, ctx, opts = {}) {
1594
1634
  requirePlayingSeat(feed, seat);
1595
1635
  // The teams: GameFeed's, else the game list's (asked once per game, kept).
1596
1636
  const { game, me, source: teamSource, known: teamsKnown } = await resolveTeamsFor(ctx, feed, seat);
1597
- const [{ territories, info }, history, chat] = await Promise.all([
1637
+ const [{ territories, info }, history, chat, surrenders] = await Promise.all([
1598
1638
  loadLiveGame(ctx, game),
1599
1639
  boardHistory(ctx, game, me, turn),
1600
1640
  // Unread chat per channel (counts only), so the agent reads chat before it submits.
1601
1641
  chatSummary(ctx, game),
1642
+ // #317: a surrender waiting on my acceptance (the game details; null when unreadable). Never throws.
1643
+ readPendingSurrenders(ctx, game, me),
1602
1644
  ]);
1603
1645
  const setup = await livePlanSetup(ctx, {
1604
1646
  game, map, me, turn, territories, info, history, teamsKnown,
@@ -1858,11 +1900,23 @@ export function registerTurnTools(server, ctx, opts = {}) {
1858
1900
  ...(advised ? { orderPriority: true } : {}),
1859
1901
  });
1860
1902
  const guessOrders = guess ? guessOrdersOf(orders, guess) : undefined;
1903
+ // #317: a surrender waiting on my acceptance is the first thing said, before the commander's line.
1904
+ const owedLine = surrenderOwedLine(surrenders);
1905
+ if (owedLine)
1906
+ warnings.unshift(owedLine);
1907
+ // #312 E3: after turns 4 and 8, my income beside the pace my finished games on this map set
1908
+ // (reported only: read after the plan is made, never an input to it).
1909
+ const paceRecord = PACE_TURNS.includes(turnsCompleted(game))
1910
+ ? await mapRecordFor(ctx.dataDir, opts.env, game.settings?.mapId)
1911
+ : undefined;
1912
+ const pace = paceRecord && paceRecord !== 'unreadable' ? paceView(paceRecord, turnsCompleted(game), myIncome) : undefined;
1861
1913
  return respond(view, VIEWS, (rung) => ({
1862
1914
  game: { id: game.id, name: game.name ?? null, turn: currentTurn(game) },
1863
1915
  player: { id: me.id, name: me.name },
1864
1916
  // Part A1: messages not yet marked seen (warapp_get_chat reads them); absent when no chat can be read.
1865
1917
  ...(chat ? { chat } : {}),
1918
+ // #317: the surrenders pending (the game details; null: unreadable, never "none").
1919
+ surrenderPending: surrenders,
1866
1920
  goal: plan.goal,
1867
1921
  goalSource: goal !== undefined ? 'explicit' : 'profile',
1868
1922
  // #276: the guard case first, on or off, with what it means for interior defence.
@@ -1876,8 +1930,16 @@ export function registerTurnTools(server, ctx, opts = {}) {
1876
1930
  ...(plan.profile.standingSource === 'tracked' ? { standingSource: 'tracked' } : {}),
1877
1931
  ...(plan.profile.endsWith !== null ? { endsWith: plan.profile.endsWith } : {}),
1878
1932
  },
1933
+ // #309: full only — the ids of the strategy notes this plan's own profile matches (warapp_strategy
1934
+ // serves their text). Reported only: the plan never reads them.
1935
+ ...(rung === 'full'
1936
+ ? { notes: notesFor(plan.profile, undefined, { ...noteContext(game.settings), negativeBonus: hasCostlyBonus(graph) }).map((n) => n.id) }
1937
+ : {}),
1879
1938
  // #178: the outlook and its basis; full adds each turn judged.
1880
- outlook: rung === 'full' ? outlook : { state: outlook.state, basis: outlook.basis },
1939
+ // #304: the compact view keeps what the state rests on beside it (`evidence`).
1940
+ outlook: rung === 'full'
1941
+ ? outlook
1942
+ : { state: outlook.state, basis: outlook.basis, ...(outlook.evidence ? { evidence: outlook.evidence } : {}) },
1881
1943
  // Part D: the opponent reads (reported only, never planned on); absent when none is at the bar.
1882
1944
  ...(reads?.length
1883
1945
  ? {
@@ -1893,6 +1955,8 @@ export function registerTurnTools(server, ctx, opts = {}) {
1893
1955
  }
1894
1956
  : {}),
1895
1957
  income,
1958
+ // #312 E3: the pace beside my income after turns 4 and 8 (my finished games on this map).
1959
+ ...(pace ? { pace } : {}),
1896
1960
  // #253: the army cap's arithmetic (min(income, round(cap × income) − my armies on the board)), when the game has one.
1897
1961
  ...(setup.incomeCap ? { incomeCapped: setup.incomeCap } : {}),
1898
1962
  enemyDeploy: plan.enemyDeploy,
@@ -2205,7 +2269,7 @@ export function registerTurnTools(server, ctx, opts = {}) {
2205
2269
  '(`target`), Surveillance (`bonus`), Airlift (`from` yours, `to` yours or a teammate\'s, `armies`, optional ' +
2206
2270
  '`commander`), Gift (`target` yours, `player`), Diplomacy (`players`: two), Sanctions (`player`), Bomb (`target` ' +
2207
2271
  "next to yours, not yours or a teammate's) and Emergency Blockade (`target` yours, never your commander's), encoded " +
2208
- 'as the client does but not yet verified live, each refused where war.app would refuse it (a commander is never ' +
2272
+ 'as the client does (the Airlift verified live; the others not yet), each refused where war.app would refuse it (a commander is never ' +
2209
2273
  'gifted or airlifted to a teammate, no Spy or Sanctions on yourself or a teammate, no Diplomacy between ' +
2210
2274
  'teammates); discards any card (`{ kind: "discard", card }`); refuses ' +
2211
2275
  'when your hand is over the hold limit and the orders do not play or discard enough cards; in a team game warns ' +
@@ -2366,7 +2430,7 @@ export function registerTurnTools(server, ctx, opts = {}) {
2366
2430
  seen: newCardPlaySeen(),
2367
2431
  };
2368
2432
  for (const p of plays) {
2369
- if (UNVERIFIED_CARD_PLAYS.has(p.kind))
2433
+ if (TARGETED_CARD_PLAYS.has(p.kind))
2370
2434
  p.targets = resolveCardTargets(p.kind, p.card.name, p.input, cardContext);
2371
2435
  }
2372
2436
  // An Emergency Blockade (phase 37) turns its territory neutral before an Airlift (phase 43) runs.
@@ -12,6 +12,7 @@ import { gameIdArg, graphOf, namer, readAnnotations, respond, round2, untrustedD
12
12
  import { lookupMeta } from './hints.js';
13
13
  import { loadLiveGame } from './live-context.js';
14
14
  import { BRIDGE_NOTE, playerArg, resolveMe } from './live.js';
15
+ import { dealtMode, modeStarts } from './map-details.js';
15
16
  import { mapOf } from './map.js';
16
17
  import { recordProfile } from './profile-hook.js';
17
18
  import { boardHistory, currentTurn, plannerSettings, requireTurnPhase } from './turn.js';
@@ -43,15 +44,28 @@ export async function keepPickable(ctx, game, pickable, neutrals) {
43
44
  }
44
45
  /**
45
46
  * Where a player could have started, and how the candidates weigh: the pickable territories kept
46
- * during distribution, else (statistics on) every territory a player started on in the finished
47
- * games cached for the map; the prior counts those starts, plus one, when statistics are on and
48
- * some game is cached. Only files this server already wrote are read.
47
+ * during distribution; else, in a game that dealt its starts automatically from a map distribution
48
+ * mode, that mode's territories (#328: read once from war.app's map details and kept with the map);
49
+ * else (statistics on) every territory a player started on in the finished games cached for the map.
50
+ * The prior counts those starts, plus one, when statistics are on and some game is cached. Only files
51
+ * this server already wrote are read, and war.app only for the map details. `warnings` says when the
52
+ * mode's territories are unknown. Never throws on the map details.
49
53
  */
50
54
  async function startKnowledge(ctx, env, game, map, me) {
51
- if (!ctx.dataDir)
52
- return {};
53
55
  const onMap = new Set(map.territories.map((t) => t.id));
54
- const kept = (await readPickRecord(ctx.dataDir, game.id, me))?.pickable?.filter((t) => onMap.has(t)) ?? [];
56
+ const kept = ctx.dataDir ? ((await readPickRecord(ctx.dataDir, game.id, me))?.pickable?.filter((t) => onMap.has(t)) ?? []) : [];
57
+ const warnings = [];
58
+ let candidates = kept.length ? { territories: kept, source: 'pickable' } : undefined;
59
+ const dealt = candidates ? undefined : dealtMode(game.settings, map);
60
+ if (dealt) {
61
+ const read = await modeStarts(ctx, map, dealt.id);
62
+ if (read.territories)
63
+ candidates = { territories: read.territories, source: 'distribution-mode', mode: dealt.id };
64
+ else
65
+ warnings.push(...read.warnings);
66
+ }
67
+ if (!ctx.dataDir)
68
+ return { ...(candidates ? { candidates } : {}), warnings };
55
69
  const records = statsGate(env).enabled ? await cachedRecords(ctx.dataDir, map.id) : [];
56
70
  /** Territory → the players who started on it, over the cached games. */
57
71
  const started = new Map();
@@ -60,15 +74,11 @@ async function startKnowledge(ctx, env, game, map, me) {
60
74
  for (const t of new Set(p.starts))
61
75
  if (onMap.has(t))
62
76
  started.set(t, (started.get(t) ?? 0) + 1);
63
- const candidates = kept.length
64
- ? { territories: kept, source: 'pickable' }
65
- : started.size
66
- ? { territories: [...started.keys()].sort((a, b) => a - b), source: 'statistics' }
67
- : undefined;
77
+ candidates ??= started.size ? { territories: [...started.keys()].sort((a, b) => a - b), source: 'statistics' } : undefined;
68
78
  if (!candidates)
69
- return {};
79
+ return { warnings };
70
80
  if (!records.length)
71
- return { candidates };
81
+ return { candidates, warnings };
72
82
  return {
73
83
  candidates,
74
84
  prior: {
@@ -78,6 +88,7 @@ async function startKnowledge(ctx, env, game, map, me) {
78
88
  sample: records.length,
79
89
  weak: records.length < MIN_SAMPLE,
80
90
  },
91
+ warnings,
81
92
  };
82
93
  }
83
94
  export function registerWhereTool(server, ctx, deps = {}) {
@@ -102,14 +113,16 @@ export function registerWhereTool(server, ctx, deps = {}) {
102
113
  'them as guesses, and `seen` as what is known. The model assumes one capture per turn along a path, pooled ' +
103
114
  'armies when it grows a start, that a start is never abandoned, and ignores cards (the full view lists its ' +
104
115
  'assumptions). The start candidates are the territories the live board showed as pickable, kept by ' +
105
- 'warapp_plan_picks and by warapp_submit_picks; with none kept and no statistics, no start is guessed ' +
106
- '(`starts.source` is "none") and the rest works from what was seen. The start prior is uniform, unless the ' +
116
+ 'warapp_plan_picks and by warapp_submit_picks; in a game that dealt its starts automatically from a map ' +
117
+ 'distribution mode, that mode\'s territories (`starts.source` "distribution-mode"; read once from war.app\'s ' +
118
+ 'map details and kept with the map, and `warnings` says when they are unknown; `startCandidates` names the source, the count and the mode by id and name); with neither and no ' +
119
+ 'statistics, no start is guessed (`starts.source` is "none") and the rest works from what was seen. The start prior is uniform, unless the ' +
107
120
  `server runs locally with ${STATS_ENV}=1: then each candidate weighs by how often players started on it in the ` +
108
121
  'finished games warapp_map_stats already cached for the map (the sample is reported, and called weak under ' +
109
122
  `${MIN_SAMPLE} games), and with no pickable territories kept those starts are the candidates. It reads only boards ` +
110
123
  `this server already saw (the last ${CACHED_TURNS} turns warapp_plan_turn, warapp_track_opponents and this tool cached, ` +
111
124
  'or the game history when war.app sends it) plus those files: no war.app request beyond the live board and ' +
112
- `the game feed warapp_track_opponents reads. Refuses outside a turn phase. ${BRIDGE_NOTE} Read-only on war.app; it ` +
125
+ `the game feed warapp_track_opponents reads, and the map details once per map for a mode's territories. Refuses outside a turn phase. ${BRIDGE_NOTE} Read-only on war.app; it ` +
113
126
  'caches the board it read. warapp_plan_turn does not use these guesses yet.'),
114
127
  _meta: lookupMeta(['where is my opponent', 'locate opponents', 'where did they start', 'what is my opponent doing', 'what should i prepare for']),
115
128
  annotations: readAnnotations('Locate war.app opponents'),
@@ -142,7 +155,7 @@ export function registerWhereTool(server, ctx, deps = {}) {
142
155
  const proven = new Map();
143
156
  if (award?.opponent && award.reading.opponentStarts.length)
144
157
  proven.set(award.opponent.id, award.reading.opponentStarts);
145
- const { candidates, prior } = await startKnowledge(ctx, deps.env, game, map, me.id);
158
+ const { candidates, prior, warnings: startWarnings } = await startKnowledge(ctx, deps.env, game, map, me.id);
146
159
  const s = game.settings;
147
160
  const whereSettings = {
148
161
  ...settings,
@@ -268,6 +281,18 @@ export function registerWhereTool(server, ctx, deps = {}) {
268
281
  turns: boards.map((b) => b.turn).sort((a, b) => a - b),
269
282
  opponents: result.opponents.map(opponentView),
270
283
  prepare: result.prepare.map(prepareView),
284
+ // #328: where the start candidates came from, and the distribution mode that dealt them, by id and name.
285
+ startCandidates: candidates
286
+ ? {
287
+ source: candidates.source,
288
+ count: candidates.territories.length,
289
+ ...(candidates.mode !== undefined
290
+ ? { mode: { id: candidates.mode, name: map.distributionModes.find((d) => d.id === candidates.mode)?.name ?? null } }
291
+ : {}),
292
+ }
293
+ : { source: 'none', count: 0 },
294
+ // #328: the distribution mode's territories could not be had (they are no start candidates then).
295
+ ...(startWarnings.length ? { warnings: startWarnings } : {}),
271
296
  ...(full ? { assumptions: result.assumptions } : {}),
272
297
  };
273
298
  });
@@ -22,12 +22,18 @@
22
22
  // warapp_leave_game left → confirmed; unconfirmed; unknown
23
23
  // warapp_surrender surrendered → confirmed; pending, still_playing → accepted;
24
24
  // unchanged → unconfirmed; unknown
25
+ // warapp_accept_surrender accepted, pending (my acceptance read back, others still owe
26
+ // theirs) → confirmed; unconfirmed; unknown
25
27
  // warapp_uncommit_turn uncommitted → confirmed; unconfirmed; unknown
26
28
  // warapp_submit_turn resolved, committed → confirmed; unknown after a send war.app
27
29
  // accepted (read-back failed or shows nothing yet) → unconfirmed;
28
30
  // unknown (no answer) → unknown
29
31
  // warapp_submit_picks verified → confirmed; unconfirmed; unknown
30
32
  // warapp_send_chat sent → accepted; unknown
33
+ // warapp_dismiss_notification dismissed → confirmed; unconfirmed; unknown
34
+ // warapp_delete_notification deleted → confirmed; unconfirmed (also after a refusal past the
35
+ // first id); unknown
36
+ // warapp_mark_chat_read read → confirmed; unconfirmed; unknown
31
37
  // warapp_link_session linked → confirmed
32
38
  import { defineWrite, McpToolError, registerWrite, } from '@chrischall/mcp-utils';
33
39
  import { notSent, WarappServerError } from '../protocol/rpc.js';
package/dist/trend.js CHANGED
@@ -29,6 +29,10 @@ import { asInt } from './scalars.js';
29
29
  const isRec = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
30
30
  const STANDING_KEYS = ['standing', 'standings', 'latestStanding', 'Standing'];
31
31
  const NUMBER_KEYS = ['turnNumber', 'turn', 'number', 'TurnNumber'];
32
+ /** Keys that wrap a history's turns (#302: GameFeed's spelling is unverified). */
33
+ const WRAPPER_KEYS = ['turns', 'Turns', 'history', 'History', 'standings', 'Standings'];
34
+ const DISTRIBUTION_KEYS = ['distributionStanding', 'DistributionStanding'];
35
+ const STANDING_KEY = /^standing_?(\d+)$/i;
32
36
  function standingOf(entry) {
33
37
  if (!isRec(entry))
34
38
  return entry;
@@ -37,41 +41,117 @@ function standingOf(entry) {
37
41
  return entry[k];
38
42
  return entry;
39
43
  }
40
- /** History entries as (completed turns, raw standing), in any of the plausible layouts. */
41
- function entriesOf(history, out = []) {
44
+ /** Whether a raw standing shows any territory held by a player (a pre-pick board shows none). */
45
+ const playerLand = (raw) => boardFromStanding(standingOf(raw))?.territories.some((t) => t.owner.kind === 'player') ?? false;
46
+ const ORDER_LIST_KEYS = ['orders', 'Orders'];
47
+ const ORDER_TYPE_KEYS = ['type', 'Type', 'orderType', 'OrderType'];
48
+ /**
49
+ * Whether a history entry carries a turn's orders rather than a standing: a record with an `orders`
50
+ * list and no standing key, or a list whose records name an order type (`type` / `orderType`).
51
+ */
52
+ function carriesOrders(entry) {
53
+ if (Array.isArray(entry))
54
+ return entry.some((e) => isRec(e) && ORDER_TYPE_KEYS.some((k) => typeof e[k] === 'string'));
55
+ if (!isRec(entry))
56
+ return false;
57
+ return ORDER_LIST_KEYS.some((k) => entry[k] !== undefined) && !STANDING_KEYS.some((k) => entry[k] !== undefined);
58
+ }
59
+ /** History entries in any of the plausible layouts (#302). Throws only on a hostile getter (callers catch). */
60
+ function parseHistory(history, opts = {}) {
61
+ if (typeof history === 'string') {
62
+ let parsed;
63
+ try {
64
+ parsed = JSON.parse(history);
65
+ }
66
+ catch {
67
+ return { entries: [], layout: 'none', shape: 'string' };
68
+ }
69
+ const inner = parseHistory(parsed, opts);
70
+ return { ...inner, layout: `json>${inner.layout}` };
71
+ }
42
72
  if (Array.isArray(history)) {
43
- history.forEach((e, i) => {
73
+ const entries = history.map((e, i) => {
44
74
  let n;
45
75
  if (isRec(e))
46
76
  for (const k of NUMBER_KEYS)
47
77
  n ??= asInt(e[k]);
48
- out.push([n ?? i, standingOf(e)]);
78
+ return [n ?? i, standingOf(e)];
49
79
  });
50
- return out;
80
+ return { entries, layout: 'array', shape: 'array' };
51
81
  }
52
82
  if (!isRec(history))
53
- return out;
54
- const turns = history.turns ?? history.Turns;
55
- if (turns !== undefined)
56
- return entriesOf(turns, out);
83
+ return { entries: [], layout: 'none', shape: history === null ? 'null' : typeof history };
84
+ for (const k of WRAPPER_KEYS) {
85
+ const v = history[k];
86
+ if (v === undefined)
87
+ continue;
88
+ const inner = parseHistory(v, opts);
89
+ return { ...inner, layout: `wrapper:${k}>${inner.layout}`, shape: 'object' };
90
+ }
91
+ let dist;
92
+ for (const k of DISTRIBUTION_KEYS)
93
+ dist ??= history[k];
94
+ const standings = [];
57
95
  for (const [k, v] of Object.entries(history)) {
58
- const m = /^(?:turn|standing)?_?(\d+)$/i.exec(k);
96
+ const m = STANDING_KEY.exec(k);
59
97
  if (m)
60
- out.push([Number(m[1]), standingOf(v)]);
98
+ standings.push([Number(m[1]), standingOf(v)]);
61
99
  }
62
- return out;
100
+ if (standings.length) {
101
+ // Top-level `standing<N>` keys (#302), `turn<N>` beside them being orders: is standing0 the
102
+ // start, or the board after the first turn? UNVERIFIED. A distribution standing beside them
103
+ // decides: one on which no player holds land is the board before picks, so standing0 is the
104
+ // start (the board after picks); one with player land is the start itself, so standing0 is one
105
+ // turn on. Without one, the game's completed turns decide when the last N reaches them or
106
+ // falls one short.
107
+ const last = Math.max(...standings.map(([n]) => n));
108
+ const t = opts.numberOfTurns;
109
+ const offset = dist !== undefined
110
+ ? playerLand(dist)
111
+ ? 1
112
+ : 0
113
+ : t !== undefined && last === t - 1
114
+ ? 1
115
+ : 0;
116
+ const entries = standings.map(([n, v]) => [n + offset, v]);
117
+ if (dist !== undefined && !entries.some(([n]) => n === 0))
118
+ entries.push([0, standingOf(dist)]);
119
+ return {
120
+ entries,
121
+ layout: `standing-keys${offset ? '+1' : ''}${dist !== undefined ? '+distribution' : ''}`,
122
+ shape: 'object',
123
+ };
124
+ }
125
+ // Turn-numbered keys (`turn<N>` / `<N>`): an entry that carries orders is never a board (the
126
+ // Warlight-era `turn<N>` is the turn's orders). A distribution standing is entry 0 only when a
127
+ // player holds land on it: a land-free one is the board before picks, never turn 1's previous board.
128
+ const entries = [];
129
+ for (const [k, v] of Object.entries(history)) {
130
+ const m = /^(?:turn)?_?(\d+)$/i.exec(k);
131
+ if (m && !carriesOrders(v))
132
+ entries.push([Number(m[1]), standingOf(v)]);
133
+ }
134
+ if (dist !== undefined && playerLand(dist) && !entries.some(([n]) => n === 0))
135
+ entries.push([0, standingOf(dist)]);
136
+ return { entries, layout: 'numbered-keys', shape: 'object' };
63
137
  }
64
138
  /**
65
139
  * The standing after `completedTurns` turns from a raw `GetHistory` payload,
66
140
  * with owners keyed by GameFeed player id; `undefined` when it is absent or
67
141
  * unusable. An entry's number is read as the count of completed turns its
68
- * standing reflects (an assumption: the in-progress shape is unverified).
69
- * Never throws.
142
+ * standing reflects (an assumption: the shape is unverified, #302). The first
143
+ * entry of that number that parses wins. Never throws.
70
144
  */
71
- export function boardFromHistory(history, completedTurns, players) {
145
+ export function boardFromHistory(history, completedTurns, players, opts = {}) {
72
146
  try {
73
- const raw = entriesOf(history).find(([n]) => n === completedTurns)?.[1];
74
- return feedOwners(boardFromStanding(raw), players);
147
+ for (const [n, raw] of parseHistory(history, opts).entries) {
148
+ if (n !== completedTurns)
149
+ continue;
150
+ const board = feedOwners(boardFromStanding(raw), players);
151
+ if (board)
152
+ return board;
153
+ }
154
+ return undefined;
75
155
  }
76
156
  catch {
77
157
  return undefined;
@@ -97,13 +177,13 @@ function feedOwners(board, players) {
97
177
  * Every usable standing in a raw `GetHistory` payload, ascending by entry
98
178
  * number (completed turns, as {@link boardFromHistory} reads it), owners keyed
99
179
  * by GameFeed player id. Entries that do not parse are left out; the first of
100
- * two entries with one number wins. Never throws.
180
+ * two entries with one number that parses wins. Never throws.
101
181
  */
102
- export function historyBoards(history, players) {
182
+ export function historyBoards(history, players, opts = {}) {
103
183
  try {
104
184
  const seen = new Set();
105
185
  const out = [];
106
- for (const [turn, raw] of entriesOf(history)) {
186
+ for (const [turn, raw] of parseHistory(history, opts).entries) {
107
187
  if (seen.has(turn))
108
188
  continue;
109
189
  const board = feedOwners(boardFromStanding(raw), players);
@@ -118,6 +198,51 @@ export function historyBoards(history, players) {
118
198
  return [];
119
199
  }
120
200
  }
201
+ /** At most this many key names go into a report (#302). */
202
+ const MAX_REPORTED_KEYS = 40;
203
+ /** A key name that may be reported: an identifier, never free text. */
204
+ const SAFE_KEY = /^[A-Za-z][A-Za-z0-9_]{0,39}$/;
205
+ /** The key names of a reply or entry worth reporting: identifiers only, capped (#302). */
206
+ export function safeKeys(keys) {
207
+ return keys.filter((k) => SAFE_KEY.test(k)).slice(0, MAX_REPORTED_KEYS);
208
+ }
209
+ /**
210
+ * Whether a game's history reads, and if not why (#302): one live call then shows GameFeed's real
211
+ * shape. `needPlayerLand` (map statistics) also asks that some board shows a player of the game
212
+ * holding land. Name-free; never throws.
213
+ */
214
+ export function historyReport(game, opts = {}) {
215
+ const keys = safeKeys(game.feedKeys ?? []);
216
+ if (game.history === undefined)
217
+ return { unreadable: { reason: 'absent', keys } };
218
+ let parsed;
219
+ try {
220
+ parsed = parseHistory(game.history, game.numberOfTurns !== undefined ? { numberOfTurns: game.numberOfTurns } : {});
221
+ }
222
+ catch {
223
+ parsed = { entries: [], layout: 'none', shape: 'object' };
224
+ }
225
+ const { entries, shape, layout } = parsed;
226
+ if (shape === 'string')
227
+ return { unreadable: { reason: 'not-json', keys, shape } };
228
+ if (!entries.length) {
229
+ const own = isRec(game.history) ? { historyKeys: safeKeys(Object.keys(game.history)) } : {};
230
+ return { unreadable: { reason: 'no-turns', keys, shape, ...own } };
231
+ }
232
+ const boards = historyBoards(game.history, game.players, game.numberOfTurns !== undefined ? { numberOfTurns: game.numberOfTurns } : {});
233
+ if (!boards.length) {
234
+ const first = entries[0][1];
235
+ const entryKeys = isRec(first) ? { entryKeys: safeKeys(Object.keys(first)) } : {};
236
+ return { unreadable: { reason: 'no-standing', keys, shape, turns: entries.length, ...entryKeys } };
237
+ }
238
+ if (opts.needPlayerLand) {
239
+ const ids = new Set(game.players.map((p) => p.id));
240
+ const land = boards.some(({ board }) => board.territories.some((t) => t.owner.kind === 'player' && ids.has(t.owner.playerId)));
241
+ if (!land)
242
+ return { unreadable: { reason: 'no-player-land', keys, shape, turns: boards.length } };
243
+ }
244
+ return { read: { turns: boards.length, first: boards[0].turn, last: boards[boards.length - 1].turn, layout } };
245
+ }
121
246
  /** Where the last planned boards of a game are cached. */
122
247
  export const boardCachePath = (dir, gameId) => join(dir, 'boards', `${gameId}.json`);
123
248
  /**
package/dist/version.js CHANGED
@@ -1,4 +1,4 @@
1
1
  // Single source of truth for the server version. release-please bumps the
2
2
  // literal on the marked line (registered in release-please-config.json
3
3
  // extra-files); every other module imports VERSION from here.
4
- export const VERSION = '0.1.0'; // x-release-please-version
4
+ export const VERSION = '0.2.0'; // x-release-please-version