hoi4-agent-tools 4.8.0 → 4.10.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 (93) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/dist/hoi4_agent_tools/core/index.js +28 -0
  3. package/dist/hoi4_agent_tools/decision/service.js +39 -2
  4. package/dist/hoi4_agent_tools/event/graph.js +16 -2
  5. package/dist/hoi4_agent_tools/event/queries.js +25 -2
  6. package/dist/hoi4_agent_tools/event/service.js +66 -11
  7. package/dist/hoi4_agent_tools/event/source-analysis.js +35 -16
  8. package/dist/hoi4_agent_tools/impact/service.js +15 -0
  9. package/dist/hoi4_agent_tools/map/appearance-validation.js +14 -2
  10. package/dist/hoi4_agent_tools/map/gameplay/reachability.js +81 -0
  11. package/dist/hoi4_agent_tools/map/geography/resolve.js +6 -2
  12. package/dist/hoi4_agent_tools/map/operations.js +8 -0
  13. package/dist/hoi4_agent_tools/map/partition-tuning.js +2 -1
  14. package/dist/hoi4_agent_tools/map/reference-world.js +17 -3
  15. package/dist/hoi4_agent_tools/map/relief/painted-relief.js +143 -0
  16. package/dist/hoi4_agent_tools/map/relief/terrain-synthesis.js +13 -0
  17. package/dist/hoi4_agent_tools/map/tool-operations.js +41 -0
  18. package/dist/hoi4_agent_tools/map/world-edge.js +117 -15
  19. package/dist/hoi4_agent_tools/map/world.js +243 -34
  20. package/dist/hoi4_agent_tools/mcp/server/argument-errors.js +57 -9
  21. package/dist/hoi4_agent_tools/mcp/server/create-modern-operations.js +1 -1
  22. package/dist/hoi4_agent_tools/mcp/server/request-lifecycle.js +1 -1
  23. package/dist/hoi4_agent_tools/mcp/tools/analysis.js +4 -2
  24. package/dist/hoi4_agent_tools/mcp/tools/event.js +13 -0
  25. package/dist/hoi4_agent_tools/mcp/tools/gui.js +1 -1
  26. package/dist/hoi4_agent_tools/mcp/tools/reference.js +25 -0
  27. package/dist/hoi4_agent_tools/probability/model.js +4 -4
  28. package/dist/hoi4_agent_tools/probability/operations.js +6 -0
  29. package/dist/hoi4_agent_tools/probability/service.js +23 -0
  30. package/dist/hoi4_agent_tools/reference/error-log.js +35 -1
  31. package/dist/hoi4_agent_tools/reference/operations.js +141 -14
  32. package/dist/hoi4_agent_tools/reference/script-validation.js +113 -2
  33. package/dist/hoi4_agent_tools/schemas/geography.js +5 -0
  34. package/dist/hoi4_agent_tools/schemas/ideas.js +4 -4
  35. package/dist/hoi4_agent_tools/schemas/map.js +61 -4
  36. package/dist/hoi4_agent_tools/schemas/script-validation.js +8 -1
  37. package/dist/hoi4_agent_tools/schemas/system.js +157 -0
  38. package/dist/hoi4_agent_tools/system/inspect.js +55 -0
  39. package/dist/hoi4_agent_tools/version.js +1 -1
  40. package/docs/analysis.md +2 -2
  41. package/docs/events.md +1 -1
  42. package/docs/map.md +31 -17
  43. package/docs/probability.md +1 -1
  44. package/docs/research/probability-adapter-evidence.md +15 -2
  45. package/docs/tools.md +49 -43
  46. package/engine/README.md +9 -0
  47. package/engine/bin/darwin-arm64/hoi4-engine +0 -0
  48. package/engine/bin/linux-arm64/hoi4-engine +0 -0
  49. package/engine/bin/linux-x64/hoi4-engine +0 -0
  50. package/engine/bin/manifest.json +8 -8
  51. package/engine/bin/win32-x64/hoi4-engine.exe +0 -0
  52. package/npm-shrinkwrap.json +2 -2
  53. package/package.json +1 -1
  54. package/schemas/configuration.schema.json +1 -1
  55. package/schemas/continuous-focus-palette.schema.json +1 -1
  56. package/schemas/custom-weighted-pool.schema.json +1 -1
  57. package/schemas/decision-inspect-input.schema.json +1 -1
  58. package/schemas/error-log-input.schema.json +1 -1
  59. package/schemas/event-feature-manifest.schema.json +1 -1
  60. package/schemas/focus-plan.schema.json +1 -1
  61. package/schemas/focus-planning-sidecar.schema.json +1 -1
  62. package/schemas/geography-model.schema.json +4 -1
  63. package/schemas/gui-animation-source.schema.json +1 -1
  64. package/schemas/gui-helper.schema.json +1 -1
  65. package/schemas/gui-scenario.schema.json +1 -1
  66. package/schemas/helper-expansion-request.schema.json +1 -1
  67. package/schemas/helper-expansion-summary.schema.json +1 -1
  68. package/schemas/impact-inspect-input.schema.json +1 -1
  69. package/schemas/map-operation.schema.json +234 -111
  70. package/schemas/mechanic-test-input.schema.json +1 -1
  71. package/schemas/mod-index-input.schema.json +1 -1
  72. package/schemas/operation-result.schema.json +1 -1
  73. package/schemas/package-check-input.schema.json +1 -1
  74. package/schemas/package-manifest.schema.json +1 -1
  75. package/schemas/probability-analysis-result.schema.json +1 -1
  76. package/schemas/probability-compare-input.schema.json +1 -1
  77. package/schemas/probability-evaluate-input.schema.json +1 -1
  78. package/schemas/probability-inspect-input.schema.json +1 -1
  79. package/schemas/probability-render-input.schema.json +1 -1
  80. package/schemas/probability-scenario-set.schema.json +1 -1
  81. package/schemas/probability-sequence-input.schema.json +1 -1
  82. package/schemas/probability-simulate-input.schema.json +1 -1
  83. package/schemas/probability-sweep-input.schema.json +1 -1
  84. package/schemas/reference-context-input.schema.json +1 -1
  85. package/schemas/reference-read-input.schema.json +1 -1
  86. package/schemas/reference-search-input.schema.json +1 -1
  87. package/schemas/reference-sheets.schema.json +1 -1
  88. package/schemas/scenario-suite.schema.json +1 -1
  89. package/schemas/scenario-test-input.schema.json +1 -1
  90. package/schemas/script-validate-input.schema.json +1 -1
  91. package/schemas/shared-scenario.schema.json +1 -1
  92. package/schemas/source-lookup-input.schema.json +1 -1
  93. package/server.json +2 -2
