hoi4-agent-tools 4.15.0 → 4.17.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 (101) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/README.md +1 -0
  3. package/dist/hoi4_agent_tools/core/analysis-checkpoints.js +11 -4
  4. package/dist/hoi4_agent_tools/core/engine-client.js +30 -1
  5. package/dist/hoi4_agent_tools/core/engine.js +56 -27
  6. package/dist/hoi4_agent_tools/core/managed-outputs.js +153 -26
  7. package/dist/hoi4_agent_tools/core/scanner.js +148 -7
  8. package/dist/hoi4_agent_tools/core/server-state.js +50 -2
  9. package/dist/hoi4_agent_tools/core/source/localisation.js +7 -1
  10. package/dist/hoi4_agent_tools/event/compare.js +47 -13
  11. package/dist/hoi4_agent_tools/focus/importer.js +2 -5
  12. package/dist/hoi4_agent_tools/focus/lint.js +2 -5
  13. package/dist/hoi4_agent_tools/focus/model.js +19 -0
  14. package/dist/hoi4_agent_tools/focus/tool-operations.js +16 -1
  15. package/dist/hoi4_agent_tools/focus/tool-support.js +14 -0
  16. package/dist/hoi4_agent_tools/map/appearance-validation.js +6 -1
  17. package/dist/hoi4_agent_tools/map/engine-raster.js +160 -0
  18. package/dist/hoi4_agent_tools/map/model.js +9 -8
  19. package/dist/hoi4_agent_tools/map/operations.js +74 -2
  20. package/dist/hoi4_agent_tools/map/partition-provinces.js +6 -2
  21. package/dist/hoi4_agent_tools/map/partition-tuning.js +37 -0
  22. package/dist/hoi4_agent_tools/map/service.js +25 -12
  23. package/dist/hoi4_agent_tools/map/territory-operations.js +114 -3
  24. package/dist/hoi4_agent_tools/map/territory-quality.js +39 -0
  25. package/dist/hoi4_agent_tools/map/territory.js +63 -2
  26. package/dist/hoi4_agent_tools/map/tool-operations.js +27 -1
  27. package/dist/hoi4_agent_tools/map/validation.js +23 -3
  28. package/dist/hoi4_agent_tools/map/water.js +13 -10
  29. package/dist/hoi4_agent_tools/map/world-outputs.js +53 -25
  30. package/dist/hoi4_agent_tools/map/world.js +51 -1
  31. package/dist/hoi4_agent_tools/mcp/tools/map.js +23 -0
  32. package/dist/hoi4_agent_tools/mcp/tools/reference.js +2 -2
  33. package/dist/hoi4_agent_tools/mcp/tools/technology.js +25 -1
  34. package/dist/hoi4_agent_tools/reference/closure.js +65 -0
  35. package/dist/hoi4_agent_tools/reference/command-phrases.json +7899 -1127
  36. package/dist/hoi4_agent_tools/reference/operations.js +38 -21
  37. package/dist/hoi4_agent_tools/reference/ranking.js +77 -2
  38. package/dist/hoi4_agent_tools/reference/script-validation.js +4 -2
  39. package/dist/hoi4_agent_tools/reference/service.js +45 -2
  40. package/dist/hoi4_agent_tools/reference/source-lookup.js +43 -121
  41. package/dist/hoi4_agent_tools/runtime.js +27 -11
  42. package/dist/hoi4_agent_tools/schemas/lenient-arguments.js +7 -1
  43. package/dist/hoi4_agent_tools/schemas/map.js +41 -0
  44. package/dist/hoi4_agent_tools/schemas/mod-tools.js +49 -0
  45. package/dist/hoi4_agent_tools/schemas/reference.js +1 -1
  46. package/dist/hoi4_agent_tools/schemas/script-validation.js +57 -3
  47. package/dist/hoi4_agent_tools/technology/operations.js +5 -0
  48. package/dist/hoi4_agent_tools/technology/queries.js +54 -0
  49. package/dist/hoi4_agent_tools/version.js +1 -1
  50. package/docs/configuration.md +1 -1
  51. package/docs/map.md +14 -10
  52. package/docs/research/reference-benchmark.md +64 -0
  53. package/docs/tools.md +20 -20
  54. package/docs/troubleshooting.md +4 -0
  55. package/engine/bin/darwin-arm64/hoi4-engine +0 -0
  56. package/engine/bin/linux-arm64/hoi4-engine +0 -0
  57. package/engine/bin/linux-x64/hoi4-engine +0 -0
  58. package/engine/bin/manifest.json +8 -8
  59. package/engine/bin/win32-x64/hoi4-engine.exe +0 -0
  60. package/npm-shrinkwrap.json +2 -2
  61. package/package.json +5 -3
  62. package/schemas/configuration.schema.json +1 -1
  63. package/schemas/continuous-focus-palette.schema.json +1 -1
  64. package/schemas/custom-weighted-pool.schema.json +1 -1
  65. package/schemas/decision-inspect-input.schema.json +1 -1
  66. package/schemas/error-log-input.schema.json +1 -1
  67. package/schemas/event-feature-manifest.schema.json +1 -1
  68. package/schemas/focus-plan.schema.json +1 -1
  69. package/schemas/focus-planning-sidecar.schema.json +1 -1
  70. package/schemas/geography-model.schema.json +1 -1
  71. package/schemas/gui-animation-source.schema.json +1 -1
  72. package/schemas/gui-helper.schema.json +1 -1
  73. package/schemas/gui-scenario.schema.json +1 -1
  74. package/schemas/helper-expansion-request.schema.json +1 -1
  75. package/schemas/helper-expansion-summary.schema.json +1 -1
  76. package/schemas/impact-inspect-input.schema.json +1 -1
  77. package/schemas/map-operation.schema.json +838 -728
  78. package/schemas/mechanic-test-input.schema.json +1 -1
  79. package/schemas/mod-index-input.schema.json +1 -1
  80. package/schemas/operation-result.schema.json +1 -1
  81. package/schemas/package-check-input.schema.json +1 -1
  82. package/schemas/package-manifest.schema.json +1 -1
  83. package/schemas/probability-analysis-result.schema.json +1 -1
  84. package/schemas/probability-compare-input.schema.json +1 -1
  85. package/schemas/probability-evaluate-input.schema.json +1 -1
  86. package/schemas/probability-inspect-input.schema.json +1 -1
  87. package/schemas/probability-render-input.schema.json +1 -1
  88. package/schemas/probability-scenario-set.schema.json +1 -1
  89. package/schemas/probability-sequence-input.schema.json +1 -1
  90. package/schemas/probability-simulate-input.schema.json +1 -1
  91. package/schemas/probability-sweep-input.schema.json +1 -1
  92. package/schemas/reference-context-input.schema.json +1 -1
  93. package/schemas/reference-read-input.schema.json +1 -1
  94. package/schemas/reference-search-input.schema.json +2 -2
  95. package/schemas/reference-sheets.schema.json +1 -1
  96. package/schemas/scenario-suite.schema.json +1 -1
  97. package/schemas/scenario-test-input.schema.json +1 -1
  98. package/schemas/script-validate-input.schema.json +7 -1
  99. package/schemas/shared-scenario.schema.json +1 -1
  100. package/schemas/source-lookup-input.schema.json +1 -1
  101. package/server.json +2 -2
