@chrischall/warapp-mcp 0.24.0 → 0.25.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.
@@ -184,6 +184,20 @@ export function myAllies(state, me) {
184
184
  }
185
185
  return [...out].sort((x, y) => x - y);
186
186
  }
187
+ /**
188
+ * #680: the alliances between two other players (in-game ids, each pair ascending, once), by pair — a pact
189
+ * between them, report only. Never a pair with `me` in it, nor a player with itself.
190
+ */
191
+ export function othersAlliances(state, me) {
192
+ const out = new Map();
193
+ for (const a of state.alliances) {
194
+ if (a.proposer === a.accepter || a.proposer === me || a.accepter === me)
195
+ continue;
196
+ const pair = [a.proposer, a.accepter].sort((x, y) => x - y);
197
+ out.set(pair.join(','), pair);
198
+ }
199
+ return [...out.values()].sort((x, y) => x[0] - y[0] || x[1] - y[1]);
200
+ }
187
201
  /** The alerts that report a break of an alliance with me (the mod's own wording). */
188
202
  export const breakAlerts = (state) => state.alerts.filter((a) => / has broken their alliance with you$/.test(a.message));
189
203
  /** Whether a game's mods (GameFeed settings, `modIds`) include Diplomacy 2. */
@@ -225,6 +225,10 @@ export class Reader {
225
225
  get remaining() {
226
226
  return this.buf.length - this.pos;
227
227
  }
228
+ /** A second reader over the same bytes from this position, so one reply can be read two ways. */
229
+ fork() {
230
+ return new Reader(this.buf, this.pos);
231
+ }
228
232
  need(n) {
229
233
  if (this.pos + n > this.buf.length) {
230
234
  throw new ProtocolError('truncated', `read past end: need ${n} byte(s) at offset ${this.pos} of ${this.buf.length}`);
@@ -20,13 +20,19 @@
20
20
  // `intel` (#386): avoid targets and stated incomes from diplomacy (warapp_record_intel), applied by
21
21
  // warapp_plan_turn and warapp_check_plan by default.
22
22
  //
23
+ // `pacts` (#680): agreements among three or more with me, or between other players (`parties`, ids `p<n>`, a
24
+ // `source` of ledger or reported, each party's notice), kept apart from `agreements` so that every reader of
25
+ // the two-party truces reads exactly what it did; `ledgerTruces` adds the pacts I am in as one pairwise
26
+ // agreement per partner for the planner, the submit refusal and the checks. Files written before it have none.
27
+ //
23
28
  // `usage` (part B2): per planned turn, what each honoured truce freed and what a break would have
24
29
  // cost (rule T6: the armies and the income); warapp_plan_turn calls `recordTruceUsage`.
25
30
  import { randomUUID } from 'node:crypto';
26
31
  import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';
27
32
  import { join } from 'node:path';
28
33
  import { withPathLock } from './path-lock.js';
29
- import { AGREEMENT_STATUSES, EXCEPTION_DIRECTIONS, MAX_CAPS, MAX_EXCEPTION_NOTE, MAX_EXCEPTIONS, MAX_NOTICE_TURNS, } from './analysis/relations.js';
34
+ import { AGREEMENT_STATUSES, EXCEPTION_DIRECTIONS, MAX_CAPS, MAX_EXCEPTION_NOTE, MAX_EXCEPTIONS, MAX_NOTICE_TURNS, MAX_PARTIES, } from './analysis/relations.js';
35
+ import { trucesWithMe } from './analysis/pacts.js';
30
36
  import { COMMITMENT_KINDS } from './analysis/commitments.js';
31
37
  import { coordinationOf, MAX_COORDINATION } from './analysis/coordination.js';
32
38
  import { AVOID_REASONS, intelIsEmpty } from './analysis/intel.js';
@@ -45,8 +51,10 @@ export const MAX_INTEL_PLAYERS = 50;
45
51
  export const relationsDir = (dir) => join(dir, 'relations');
46
52
  export const relationsPath = (dir, gameId, playerId) => join(relationsDir(dir), `${gameId}-${playerId}.json`);
47
53
  const AGREEMENT_ID = /^a(\d{1,9})$/;
48
- /** An agreement id's number (`a7` is 7); ids are made by {@link nextAgreementId}. */
49
- const idNumber = (id) => Number(AGREEMENT_ID.exec(id)?.[1] ?? 0);
54
+ /** #680: a pact's id. */
55
+ const PACT_ID = /^p(\d{1,9})$/;
56
+ /** An agreement or pact id's number (`a7` and `p7` are 7); ids are made by {@link nextAgreementId} and {@link nextPactId}. */
57
+ const idNumber = (id) => Number((AGREEMENT_ID.exec(id) ?? PACT_ID.exec(id))?.[1] ?? 0);
50
58
  function scopeOf(v) {
51
59
  if (v === 'all')
52
60
  return 'all';
@@ -76,14 +84,44 @@ function termsOf(v) {
76
84
  t.against = v.against;
77
85
  return t;
78
86
  }
79
- /** An agreement read back, or `undefined` when it is unusable. */
87
+ /**
88
+ * An agreement read back, or `undefined` when it is unusable. A two-party agreement (`a<n>`) reads exactly as
89
+ * before #680: any `parties`, `source` or `notices` on it is ignored.
90
+ */
80
91
  export function agreementOf(v) {
81
- if (!isRec(v) || typeof v.id !== 'string' || !AGREEMENT_ID.test(v.id) || !isInt(v.with) || v.kind !== 'truce' || !isStatus(v.status) || !isInt(v.createdTurn))
92
+ return agreementLike(v, AGREEMENT_ID);
93
+ }
94
+ /** #680: a pact read back (`p<n>`, 2–{@link MAX_PARTIES} distinct parties), or `undefined` when it is unusable. */
95
+ export function pactOf(v) {
96
+ const a = agreementLike(v, PACT_ID);
97
+ if (!a || !isRec(v))
98
+ return undefined;
99
+ const parties = ints(v.parties);
100
+ if (!parties || parties.length < 2 || parties.length > MAX_PARTIES || new Set(parties).size !== parties.length)
101
+ return undefined;
102
+ a.parties = [...parties].sort((x, y) => x - y);
103
+ if (v.source === 'reported')
104
+ a.source = 'reported';
105
+ else if (v.source === 'ledger')
106
+ a.source = 'ledger';
107
+ const notices = Array.isArray(v.notices)
108
+ ? v.notices.filter((n) => isRec(n) && isInt(n.player) && isInt(n.turn) && a.parties.includes(n.player))
109
+ : [];
110
+ const restOf = (r) => (r === 'continue' || r === 'end' ? { rest: r } : {});
111
+ if (notices.length)
112
+ a.notices = [...new Map(notices.map((n) => [n.player, { player: n.player, turn: n.turn, ...restOf(n.rest) }])).values()];
113
+ return a;
114
+ }
115
+ function agreementLike(v, idPattern) {
116
+ if (!isRec(v) || typeof v.id !== 'string' || !idPattern.test(v.id) || !isInt(v.with) || v.kind !== 'truce' || !isStatus(v.status) || !isInt(v.createdTurn))
82
117
  return undefined;
83
118
  const terms = termsOf(v.terms);
84
119
  if (!terms || !Array.isArray(v.history))
85
120
  return undefined;
86
- const history = v.history.filter((h) => isRec(h) && isInt(h.turn) && isStatus(h.status));
121
+ const pact = idPattern === PACT_ID;
122
+ const history = v.history
123
+ .filter((h) => isRec(h) && isInt(h.turn) && isStatus(h.status))
124
+ .map((h) => (pact && isInt(h.by) ? { turn: h.turn, status: h.status, by: h.by } : { turn: h.turn, status: h.status }));
87
125
  const a = { id: v.id, with: v.with, kind: 'truce', status: v.status, createdTurn: v.createdTurn, terms, history };
88
126
  if (isInt(v.agreedTurn))
89
127
  a.agreedTurn = v.agreedTurn;
@@ -134,6 +172,11 @@ function exceptionOf(v) {
134
172
  return e;
135
173
  }
136
174
  const COMMITMENT_ID = /^c(\d{1,9})$/;
175
+ /** #685: a pact commitment's other parties (2+ distinct ids, ascending); nothing when absent or unusable. */
176
+ function partiesOf(v) {
177
+ const ids = ints(v);
178
+ return ids && ids.length >= 2 && ids.length < MAX_PARTIES && new Set(ids).size === ids.length ? { parties: [...ids].sort((x, y) => x - y) } : {};
179
+ }
137
180
  /** A commitment read back, or `undefined` when it is unusable. */
138
181
  export function commitmentOf(v) {
139
182
  if (!isRec(v) || typeof v.id !== 'string' || !COMMITMENT_ID.test(v.id) || !isInt(v.sentTurn))
@@ -155,11 +198,11 @@ export function commitmentOf(v) {
155
198
  case 'notice':
156
199
  if (typeof v.agreement !== 'string' || !isInt(v.with) || !isInt(v.endsTurn))
157
200
  return undefined;
158
- return { ...base, kind: 'notice', agreement: v.agreement, with: v.with, endsTurn: v.endsTurn };
201
+ return { ...base, kind: 'notice', agreement: v.agreement, with: v.with, ...partiesOf(v.parties), endsTurn: v.endsTurn };
159
202
  default:
160
203
  if (typeof v.agreement !== 'string' || !isInt(v.with))
161
204
  return undefined;
162
- return { ...base, kind: v.kind, agreement: v.agreement, with: v.with };
205
+ return { ...base, kind: v.kind, agreement: v.agreement, with: v.with, ...partiesOf(v.parties) };
163
206
  }
164
207
  }
165
208
  /** The commitments of a ledger file, the unusable dropped; absent when none. */
@@ -169,6 +212,13 @@ function commitmentsOf(v) {
169
212
  const list = v.map(commitmentOf).filter((c) => c !== undefined);
170
213
  return list.length ? { commitments: list } : {};
171
214
  }
215
+ /** #680: the pacts of a ledger file, the unusable dropped; absent when none. */
216
+ function pactsOf(v) {
217
+ if (!Array.isArray(v))
218
+ return {};
219
+ const list = v.map(pactOf).filter((a) => a !== undefined);
220
+ return list.length ? { pacts: list } : {};
221
+ }
172
222
  /** The next commitment id in `ledger`: `c1`, `c2`, … */
173
223
  export function nextCommitmentId(ledger) {
174
224
  const n = (ledger.commitments ?? []).reduce((m, c) => Math.max(m, Number(COMMITMENT_ID.exec(c.id)?.[1] ?? 0)), 0);
@@ -230,7 +280,7 @@ export async function readLedger(dir, gameId, playerId) {
230
280
  if (!isRec(c) || c.gameId !== gameId || c.playerId !== playerId || !Array.isArray(c.agreements))
231
281
  return undefined;
232
282
  const agreements = c.agreements.map(agreementOf).filter((a) => a !== undefined);
233
- return { gameId, playerId, agreements, usage: usageOf(c.usage), ...commitmentsOf(c.commitments), ...intelOf(c.intel), ...coordinationsOf(c.coordination) };
283
+ return { gameId, playerId, agreements, ...pactsOf(c.pacts), usage: usageOf(c.usage), ...commitmentsOf(c.commitments), ...intelOf(c.intel), ...coordinationsOf(c.coordination) };
234
284
  }
235
285
  catch {
236
286
  return undefined;
@@ -254,7 +304,7 @@ export async function readLedgerForWrite(dir, gameId, playerId) {
254
304
  if (!isRec(c) || c.gameId !== gameId || c.playerId !== playerId || !Array.isArray(c.agreements))
255
305
  return 'unreadable';
256
306
  const agreements = c.agreements.map(agreementOf).filter((a) => a !== undefined);
257
- return { gameId, playerId, agreements, usage: usageOf(c.usage), ...commitmentsOf(c.commitments), ...intelOf(c.intel), ...coordinationsOf(c.coordination) };
307
+ return { gameId, playerId, agreements, ...pactsOf(c.pacts), usage: usageOf(c.usage), ...commitmentsOf(c.commitments), ...intelOf(c.intel), ...coordinationsOf(c.coordination) };
258
308
  }
259
309
  catch {
260
310
  return 'unreadable';
@@ -265,19 +315,24 @@ export async function readLedgerForWrite(dir, gameId, playerId) {
265
315
  * dropped oldest first), and at most {@link MAX_USAGE_TURNS} usage turns.
266
316
  */
267
317
  export function boundLedger(ledger) {
268
- let agreements = [...ledger.agreements].sort((a, b) => idNumber(a.id) - idNumber(b.id) || (a.id < b.id ? -1 : 1));
269
- if (agreements.length > MAX_AGREEMENTS) {
270
- const over = agreements.filter((a) => a.endedTurn !== undefined).sort((a, b) => a.endedTurn - b.endedTurn || (a.id < b.id ? -1 : 1));
271
- const drop = new Set(over.slice(0, agreements.length - MAX_AGREEMENTS).map((a) => a.id));
272
- agreements = agreements.filter((a) => !drop.has(a.id)).slice(-MAX_AGREEMENTS);
273
- }
318
+ const bounded = (list) => {
319
+ let out = [...list].sort((a, b) => idNumber(a.id) - idNumber(b.id) || (a.id < b.id ? -1 : 1));
320
+ if (out.length > MAX_AGREEMENTS) {
321
+ const over = out.filter((a) => a.endedTurn !== undefined).sort((a, b) => a.endedTurn - b.endedTurn || (a.id < b.id ? -1 : 1));
322
+ const drop = new Set(over.slice(0, out.length - MAX_AGREEMENTS).map((a) => a.id));
323
+ out = out.filter((a) => !drop.has(a.id)).slice(-MAX_AGREEMENTS);
324
+ }
325
+ return out;
326
+ };
327
+ const agreements = bounded(ledger.agreements);
328
+ const pacts = ledger.pacts?.length ? { pacts: bounded(ledger.pacts) } : {};
274
329
  const turns = Object.keys(ledger.usage)
275
330
  .map(Number)
276
331
  .sort((a, b) => b - a)
277
332
  .slice(0, MAX_USAGE_TURNS)
278
333
  .sort((a, b) => a - b);
279
334
  const commitments = ledger.commitments?.length ? { commitments: ledger.commitments.slice(-MAX_COMMITMENTS) } : {};
280
- const { commitments: _all, intel: _intel, coordination: _coord, ...rest } = ledger;
335
+ const { commitments: _all, intel: _intel, coordination: _coord, pacts: _pacts, ...rest } = ledger;
281
336
  const coordination = ledger.coordination?.length ? { coordination: ledger.coordination.slice(-MAX_COORDINATION) } : {};
282
337
  const intel = intelIsEmpty(ledger.intel)
283
338
  ? {}
@@ -288,7 +343,7 @@ export function boundLedger(ledger) {
288
343
  incomes: ledger.intel.incomes.slice(-MAX_INTEL_PLAYERS),
289
344
  },
290
345
  };
291
- return { ...rest, agreements, usage: Object.fromEntries(turns.map((t) => [String(t), ledger.usage[String(t)]])), ...commitments, ...intel, ...coordination };
346
+ return { ...rest, agreements, ...pacts, usage: Object.fromEntries(turns.map((t) => [String(t), ledger.usage[String(t)]])), ...commitments, ...intel, ...coordination };
292
347
  }
293
348
  /** Write the ledger (bounded), atomically, 0600. `true` when written; never throws. */
294
349
  export async function writeLedger(dir, ledger) {
@@ -309,6 +364,16 @@ export function nextAgreementId(ledger) {
309
364
  const n = ledger.agreements.reduce((m, a) => Math.max(m, idNumber(a.id)), 0);
310
365
  return `a${n + 1}`;
311
366
  }
367
+ /** #680: the next pact id in `ledger`: `p1`, `p2`, … */
368
+ export function nextPactId(ledger) {
369
+ const n = (ledger.pacts ?? []).reduce((m, a) => Math.max(m, idNumber(a.id)), 0);
370
+ return `p${n + 1}`;
371
+ }
372
+ /**
373
+ * #680: every truce with me in `ledger` as the planner, the submit refusal and the checks read it: the two-party
374
+ * agreements, then each pact I am a party to as one pairwise agreement per partner (`trucesWithMe`). `[]` without a ledger.
375
+ */
376
+ export const ledgerTruces = (ledger) => ledger ? trucesWithMe(ledger.agreements, ledger.pacts, ledger.playerId) : [];
312
377
  /**
313
378
  * Part B2: record what each truce freed and would cost on `turn`. Writes only when a ledger
314
379
  * exists for the game. `true` when written; never throws.
@@ -11,7 +11,7 @@ import { chatBlocks } from '../analysis/chat-blocks.js';
11
11
  import { playersByInGameId } from '../live.js';
12
12
  import { carriesTeam } from '../teams.js';
13
13
  import { readOutlookLog } from '../outlook-log.js';
14
- import { readLedger } from '../relations-store.js';
14
+ import { ledgerTruces, readLedger } from '../relations-store.js';
15
15
  import { shown } from './chat.js';
16
16
  import { currentTurn } from './common.js';
17
17
  /** What every view carrying `intent` / `advice` says beside them. */
@@ -91,7 +91,7 @@ export async function chatAdviceContext(ctx, game, me) {
91
91
  try {
92
92
  const [log, ledger] = await Promise.all([readOutlookLog(ctx.dataDir, game.id, meId), readLedger(ctx.dataDir, game.id, meId)]);
93
93
  const standing = standingFromOutlook(log);
94
- const truces = chatTruces(ledger?.agreements, currentTurn(game), game.players);
94
+ const truces = chatTruces(ledger ? ledgerTruces(ledger) : undefined, currentTurn(game), game.players);
95
95
  return { ...base, ...(standing ? { standing } : {}), ...(truces.size ? { truces } : {}) };
96
96
  }
97
97
  catch {