hoi4-agent-tools 4.16.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 +29 -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 +54 -3
  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 +20 -5
  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 +41 -26
  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 +33 -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 +13 -11
  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 +817 -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
@@ -12,6 +12,27 @@ export const PARTITION_DEFAULTS = {
12
12
  minProvincePixels: 40,
13
13
  narrowStraitPx: 24,
14
14
  };
15
+ /** The smallest and largest `areaByRow` factor. */
16
+ export const AREA_BY_ROW_FACTOR = [0.25, 8];
17
+ /**
18
+ * The `areaByRow` factor of a pixel row: linear between the points, held beyond the ends, 1
19
+ * without points.
20
+ */
21
+ export function areaRowFactor(points, y, height) {
22
+ if (points === undefined || points.length === 0)
23
+ return 1;
24
+ const row = (y + 0.5) / height;
25
+ if (row <= points[0][0])
26
+ return points[0][1];
27
+ for (let index = 1; index < points.length; index += 1) {
28
+ const [r1, f1] = points[index];
29
+ if (row <= r1) {
30
+ const [r0, f0] = points[index - 1];
31
+ return f0 + ((f1 - f0) * (row - r0)) / (r1 - r0);
32
+ }
33
+ }
34
+ return points[points.length - 1][1];
35
+ }
15
36
  /** The province count above which the wiki and the text-table limit advise against a map. */
16
37
  export const PARTITION_PROVINCE_WARNING = 14_000;
17
38
  export const PARTITION_PROVINCE_ERROR = 21_000;