@@ -3,6 +3,7 @@ import { BORDER_PROVINCE_KIND, buildBorderEdgeTableSteps, scoreBorderAssignment,
3
3
  import { borderQualityInputFromIndex } from './border-quality-input.js';
4
4
  import { cloneState, commitState, currentIndex, uniqueStrings, } from './operations.js';
5
5
  import { clusterProvinces } from './partition-groups.js';
6
+ import { declaredCountryTags } from './references.js';
6
7
  import { restructureStates } from './state-restructure.js';
7
8
  import { buildTerritoryAtoms, buildTerritoryProvinceGraph, } from './territory-graph.js';
8
9
  import { growTerritory, TERRITORY_MAX_COUNTRIES, } from './territory.js';
@@ -172,14 +173,50 @@ function buildAtomModel(world, unit, scope) {
172
173
  excluded,
173
174
  };
174
175
  }
176
+ /** The land province nearest the centre of a water province, searched within 256 pixels. */
177
+ function nearestLandProvince(world, province) {
178
+ const raster = world.index.raster;
179
+ if (raster === undefined)
180
+ return undefined;
181
+ const { width, height, provinceIds } = raster;
182
+ let sumX = 0;
183
+ let sumY = 0;
184
+ let count = 0;
185
+ for (let pixel = 0; pixel < provinceIds.length; pixel += 1)
186
+ if (provinceIds[pixel] === province) {
187
+ sumX += pixel % width;
188
+ sumY += Math.floor(pixel / width);
189
+ count += 1;
190
+ }
191
+ if (count === 0)
192
+ return undefined;
193
+ const cx = Math.round(sumX / count);
194
+ const cy = Math.round(sumY / count);
195
+ for (let radius = 1; radius <= 256; radius += 1)
196
+ for (let dy = -radius; dy <= radius; dy += 1)
197
+ for (let dx = -radius; dx <= radius; dx += 1) {
198
+ if (Math.max(Math.abs(dx), Math.abs(dy)) !== radius)
199
+ continue;
200
+ const y = cy + dy;
201
+ if (y < 0 || y >= height)
202
+ continue;
203
+ const x = (((cx + dx) % width) + width) % width;
204
+ const id = provinceIds[y * width + x];
205
+ if (isLandProvince(world.table, id))
206
+ return id;
207
+ }
208
+ return undefined;
209
+ }
175
210
  function resolveProvince(world, model, province, label) {
176
211
  const { index, table } = world;
177
212
  if (!index.definitionsById.has(province))
178
213
  refuse('MAP_TERRITORY_PROVINCE_UNKNOWN', `${label}: province ${province} does not exist`, {
179
214
  province,
180
215
  });
181
- if (!isLandProvince(table, province))
182
- refuse('MAP_TERRITORY_SEED_IN_WATER', `${label}: province ${province} is not land (sea and lake provinces cannot be owned)`, { province });
216
+ if (!isLandProvince(table, province)) {
217
+ const nearest = nearestLandProvince(world, province);
218
+ refuse('MAP_TERRITORY_SEED_IN_WATER', `${label}: province ${province} is not land (sea and lake provinces cannot be owned)${nearest === undefined ? '' : `; the nearest land province is ${nearest}`}`, { province, ...(nearest === undefined ? {} : { nearestLandProvince: nearest }) });
219
+ }
183
220
  const atom = model.atoms.atomOfProvince[province];
184
221
  if (atom < 0)
185
222
  refuse('MAP_TERRITORY_PROVINCE_WITHOUT_STATE', `${label}: province ${province} belongs to no state, so it cannot have an owner`, { province });
@@ -348,6 +385,39 @@ function growInRequestTerms(model, countries, options) {
348
385
  });