@@ -16,13 +16,16 @@ import { buildTerritoryAtoms, territoryGraphFromPartition } from './territory-gr
16
16
  import { growTerritory } from './territory.js';
17
17
  import { geographyPartitionFields, provinceCountNote, surfacePartitionFields, } from './world-partition.js';
18
18
  import { adjacencyRowText, adjacencyRulesText } from './gameplay/crossings.js';
19
+ import { realmReachNotes } from './gameplay/reachability.js';
19
20
  import { convertInlandSeas } from './gameplay/inland-sea.js';
20
21
  import { planEconomy } from './gameplay/economy.js';
21
22
  import { prepareGameplay } from './gameplay/prepare.js';
22
23
  import { fractal, lattice } from './world-noise.js';
23
24
  import { calibratedColourMap, COLOUR_CLASSES, } from './colormap.js';
24
- import { ambientObjectText, applyEdgePolicy, assertFeaturesOutsideBand, edgeWaterDarkness, RIM_COLOUR_FACTOR, rimAdjacencyRows, rimHeight, rimStrength, } from './world-edge.js';
25
+ import { ambientObjectText, applyEdgePolicy, assertFeaturesOutsideBand, edgeWaterDarkness, hasRimRange, RIM_COLOUR_FACTOR, rimAdjacencyRows, rimHeight, rimStrength, WALL_TERRAIN_KINDS, wallRowKinds, } from './world-edge.js';
25
26
  import { landDistanceField, lakeHeight, normalizeLakes, waterColourLevel } from './water.js';
27
+ import { DEFAULT_PAINTED_RELIEF } from './relief/painted-relief.js';
28
+ import { rowStrips, scanAreaStrip } from './geography/index.js';
26
29
  import { overlayGeographyLakes, rasterizeGeographyKind } from './relief/land.js';
27
30
  import { checkTerrainRivers, synthesizeTerrain, } from './relief/terrain-synthesis.js';
28
31
  import { assignUnreachedRealmLand, checkRealmPoints, realmPointsError, resolveRealmRules, } from './world-realms.js';
@@ -255,6 +258,8 @@ function geographySurface(spec, geography, reference) {
255
258
  }
256
259
  return { kind, elevation: new Float32Array(total), moisture };
257
260
  }