@@ -78,6 +99,19 @@ export function resolvePartitionTuning(tuning, base) {
78
99
  refuse('MAP_PARTITION_STRENGTH_INVALID', 'partition barrierStrength must be from 0 to 60', {
79
100
  barrierStrength: strength,
80
101
  });
102
+ const areaByRow = tuning?.areaByRow;
103
+ if (areaByRow !== undefined) {
104
+ const valid = areaByRow.length > 0 &&
105
+ areaByRow.every(([row, factor], index) => Number.isFinite(row) &&
106
+ row >= 0 &&
107
+ row <= 1 &&
108
+ Number.isFinite(factor) &&
109
+ factor >= AREA_BY_ROW_FACTOR[0] &&
110
+ factor <= AREA_BY_ROW_FACTOR[1] &&
111
+ (index === 0 || row > areaByRow[index - 1][0]));
112
+ if (!valid)
113
+ refuse('MAP_PARTITION_AREA_BY_ROW_INVALID', `partition areaByRow must be [row, factor] points with rows from 0 to 1 in increasing order and factors from ${AREA_BY_ROW_FACTOR[0]} to ${AREA_BY_ROW_FACTOR[1]}`, { areaByRow });
114
+ }
81
115
  const strait = tuning?.narrowStraitPx ?? PARTITION_DEFAULTS.narrowStraitPx;
82
116
  if (!Number.isInteger(strait) || strait < 4 || strait > 64)
83
117
  refuse('MAP_PARTITION_STRENGTH_INVALID', 'partition narrowStraitPx must be from 4 to 64', {
@@ -94,6 +128,9 @@ export function resolvePartitionTuning(tuning, base) {
94
128
  minProvincePixels,
95
129
  narrowStraitPx: strait,
96
130
  maxProvincePixels: cellLimit,
131
+ ...(areaByRow === undefined
132
+ ? {}
133
+ : { areaByRow: areaByRow.map(([row, factor]) => [row, factor]) }),
97
134
  normalizeLand: bands === undefined || Object.keys(bands).length === 0,
98
135
  normalizeSea: sea === undefined || Object.keys(sea).length === 0,
99
136
  landBase: land,
@@ -6,7 +6,6 @@ import { canonicalJson, compareCodeUnits, hashCanonical, sha256Bytes } from '../
6
6
  import { sortDiagnostics } from '../core/diagnostics.js';
7
7
  import { diagnosticSeverityCounts, rollupRepeatedSoftDiagnostics, } from '../core/diagnostic-rollup.js';
8
8
  import { CoreEngine } from '../core/engine.js';
9
- import { SymbolIndex } from '../core/index.js';
10
9
  import { RenderBudget } from '../core/render-budget.js';
11
10
  import { ServiceError } from '../core/result.js';
12
11
  import { WorkspaceScanner } from '../core/scanner.js';
@@ -23,7 +22,7 @@ import { WORLD_OUTPUT_MANIFEST } from './world-outputs.js';
23
22
  import { renderMap, renderMapDiff, } from './render.js';
24
23
  import { validateMapAsync } from './validation.js';
25
24
  import { buildWorldPreviewArtifacts, generatedWorldOperationIds } from './world-preview.js';
26
- import { evaluateTerritoryQuality, territoryArtifactContent, } from './territory-quality.js';
25
+ import { evaluateTerritoryQuality, territoryAssignmentContent, territoryArtifactContent, } from './territory-quality.js';
27
26
  /**
28
27
  * Evidence of an imported reference: registered sheets, an exact or frame-fitted picture, or a
29
28
  * geography model beside the picture. Plain pictures keep their previous output.
@@ -635,19 +634,19 @@ export class AgentNudger {
635
634
  states: workspace.registration.roots.states,
636
635
  localisation: workspace.registration.roots.localisation,
637
636
  };
638
- const selectorSnapshot = await this.engine.scan(workspaceId, { patterns: defaultMapPatterns(sourceRoots) }, principal, signal);
637
+ const selectorSnapshot = await this.engine.scanFiles(workspaceId, { patterns: defaultMapPatterns(sourceRoots) }, principal, signal);
639
638
  const bitmapPatterns = provinceBitmapPatterns(selectorSnapshot.files, sourceRoots.map, includeAppearance || includeBorderInputs
640
639
  ? BORDER_BITMAP_SELECTORS
641
640
  : PROVINCE_BITMAP_SELECTORS);
642
- const contentSnapshot = await this.engine.scan(workspaceId, { patterns: [...sourceTextPatterns(sourceRoots), ...bitmapPatterns] }, principal, signal);
643
- const locatorSnapshot = await this.engine.scan(workspaceId, { patterns: ['**/*.asset'], rootKinds: ['mod', 'fixture'] }, principal, signal);
641
+ const contentSnapshot = await this.engine.scanFiles(workspaceId, { patterns: [...sourceTextPatterns(sourceRoots), ...bitmapPatterns] }, principal, signal);
642
+ const locatorSnapshot = await this.engine.scanFiles(workspaceId, { patterns: ['**/*.asset'], rootKinds: ['mod', 'fixture'] }, principal, signal);
644
643
  const externalScriptSnapshot = includeExternalScriptReferences
645
- ? await this.engine.scan(workspaceId, {
644
+ ? await this.engine.scanFiles(workspaceId, {
646
645
  patterns: [...MAP_REFERENCE_SCRIPT_PATTERNS],
647
646
  }, principal, signal)
648
647
  : undefined;
649
648
  const worldContextSnapshot = includeWorldContext
650
- ? await this.engine.scan(workspaceId, {
649
+ ? await this.engine.scanFiles(workspaceId, {
651
650
  patterns: [
652
651
  'common/state_category/**/*.txt',
653
652
  'common/country_tags/*.txt',
@@ -656,7 +655,7 @@ export class AgentNudger {
656
655
  }, principal, signal)
657
656
  : undefined;
658
657
  const generatedOutputsSnapshot = includeWorldContext
659
- ? await this.engine.scan(workspaceId, {
658
+ ? await this.engine.scanFiles(workspaceId, {
660
659
  rootKinds: ['mod'],
661
660
  patterns: [
662
661
  'common/countries/*.txt',
@@ -673,7 +672,7 @@ export class AgentNudger {
673
672
  : undefined;
674
673
  // Appearance validation reads the bitmaps and colour maps the mod itself ships.
675
674
  const appearanceSnapshot = includeAppearance
676
- ? await this.engine.scan(workspaceId, {
675
+ ? await this.engine.scanFiles(workspaceId, {
677
676
  rootKinds: ['mod', 'fixture'],
678
677
  patterns: [
679
678
  ...provinceBitmapPatterns(selectorSnapshot.files, sourceRoots.map, APPEARANCE_BITMAP_SELECTORS),
@@ -690,7 +689,7 @@ export class AgentNudger {
690
689
  : undefined;
691
690
  // Scripts that may name a continent, read when a new world drops the inherited continents.
692
691
  const continentSnapshot = includeContinentReferences
693
- ? await this.engine.scan(workspaceId, { patterns: [...CONTINENT_REFERENCE_SCRIPT_PATTERNS] }, principal, signal)
692
+ ? await this.engine.scanFiles(workspaceId, { patterns: [...CONTINENT_REFERENCE_SCRIPT_PATTERNS] }, principal, signal)
694
693
  : undefined;
695
694
  signal?.throwIfAborted();
696
695
  const collected = [
@@ -711,7 +710,7 @@ export class AgentNudger {
711
710
  workspaceId,
712
711
  revision,
713
712
  files,
714
- index: MapWorkspaceIndex.build(files, sourceRoots, SymbolIndex.build(files)),
713
+ index: MapWorkspaceIndex.build(files, sourceRoots),
715
714
  };
716
715
  }
717
716
  async validate(workspaceId, principal, signal, scripts = false, includeAppearance = false) {
@@ -744,7 +743,9 @@ export class AgentNudger {
744
743
  signal?.throwIfAborted();
745
744
  const snapshot = await this.scan(workspaceId, principal, signal, operations.some((operation) => operation.kind === 'renumber_map_entity' ||
746
745
  operation.kind === 'remap_map_references' ||
747
- 'remapReferences' in operation), operations.some((operation) => operation.kind === 'create_world'), false, operations.some((operation) => operation.kind === 'assign_territory' || operation.kind === 'repartition_states'), operations.some((operation) => operation.kind === 'create_world' && operation.inheritedContinents === 'drop'));
746
+ 'remapReferences' in operation),
747
+ // record_world_outputs needs every world output scanned, as create_world does.
748
+ operations.some((operation) => operation.kind === 'create_world' || operation.kind === 'record_world_outputs'), false, operations.some((operation) => operation.kind === 'assign_territory' || operation.kind === 'repartition_states'), operations.some((operation) => operation.kind === 'create_world' && operation.inheritedContinents === 'drop'));
748
749
  const referenceWorlds = new Map();
749
750
  const referenceImages = [];
750
751
  const referenceLoads = new Map();
@@ -1369,6 +1370,18 @@ export class AgentNudger {
1369
1370
  schemaVersion: 'map-territory.v1',
1370
1371
  },
1371
1372
  });
1373
+ if (prepared.territory.reports.length > 0)
1374
+ writes.push({
1375
+ name: 'map-territory-assignment.json',
1376
+ mimeType: 'application/json',
1377
+ content: `${canonicalJson(territoryAssignmentContent(prepared.territory.reports, plan.finalIndex))}
1378
+ `,
1379
+ provenance: {
1380
+ ...provenance,
1381
+ kind: 'map-territory-assignment',
1382
+ schemaVersion: 'map-territory-assignment.v1',
1383
+ },
1384
+ });
1372
1385
  for (const [ordinal, imported] of prepared.imports.entries())
1373
1386
  writes.push(...(await buildImportArtifacts(imported, ordinal)));
1374
1387
  if (plan.worldOutputs !== undefined)
@@ -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