349
386
  }
350
387
  }
388
+ /**
389
+ * The culture groups of `assign_territory` on the atoms: a province atom takes its province's
390
+ * group, a state atom the group most of its land provinces have (the lowest name on a tie).
391
+ */
392
+ function atomGroups(world, model, operation) {
393
+ const input = operation.groups;
394
+ if (input === undefined || Object.keys(input).length === 0)
395
+ return {};
396
+ const names = [...new Set(Object.values(input))].sort();
397
+ const code = new Map(names.map((name, position) => [name, position]));
398
+ const votes = new Map();
399
+ for (const [key, name] of Object.entries(input)) {
400
+ const province = Number(key);
401
+ if (!Number.isInteger(province) || !world.index.definitionsById.has(province))
402
+ refuse('MAP_TERRITORY_PROVINCE_UNKNOWN', `groups: province ${key} does not exist`, {
403
+ province: key,
404
+ });
405
+ const atom = model.atoms.atomOfProvince[province] ?? -1;
406
+ if (atom < 0)
407
+ continue;
408
+ const tally = votes.get(atom) ?? new Map();
409
+ tally.set(code.get(name), (tally.get(code.get(name)) ?? 0) + 1);
410
+ votes.set(atom, tally);
411
+ }
412
+ const groups = new Int32Array(model.atoms.count).fill(-1);
413
+ for (const [atom, tally] of votes)
414
+ groups[atom] = [...tally].sort(([a, x], [b, y]) => y - x || a - b)[0][0];
415
+ return {
416
+ groups,
417
+ ...(operation.groupPenalty === undefined ? {} : { groupPenalty: operation.groupPenalty }),
418
+ ...(operation.groupHard === true ? { groupHard: true } : {}),
419
+ };
420
+ }
351
421
  function limited(values, limit = 1_000) {
352
422
  return values.slice(0, limit);
353
423
  }
@@ -386,6 +456,8 @@ export function* applyAssignTerritory(base, changes, allocations, operation, sig
386
456
  };
387
457
  if (country.overlord !== undefined)
388
458
  entry.overlord = country.overlord;
459
+ if (country.fixed === true)
460
+ entry.fixed = true;
389
461
  if (country.mergeInto !== undefined)
390
462
  entry.mergeInto = country.mergeInto;
391
463
  countries.push(entry);
@@ -412,6 +484,7 @@ export function* applyAssignTerritory(base, changes, allocations, operation, sig
412
484
  ? {}
413
485
  : { maxShareChange: operation.smoothing.maxShareChange }),
414
486
  },
487
+ ...atomGroups(world, model, operation),
415
488
  ...(signal === undefined ? {} : { signal }),
416
489
  };
417
490
  const result = growInRequestTerms(model, countries, options);
@@ -499,7 +572,45 @@ export function* applyAssignTerritory(base, changes, allocations, operation, sig
499
572
  ...(operation.borderTargets === undefined ? {} : { targets: operation.borderTargets }),
500
573
  },
501
574
  };
502
- return { diagnostics: territoryDiagnostics(operation, world, report, result, model), report };
575
+ const undefinedTags = undefinedTagDiagnostics(index, operation);
576
+ if (operation.strictTags === true && undefinedTags.length > 0)
577
+ refuse('MAP_TERRITORY_TAG_UNDEFINED', `strictTags: no common/country_tags file declares ${undefinedTags
578
+ .map(({ details }) => String(details?.tag))
579
+ .join(', ')}; declare the countries first or leave strictTags off`, { tags: undefinedTags.map(({ details }) => details?.tag) });
580
+ return {
581
+ diagnostics: [
582
+ ...territoryDiagnostics(operation, world, report, result, model),
583
+ ...undefinedTags,
584
+ ],
585
+ report,
586
+ };
587
+ }
588
+ /**
589
+ * A warning for each country or overlord tag no active `common/country_tags` file declares: the
590
+ * states are written, but the game does not know the owner until the country is defined. Nothing
591
+ * is said when the workspace declares no tags at all, since then nothing can be checked.
592
+ */
593
+ function undefinedTagDiagnostics(index, operation) {
594
+ const declared = declaredCountryTags(index.sourceFiles);
595
+ if (declared === undefined)
596
+ return [];
597
+ const used = new Map();
598
+ for (const country of operation.countries) {
599
+ used.set(country.tag, 'country');
600
+ if (country.overlord !== undefined && !used.has(country.overlord))
601
+ used.set(country.overlord, 'overlord');
602
+ }
603
+ return [...used]
604
+ .filter(([tag]) => !declared.has(tag))
605
+ .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
606
+ .map(([tag, role]) => ({
607
+ code: 'MAP_TERRITORY_TAG_UNDEFINED',
608
+ severity: 'warning',
609
+ category: 'map',
610
+ operationId: operation.id,
611
+ message: `${tag} gets land, but no common/country_tags file declares it; define the country (country_tags, common/countries and history/countries) before the game loads the mod`,
612
+ details: { tag, role },
613
+ }));
503
614
  }
504
615
  const excludedCache = new WeakMap();
