hoi4-agent-tools 4.11.0 → 4.12.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 (85) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/dist/bin/stdio.js +8 -10
  3. package/dist/hoi4_agent_tools/core/configuration.js +13 -0
  4. package/dist/hoi4_agent_tools/core/engine.js +18 -2
  5. package/dist/hoi4_agent_tools/core/job-store.js +1 -1
  6. package/dist/hoi4_agent_tools/focus/native-effects.js +1 -1
  7. package/dist/hoi4_agent_tools/map/gameplay/crossings.js +55 -16
  8. package/dist/hoi4_agent_tools/map/operations.js +37 -8
  9. package/dist/hoi4_agent_tools/map/partition-fields.js +14 -0
  10. package/dist/hoi4_agent_tools/map/partition-geography.js +55 -6
  11. package/dist/hoi4_agent_tools/map/partition-provinces.js +105 -24
  12. package/dist/hoi4_agent_tools/map/references.js +87 -0
  13. package/dist/hoi4_agent_tools/map/relief/hydrology.js +16 -2
  14. package/dist/hoi4_agent_tools/map/relief/macro-relief.js +21 -1
  15. package/dist/hoi4_agent_tools/map/relief/painted-relief.js +8 -5
  16. package/dist/hoi4_agent_tools/map/relief/terrain-synthesis.js +1 -0
  17. package/dist/hoi4_agent_tools/map/service.js +13 -4
  18. package/dist/hoi4_agent_tools/map/tool-operations.js +6 -0
  19. package/dist/hoi4_agent_tools/map/world-provinces.js +36 -19
  20. package/dist/hoi4_agent_tools/map/world.js +168 -40
  21. package/dist/hoi4_agent_tools/mcp/plugins.js +74 -0
  22. package/dist/hoi4_agent_tools/mcp/server/create-modern-operations.js +7 -18
  23. package/dist/hoi4_agent_tools/mcp/transports/negotiated-stdio.js +64 -6
  24. package/dist/hoi4_agent_tools/probability/model.js +4 -4
  25. package/dist/hoi4_agent_tools/reference/mod-index.js +63 -65
  26. package/dist/hoi4_agent_tools/runtime.js +6 -2
  27. package/dist/hoi4_agent_tools/schemas/map.js +4 -0
  28. package/dist/hoi4_agent_tools/schemas/mod-tools.js +50 -0
  29. package/dist/hoi4_agent_tools/version.js +1 -1
  30. package/docs/configuration.md +10 -10
  31. package/docs/development.md +2 -0
  32. package/docs/jobs.md +1 -0
  33. package/docs/map.md +22 -18
  34. package/docs/reference.md +2 -0
  35. package/docs/research/probability-adapter-evidence.md +11 -1
  36. package/docs/tools.md +2 -3
  37. package/docs/troubleshooting.md +1 -1
  38. package/engine/bin/darwin-arm64/hoi4-engine +0 -0
  39. package/engine/bin/linux-arm64/hoi4-engine +0 -0
  40. package/engine/bin/linux-x64/hoi4-engine +0 -0
  41. package/engine/bin/manifest.json +8 -8
  42. package/engine/bin/win32-x64/hoi4-engine.exe +0 -0
  43. package/npm-shrinkwrap.json +2 -2
  44. package/package.json +1 -1
  45. package/schemas/configuration.schema.json +154 -138
  46. package/schemas/continuous-focus-palette.schema.json +1 -1
  47. package/schemas/custom-weighted-pool.schema.json +1 -1
  48. package/schemas/decision-inspect-input.schema.json +1 -1
  49. package/schemas/error-log-input.schema.json +1 -1
  50. package/schemas/event-feature-manifest.schema.json +1 -1
  51. package/schemas/focus-plan.schema.json +1 -1
  52. package/schemas/focus-planning-sidecar.schema.json +1 -1
  53. package/schemas/geography-model.schema.json +1 -1
  54. package/schemas/gui-animation-source.schema.json +1 -1
  55. package/schemas/gui-helper.schema.json +1 -1
  56. package/schemas/gui-scenario.schema.json +1 -1
  57. package/schemas/helper-expansion-request.schema.json +1 -1
  58. package/schemas/helper-expansion-summary.schema.json +1 -1
  59. package/schemas/impact-inspect-input.schema.json +1 -1
  60. package/schemas/map-operation.schema.json +152 -138
  61. package/schemas/mechanic-test-input.schema.json +1 -1
  62. package/schemas/mod-index-input.schema.json +1 -1
  63. package/schemas/operation-result.schema.json +1 -1
  64. package/schemas/package-check-input.schema.json +1 -1
  65. package/schemas/package-manifest.schema.json +1 -1
  66. package/schemas/probability-analysis-result.schema.json +1 -1
  67. package/schemas/probability-compare-input.schema.json +1 -1
  68. package/schemas/probability-evaluate-input.schema.json +1 -1
  69. package/schemas/probability-inspect-input.schema.json +1 -1
  70. package/schemas/probability-render-input.schema.json +1 -1
  71. package/schemas/probability-scenario-set.schema.json +1 -1
  72. package/schemas/probability-sequence-input.schema.json +1 -1
  73. package/schemas/probability-simulate-input.schema.json +1 -1
  74. package/schemas/probability-sweep-input.schema.json +1 -1
  75. package/schemas/reference-context-input.schema.json +1 -1
  76. package/schemas/reference-read-input.schema.json +1 -1
  77. package/schemas/reference-search-input.schema.json +1 -1
  78. package/schemas/reference-sheets.schema.json +1 -1
  79. package/schemas/scenario-suite.schema.json +1 -1
  80. package/schemas/scenario-test-input.schema.json +1 -1
  81. package/schemas/script-validate-input.schema.json +1 -1
  82. package/schemas/shared-scenario.schema.json +1 -1
  83. package/schemas/source-lookup-input.schema.json +1 -1
  84. package/server.json +2 -2
  85. package/dist/hoi4_agent_tools/mcp/tools/chaosx.js +0 -509