261
+ /** Land relief of the base game 1.19.4.1 (`reliefStatistics` over its land provinces). */
262
+ export const VANILLA_RELIEF = { median: 107, p99: 213, maximum: 239, meanStep: 2.69 };
258
263
  function terrainSummaryNote(terrain, geography) {
259
264
  const { relief, riverStatistics } = terrain;
260
265
  return {
@@ -264,6 +269,8 @@ function terrainSummaryNote(terrain, geography) {
264
269
  details: {
265
270
  modelHash: geography.hash,
266
271
  relief,
272
+ // The base game 1.19.4.1 over its land provinces, for comparison.
273
+ vanilla: VANILLA_RELIEF,
267
274
  rivers: riverStatistics,
268
275
  // The first of the named rivers only: the response budget is shared with everything else the
269
276
  // world reports, and a river that did not complete is always listed.
@@ -465,6 +472,83 @@ function realmPins(realms, width, height, kind) {
465
472
  }
466
473
  return pins.map(({ pixel }) => pixel);
467
474
  }
475
+ /** The union of painted impassable land and the model's impassable regions, or undefined. */
476
+ function impassableLand(painted, geography, width, height) {
477
+ const regions = (geography?.regions ?? []).filter((region) => region.impassable === true && region.area !== undefined);
478
+ if (regions.length === 0)
479
+ return painted;
480
+ const mask = painted === undefined ? new Uint8Array(width * height) : new Uint8Array(painted);
481
+ const grid = { width, height };
482
+ for (const strip of rowStrips(grid))
483
+ for (const region of regions)
484
+ scanAreaStrip(region.area, grid, strip, (y, x0, x1) => mask.fill(1, y * width + x0, y * width + x1));
485
+ return mask;
486
+ }
487
+ /**
488
+ * Make the states of a `wall` edge and of impassable land (ZR-28) what the base game's impassable
489
+ * states are: `impassable = yes`,
490
+ * linked by `force_link_ownership_to` to the nearest passable state and owned as it is, `enclave`
491
+ * where the category exists, and without infrastructure, buildings, resources, victory points,
492
+ * ports or forts. Nearest counts province steps over land and water, since a wall often stands
493
+ * in what was sea; ties go to the passable state met through most borders, then the lowest id.
494
+ */
495
+ function finishImpassableStates(states, neighbors, context) {
496
+ const stateOfProvince = new Map();
497
+ for (const state of states)
498
+ for (const id of state.provinces)
499
+ stateOfProvince.set(id, state);
500
+ const enclave = context.stateCategories === undefined || context.stateCategories.has('enclave');
501
+ const nearestPassable = (start) => {
502
+ const seen = new Set(start);
503
+ let frontier = [...start].sort((a, b) => a - b);
504
+ while (frontier.length > 0) {
505
+ const found = new Map();
506
+ const next = [];
507
+ for (const id of frontier)
508
+ for (const other of [...neighbors[id]].sort((a, b) => a - b)) {
509
+ const state = stateOfProvince.get(other);
510
+ if (state !== undefined && state.impassable !== true)
511
+ found.set(state.id, (found.get(state.id) ?? 0) + 1);
512
+ if (seen.has(other))
513
+ continue;
514
+ seen.add(other);
515
+ next.push(other);
516
+ }
517
+ if (found.size > 0)
518
+ return [...found].sort(([a, left], [b, right]) => right - left || a - b)[0][0];
519
+ frontier = next;
520
+ }
521
+ return undefined;
522
+ };
523
+ for (const state of states) {
524
+ if (state.impassable !== true)
525
+ continue;
526
+ const link = nearestPassable(state.provinces);
527
+ if (link === undefined) {
528
+ delete state.link;
529
+ delete state.owner;
530
+ }
531
+ else {
532
+ state.link = link;
533
+ const owner = states[link - 1].owner;
534
+ if (owner === undefined)
535
+ delete state.owner;
536
+ else
537
+ state.owner = owner;
538
+ }
539
+ if (enclave)
540
+ state.category = 'enclave';
541
+ state.infrastructure = 0;
542
+ state.civilian = 0;
543
+ state.military = 0;
544
+ state.dockyard = 0;
545
+ state.airBase = 0;
546
+ state.resources = new Map();
547
+ state.victoryPoints = new Map();
548
+ state.navalBases = new Map();
549
+ state.forts = new Map();
550
+ }
551
+ }
468
552
  export function generateWorld(spec, context, options = {}) {
469
553
  const { width, height } = spec;
470
554
  if (width % 256 !== 0 || height % 256 !== 0)
@@ -490,6 +574,8 @@ export function generateWorld(spec, context, options = {}) {
490
574
  if (reference !== undefined && (reference.width !== width || reference.height !== height))
491
575
  throw new ServiceError('MAP_WORLD_REFERENCE_DIMENSIONS', 'Reference raster dimensions do not match the world');
492
576
  const geography = spec.geography;
577
+ if (spec.paintedRelief !== undefined && (reference === undefined || geography === undefined))
578
+ throw new ServiceError('MAP_RELIEF_PAINTED_INPUTS', 'relief.painted raises the relief from the classes of a reference picture onto a geography model; give both reference and geography', { reference: reference !== undefined, geography: geography !== undefined });
493
579
  if (geography !== undefined &&
494
580
  (geography.frame.width !== width || geography.frame.height !== height))
495
581
  throw new ServiceError('MAP_GEOGRAPHY_FRAME_MISMATCH', 'The geography model was resolved for a different map size than the world being created', {
@@ -507,10 +593,33 @@ export function generateWorld(spec, context, options = {}) {
507
593
  };
508
594
  const notes = [];
509
595
  const edge = spec.edge ?? { mode: 'none', bandPx: 0, polarPx: 0, rimPx: 0 };
596
+ let wallMask;
597
+ // Land no army may enter: painted `impassable_mountain` of the reference picture and the
598
+ // impassable regions of the geography model (ZR-28).
599
+ const impassableMask = impassableLand(reference?.impassable, geography, width, height);
600
+ // Impassable land is the highest ground even without relief.painted: then only it is raised.
601
+ const painted = geography === undefined
602
+ ? undefined
603
+ : spec.paintedRelief !== undefined && reference !== undefined
604
+ ? {
605
+ classes: reference.terrain,
606
+ impassable: impassableMask,
607
+ settings: spec.paintedRelief,
608
+ seed: spec.seed,
609
+ }
610
+ : impassableMask !== undefined
611
+ ? {
612
+ classes: new Uint8Array(width * height),
613
+ impassable: impassableMask,
614
+ settings: DEFAULT_PAINTED_RELIEF,
615
+ seed: spec.seed,
616
+ }
617
+ : undefined;
510
618
  if (edge.mode !== 'none') {
511
619
  assertFeaturesOutsideBand(edge, width, height, (spec.referenceCities ?? []).map(({ name, x, y }) => ({ name, x, y, kind: 'city' })));
512
620
  const applied = applyEdgePolicy(surface.kind, surface.elevation, width, height, edge, spec.seed, Math.max(40, Math.round(spec.landProvincePixels / 4)));
513
621
  notes.push(...applied.notes.map((note) => note));
622
+ wallMask = applied.wall;
514
623
  }
515
624
  // Lakes need a minimum size and may not touch the open sea (ADR 0053).
516
625
  for (const note of normalizeLakes(surface.kind, surface.elevation, width, height))
@@ -555,9 +664,10 @@ export function generateWorld(spec, context, options = {}) {
555
664
  kind: surface.kind,
556
665
  relief: spec.relief,
557
666
  rivers: { density: spec.riverDensity, count: spec.riverCount },
558
- adjustHeight: edge.mode === 'rim'
667
+ adjustHeight: hasRimRange(edge)
559
668
  ? (x, _y, value) => rimHeight(value, rimStrength(edge, width, x))
560
669
  : undefined,
670
+ painted,
561
671
  signal: options.signal,
562
672
  });
563
673
  for (const note of checked) {
@@ -616,9 +726,10 @@ export function generateWorld(spec, context, options = {}) {
616
726
  kind: surface.kind,
617
727
  relief: spec.relief,
618
728
  rivers: { density: spec.riverDensity, count: spec.riverCount },
619
- adjustHeight: edge.mode === 'rim'
729
+ adjustHeight: hasRimRange(edge)
620
730
  ? (x, _y, value) => rimHeight(value, rimStrength(edge, width, x))
621
731
  : undefined,
732
+ painted,
622
733
  signal: options.signal,
623
734
  });
624
735
  if (synthesized !== undefined) {
@@ -773,6 +884,32 @@ export function generateWorld(spec, context, options = {}) {
773
884
  const landIds = [...Array(count).keys()].filter((id) => provinces.kind[id] === LAND);
774
885
  const seaIds = [...Array(count).keys()].filter((id) => provinces.kind[id] === SEA);
775
886
  const lakeIds = [...Array(count).keys()].filter((id) => provinces.kind[id] === LAKE);
887
+ // A land province with most of its pixels in the wall, or in land painted impassable (ZR-28),
888
+ // belongs to impassable states.
889
+ const majorityIn = (mask) => {
890
+ const found = new Set();
891
+ if (mask === undefined)
892
+ return found;
893
+ const inside = new Uint32Array(count);
894
+ for (let pixel = 0; pixel < mask.length; pixel += 1)
895
+ if (mask[pixel] === 1)
896
+ inside[provinces.pixel[pixel]] += 1;
897
+ for (const id of landIds)
898
+ if (inside[id] * 2 > provinces.size[id])
899
+ found.add(id);
900
+ return found;
901
+ };
902
+ const wallProvinces = majorityIn(wallMask);
903
+ const impassableProvinces = new Set([...wallProvinces, ...majorityIn(impassableMask)]);
904
+ const offendingCities = (spec.referenceCities ?? []).filter(({ x, y }) => {
905
+ const pixel = Math.floor(y) * width + Math.floor(x);
906
+ return impassableMask?.[pixel] === 1;
907
+ });
908
+ if (offendingCities.length > 0)
909
+ throw new ServiceError('MAP_FEATURE_IN_IMPASSABLE', `${offendingCities.length} city or cities stand on impassable land: ${offendingCities
910
+ .slice(0, 5)
911
+ .map(({ name, x, y }) => `${name} (${Math.round(x)}, ${Math.round(y)})`)
912
+ .join('; ')}. Move them or repaint the land.`, { cities: offendingCities.slice(0, 20) });
776
913
  if (landIds.length < spec.countries.length)
777
914
  throw new ServiceError('MAP_WORLD_LAND_TOO_SMALL', 'The generated land has fewer provinces than countries; raise landCoverage or lower landProvincePixels', { landProvinces: landIds.length, countries: spec.countries.length });
778
915
  const coastal = (id) => [...provinces.neighbors[id]].some((other) => provinces.kind[id] === SEA
@@ -997,7 +1134,9 @@ export function generateWorld(spec, context, options = {}) {
997
1134
  };
998
1135
  });
999
1136
  const capitals = [];
1000
- const largest = [...landIds].sort((left, right) => provinces.size[right] - provinces.size[left] || left - right);
1137
+ const largest = landIds
1138
+ .filter((id) => !impassableProvinces.has(id))
1139
+ .sort((left, right) => provinces.size[right] - provinces.size[left] || left - right);
1001
1140
  const realmRules = spec.realms === undefined
1002
1141
  ? undefined
1003
1142
  : resolveRealmRules(spec.realms, {
@@ -1007,8 +1146,19 @@ export function generateWorld(spec, context, options = {}) {
1007
1146
  provinceSize: provinces.size,
1008
1147
  isLand: (id) => provinces.kind[id] === LAND,
1009
1148
  });
1010
- if (realmRules !== undefined)
1149
+ if (realmRules !== undefined) {
1150
+ const walled = realmRules.capitals.flatMap((id, index) => impassableProvinces.has(id)
1151
+ ? [{ tag: spec.countries[index]?.tag, wall: wallProvinces.has(id), ...center(id) }]
1152
+ : []);
1153
+ if (walled.length > 0) {
1154
+ const atSeam = walled.some(({ wall }) => wall);
1155
+ throw new ServiceError(atSeam ? 'MAP_EDGE_FEATURE_IN_BAND' : 'MAP_FEATURE_IN_IMPASSABLE', `${walled.length} capital(s) stand on impassable land${atSeam ? ' (the wall at the seam)' : ''}: ${walled
1156
+ .slice(0, 5)
1157
+ .map(({ tag, x, y }) => `${tag ?? '?'} (${Math.round(x)}, ${Math.round(y)})`)
1158
+ .join('; ')}. Move them${atSeam ? ' inland or narrow edge.rimPx' : ' onto passable land'}.`, { mode: edge.mode, rimPx: edge.rimPx, capitals: walled.slice(0, 20) });
1159
+ }
1011
1160
  capitals.push(...realmRules.capitals);
1161
+ }
1012
1162
  while (capitals.length < countryCount) {
1013
1163
  const countryIndex = capitals.length;
1014
1164
  const regionCandidates = largest.filter((id) => referenceOwners.get(id) === countryIndex && !capitals.includes(id));
@@ -1031,7 +1181,7 @@ export function generateWorld(spec, context, options = {}) {
1031
1181
  let best = -1;
1032
1182
  let bestDistance = -1;
1033
1183
  for (const id of landIds) {
1034
- if (capitals.includes(id))
1184
+ if (capitals.includes(id) || impassableProvinces.has(id))
1035
1185
  continue;
1036
1186
  const c = center(id);
1037
1187
  const distance = Math.min(...capitals.map((other) => Math.hypot(center(other).x - c.x, center(other).y - c.y)));
@@ -1144,7 +1294,7 @@ export function generateWorld(spec, context, options = {}) {
1144
1294
  // States: within each region and country, clusters of about provincesPerState.
1145
1295
  const groups = new Map();
1146
1296
  for (const id of landIds) {
1147
- const key = `${regionOf.get(id)}:${owner.get(id) ?? -1}`;
1297
+ const key = `${regionOf.get(id)}:${owner.get(id) ?? -1}${impassableProvinces.has(id) ? ':impassable' : ''}`;
1148
1298
  const list = groups.get(key) ?? [];
1149
1299
  list.push(id);
1150
1300
  groups.set(key, list);
@@ -1182,6 +1332,7 @@ export function generateWorld(spec, context, options = {}) {
1182
1332
  victoryPoints: new Map(),
1183
1333
  navalBases: new Map(),
1184
1334
  forts: new Map(),
1335
+ ...(key.endsWith(':impassable') ? { impassable: true } : {}),
1185
1336
  };
1186
1337
  states.push(draft);
1187
1338
  for (const id of sorted)
@@ -1370,6 +1521,7 @@ export function generateWorld(spec, context, options = {}) {
1370
1521
  if (stateOf.get(id).navalBases.has(id))
1371
1522
  hasPort = true;
1372
1523
  if (coastal(id) &&
1524
+ !impassableProvinces.has(id) &&
1373
1525
  (bestCoast === undefined || provinces.size[id] > provinces.size[bestCoast]))
1374
1526
  bestCoast = id;
1375
1527
  for (const next of provinces.neighbors[id])
@@ -1384,6 +1536,8 @@ export function generateWorld(spec, context, options = {}) {
1384
1536
  stateOf.get(bestCoast).navalBases.set(bestCoast, 1);
1385
1537
  }
1386
1538
  }
1539
+ if (impassableProvinces.size > 0)
1540
+ finishImpassableStates(states, provinces.neighbors, context);
1387
1541
  // Province IDs: 1-based in reading order of the province's first pixel; 0 is the null row.
1388
1542
  const provinceId = (index) => index + 1;
1389
1543
  // Unique colours, never black.
@@ -1435,7 +1589,7 @@ export function generateWorld(spec, context, options = {}) {
1435
1589
  '',
1436
1590
  ].join('\n')));
1437
1591
  add(`${map}/continent.txt`, text(`continents = {\n${[...new Set([...continentNames.map((_, index) => `world_continent_${index + 1}`), ...(context.continentKeys ?? [])])].map((key) => `\t${key}`).join('\n')}\n}\n`));
1438
- const rimRows = edge.mode === 'rim'
1592
+ const rimRows = hasRimRange(edge)
1439
1593
  ? rimAdjacencyRows({
1440
1594
  provincePixels: provinces.pixel,
1441
1595
  provinceKinds: provinces.kind,
@@ -1447,10 +1601,31 @@ export function generateWorld(spec, context, options = {}) {
1447
1601
  notes.push({
1448
1602
  code: 'MAP_EDGE_RIM_ADJACENCIES',
1449
1603
  severity: 'info',
1450
- message: `The rim edge policy wrote ${rimRows.length} impassable adjacency row(s) for provinces that meet across the seam`,
1604
+ message: `The ${edge.mode} edge policy wrote ${rimRows.length} impassable adjacency row(s) for provinces that meet across the seam`,
1451
1605
  details: { rows: rimRows.length },
1452
1606
  });
1453
1607
  const crossingRows = (gameplay?.crossings.rows ?? []).map(adjacencyRowText);
1608
+ // Impassable land and rows must not cut a realm apart or box it in by accident (ZR-28).
1609
+ if (impassableProvinces.size > 0 || (gameplay?.crossings.blocked.length ?? 0) > 0)
1610
+ for (const note of realmReachNotes({
1611
+ kind: provinces.kind,
1612
+ neighbors: provinces.neighbors,
1613
+ impassable: impassableProvinces,
1614
+ blocked: [
1615
+ ...(gameplay?.crossings.blocked ?? []),
1616
+ ...rimRows.map((row) => {
1617
+ const [from, to] = row.split(';').map(Number);
1618
+ return [from - 1, to - 1];
1619
+ }),
1620
+ ],
1621
+ crossings: (gameplay?.crossings.rows ?? [])
1622
+ .filter(({ type }) => type === 'sea')
1623
+ .map(({ from, to }) => [from - 1, to - 1]),
1624
+ owner,
1625
+ capitals,
1626
+ tags: spec.countries.map(({ tag }) => tag),
1627
+ }))
1628
+ notes.push(note);
1454
1629
  add(`${map}/adjacencies.csv`, text(`From;To;Type;Through;start_x;start_y;stop_x;stop_y;adjacency_rule_name;Comment\r\n${[...crossingRows, ...rimRows].map((row) => `${row}\r\n`).join('')}-1;-1;;-1;-1;-1;-1;-1;-1\r\n`));
1455
1630
  add(`${map}/adjacency_rules.txt`, text(gameplay === undefined
1456
1631
  ? '# No straits or canals in this world yet.\n'
@@ -1531,34 +1706,62 @@ export function generateWorld(spec, context, options = {}) {
1531
1706
  Math.abs(heights[Math.min(height - 1, y + 1) * width + x] -
1532
1707
  heights[Math.max(0, y - 1) * width + x]) <=
1533
1708
  2;
1709
+ const snowAt = (pixel, type) => synthesized !== undefined
1710
+ ? (synthesized.snow[pixel] === 1 || reference?.terrain[pixel] === 4) &&
1711
+ surface.kind[pixel] === LAND
1712
+ : reference === undefined
1713
+ ? type === 'mountain' && latitude(provinces.pixel[pixel]) > 0.7
1714
+ : reference.terrain[pixel] === 4 && surface.kind[pixel] === LAND;
1715
+ // A wall takes the look of the land it meets, row by row on each side.
1716
+ const wallLook = wallMask === undefined
1717
+ ? undefined
1718
+ : wallRowKinds({
1719
+ edge,
1720
+ width,
1721
+ height,
1722
+ wall: wallMask,
1723
+ landKind: (pixel) => {
1724
+ if (surface.kind[pixel] !== LAND)
1725
+ return undefined;
1726
+ const type = visualTerrain(pixel);
1727
+ if (snowAt(pixel, type))
1728
+ return 'snow';
1729
+ return WALL_TERRAIN_KINDS.includes(type)
1730
+ ? type
1731
+ : 'plains';
1732
+ },
1733
+ });
1534
1734
  for (let pixel = 0; pixel < width * height; pixel += 1) {
1535
- const id = provinces.pixel[pixel];
1536
1735
  const type = visualTerrain(pixel);
1537
- const snowy = synthesized !== undefined
1538
- ? (synthesized.snow[pixel] === 1 || reference?.terrain[pixel] === 4) &&
1539
- surface.kind[pixel] === LAND
1540
- : reference === undefined
1541
- ? type === 'mountain' && latitude(id) > 0.7
1542
- : reference.terrain[pixel] === 4 && surface.kind[pixel] === LAND;
1736
+ const snowy = snowAt(pixel, type);
1543
1737
  const x = pixel % width;
1544
- const rimmed = rimStrength(edge, width, x) > 0.35 && surface.kind[pixel] === LAND;
1545
- let index = snowy
1546
- ? reference === undefined
1547
- ? 16
1548
- : 19
1549
- : rimmed
1738
+ const walled = wallLook === undefined || wallMask[pixel] !== 1 || surface.kind[pixel] !== LAND
1739
+ ? undefined
1740
+ : (x < width / 2 ? wallLook.west : wallLook.east)[(pixel - x) / width];
1741
+ const rimmed = walled === undefined &&
1742
+ wallLook === undefined &&
1743
+ rimStrength(edge, width, x) > 0.35 &&
1744
+ surface.kind[pixel] === LAND;
1745
+ let index = walled !== undefined
1746
+ ? walled === 'snow'
1550
1747
  ? 16
1551
- : type === 'lakes'
1552
- ? lakeIndex
1553
- : (terrainIndex.get(type) ?? DEFAULT_TERRAIN_INDEX.get(type) ?? 0);
1554
- let colour = type === 'lakes' || type === 'ocean' || type === 'urban'
1555
- ? type === 'urban'
1556
- ? 'urban'
1557
- : type
1558
- : snowy || rimmed
1559
- ? 'snow'
1560
- : type;
1561
- if (calibrated && !snowy && !rimmed && surface.kind[pixel] === LAND) {
1748
+ : (terrainIndex.get(walled) ?? DEFAULT_TERRAIN_INDEX.get(walled) ?? 0)
1749
+ : snowy
1750
+ ? reference === undefined
1751
+ ? 16
1752
+ : 19
1753
+ : rimmed
1754
+ ? 16
1755
+ : type === 'lakes'
1756
+ ? lakeIndex
1757
+ : (terrainIndex.get(type) ?? DEFAULT_TERRAIN_INDEX.get(type) ?? 0);
1758
+ let colour = walled ??
1759
+ (type === 'lakes' || type === 'ocean' || type === 'urban'
1760
+ ? type
1761
+ : snowy || rimmed
1762
+ ? 'snow'
1763
+ : type);
1764
+ if (calibrated && walled === undefined && !snowy && !rimmed && surface.kind[pixel] === LAND) {
1562
1765
  // Variant graphical terrains by rule, so one class is not one flat texture.
1563
1766
  const y = (pixel - x) / width;
1564
1767
  if (type === 'plains' &&
@@ -1732,7 +1935,7 @@ export function generateWorld(spec, context, options = {}) {
1732
1935
  colormap[offset + 3] = cityPixels[source] === 15 ? 200 : 0;
1733
1936
  }
1734
1937
  }
1735
- if (edge.mode === 'rim')
1938
+ if (hasRimRange(edge))
1736
1939
  for (let y = 0; y < halfHeight; y += 1)
1737
1940
  for (let x = 0; x < halfWidth; x += 1) {
1738
1941
  const strength = rimStrength(edge, width, x * 2);
@@ -1809,6 +2012,12 @@ export function generateWorld(spec, context, options = {}) {
1809
2012
  `\tid = ${state.id}`,
1810
2013
  `\tname = "STATE_${state.id}"`,
1811
2014
  `\tmanpower = ${state.manpower}`,
2015
+ ...(state.impassable === true
2016
+ ? [
2017
+ '\timpassable = yes',
2018
+ ...(state.link === undefined ? [] : [`\tforce_link_ownership_to = ${state.link}`]),
2019
+ ]
2020
+ : []),
1812
2021
  `\tstate_category = ${state.category}`,
1813
2022
  ...(resources.length === 0
1814
2023
  ? []
@@ -15,6 +15,9 @@ export const ARGUMENT_EXAMPLES = {
15
15
  'hoi4.mod_index': '{"mode":"overview"} or {"mode":"next_id","kind":"event","namespace":"my_mod"}',
16
16
  'hoi4.localisation_inspect': '{"mode":"key","key":"my_event.1.t"} or {"mode":"audit"}',
17
17
  'hoi4.idea_inspect': '{"kind":"idea","id":"my_idea"} or {"kind":"character","audit":true}',
18
+ 'hoi4.system_inspect': '{"kind":"mio","id":"my_organization"} or {"kind":"on_actions","audit":true}',
19
+ 'hoi4.unit_inspect': '{"kind":"oob","id":"GER_1936"} or {"kind":"variant","audit":true}',
20
+ 'hoi4.asset_inspect': '{"kind":"sprite","id":"GFX_my_icon"} or {"kind":"flag","audit":true}',
18
21
  'hoi4.event_inspect': '{"mode":"lint","selector":"chaosx.nr14"} or {"mode":"trace","selector":"chaosx.nr14.1","direction":"downstream"}',
19
22
  'hoi4.event_render': '{"view":"overview","selector":"chaosx.nr14"}',
20
23
  'hoi4.focus_inspect': '{"treeId":"my_focus_tree"}',
@@ -22,7 +25,7 @@ export const ARGUMENT_EXAMPLES = {
22
25
  'hoi4.focus_rewrite': '{"relativePath":"common/national_focus/my_tree.txt","treeId":"my_focus_tree","layoutMode":"compact"}',
23
26
  'hoi4.gui_inspect': '{"windowName":"my_window"}',
24
27
  'hoi4.gui_render': '{"windowName":"my_window","scenario":{"id":"normal"}}',
25
- 'hoi4.gui_rewrite': '{"mode":"patches","relativePath":"interface/my_window.gui","windowName":"my_window","scenario":{"id":"normal"},"expectedSourceHash":"<sha256 of the file>","patches":[{"start":120,"end":130,"expectedText":"x = 10 y","text":"x = 40 y"}]}',
28
+ 'hoi4.gui_rewrite': '{"mode":"patches","relativePath":"interface/my_window.gui","windowName":"my_window","scenario":{"id":"normal"},"expectedSourceHash":"<sha256 of the file>","patches":[{"description":"Move the button right","start":120,"end":130,"expectedText":"x = 10 y","text":"x = 40 y"}]}',
26
29
  'hoi4.map_inspect': '{"query":"Brandenburg","lookupOnly":true} or {"layer":"state","tile":{"x":2600,"y":500,"width":256,"height":256}}',
27
30
  'hoi4.map_rewrite': '{"operations":[{"id":"new-state","kind":"create_state","provinceIds":[120,121],"displayName":"New State"}]}',
28
31
  'hoi4.tech_inspect': '{"mode":"scan"} or {"mode":"explain","technologyId":"my_tech"} or {"mode":"lint"}',
@@ -37,11 +40,56 @@ export const ARGUMENT_EXAMPLES = {
37
40
  'hoi4.job_inspect': '{"jobId":"job_<64 hex characters from a native task id>"}',
38
41
  'hoi4.job_cancel': '{"jobId":"job_<64 hex characters from a native task id>"}',
39
42
  };
40
- function describeIssue(issue) {
43
+ function defOf(schema) {
44
+ return schema?._zod?.def;
45
+ }
46
+ /**
47
+ * The fields the object at a path accepts, so an unknown field names the expected shape (#65).
48
+ * Wrappers are unwrapped and the fields of every union alternative are listed.
49
+ */
50
+ export function acceptedFields(schema, path, depth = 0) {
51
+ const def = defOf(schema);
52
+ if (def === undefined || depth > 32)
53
+ return [];
54
+ switch (def.type) {
55
+ case 'optional':
56
+ case 'nullable':
57
+ case 'default':
58
+ case 'prefault':
59
+ case 'readonly':
60
+ case 'catch':
61
+ case 'nonoptional':
62
+ return acceptedFields(def.innerType, path, depth + 1);
63
+ case 'pipe': {
64
+ // A preprocess step pipes from an unknown or a transform; then out checks the fields.
65
+ const fromInput = acceptedFields(def.in, path, depth + 1);
66
+ return fromInput.length > 0 ? fromInput : acceptedFields(def.out, path, depth + 1);
67
+ }
68
+ case 'union':
69
+ return [
70
+ ...new Set((def.options ?? []).flatMap((option) => acceptedFields(option, path, depth + 1))),
71
+ ];
72
+ case 'array':
73
+ return typeof path[0] === 'number'
74
+ ? acceptedFields(def.element, path.slice(1), depth + 1)
75
+ : [];
76
+ case 'record':
77
+ return path.length === 0 ? [] : acceptedFields(def.valueType, path.slice(1), depth + 1);
78
+ case 'object':
79
+ if (path.length === 0)
80
+ return Object.keys(def.shape ?? {});
81
+ return acceptedFields(def.shape?.[String(path[0])], path.slice(1), depth + 1);
82
+ default:
83
+ return [];
84
+ }
85
+ }
86
+ function describeIssue(issue, schema) {
41
87
  const field = issue.path.length === 0 ? '(arguments)' : issue.path.map(String).join('.');
42
88
  let problem = issue.message;
43
- if (issue.code === 'unrecognized_keys')
44
- problem = `unknown field${issue.keys.length === 1 ? '' : 's'} ${issue.keys.join(', ')}`;
89
+ if (issue.code === 'unrecognized_keys') {
90
+ const accepted = acceptedFields(schema, issue.path);
91
+ problem = `unknown field${issue.keys.length === 1 ? '' : 's'} ${issue.keys.join(', ')}${accepted.length === 0 ? '' : `; accepted fields: ${accepted.join(', ')}`}`;
92
+ }
45
93
  else if (issue.code === 'invalid_value')
46
94
  problem = `expected one of ${issue.values.map((value) => JSON.stringify(value)).join(', ')}`;
47
95
  else if (issue.code === 'invalid_union') {
@@ -49,14 +97,14 @@ function describeIssue(issue) {
49
97
  const closest = [...issue.errors].sort((left, right) => left.length - right.length)[0];
50
98
  const first = closest?.[0];
51
99
  if (first !== undefined) {
52
- const nested = describeIssue(first);
100
+ const nested = describeIssue(first, schema);
53
101
  problem = `${issue.message}; closest form: ${nested.field === '(arguments)' ? '' : `${nested.field}: `}${nested.problem}`;
54
102
  }
55
103
  }
56
104
  return { field, problem: problem.slice(0, 300) };
57
105
  }
58
- export function invalidArgumentsError(toolName, error) {
59
- const issues = error.issues.slice(0, 6).map(describeIssue);
106
+ export function invalidArgumentsError(toolName, error, schema) {
107
+ const issues = error.issues.slice(0, 6).map((issue) => describeIssue(issue, schema));
60
108
  const example = ARGUMENT_EXAMPLES[toolName];
61
109
  const message = [
62
110
  `Invalid arguments for ${toolName}: ${issues.map(({ field, problem }) => `${field}: ${problem}`).join('; ')}.`,
@@ -69,6 +117,6 @@ export function invalidArgumentsError(toolName, error) {
69
117
  ...(example === undefined ? {} : { example }),
70
118
  });
71
119
  }
72
- export function invalidArgumentsResult(toolName, error, workspaceId) {
73
- return errorResult(invalidArgumentsError(toolName, error), typeof workspaceId === 'string' ? workspaceId : 'current');
120
+ export function invalidArgumentsResult(toolName, error, workspaceId, schema) {
121
+ return errorResult(invalidArgumentsError(toolName, error, schema), typeof workspaceId === 'string' ? workspaceId : 'current');
74
122
  }
@@ -101,7 +101,7 @@ export function createModernOperationServer(engine, context = {}, tasks = new Op
101
101
  const workspaceId = request.params.arguments
102
102
  ?.workspaceId;
103
103
  return CallToolResultSchema.parse({
104
- ...invalidArgumentsResult(definition.name, input.error, workspaceId),
104
+ ...invalidArgumentsResult(definition.name, input.error, workspaceId, definition.inputSchema),
105
105
  resultType: 'complete',
106
106
  ttlMs: 0,
107
107
  cacheScope: 'private',
@@ -34,7 +34,7 @@ export function installRequestLifecycle(server, engine) {
34
34
  const schema = params.task === undefined ? inputSchema(params.name) : undefined;
35
35
  const parsed = schema?.safeParse(params.arguments ?? {});
36
36
  if (parsed !== undefined && !parsed.success)
37
- return Promise.resolve(invalidArgumentsResult(params.name, parsed.error, params.arguments?.workspaceId));
37
+ return Promise.resolve(invalidArgumentsResult(params.name, parsed.error, params.arguments?.workspaceId, schema));
38
38
  }
39
39
  const progress = progressReporter(extra);
40
40
  const taskCall = CallToolRequestSchema.safeParse(request);
@@ -37,6 +37,8 @@ const decisionOutputSchema = strictOperationResultSchema(z
37
37
  overrides: nonNegativeIntegerSchema,
38
38
  scenarios: nonNegativeIntegerSchema,
39
39
  unresolvedDefinitions: nonNegativeIntegerSchema,
40
+ decisionIds: z.array(z.string()).max(64).optional(),
41
+ decisionIdsTruncated: z.boolean().optional(),
40
42
  unresolvedSample: z
41
43
  .array(z.object({ id: z.string(), path: z.string(), reason: z.string() }).strict())
42
44
  .max(8)
@@ -141,7 +143,7 @@ export const analysisTaskTools = [
141
143
  {
142
144
  name: 'hoi4.decision_inspect',
143
145
  title: 'Inspect decisions and missions',
144
- description: 'Explain why a decision or mission is hidden, unavailable or unaffordable. Inspect conditions, costs and lifecycle for declared actors and targets, or compare proposed source. Example: {"mode":"inspect","id":"my_decision","scenarios":[{"id":"base","actor":"GER","state":{}}]}. Returns each scenario outcome inline; full evidence is linked.',
146
+ description: 'Explain why a decision or mission is hidden, unavailable or unaffordable. Inspect conditions, costs and lifecycle for declared actors and targets, or compare proposed source. Example: {"mode":"inspect","id":"my_decision","scenarios":[{"id":"base","actor":"GER","state":{}}]}. Inventory mode with an id lists only that category\'s decisions, or that one decision. Returns each scenario outcome inline; full evidence is linked.',
145
147
  inputSchema: decisionInspectRequestSchema,
146
148
  outputSchema: decisionOutputSchema,
147
149
  annotations: readOnlyAnalysisTool,
@@ -149,7 +151,7 @@ export const analysisTaskTools = [
149
151
  {
150
152
  name: 'hoi4.mechanic_test',
151
153
  title: 'Test scripted effects',
152
- description: 'Test what an effect, event option, decision or focus reward does to a declared state. Run steps and check assertions; unsupported effects stay unresolved. See docs/mechanics.md. Example: {"test":{"id":"t","scenario":{"schemaVersion":"1.0","id":"t","state":{"treasury":10}},"steps":[...],"assertions":[...]}}.',
154
+ description: 'Test what an effect, option, decision or focus reward does to a declared state (docs/mechanics.md). Example: {"test":{"id":"t","scenario":{"schemaVersion":"1.0","id":"t","state":{}},"steps":[{"kind":"effect","source":{"kind":"scripted_effect","id":"e"}}],"assertions":[{"id":"a","kind":"conservation","paths":[{"key":"x"},{"key":"y"}]}]}}.',
153
155
  inputSchema: mechanicInputSchema,
154
156
  outputSchema: mechanicOutputSchema,
155
157
  annotations: readOnlyAnalysisTool,
@@ -111,6 +111,19 @@ const eventInspectSummarySchema = z
111
111
  })
112
112
  .strict()
113
113
  .optional(),
114
+ flow: z
115
+ .object({
116
+ subject: z.string().max(1024),
117
+ producers: nonNegativeIntegerSchema,
118
+ consumers: nonNegativeIntegerSchema,
119
+ clears: nonNegativeIntegerSchema,
120
+ links: nonNegativeIntegerSchema,
121
+ unproducedReads: nonNegativeIntegerSchema,
122
+ producedAt: z.array(z.string().max(1100)).max(8),
123
+ readAt: z.array(z.string().max(1100)).max(8),
124
+ })
125
+ .strict()
126
+ .optional(),
114
127
  entryPoints: nonNegativeIntegerSchema.optional(),
115
128
  entryKinds: countMapSchema.optional(),
116
129
  automaticEvents: nonNegativeIntegerSchema.optional(),
@@ -88,7 +88,7 @@ export const guiTaskTools = [
88
88
  {
89
89
  name: 'hoi4.gui_rewrite',
90
90
  title: 'Create or edit a window',
91
- description: 'Create or edit a window using complete source, structured helpers or exact patches. Include related text files with additionalFiles; binary art must already be in the mod. Example: {"mode":"helpers","relativePath":"interface/my_window.gui","windowName":"my_window","scenario":{"id":"normal"},"helper":{...}}. Returns the changed files.',
91
+ description: 'Create or edit a window from complete source, structured helpers or exact patches. Add related text files in additionalFiles; binary art must already be in the mod. Example: {"mode":"helpers","relativePath":"interface/my_window.gui","windowName":"my_window","scenario":{"id":"normal"},"helper":{"root":{"id":"w","kind":"column","name":"my_window"}}}.',
92
92
  inputSchema: guiRewriteRequestSchema,
93
93
  outputSchema: guiPlanOutputSchema,
94
94
  annotations: {