505
616
  function excludedSet(model) {
@@ -187,3 +187,42 @@ export function territoryArtifactContent(reports, quality) {
187
187
  skippedInputs: quality?.skippedInputs ?? [],
188
188
  };
189
189
  }
190
+ /**
191
+ * The compact result of the territory operations as `map-territory-assignment.json`: who owns
192
+ * which provinces and which provinces make each new or changed state, without the whole map.
193
+ */
194
+ export function territoryAssignmentContent(reports, finalIndex) {
195
+ const touched = new Set();
196
+ const removed = new Set();
197
+ // The report lists are capped, so every state of an assigned country counts as well.
198
+ const tags = new Set();
199
+ for (const report of reports) {
200
+ for (const id of [...report.states.changed, ...report.states.created])
201
+ touched.add(id);
202
+ for (const id of report.states.removed)
203
+ removed.add(id);
204
+ for (const country of report.stats?.countries ?? [])
205
+ tags.add(country.tag);
206
+ }
207
+ for (const state of finalIndex.states)
208
+ if (state.owner !== undefined && tags.has(state.owner))
209
+ touched.add(state.id);
210
+ const owners = {};
211
+ const states = {};
212
+ for (const state of [...finalIndex.states].sort((a, b) => a.id - b.id)) {
213
+ if (!touched.has(state.id))
214
+ continue;
215
+ const provinces = [...state.provinces].sort((a, b) => a - b);
216
+ states[String(state.id)] = provinces;
217
+ const tag = state.owner ?? '';
218
+ owners[tag] = [...(owners[tag] ?? []), ...provinces];
219
+ }
220
+ for (const list of Object.values(owners))
221
+ list.sort((a, b) => a - b);
222
+ return {
223
+ schemaVersion: 1,
224
+ owners,
225
+ states,
226
+ removedStates: [...removed].sort((a, b) => a - b),
227
+ };
228
+ }
@@ -219,6 +219,9 @@ class TerritoryRun {
219
219
  rules;
220
220
  barriers;
221
221
  seaCost;
222
+ groups;
223
+ groupFactor;
224
+ groupHard;
222
225
  jitter;
223
226
  seed;
224
227
  tolerance;
@@ -244,6 +247,9 @@ class TerritoryRun {
244
247
  };
245
248
  this.barriers = options.barriers ?? 'natural';
246
249
  this.seaCost = options.seaCost ?? 3;
250
+ this.groups = options.groups;
251
+ this.groupFactor = 1 + (options.groupPenalty ?? 2);
252
+ this.groupHard = options.groupHard === true;
247
253
  this.jitter = options.jitter ?? 0.08;
248
254
  this.seed = options.seed ?? 0;
249
255
  this.tolerance = options.shareTolerance ?? 0.15;
@@ -422,6 +428,10 @@ class TerritoryRun {
422
428
  high[index] += islandTotal;
423
429
  }
424
430
  const fixedTarget = new Float64Array(entityCount).fill(-1);
431
+ // A fixed country's target is the land it starts with.
432
+ for (const [index, entity] of entities.entries())
433
+ if (entity.fixed)
434
+ fixedTarget[index] = [...new Set([...entity.seeds, ...entity.forced])].reduce((sum, atom) => sum + (open[atom] === 1 ? graph.size[atom] : 0), 0);
425
435
  this.lastTargets = targets;
426
436
  for (let pass = 0; pass < entityCount + 1; pass += 1) {
427
437
  let remaining = openWeight;
@@ -471,22 +481,45 @@ class TerritoryRun {
471
481
  for (let index = 0; index < entityCount; index += 1)
472
482
  for (const atom of sources(index))
473
483
  give(atom, index);
484
+ const groups = this.groups;
485
+ // A step across a culture line costs more, or is never taken when the lines are hard.
486
+ const across = (atom, next) => {
487
+ if (groups === undefined)
488
+ return 1;
489
+ const from = groups[atom];
490
+ const to = groups[next];
491
+ if (from < 0 || to < 0 || from === to)
492
+ return 1;
493
+ return this.groupHard ? 0 : this.groupFactor;
494
+ };
474
495
  const relax = (atom, index, distance) => {
475
496
  const entity = entities[index];
497
+ if (entity.fixed)
498
+ return;
476
499
  // With the nearest policy an unseeded landmass is reached atom by atom over sea edges.
477
500
  const byLand = !(this.rules.islandPolicy === 'nearest' && seeded[component[atom]] === 0);
478
501
  for (let slot = graph.offsets[atom]; byLand && slot < graph.offsets[atom + 1]; slot += 1) {
479
502
  const next = graph.to[slot];
480
503
  if (open[next] === 0 || owner[next] >= 0 || entity.blocked.has(next))
481
504
  continue;
482
- heap.push(distance + (this.baseCost[slot] * regionFactor(index, next)) / multiplier[index], index, next);
505
+ const culture = across(atom, next);
506
+ if (culture === 0)
507
+ continue;
508
+ heap.push(distance +
509
+ (this.baseCost[slot] * regionFactor(index, next) * culture) / multiplier[index], index, next);
483
510
  }
484
511
  for (let slot = seaOffsets[atom]; slot < seaOffsets[atom + 1]; slot += 1) {
485
512
  const next = seaAdjacent[slot];
486
513
  if (owner[next] >= 0 || entity.blocked.has(next))
487
514
  continue;
515
+ const seaCulture = across(atom, next);
516
+ if (seaCulture === 0)
517
+ continue;
488
518
  heap.push(distance +
489
- (this.centreDistance(atom, next) * this.seaCost * jitterSea(atom, next)) /
519
+ (this.centreDistance(atom, next) *
520
+ this.seaCost *
521
+ jitterSea(atom, next) *
522
+ seaCulture) /
490
523
  multiplier[index], index, next);
491
524
  }
492
525
  };
@@ -624,6 +657,8 @@ class TerritoryRun {
624
657
  #joinCutSeeds(entities, owner, forcedExtra, open, component, sourceOwner) {
625
658
  const graph = this.graph;
626
659
  for (const [index, entity] of entities.entries()) {
660
+ if (entity.fixed)
661
+ continue;
627
662
  const capital = entity.seeds[0] ?? entity.forced[0];
628
663
  if (capital === undefined)
629
664
  continue;
@@ -730,6 +765,10 @@ class TerritoryRun {
730
765
  tried.add(candidate);
731
766
  if (entities[candidate].blocked.has(atom))
732
767
  continue;
768
+ if (entities[candidate].fixed || entities[from].fixed)
769
+ continue;
770
+ if (this.groupHard && !this.#sameGroupNeighbour(atom, candidate, owner))
771
+ continue;
733
772
  // Artificial border length before and after, over the atom's edges.
734
773
  let gain = 0;
735
774
  for (let s = graph.offsets[atom]; s < graph.offsets[atom + 1]; s += 1) {
@@ -765,6 +804,19 @@ class TerritoryRun {
765
804
  break;
766
805
  }
767
806
  }
807
+ /** With hard culture lines: whether `atom` touches land of `candidate` in its own group. */
808
+ #sameGroupNeighbour(atom, candidate, owner) {
809
+ const groups = this.groups;
810
+ if (groups === undefined || groups[atom] < 0)
811
+ return true;
812
+ const graph = this.graph;
813
+ for (let slot = graph.offsets[atom]; slot < graph.offsets[atom + 1]; slot += 1) {
814
+ const next = graph.to[slot];
815
+ if (owner[next] === candidate && (groups[next] < 0 || groups[next] === groups[atom]))
816
+ return true;
817
+ }
818
+ return false;
819
+ }
768
820
  /** Whether the neighbours of `atom` owned by `from` stay joined when `atom` is taken away. */
769
821
  #staysConnected(atom, from, owner) {
770
822
  const graph = this.graph;
@@ -843,6 +895,7 @@ function validateCountries(atoms, countries, options) {
843
895
  forced,
844
896
  blocked: new Set(country.blocked ?? []),
845
897
  home: new Set(country.homeRegions ?? []),
898
+ fixed: country.fixed === true,
846
899
  overlord: -1,
847
900
  mergeInto: -1,
848
901
  });
@@ -891,6 +944,7 @@ export function growTerritory(atoms, countries, options = {}) {
891
944
  ['jitter', options.jitter ?? 0.08, 0, 0.5],
892
945
  ['barrierStrength', options.barrierStrength ?? 6, 0, 60],
893
946
  ['seaCost', options.seaCost ?? 3, 1, 50],
947
+ ['groupPenalty', options.groupPenalty ?? 2, 0, 100],
894
948
  ['smoothing.maxShareChange', options.smoothing?.maxShareChange ?? 0.15, 0, 1],
895
949
  ])
896
950
  if (!Number.isFinite(value) || value < low || value > high)
@@ -904,6 +958,11 @@ export function growTerritory(atoms, countries, options = {}) {
904
958
  option: 'smoothing.passes',
905
959
  value: passes,
906
960
  });
961
+ if (options.groups !== undefined && options.groups.length !== atoms.count)
962
+ refuse('MAP_TERRITORY_OPTION_INVALID', 'Territory groups must give one group per atom', {
963
+ option: 'groups',
964
+ value: options.groups.length,
965
+ });
907
966
  const resolved = validateCountries(atoms, countries, options);
908
967
  const run = new TerritoryRun(atoms, options);
909
968
  const signal = options.signal;
@@ -915,6 +974,7 @@ export function growTerritory(atoms, countries, options = {}) {
915
974
  forced: resolved[index].forced,
916
975
  blocked: resolved[index].blocked,
917
976
  home: resolved[index].home,
977
+ fixed: resolved[index].fixed,
918
978
  });
919
979
  // Subjects form a tree under their overlord; a bloc is grown as one entity first.
920
980
  const children = new Map();
@@ -941,6 +1001,7 @@ export function growTerritory(atoms, countries, options = {}) {
941
1001
  forced: members.flatMap((member) => resolved[member].forced),
942
1002
  blocked,
943
1003
  home: new Set(members.flatMap((member) => [...resolved[member].home])),
1004
+ fixed: members.every((member) => resolved[member].fixed),
944
1005
  };
945
1006
  };
946
1007
  const origin = new Int32Array(n).fill(-1);
@@ -11,7 +11,31 @@ import { allocateMapIdentifiersAsync, WORLD_OUTPUT_PATH_SAMPLE, } from './operat
11
11
  import { compactTerritoryReport } from './territory-operations.js';
12
12
  import { borderQualityDiagnostics } from './border-quality.js';
13
13
  import { measureIndexBorderNaturalness, summarizeBorderQuality, } from './border-quality-input.js';
14
- import { buildMapCatalog, lookupMapCoordinate, searchMapCatalog } from './catalog.js';
14
+ import { buildMapCatalog, lookupMapCoordinate, searchMapCatalog, } from './catalog.js';
15
+ /** Matches named inline, so a lookup answers without reading its artifact. */
16
+ const INLINE_MATCH_LIMIT = 20;
17
+ function inlineMatches(queryMatches, coordinateMatches) {
18
+ return {
19
+ ...(queryMatches.length === 0
20
+ ? {}
21
+ : {
22
+ matches: queryMatches
23
+ .slice(0, INLINE_MATCH_LIMIT)
24
+ .map(({ kind, id, key, displayName }) => ({ kind, id, key, name: displayName })),
25
+ }),
26
+ ...(coordinateMatches.length === 0
27
+ ? {}
28
+ : {
29
+ coordinateMatches: coordinateMatches
30
+ .slice(0, INLINE_MATCH_LIMIT)
31
+ .map(({ provinceId, stateIds, regionIds }) => ({
32
+ provinceId,
33
+ stateIds: stateIds.slice(0, 16),
34
+ regionIds: regionIds.slice(0, 16),
35
+ })),
36
+ }),
37
+ };
38
+ }
15
39
  import { GEOGRAPHY_FEATURE_KINDS } from './geography/model.js';
16
40
  import { operationHasGeography } from './geography/preparation.js';
17
41
  import { unsupportedGeographyParts } from './relief/index.js';
@@ -745,6 +769,7 @@ export async function inspectMap(engine, nudger, input, context) {
745
769
  allocationCount: 0,
746
770
  queryMatchCount: queryMatches.length,
747
771
  coordinateMatchCount: coordinateMatches.length,
772
+ ...inlineMatches(queryMatches, coordinateMatches),
748
773
  overviewRendered: false,
749
774
  provinceGeometryCount: 0,
750
775
  provinceGeometryPixelCount: 0,
@@ -971,6 +996,7 @@ export async function inspectMap(engine, nudger, input, context) {
971
996
  allocationCount: allocationPreviews.length,
972
997
  queryMatchCount: queryMatches.length,
973
998
  coordinateMatchCount: coordinateMatches.length,
999
+ ...inlineMatches(queryMatches, coordinateMatches),
974
1000
  overviewRendered,
975
1001
  provinceGeometryCount: provinceGeometry?.provinces.length ?? 0,
976
1002
  provinceGeometryPixelCount: provinceGeometry?.pixelCount ?? 0,
@@ -240,6 +240,25 @@ function* provinceHoleCounts(raster, components, signal) {
240
240
  }
241
241
  return holes;
242
242
  }
243
+ /**
244
+ * The TypeScript geometry checks on a raster, run to the end: the reference the engine's
245
+ * topology (ADR 0084) is checked against in tests and `scripts/map-raster-parity.ts`.
246
+ */
247
+ export function typeScriptProvinceTopology(raster) {
248
+ const run = (steps) => {
249
+ for (;;) {
250
+ const next = steps.next();
251
+ if (next.done === true)
252
+ return next.value;
253
+ }
254
+ };
255
+ const components = run(provinceComponents(raster));
256
+ return {
257
+ components,
258
+ holes: run(provinceHoleCounts(raster, components)),
259
+ thin: run(provinceThinPixels(raster)),
260
+ };
261
+ }
243
262
  function* validateGeometry(index, diagnostics, options) {
244
263
  yield* cancellationCheckpoint(options.signal);
245
264
  const bitmap = index.provinceBitmap;
@@ -366,9 +385,10 @@ function* validateGeometry(index, diagnostics, options) {
366
385
  },
367
386
  });
368
387
  }