@@ -506,3 +506,90 @@ export function mapScriptConsistency(index) {
506
506
  }
507
507
  return { diagnostics, references: references.length, missing };
508
508
  }
509
+ /**
510
+ * Folders whose scripts may name a continent: triggers and effects anywhere in `common`, events
511
+ * and country history, the AI areas, and the portrait pools.
512
+ */
513
+ export const CONTINENT_REFERENCE_SCRIPT_PATTERNS = [
514
+ 'common/**/*.txt',
515
+ 'events/**/*.txt',
516
+ 'history/countries/**/*.txt',
517
+ 'portraits/**/*.txt',
518
+ ];
519
+ const CONTINENT_SCRIPT_FILE = /^(?:common|events|history\/countries|portraits)\/.+\.txt$/iu;
520
+ /** Every place an active script names one of `keys` as a continent, in load order. */
521
+ export function collectContinentReferences(files, keys) {
522
+ const references = [];
523
+ if (keys.size === 0)
524
+ return references;
525
+ const active = files
526
+ .filter((file) => file.shadowedBy === undefined &&
527
+ CONTINENT_SCRIPT_FILE.test(file.relativePath.replaceAll('\\', '/')))
528
+ .sort((left, right) => left.loadOrder - right.loadOrder || compareCodeUnits(left.displayPath, right.displayPath));
529
+ for (const file of active) {
530
+ // A cheap byte check skips the many files that name no continent key at all.
531
+ const text = file.bytes.toString('latin1');
532
+ if (![...keys].some((key) => text.includes(key)))
533
+ continue;
534
+ const document = parseClausewitz(file.bytes, file.displayPath);
535
+ const folder = file.relativePath.replaceAll('\\', '/').toLowerCase();
536
+ const aiAreas = folder.startsWith('common/ai_areas/');
537
+ const portraits = folder.startsWith('portraits/');
538
+ const add = (node, kind) => {
539
+ if (keys.has(node.value))
540
+ references.push({ continent: node.value, kind, file, document, node });
541
+ };
542
+ const visit = (entry) => {
543
+ if (entry.type === 'block') {
544
+ for (const child of entry.entries)
545
+ visit(child);
546
+ return;
547
+ }
548
+ if (entry.type !== 'assignment')
549
+ return;
550
+ const key = entry.key.value;
551
+ if (entry.value.type === 'scalar') {
552
+ if (key === 'is_on_continent')
553
+ add(entry.value, 'is_on_continent');
554
+ else if (key === 'continent')
555
+ add(entry.value, 'continent');
556
+ return;
557
+ }
558
+ if (aiAreas && key === 'continents')
559
+ for (const item of entry.value.entries)
560
+ if (item.type === 'scalar')
561
+ add(item, 'ai_area');
562
+ if (portraits && key === 'continent')
563
+ for (const child of entry.value.entries)
564
+ if (child.type === 'assignment' &&
565
+ child.key.value === 'name' &&
566
+ child.value.type === 'scalar')
567
+ add(child.value, 'portrait');
568
+ for (const child of entry.value.entries)
569
+ visit(child);
570
+ };
571
+ visit(document.root);
572
+ }
573
+ return references;
574
+ }
575
+ const CONTINENT_REFERENCE_FORMS = {
576
+ is_on_continent: 'is_on_continent',
577
+ continent: 'continent',
578
+ ai_area: "an AI area's continents",
579
+ portrait: "a portrait pool's continent",
580
+ };
581
+ /** One warning for each script reference to a continent the new `continent.txt` leaves out. */
582
+ export function droppedContinentDiagnostics(references) {
583
+ return references.map((reference) => ({
584
+ code: 'MAP_CONTINENT_DROPPED_REFERENCED',
585
+ severity: 'warning',
586
+ category: 'map',
587
+ message: `${reference.file.relativePath} names the dropped continent ${reference.continent} (${CONTINENT_REFERENCE_FORMS[reference.kind]}); the new continent.txt no longer declares it`,
588
+ location: nodeLocation(reference.document, reference.node),
589
+ details: {
590
+ continent: reference.continent,
591
+ kind: reference.kind,
592
+ layer: reference.file.rootKind,
593
+ },
594
+ }));
595
+ }
@@ -648,6 +648,15 @@ function routeNamedRivers(context) {
648
648
  const target = landCellAt(macro, mouth.x, mouth.y, 8);
649
649
  if (target < 0)
650
650
  unreachable('its mouth lies far from any land');
651
+ if (target !== current && occupant[target] === ownId) {
652
+ // The course already runs through the mouth's cell, which happens when the last via
653
+ // point lies within a cell of the mouth: the river ends there instead of looking for
654
+ // a way back into its own bed, which the router never enters.
655
+ const at = cells.lastIndexOf(target);
656
+ for (const cell of cells.splice(at + 1))
657
+ occupant[cell] = 0;
658
+ current = target;
659
+ }
651
660
  final =
652
661
  target === current
653
662
  ? { cells: [current], joined: -1 }
@@ -741,10 +750,14 @@ function routeNamedRivers(context) {
741
750
  }
742
751
  }