369
- const components = yield* provinceComponents(raster, options.signal);
370
- const holes = yield* provinceHoleCounts(raster, components, options.signal);
371
- const thin = yield* provinceThinPixels(raster, options.signal);
388
+ // The engine computes these with the raster (ADR 0084); a raster built in TypeScript does not.
389
+ const components = raster.topology?.components ?? (yield* provinceComponents(raster, options.signal));
390
+ const holes = raster.topology?.holes ?? (yield* provinceHoleCounts(raster, components, options.signal));
391
+ const thin = raster.topology?.thin ?? (yield* provinceThinPixels(raster, options.signal));
372
392
  for (const definition of index.definitions) {
373
393
  if (definition.id === 0)
374
394
  continue;
@@ -54,29 +54,32 @@ export function landDistanceField(kind, width, height, limit = 255) {
54
54
  distance[pixel] = 0;
55
55
  queue[tail++] = pixel;
56
56
  }
57
+ // No closure per pixel: on the game's 11.5 million pixels it was most of this function's time.
57
58
  while (head < tail) {
58
59
  const pixel = queue[head++];
59
60
  const next = distance[pixel] + 1;
60
61
  if (next >= limit)
61
62
  continue;
62
63
  const x = pixel % width;
63
- const visit = (other) => {
64
- if (distance[other] === limit && kind[other] !== LAND) {
65
- distance[other] = next;
66
- queue[tail++] = other;
67
- }
68
- };
69
64
  if (x > 0)
70
- visit(pixel - 1);
65
+ tail = reachWater(kind, distance, queue, tail, pixel - 1, next, limit);
71
66
  if (x < width - 1)
72
- visit(pixel + 1);
67
+ tail = reachWater(kind, distance, queue, tail, pixel + 1, next, limit);
73
68
  if (pixel >= width)
74
- visit(pixel - width);
69
+ tail = reachWater(kind, distance, queue, tail, pixel - width, next, limit);
75
70
  if (pixel < total - width)
76
- visit(pixel + width);
71
+ tail = reachWater(kind, distance, queue, tail, pixel + width, next, limit);
77
72
  }
78
73
  return distance;
79
74
  }
75
+ /** Give an unreached water pixel its distance and queue it; returns the new queue end. */
76
+ function reachWater(kind, distance, queue, tail, other, next, limit) {
77
+ if (distance[other] !== limit || kind[other] === LAND)
78
+ return tail;
79
+ distance[other] = next;
80
+ queue[tail] = other;
81
+ return tail + 1;
82
+ }
80
83
  /**
81
84
  * Enforce the lake rules on a raster of 0 sea, 1 land and 2 lake (modified in place, with the
82
85
  * matching elevation values): lake water that touches the open sea is sea, and enclosed water
@@ -1,5 +1,5 @@
1
1
  import path from 'node:path';
2
- import { planManagedOutputs } from '../core/managed-outputs.js';
2
+ import { planManagedOutputs, refreshManagedOutputs, } from '../core/managed-outputs.js';
3
3
  export const WORLD_OUTPUT_MANIFEST = '.hoi4-agent-world.json';
4
4
  /** Country outputs of a generated world: tags, country files, histories, units, flags, bookmark. */
5
5
  export function isWorldCountryOutput(relativePath) {
@@ -19,31 +19,56 @@ export function reconcileWorldOutputs(sources, proposed, operationId, mapRoot, s
19
19
  return planWorldOutputs(sources, proposed, operationId, mapRoot, stateRoots, localisationRoots)
20
20
  .changes;
21
21
  }
22
- export function planWorldOutputs(sources, proposed, operationId, mapRoot, stateRoots, localisationRoots, options = {}) {
23
- const mapFiles = new Set([
24
- 'provinces.bmp',
25
- 'definition.csv',
26
- 'default.map',
27
- 'continent.txt',
28
- 'adjacencies.csv',
29
- 'adjacency_rules.txt',
30
- 'positions.txt',
31
- 'ambient_object.txt',
32
- 'heightmap.bmp',
33
- 'terrain.bmp',
34
- 'rivers.bmp',
35
- 'trees.bmp',
36
- 'cities.bmp',
37
- 'world_normal.bmp',
38
- 'buildings.txt',
39
- 'unitstacks.txt',
40
- 'weatherpositions.txt',
41
- 'supply_nodes.txt',
42
- 'railways.txt',
43
- ]);
44
- const permitsPath = (name) => {
22
+ /**
23
+ * The world inventory brought up to date with the bytes a request leaves behind: every recorded
24
+ * output the request writes gets its new hash, or with `adoptAll` every recorded output its
25
+ * current bytes (`record_world_outputs`). Undefined when the workspace has no world inventory.
26
+ */
27
+ export function refreshWorldOutputs(sources, proposed, roots, options = {}) {
28
+ const permits = worldOutputPermits(roots);
29
+ return refreshManagedOutputs({
30
+ manifestPath: WORLD_OUTPUT_MANIFEST,
31
+ sources,
32
+ proposed,
33
+ // New files join the record where the world keeps its map outputs; country files stay out,
34
+ // since a workspace may own its countries (ADR 0069).
35
+ addable: (name) => permits(name) && !isWorldCountryOutput(name),
36
+ // States and strategic regions are in every map scan; bitmaps, colour maps and the world
37
+ // scripts only in some, so only the first can be known to be gone.
38
+ alwaysScanned: (name) => {
39
+ const dir = path.posix.dirname(name);
40
+ return roots.stateRoots.includes(dir) || dir === `${roots.mapRoot}/strategicregions`;
41
+ },
42
+ ...(options.adoptAll === true ? { adoptAll: true } : {}),
43
+ ...(options.adoptUnrecorded === true ? { adoptUnrecorded: true } : {}),
44
+ });
45
+ }
46
+ const WORLD_MAP_FILES = new Set([
47
+ 'provinces.bmp',
48
+ 'definition.csv',
49
+ 'default.map',
50
+ 'continent.txt',
51
+ 'adjacencies.csv',
52
+ 'adjacency_rules.txt',
53
+ 'positions.txt',
54
+ 'ambient_object.txt',
55
+ 'heightmap.bmp',
56
+ 'terrain.bmp',
57
+ 'rivers.bmp',
58
+ 'trees.bmp',
59
+ 'cities.bmp',
60
+ 'world_normal.bmp',
61
+ 'buildings.txt',
62
+ 'unitstacks.txt',
63
+ 'weatherpositions.txt',
64
+ 'supply_nodes.txt',
65
+ 'railways.txt',
66
+ ]);
67
+ /** The paths a generated world records as its outputs. */
68
+ export function worldOutputPermits({ mapRoot, stateRoots, localisationRoots, }) {
69
+ return (name) => {
45
70
  const dir = path.posix.dirname(name), file = path.posix.basename(name);
46
- return ((dir === mapRoot && mapFiles.has(file)) ||
71
+ return ((dir === mapRoot && WORLD_MAP_FILES.has(file)) ||
47
72
  (dir === `${mapRoot}/terrain` && /^colormap_[a-z0-9_]+\.dds$/u.test(file)) ||
48
73
  (dir === `${mapRoot}/strategicregions` && /^\d+.*\.txt$/u.test(file)) ||
49
74
  (stateRoots.includes(dir) && /^\d+.*\.txt$/u.test(file)) ||
@@ -56,6 +81,9 @@ export function planWorldOutputs(sources, proposed, operationId, mapRoot, stateR
56
81
  localisationRoots.some((root) => name === `${root}/english/world_l_english.yml` ||
57
82
  name === `${root}/replace/world_l_english.yml`));
58
83
  };
84
+ }
85
+ export function planWorldOutputs(sources, proposed, operationId, mapRoot, stateRoots, localisationRoots, options = {}) {
86
+ const permitsPath = worldOutputPermits({ mapRoot, stateRoots, localisationRoots });
59
87
  return planManagedOutputs({
60
88
  manifestPath: WORLD_OUTPUT_MANIFEST,
61
89
  sources,
@@ -11,7 +11,7 @@ import { generateWorldDrainage } from './world-drainage.js';
11
11
  import { generateWorldProvinces } from './world-provinces.js';
12
12
  import { clusterRegions, clusterStates, partitionWorldFromRequest, } from './partition.js';
13
13
  import { repairSeamCorners, smoothDiagonalContacts } from './partition-fields.js';
14
- import { PARTITION_PROVINCE_ERROR, PARTITION_PROVINCE_WARNING } from './partition-tuning.js';
14
+ import { areaRowFactor, PARTITION_PROVINCE_ERROR, PARTITION_PROVINCE_WARNING, } from './partition-tuning.js';
15
15
  import { buildTerritoryAtoms, territoryGraphFromPartition } from './territory-graph.js';
16
16
  import { growTerritory } from './territory.js';
17
17
  import { geographyPartitionFields, provinceCountNote, surfacePartitionFields, } from './world-partition.js';
@@ -409,6 +409,53 @@ function estimatePermanentSnow(input) {
409
409
  }
410
410
  return count;
411
411
  }
412
+ /**
413
+ * The realised land province areas of `partitionTuning.areaByRow`: for each band between two of
414
+ * its rows (and the rows beyond its ends), the land provinces whose centre lies there, their mean
415
+ * area and its ratio to the mean of the band with the smallest factor.
416
+ */
417
+ function areaByRowNote(provinces, points, height) {
418
+ const edges = [...new Set([0, ...points.map(([row]) => row), 1])].sort((a, b) => a - b);
419
+ const bands = edges.slice(0, -1).map((from, index) => ({
420
+ from,
421
+ to: edges[index + 1],
422
+ factor: [
423
+ Number(areaRowFactor(points, from * height - 0.5, height).toFixed(3)),
424
+ Number(areaRowFactor(points, edges[index + 1] * height - 0.5, height).toFixed(3)),
425
+ ],
426
+ provinces: 0,
427
+ pixels: 0,
428
+ }));
429
+ for (let id = 0; id < provinces.kind.length; id += 1) {
430
+ if (provinces.kind[id] !== LAND || (provinces.size[id] ?? 0) === 0)
431
+ continue;
432
+ const row = provinces.sumY[id] / provinces.size[id] / height;
433
+ const band = bands.find(({ from, to }, index) => row >= from && (row < to || index === bands.length - 1)) ?? bands[bands.length - 1];
434
+ band.provinces += 1;
435
+ band.pixels += provinces.size[id];
436
+ }
437
+ const filled = bands.filter(({ provinces: count }) => count > 0);
438
+ const smallest = filled.reduce((best, band) => best === undefined || Math.max(...band.factor) < Math.max(...best.factor) ? band : best, undefined);
439
+ const reference = smallest === undefined ? 0 : smallest.pixels / smallest.provinces;
440
+ const report = bands.map(({ from, to, factor, provinces: count, pixels }) => {
441
+ const mean = count === 0 ? 0 : pixels / count;
442
+ return {
443
+ rows: [from, to],
444
+ factor,
445
+ landProvinces: count,
446
+ meanAreaPx: Math.round(mean),
447
+ ...(reference > 0 && count > 0 ? { ratio: Number((mean / reference).toFixed(2)) } : {}),
448
+ };
449
+ });
450
+ return {
451
+ code: 'MAP_PARTITION_AREA_BY_ROW',
452
+ severity: 'info',
453
+ message: `Land province area by row: ${report
454
+ .map(({ rows, landProvinces, meanAreaPx }) => `rows ${rows[0]}-${rows[1]}: ${landProvinces} provinces of ${meanAreaPx} px on average`)
455
+ .join('; ')}`,
456
+ details: { areaByRow: points, bands: report },
457
+ };
458
+ }
412
459
  /** Land relief of the base game 1.19.4.1 (`reliefStatistics` over its land provinces). */
413
460
  export const VANILLA_RELIEF = { median: 107, p99: 213, maximum: 239, meanStep: 2.69 };
414
461
  function terrainSummaryNote(terrain, geography) {
@@ -1039,6 +1086,9 @@ export function generateWorld(spec, context, options = {}) {
1039
1086
  provinces = featurePartition.provinces;
1040
1087
  for (const note of featurePartition.notes)
1041
1088
  notes.push(note);
1089
+ const areaByRow = featurePartition.tuning.areaByRow;
1090
+ if (areaByRow !== undefined)
1091
+ notes.push(areaByRowNote(provinces, areaByRow, height));
1042
1092
  }
1043
1093
  else
1044
1094
  provinces = generateWorldProvinces({