743
752
  }
744
- void notes;
745
753
  if (failures.length > 0) {
746
754
  const first = failures[0];
747
- fail('MAP_RIVER_UNREACHABLE_MOUTH', failures.length === 1
755
+ const report = context.collectUnreachable
756
+ ? (code, message, details) => {
757
+ notes.push({ code, severity: 'error', message, details });
758
+ }
759
+ : fail;
760
+ report('MAP_RIVER_UNREACHABLE_MOUTH', failures.length === 1
748
761
  ? `River ${first.riverId} cannot reach its mouth: ${first.reason}`
749
762
  : `${failures.length} rivers cannot reach their mouths: ${failures
750
763
  .slice(0, 12)
@@ -1317,6 +1330,7 @@ export function synthesizeHydrology(input) {
1317
1330
  notes,
1318
1331
  seed,
1319
1332
  signal: input.signal,
1333
+ collectUnreachable: input.collectUnreachable,
1320
1334
  });
1321
1335
  // Burn the channels into the heights and flood again with the channels as outlets, so every
1322
1336
  // other cell drains either to the coast or into a channel.
@@ -33,6 +33,13 @@ export function peakHeight(peak, scale) {
33
33
  export function plateauHeight(height, scale) {
34
34
  return Math.min(HEIGHT_CEILING, LAND_FLOOR + PEAK_SPAN * height * scale);
35
35
  }
36
+ /** Lower `height` toward a pass cap: unchanged outside a corridor or where it is already lower. */
37
+ export function cappedAtPass(caps, cell, height) {
38
+ if (caps === undefined)
39
+ return height;
40
+ const level = caps.level[cell];
41
+ return level < height ? height + (level - height) * caps.weight[cell] : height;
42
+ }
36
43
  /** Kind of each macro cell: the majority of its four pixels, with lake before land before sea. */
37
44
  function downsampleKind(kind, width, height) {
38
45
  const mw = width / 2;
@@ -487,6 +494,7 @@ function applyVolcano(volcano, base, kind, mw, mh, scale, seed, targets) {
487
494
  * sides wherever it lies.
488
495
  */
489
496
  function carvePassSaddles(geography, tables, heights, kind, mw, mh) {
497
+ let caps;
490
498
  const aspect = mh / mw;
491
499
  // The line of every range in cell units, one point per table entry, with its footprint.
492
500
  const lines = new Map();
@@ -579,10 +587,21 @@ function carvePassSaddles(geography, tables, heights, kind, mw, mh) {
579
587
  const weight = nearestDistance <= corridor ? 1 : 1 - smoothstep((nearestDistance - corridor) / edge);
580
588
  if (cap < heights[cell])
581
589
  heights[cell] = heights[cell] + (cap - heights[cell]) * weight;
590
+ // Kept for the stages that raise the relief afterwards (painted relief), so they
591
+ // cannot fill the saddle back up to the crest.
592
+ caps ??= {
593
+ level: new Float32Array(mw * mh).fill(Infinity),
594
+ weight: new Float32Array(mw * mh),
595
+ };
596
+ if (cap < caps.level[cell])
597
+ caps.level[cell] = cap;
598
+ if (weight > caps.weight[cell])
599
+ caps.weight[cell] = weight;
582
600
  }
583
601
  }
584
602
  }
585
603
  void aspect;
604
+ return caps;
586
605
  }
587
606
  /** Build the macro relief of the model. */
588
607
  export function synthesizeMacroRelief(input) {
@@ -625,7 +644,7 @@ export function synthesizeMacroRelief(input) {
625
644
  heights[index] = Math.min(HEIGHT_CEILING, heights[index] + targets.delta[index]);
626
645
  footprint[index] = Math.max(footprint[index], targets.footprint[index]);
627
646
  }
628
- carvePassSaddles(geography, ranges, heights, kind, mw, mh);
647
+ const passCap = carvePassSaddles(geography, ranges, heights, kind, mw, mh);
629
648
  return {
630
649
  width: mw,
631
650
  height: mh,
@@ -636,6 +655,7 @@ export function synthesizeMacroRelief(input) {
636
655
  snowLine: targets.snow,
637
656
  crest: targets.crest,
638
657
  barrier: targets.barrier,
658
+ ...(passCap === undefined ? {} : { passCap }),
639
659
  ranges,
640
660
  scale,
641
661
  };
@@ -11,12 +11,14 @@
11
11
  * - a cell keeps the model's height where that is higher, and every other cell keeps the model's
12
12
  * broad elevation untouched;
13
13
  * - impassable land (ZR-28) rises toward `impassablePeak`, the highest ground of the map;
14
+ * - a declared pass keeps the saddle the macro relief carved for it: the raise is capped there
15
+ * as the carving capped the model's own heights, so a painted range never fills its pass;
14
16
  * - painted mountains and volcanoes get permanent snow above a height that falls from the
15
17
  * equator toward the poles, and weight the full-resolution detail as model ranges do.
16
18
  */
17
19
  import { LAND } from './grid.js';
18
20
  import { fractal2, ridged2, smoothstep } from './math.js';
19
- import { HEIGHT_CEILING, PEAK_BASE, PEAK_SPAN } from './macro-relief.js';
21
+ import { cappedAtPass, HEIGHT_CEILING, PEAK_BASE, PEAK_SPAN, } from './macro-relief.js';
20
22
  /** Reference terrain codes the stage reads (`REFERENCE_TERRAIN` of the reference interpretation). */
21
23
  export const PAINTED_MOUNTAIN = 3;
22
24
  export const PAINTED_VOLCANO = 5;
@@ -112,11 +114,12 @@ export function applyPaintedRelief(target, input) {
112
114
  const goal = Math.min(HEIGHT_CEILING, Math.max(PEAK_BASE + lift(input.settings.mountainPeak) * m * ridges, PEAK_BASE + lift(input.settings.hillsPeak) * h * swell, PEAK_BASE + lift(input.settings.volcanoPeak) * v,
113
115
  // Impassable land keeps its crests but never sinks below most of its peak.
114
116
  PEAK_BASE + lift(input.settings.impassablePeak) * i * (0.8 + 0.2 * ridges)));
115
- if (goal > target.heights[cell]) {
116
- target.heights[cell] = goal;
117
+ const raised = cappedAtPass(target.passCap, cell, goal);
118
+ if (raised > target.heights[cell]) {
119
+ target.heights[cell] = raised;
117
120
  raisedCells += 1;
118
- if (goal > highest)
119
- highest = goal;
121
+ if (raised > highest)
122
+ highest = raised;
120
123
  }
121
124
  const weight = Math.max(m, 0.6 * h, v, i);
122
125
  if (weight > target.footprint[cell])
@@ -128,6 +128,7 @@ export function checkTerrainRivers(input) {
128
128
  rainfall: input.rainfall,
129
129
  landPixels,
130
130
  signal: input.signal,
131
+ collectUnreachable: true,
131
132
  });
132
133
  const notes = [...hydrology.notes];
133
134
  // The pass test of the write, on the macro grid: a declared pass must be a saddle lower than
@@ -1,4 +1,4 @@
1
- import { MAP_REFERENCE_SCRIPT_PATTERNS, mapScriptConsistency } from './references.js';
1
+ import { CONTINENT_REFERENCE_SCRIPT_PATTERNS, MAP_REFERENCE_SCRIPT_PATTERNS, mapScriptConsistency, } from './references.js';
2
2
  import path from 'node:path';
3
3
  import { escapeFileGlob } from '../core/file-glob.js';
4
4
  import { ArtifactStore, boundedSourceHashEvidence, publicArtifactLink, } from '../core/artifacts.js';
@@ -627,7 +627,7 @@ export class AgentNudger {
627
627
  this.scanner = this.engine.scanner;
628
628
  this.transactions = this.engine.transactions;
629
629
  }
630
- async scan(workspaceId, principal, signal, includeExternalScriptReferences = false, includeWorldContext = false, includeAppearance = false, includeBorderInputs = false) {
630
+ async scan(workspaceId, principal, signal, includeExternalScriptReferences = false, includeWorldContext = false, includeAppearance = false, includeBorderInputs = false, includeContinentReferences = false) {
631
631
  signal?.throwIfAborted();
632
632
  const workspace = this.resolver.get(workspaceId, principal);
633
633
  const sourceRoots = {
@@ -688,14 +688,23 @@ export class AgentNudger {
688
688
  ],
689
689
  }, principal, signal)
690
690
  : undefined;
691
+ // Scripts that may name a continent, read when a new world drops the inherited continents.
692
+ const continentSnapshot = includeContinentReferences
693
+ ? await this.engine.scan(workspaceId, { patterns: [...CONTINENT_REFERENCE_SCRIPT_PATTERNS] }, principal, signal)
694
+ : undefined;
691
695
  signal?.throwIfAborted();
692
- const files = [
696
+ const collected = [
693
697
  ...contentSnapshot.files,
694
698
  ...locatorSnapshot.files,
695
699
  ...(externalScriptSnapshot?.files ?? []),
696
700
  ...(worldContextSnapshot?.files ?? []).filter((file) => !contentSnapshot.files.some((existing) => existing.displayPath === file.displayPath)),
697
701
  ...(appearanceSnapshot?.files ?? []).filter((file) => ![...contentSnapshot.files, ...(worldContextSnapshot?.files ?? [])].some((existing) => existing.displayPath === file.displayPath)),
698
702
  ...(generatedOutputsSnapshot?.files ?? []).filter((file) => ![...contentSnapshot.files, ...(worldContextSnapshot?.files ?? [])].some((existing) => existing.displayPath === file.displayPath)),
703
+ ];
704
+ const collectedPaths = new Set(collected.map(({ displayPath }) => displayPath));
705
+ const files = [
706
+ ...collected,
707
+ ...(continentSnapshot?.files ?? []).filter((file) => !collectedPaths.has(file.displayPath)),
699
708
  ].sort((left, right) => left.loadOrder - right.loadOrder || compareCodeUnits(left.displayPath, right.displayPath));
700
709
  const revision = hashCanonical(files.map(({ displayPath, loadOrder, sha256 }) => ({ displayPath, loadOrder, sha256 })));
701
710
  return {
@@ -735,7 +744,7 @@ export class AgentNudger {
735
744
  signal?.throwIfAborted();
736
745
  const snapshot = await this.scan(workspaceId, principal, signal, operations.some((operation) => operation.kind === 'renumber_map_entity' ||
737
746
  operation.kind === 'remap_map_references' ||
738
- 'remapReferences' in operation), operations.some((operation) => operation.kind === 'create_world'), false, operations.some((operation) => operation.kind === 'assign_territory' || operation.kind === 'repartition_states'));
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'));
739
748
  const referenceWorlds = new Map();
740
749
  const referenceImages = [];
741
750
  const referenceLoads = new Map();
@@ -616,12 +616,18 @@ async function previewSynthesisCheck(nudger, input, context) {
616
616
  },
617
617
  ],
618
618
  };
619
+ // Every blocking problem the check found is listed, not only the first (one fix round, not six).
619
620
  result.blockers = [
620
621
  ...checked.plan.blockers.map(({ code, message, details }) => ({
621
622
  code,
622
623
  message,
623
624
  ...(details === undefined ? {} : { details }),
624
625
  })),
626
+ ...blocked.map(({ code, message, details }) => ({
627
+ code,
628
+ message,
629
+ ...(details === undefined ? {} : { details }),
630
+ })),
625
631
  ].slice(0, 100);
626
632
  await context.progress(2, 2, 'River check complete; nothing was written');
627
633
  return result;
@@ -1,4 +1,30 @@
1
1
  import { ServiceError } from '../core/result.js';
2
+ /** True when two pixels lie on different sides of a wall line (or one on it). */
3
+ function acrossWall(input, p, q) {
4
+ const side = input.wallSide;
5
+ if (side === undefined)
6
+ return false;
7
+ const a = side[p];
8
+ const b = side[q];
9
+ return a !== 0 && b !== 0 && a !== b;
10
+ }
11
+ /** Repair stages, strictest first; with a wall side field every stage but a last fallback keeps to its side. */
12
+ function repairStages(input) {
13
+ const stages = [];
14
+ if (input.group !== undefined && input.line !== undefined)
15
+ stages.push({ sameGroup: true, avoidLine: true });
16
+ if (input.line !== undefined)
17
+ stages.push({ sameGroup: false, avoidLine: true });
18
+ if (input.group !== undefined)
19
+ stages.push({ sameGroup: true, avoidLine: false });
20
+ stages.push({ sameGroup: false, avoidLine: false });
21
+ if (input.wallSide === undefined)
22
+ return stages.map((stage) => ({ ...stage, avoidWall: false }));
23
+ return [
24
+ ...stages.map((stage) => ({ ...stage, avoidWall: true })),
25
+ { sameGroup: false, avoidLine: false, avoidWall: false },
26
+ ];
27
+ }
2
28
  function invalid(message) {
3
29
  throw new ServiceError('MAP_WORLD_INVALID_PROVINCES', message);
4
30
  }
@@ -270,15 +296,7 @@ function absorbSlivers(input, parts) {
270
296
  // repeated because a previously isolated fragment may become mergeable afterwards. With groups
271
297
  // or lines, the first stages merge inside a group and not across a line, and the last stage
272
298
  // takes what is left.
273
- const stages = [];
274
- if (input.group !== undefined && input.line !== undefined)
275
- stages.push({ sameGroup: true, avoidLine: true });
276
- if (input.line !== undefined)
277
- stages.push({ sameGroup: false, avoidLine: true });
278
- if (input.group !== undefined)
279
- stages.push({ sameGroup: true, avoidLine: false });
280
- stages.push({ sameGroup: false, avoidLine: false });
281
- for (const { sameGroup, avoidLine } of stages) {
299
+ for (const { sameGroup, avoidLine, avoidWall } of repairStages(input)) {
282
300
  for (let pass = 0; pass < 4; pass++) {
283
301
  let changed = false;
284
302
  for (let p = 0; p < parts.pixel.length; p++) {
@@ -289,6 +307,8 @@ function absorbSlivers(input, parts) {
289
307
  continue;
290
308
  if (avoidLine && (input.line[p] !== 0 || input.line[q] !== 0))
291
309
  continue;
310
+ if (avoidWall && acrossWall(input, p, q))
311
+ continue;
292
312
  const a = root(parts, parts.pixel[p]);
293
313
  const b = root(parts, parts.pixel[q]);
294
314
  if (a === b || (parts.size[a] >= 20 && parts.size[b] >= 20))
@@ -356,7 +376,7 @@ function rebalanceSlivers(input, parts) {
356
376
  for (const p of cells) {
357
377
  const x = p % width;
358
378
  for (const q of [x > 0 ? p - 1 : -1, x + 1 < width ? p + 1 : -1, p - width, p + width]) {
359
- if (q < 0 || q >= kind.length || kind[q] !== kind[p])
379
+ if (q < 0 || q >= kind.length || kind[q] !== kind[p] || acrossWall(input, p, q))
360
380
  continue;
361
381
  const donor = root(parts, parts.pixel[q]);
362
382
  if (donor === id || parts.size[donor] <= 20 || !removable(parts, q, width, height))
@@ -387,14 +407,7 @@ function rebalanceSlivers(input, parts) {
387
407
  }
388
408
  function repairCrossings(input, parts) {
389
409
  const { width, height, kind } = input;
390
- const repairStages = [];
391
- if (input.group !== undefined && input.line !== undefined)
392
- repairStages.push({ sameGroup: true, avoidLine: true });
393
- if (input.line !== undefined)
394
- repairStages.push({ sameGroup: false, avoidLine: true });
395
- if (input.group !== undefined)
396
- repairStages.push({ sameGroup: true, avoidLine: false });
397
- repairStages.push({ sameGroup: false, avoidLine: false });
410
+ const stages = repairStages(input);
398
411
  for (let pass = 0; pass < 12; pass++) {
399
412
  let changed = false;
400
413
  for (let y = 0; y + 1 < height; y++) {
@@ -414,10 +427,12 @@ function repairCrossings(input, parts) {
414
427
  let repaired = false;
415
428
  // Whole-cell unions cannot introduce crossings or disconnected provinces. With groups or
416
429
  // lines, the repairs inside one group and not across a line come first.
417
- for (const { sameGroup, avoidLine } of repairStages) {
430
+ for (const { sameGroup, avoidLine, avoidWall } of stages) {
418
431
  for (const [i, j] of edges) {
419
432
  if (avoidLine && (input.line[corners[i]] !== 0 || input.line[corners[j]] !== 0))
420
433
  continue;
434
+ if (avoidWall && acrossWall(input, corners[i], corners[j]))
435
+ continue;
421
436
  if (merge(parts, ids[i], ids[j], width, height, sameGroup)) {
422
437
  repaired = true;
423
438
  break;
@@ -433,6 +448,8 @@ function repairCrossings(input, parts) {
433
448
  const q = corners[j];
434
449
  if (avoidLine && (input.line[p] !== 0 || input.line[q] !== 0))
435
450
  continue;
451
+ if (avoidWall && acrossWall(input, p, q))
452
+ continue;
436
453
  if (kind[p] !== kind[q] || !removable(parts, p, width, height))
437
454
  continue;
438
455
  if (sameGroup &&