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
package/CHANGELOG.md CHANGED
@@ -2,6 +2,24 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ ## 4.12.0 - 2026-11-08
6
+
7
+ - `create_world.synthesisCheck` reports every blocking problem it can find in one preview. A ZIN map write on 6 November needed six attempts, one blocked problem each; four of the six never appeared in a preview, and the check stopped at its first error. The check now lists, together and each as a blocker: realm points that cannot be placed, cities and capitals on impassable land (found from the impassable mask before the synthesis instead of after the partition), rivers that cannot reach their mouths, and passes that are not lower than their crest, which are now checked even when a river fails. A write still stops at its first blocking problem, and a city on impassable land is now refused before the synthesis instead of after the partition, with the same code and message. Leaks through a wall still need the partition, so only a write reports them.
8
+ - Release workflow: the npm and GHCR publication checks call the GitHub API with the job's token, check the release tag once before they wait for the registry, and wait up to 20 minutes for npm instead of 5. The 4.11.1 run published to npm, but npm held the version for processing longer than 5 minutes; the check retried the anonymous tag lookup every 5 seconds until GitHub refused it (403) and the release stopped before the image, GitHub release and MCP Registry steps.
9
+ - Answer the stdio handshake before startup recovery. The server checked every retained rewrite journal before it answered `initialize`, and each applied `create_world` leaves a journal of about 7 MB, so a mod with eight map writes took 4 to 5 seconds to connect (7.5 seconds with five clients starting at once, 8.7 seconds cold) and clients that allow 30 seconds gave up under load. The stdio server now answers `initialize`, `ping`, `server/discover`, `tools/list`, `prompts/list` and `logging/setLevel` at once, recovers in the background, and holds every other request, in arrival order, until recovery ends, so no call reads or writes a workspace before its interrupted rewrite is recovered. Measured on a configuration with six mods and 28 MB of map journals, the handshake takes 1.1 to 1.2 seconds (1.8 to 1.9 seconds for five at once); the first tool call waits for the rest. More than 128 held requests, or a failed recovery, closes the connection without answering them. The HTTP server still recovers before it listens.
10
+ - Add `create_world.inheritedContinents` (`keep` by default, or `drop`). With `drop`, `continent.txt` lists only the generated continents instead of also every continent of the active `continent.txt`, so a total conversion no longer shows the base game's continents in the trade window. Each active script reference to a dropped continent is reported with its file and line as `MAP_CONTINENT_DROPPED_REFERENCED` (warning): `is_on_continent`, `continent =` in `any_state_in` and its effects, AI areas' `continents` lists and portrait pools' `continent = { name = ... }`. Requests without the field are unchanged.
11
+ - Impassable land no longer joins landmasses, strategic regions or countries in `create_world`. The `wall` edge connected a landmass at the east edge with one at the west edge across the seam into one continent, and a strategic region could run over the wall from one edge to the other; land that only a painted or regional impassable strip connected was one continent too. Continents and land regions are now grouped over passable land. Each piece of impassable land takes the continent of the largest landmass it borders (or of the nearest one, when it borders only water), and joins the passable region it borders most when it is no larger than a region, or forms regions of its own. Generated countries and workspace realms also grow over passable land only, so a realm seeded at the east edge no longer takes land at the west edge over the wall; land reached only that way follows the island rule. Impassable provinces take no owner while countries grow, and their states take the owner of the passable state they link to (`force_link_ownership_to`). Worlds without impassable land are unchanged.
12
+ - Move the probability adapters' pin to game 1.19.4.2. The six documentation files they rest on and every vanilla example are unchanged from the 1.19.4.1 review, so no adapter rule changed: the target is `Operation Postern 1.19.4.2 (0bdb)` and the adapter version `hoi4-1.19.4.2.v1`. The native-effects fallback list is regenerated from the same documentation (identical list). A result on another build still carries `PROBABILITY_GAME_BUILD_UNVERIFIED`.
13
+ - Run `hoi4.mod_index` on the shared Rust engine (`hoi4-engine mod-index`, ADR 0080; M-8 step 1). The engine's new shared symbol index (`symbol_index`) reproduces the TypeScript index's kinds, definition rules and `overridden` rule, so the answers do not change: on vanilla 1.19.4.2, Chaos Redux, ZIN, Ireland Total Overhaul, Atlantis, Kaiserreich and Old World Blues, for the mod layer and every layer, each (kind, id, overridden) record, file count, completeness flag, folder total and namespace matches the TypeScript scan, and so do 203 `next_id` answers (`scripts/mod-index-parity.ts`). A first overview of Chaos Redux takes 5 s instead of 23 s, and a repeated one 1 s instead of 5 s. Without a usable engine the tool answers `ENGINE_UNAVAILABLE`; nothing is counted in TypeScript instead. `hoi4-engine symbol-index` prints every record of the index. The tests now need a cargo build of the engine, which CI and the release workflow build first. The benchmark gains warm `mod_index` cases for every corpus and an every-layer case for the game.
14
+ - Move the two ChaosX tools out of the public package (maintainer decision M-14, #110, ADR 0081). `chaosx.visual_revision` and `chaosx.focus_country_assets` are gone, and `HOI4_AGENT_TOOLS_CHAOSX` does nothing. The stdio server instead loads plugins from the absolute paths the new configuration key `plugins` lists, never from a mod folder or the environment; a plugin adds tools named `<plugin>.<tool>` (never `hoi4.`), and the HTTP server never loads one. A listed plugin file that does not exist is skipped with a warning on stderr.
15
+
16
+ ## 4.11.1 - 2026-11-07
17
+
18
+ - Close impassable walls in generated maps, and keep pass saddles and point river mouths that a 4.10.0 `create_world` lost.
19
+ - Walls leaked: the synthesis marks a wall's whole footprint as a barrier band, often 10 to 60 pixels wide, and the partition put the province border wherever its fronts met in the band or at the band's edge, not on the range path. The crossings only block borders that cross the path, so most pairs got no `impassable` row. The partition now records the side of each wall (`wallSide`), gives every band pixel to the nearest province on its own side, and keeps the sliver and corner repairs of the province assembly from merging across it. A border that touches across the path at a single pixel now gets a row, and `MAP_RANGE_NOT_CLOSED` samples the provinces that meet at the path. On a 5,120 x 2,560 world with a closed ring wall and a long massif wall the open samples went from 49 of 79 and 186 of 193 to none for either wall.
20
+ - `relief.painted` no longer fills a declared pass: its raise is capped in the pass corridor at the saddle the macro relief carved, so a painted or impassable range over a pass no longer raises `MAP_PASS_NOT_LOWER`.
21
+ - A river whose course already runs through the cell of its point mouth (its last `via` within a half-resolution cell of the mouth) now ends there instead of failing with `MAP_RIVER_UNREACHABLE_MOUTH`.
22
+
5
23
  ## 4.11.0 - 2026-11-07
6
24
 
7
25
  - Add `hoi4.skill` and the skill resources (#108, M-1). The tool lists the skills HOI4 Mod Setup installed in the mod or loads one by name, and the same `SKILL.md` text is the resource `hoi4-agent://workspace/{workspaceId}/skill/{name}`. Both serve the kit version the mod's Setup lock pins, with the kit revision and each file's SHA-256. A file edited since Setup installed it is refused with `SKILL_TEXT_DRIFTED` unless the caller accepts local edits, and a mod without a lock gets its installed skills marked unpinned.
package/dist/bin/stdio.js CHANGED
@@ -1,9 +1,12 @@
1
1
  #!/usr/bin/env node
2
+ import path from 'node:path';
2
3
  import { canonicalJson } from '../hoi4_agent_tools/core/canonical.js';
3
4
  import { StdioFrameLimitError, StdioInvalidMessageError, StdioInvalidUtf8Error, } from '../hoi4_agent_tools/mcp/transports/bounded-stdio.js';
4
5
  import { serveNegotiatedStdio } from '../hoi4_agent_tools/mcp/transports/negotiated-stdio.js';
5
6
  import { ServerRegistry } from '../hoi4_agent_tools/core/server-registry.js';
6
7
  import { StdioLifetime } from '../hoi4_agent_tools/mcp/transports/stdio-lifetime.js';
8
+ import { loadPlugins } from '../hoi4_agent_tools/mcp/plugins.js';
9
+ import { PACKAGE_VERSION } from '../hoi4_agent_tools/version.js';
7
10
  import { createEngine } from '../hoi4_agent_tools/runtime.js';
8
11
  /**
9
12
  * A client registration can set its own idle limit, because the server configuration is shared
@@ -20,10 +23,10 @@ function idleExitMinutes(configured) {
20
23
  return minutes;
21
24
  }
22
25
  async function main() {
23
- const engine = await createEngine();
24
- const chaosxTools = process.env.HOI4_AGENT_TOOLS_CHAOSX === '1'
25
- ? await import('../hoi4_agent_tools/mcp/tools/chaosx.js')
26
- : undefined;
26
+ // The handshake must not wait for journal recovery; the transport holds workspace requests.
27
+ const engine = await createEngine(undefined, { recovery: 'background' });
28
+ // Plugins load only from the paths the server configuration lists (M-14).
29
+ const plugins = await loadPlugins(engine.resolver.config().plugins, PACKAGE_VERSION, (file, reason) => process.stderr.write(`${canonicalJson({ level: 'warn', event: 'plugin_skipped', plugin: path.basename(file), reason })}\n`));
27
30
  const onerror = (error) => {
28
31
  const fatalInputError = error instanceof StdioFrameLimitError || error instanceof StdioInvalidUtf8Error;
29
32
  const rejectedMessage = error instanceof StdioInvalidMessageError;
@@ -65,12 +68,7 @@ async function main() {
65
68
  : {}),
66
69
  })}\n`);
67
70
  },
68
- ...(chaosxTools === undefined
69
- ? {}
70
- : {
71
- createModernPrivateTools: chaosxTools.createChaosxToolOperations,
72
- registerLegacy: (server) => chaosxTools.registerChaosxTools(server, engine, {}),
73
- }),
71
+ ...(plugins === undefined ? {} : { plugins }),
74
72
  });
75
73
  closeTransport = () => transport.close();
76
74
  lifetime.start();
@@ -151,6 +151,19 @@ export const serverConfigurationSchema = z
151
151
  jobDeadlineSeconds: z.number().int().min(1).max(86_400).default(1_800),
152
152
  /** A read-only job that has not stopped this long after cancellation is stopped. */
153
153
  jobCancelGraceSeconds: z.number().int().min(1).max(600).default(10),
154
+ /**
155
+ * Absolute paths of plugin modules (.mjs or .js) the stdio server loads (M-14). A plugin adds
156
+ * its own tools; the server loads nothing from a mod folder or the environment. A listed file
157
+ * that does not exist is skipped, so a shared configuration can name a private plugin.
158
+ */
159
+ plugins: z
160
+ .array(z
161
+ .string()
162
+ .min(1)
163
+ .max(1024)
164
+ .refine((value) => path.isAbsolute(value), 'A plugin path must be absolute'))
165
+ .max(8)
166
+ .default([]),
154
167
  /** A stdio server with no client traffic or open request for this long exits; 0 never. */
155
168
  stdioIdleExitMinutes: z.number().int().min(0).max(10_080).default(0),
156
169
  /** V8 heap ceiling for each job worker in MiB; unset keeps Node's default. */
@@ -35,7 +35,8 @@ function under(roots, glob) {
35
35
  function englishLocalisationPatterns(roots) {
36
36
  return [...under(roots, 'english/**/*.{yml,yaml}'), ...under(roots, '*.{yml,yaml}')];
37
37
  }
38
- function defaultPatterns(workspace) {
38
+ /** The glob patterns of the shared scan, relative to each root. `hoi4.mod_index` passes them to the engine. */
39
+ export function defaultPatterns(workspace) {
39
40
  const roots = workspace.registration.roots;
40
41
  return [
41
42
  ...new Set([
@@ -101,6 +102,7 @@ export class CoreEngine {
101
102
  #scanGenerations = new Map();
102
103
  #scanAdmissionQueue = [];
103
104
  #activeScanAdmissions = new Set();
105
+ #recovery;
104
106
  constructor(resolver, services = {}) {
105
107
  this.resolver = resolver;
106
108
  this.indexSegments = services.indexSegments ?? new IndexSegmentCache();
@@ -131,7 +133,21 @@ export class CoreEngine {
131
133
  services.transactions ??
132
134
  new TransactionManager(resolver, this.artifacts, RECOVERY_TTL_SECONDS, RECOVERY_MAX_BYTES, RECOVERY_MAX_RECORDS, resolver.serverState());
133
135
  }
134
- async initialize() {
136
+ /**
137
+ * Recover interrupted internal rewrites in every workspace. A stdio server starts this in the
138
+ * background and answers the client handshake meanwhile; it holds workspace requests until
139
+ * {@link recovered} settles.
140
+ */
141
+ initialize() {
142
+ const recovery = this.#recoverWorkspaces();
143
+ this.#recovery = recovery;
144
+ return recovery;
145
+ }
146
+ /** Settles when the latest {@link initialize} has finished, at once when none was started. */
147
+ recovered() {
148
+ return this.#recovery ?? Promise.resolve();
149
+ }
150
+ async #recoverWorkspaces() {
135
151
  for (const workspace of this.resolver.list()) {
136
152
  // Recovery repairs an interrupted internal rewrite before the workspace is exposed. A
137
153
  // journal that cannot be recovered blocks rewrites of its own workspace, not the server.
@@ -42,7 +42,7 @@ const ownerSchema = z
42
42
  .strict();
43
43
  const requestSchema = z
44
44
  .object({
45
- toolName: z.string().regex(/^(?:hoi4|chaosx)\.[a-z_]+$/u),
45
+ toolName: z.string().regex(/^hoi4\.[a-z_]+$/u),
46
46
  arguments: z.record(z.string(), z.json()),
47
47
  mutation: z.boolean(),
48
48
  requestKey: z.string().min(1).max(256).optional(),
@@ -2,7 +2,7 @@
2
2
  * Native effect identifiers used to distinguish direct scripted-effect calls
3
3
  * from engine effects while importing focus completion rewards.
4
4
  *
5
- * Generated by scripts/generate-native-effects.ts from the HOI4 1.19.4.1 effects
5
+ * Generated by scripts/generate-native-effects.ts from the HOI4 1.19.4.2 effects
6
6
  * documentation. This is the fallback list; analysis also accepts every effect the installed
7
7
  * game documents in documentation/effects_documentation.md, so effects added by later patches
8
8
  * are recognized. The nightly game-update watcher regenerates it for review on a new build.
@@ -639,13 +639,54 @@ function scanRange(range, input) {
639
639
  }
640
640
  return { range, hits, passes };
641
641
  }
642
- /** A pair is a wall crossing when enough of its border lies across the range's line. */
642
+ /**
643
+ * A pair is a wall crossing when enough of its border lies across the range's line. One pixel
644
+ * is enough: two provinces that touch across the line at a single corner of their borders are
645
+ * as open to an army as a long border.
646
+ */
643
647
  function isWallPair(hit, stat) {
644
- if (hit.wall < 2)
648
+ if (hit.wall < 1)
645
649
  return false;
646
650
  const total = stat?.count ?? hit.wall;
647
651
  return hit.wall >= 0.2 * total;
648
652
  }
653
+ /**
654
+ * The province of the first pixel strictly on one side of a line through (`cx`, `cy`) with the
655
+ * given tangent, walking out along the normal in half-pixel steps up to three pixels; -1 when
656
+ * the walk leaves the map. `side` 1 is the right of travel as drawn on screen, -1 the left.
657
+ */
658
+ function besideLine(pixel, width, height, cx, cy, tx, ty, side) {
659
+ for (let step = 1; step <= 6; step += 1) {
660
+ const k = side * step * 0.5;
661
+ const x = Math.floor(cx - ty * k);
662
+ const y = Math.floor(cy + tx * k);
663
+ if (x < 0 || y < 0 || x >= width || y >= height)
664
+ return -1;
665
+ const cross = tx * (y + 0.5 - cy) - ty * (x + 0.5 - cx);
666
+ if (cross * side > 0.25 || step === 6)
667
+ return pixel[y * width + x];
668
+ }
669
+ return -1;
670
+ }
671
+ /**
672
+ * True when province `own`, which lies on both sides of the line here, continues into land on
673
+ * the given side: walking out along the normal up to six pixels meets land (its own or another
674
+ * province's) at least three pixels out, not water first.
675
+ */
676
+ function reachesOn(pixel, kind, width, height, cx, cy, tx, ty, side, own) {
677
+ for (let step = 1; step <= 6; step += 1) {
678
+ const x = Math.floor(cx - ty * side * step);
679
+ const y = Math.floor(cy + tx * side * step);
680
+ if (x < 0 || y < 0 || x >= width || y >= height)
681
+ return false;
682
+ const province = pixel[y * width + x];
683
+ if (kind[province] !== LAND)
684
+ return false;
685
+ if (province !== own || step >= 3)
686
+ return true;
687
+ }
688
+ return true;
689
+ }
649
690
  /** Border pixel pairs inside a pass window that free a pair: any border through the gate is the gate. */
650
691
  const GATE_HITS = 1;
651
692
  // ---------------------------------------------------------------------------------------------
@@ -891,26 +932,24 @@ export function planCrossings(input) {
891
932
  continue;
892
933
  const cx = sample.x * width;
893
934
  const cy = sample.y * height;
894
- const ax = Math.round(cx - sample.tangentY * 3);
895
- const ay = Math.round(cy + sample.tangentX * 3);
896
- const bx = Math.round(cx + sample.tangentY * 3);
897
- const by = Math.round(cy - sample.tangentX * 3);
898
- if (ax < 0 ||
899
- ay < 0 ||
900
- bx < 0 ||
901
- by < 0 ||
902
- ax >= width ||
903
- bx >= width ||
904
- ay >= height ||
905
- by >= height)
935
+ // The provinces that meet at the line here: the nearest pixel on each side of it, up to
936
+ // three pixels out along the normal. Probing further out could step over a narrow
937
+ // province between them and report two provinces that do not touch.
938
+ const a = besideLine(view.pixel, width, height, cx, cy, sample.tangentX, sample.tangentY, 1);
939
+ const b = besideLine(view.pixel, width, height, cx, cy, sample.tangentX, sample.tangentY, -1);
940
+ if (a < 0 || b < 0)
906
941
  continue;
907
- const a = view.pixel[ay * width + ax];
908
- const b = view.pixel[by * width + bx];
909
942
  if (input.kind[a] !== LAND || input.kind[b] !== LAND)
910
943
  continue;
911
944
  // A pair of provinces freed at a gate is a whole border; all of it counts as the gate.
912
945
  if (a !== b && gatePairs.has(pairKey(a, b, view.count)))
913
946
  continue;
947
+ // One province on both sides is a way across only where it reaches on into the land of
948
+ // both sides; a sliver of the line that ends at water on one side leads nowhere.
949
+ if (a === b &&
950
+ !(reachesOn(view.pixel, input.kind, width, height, cx, cy, sample.tangentX, sample.tangentY, 1, a) &&
951
+ reachesOn(view.pixel, input.kind, width, height, cx, cy, sample.tangentX, sample.tangentY, -1, a)))
952
+ continue;
914
953
  samples += 1;
915
954
  if (a === b || !blockedSet.has(pairKey(a, b, view.count))) {
916
955
  open += 1;
@@ -6,7 +6,7 @@ import { applyReplacements, assignments, encodeSource, parseLocalisation, parseC
6
6
  import { rgbKey } from './bmp.js';
7
7
  import { MAP_MASK_CELL_LIMIT, MAP_POLYGON_WORK_LIMIT, MAP_SELECTED_OFFSET_BYTES, MAP_SELECTED_PIXEL_LIMIT, } from './limits.js';
8
8
  import { derivedStateCapital, encodeTextDocument, LEVEL_STATE_BUILDINGS, MapWorkspaceIndex, parseMapDate, parseTextDocument, } from './model.js';
9
- import { planReferenceRemap, ReferenceRemapError } from './references.js';
9
+ import { collectContinentReferences, droppedContinentDiagnostics, planReferenceRemap, ReferenceRemapError, } from './references.js';
10
10
  import { generateWorld } from './world.js';
11
11
  import { resolveEdge } from './world-edge.js';
12
12
  import { DEFAULT_AUTO_STRAIT_GAP_PX } from './gameplay/crossings.js';
@@ -3421,6 +3421,7 @@ function applyCreateWorld(base, changes, operation, context, signal) {
3421
3421
  ...(operation.continentNames === undefined
3422
3422
  ? {}
3423
3423
  : { continentNames: operation.continentNames }),
3424
+ ...(operation.inheritedContinents === 'drop' ? { inheritedContinents: 'drop' } : {}),
3424
3425
  startDate: operation.startDate ?? '1936.1.1',
3425
3426
  rivers: typeof operation.rivers === 'number' ? operation.rivers : reference === undefined ? 8 : 80,
3426
3427
  ...(geography === undefined
@@ -3482,13 +3483,17 @@ function applyCreateWorld(base, changes, operation, context, signal) {
3482
3483
  message: note.message,
3483
3484
  ...(note.details === undefined ? {} : { details: note.details }),
3484
3485
  })),
3485
- {
3486
- code: 'MAP_SYNTHESIS_CHECK_READY',
3487
- severity: 'info',
3488
- category: 'map',
3489
- operationId: operation.id,
3490
- message: `Every river of the model reaches its mouth over the synthesised relief of a ${world.summary.width}x${world.summary.height} map; nothing was written`,
3491
- },
3486
+ ...(world.notes.some(({ severity }) => severity === 'error')
3487
+ ? []
3488
+ : [
3489
+ {
3490
+ code: 'MAP_SYNTHESIS_CHECK_READY',
3491
+ severity: 'info',
3492
+ category: 'map',
3493
+ operationId: operation.id,
3494
+ message: `Every river of the model reaches its mouth over the synthesised relief of a ${world.summary.width}x${world.summary.height} map; nothing was written`,
3495
+ },
3496
+ ]),
3492
3497
  ];
3493
3498
  const roots = operation.replaceBaseGame === false
3494
3499
  ? []
@@ -3512,6 +3517,9 @@ function applyCreateWorld(base, changes, operation, context, signal) {
3512
3517
  if (roots.length > 0)
3513
3518
  addChange(changes, 'descriptor.mod', descriptorWithReplacePaths(base, roots), operation.id, 'text/plain');
3514
3519
  const generated = currentIndex(base, changes);
3520
+ // Scripts that stay active after the write and still name a continent the world dropped.
3521
+ const droppedContinents = world.droppedContinents ?? [];
3522
+ const continentReferences = collectContinentReferences(generated.activeFiles.all, new Set(droppedContinents));
3515
3523
  for (const file of planMapPositions(generated, { mode: 'replace' }))
3516
3524
  addChange(changes, file.relativePath, file.content, operation.id, 'text/plain');
3517
3525
  const positioned = currentIndex(base, changes);
@@ -3576,6 +3584,27 @@ function applyCreateWorld(base, changes, operation, context, signal) {
3576
3584
  },
3577
3585
  ]),
3578
3586
  ...worldTagDiagnostics(operation.id, tagCatalog, world, workspaceCountries !== undefined),
3587
+ ...(operation.inheritedContinents === 'drop'
3588
+ ? [
3589
+ {
3590
+ code: 'MAP_CONTINENTS_DROPPED',
3591
+ severity: 'info',
3592
+ category: 'map',
3593
+ operationId: operation.id,
3594
+ message: droppedContinents.length === 0
3595
+ ? 'continent.txt lists only the generated continents; the active sources declared no other'
3596
+ : `continent.txt lists only the generated continents and leaves out ${droppedContinents.length} inherited one(s); ${continentReferences.length} active script reference(s) still name them`,
3597
+ details: {
3598
+ dropped: droppedContinents,
3599
+ references: continentReferences.length,
3600
+ },
3601
+ },
3602
+ ...droppedContinentDiagnostics(continentReferences).map((diagnostic) => ({
3603
+ ...diagnostic,
3604
+ operationId: operation.id,
3605
+ })),
3606
+ ]
3607
+ : []),
3579
3608
  ...worldRealmDiagnostics(operation.id, world),
3580
3609
  ...(outputs.released.length === 0
3581
3610
  ? []
@@ -25,6 +25,8 @@ export const PARTITION_TERRAIN = {
25
25
  };
26
26
  /** Pixel kinds, as the province generator already uses them. */
27
27
  export const PARTITION_KIND = { sea: 0, land: 1, lake: 2 };
28
+ /** Values of `PartitionFields.wallSide`. */
29
+ export const WALL_SIDE = { none: 0, left: 1, right: 2, line: 3 };
28
30
  const MAP_PIXEL_LIMIT = 13_238_272;
29
31
  function invalid(message, details) {
30
32
  throw new ServiceError('MAP_PARTITION_FIELDS_INVALID', message, details);
@@ -59,6 +61,18 @@ export function assertPartitionFields(fields) {
59
61
  expected: total,
60
62
  });
61
63
  }
64
+ if (fields.wallSide !== undefined) {
65
+ if (!(fields.wallSide instanceof Uint8Array) || fields.wallSide.length !== total)
66
+ invalid('Partition field wallSide must be a Uint8Array matching the map dimensions', {
67
+ field: 'wallSide',
68
+ });
69
+ for (let p = 0; p < total; p++)
70
+ if (fields.wallSide[p] > WALL_SIDE.line)
71
+ invalid('Partition wallSide contains a value other than 0 to 3', {
72
+ pixel: p,
73
+ value: fields.wallSide[p],
74
+ });
75
+ }
62
76
  for (let p = 0; p < total; p++)
63
77
  if (fields.kind[p] > 2)
64
78
  invalid('Partition kind contains a value other than sea (0), land (1) or lake (2)', {
@@ -1,6 +1,6 @@
1
1
  import { ServiceError } from '../core/result.js';
2
- import { forEachPolylinePixel, rowStrips, scanAreaStrip, } from './geography/index.js';
3
- import { PARTITION_KIND } from './partition-fields.js';
2
+ import { clearBandStrip, createBandStrip, forEachPolylinePixel, rasterizeBandStrip, rowStrips, scanAreaStrip, } from './geography/index.js';
3
+ import { PARTITION_KIND, WALL_SIDE, } from './partition-fields.js';
4
4
  import { BARRIER_CREST, BARRIER_FORT_LINE, BARRIER_WALL, } from './relief/fields.js';
5
5
  /**
6
6
  * Geography inputs of the partition (ADR 0058): the named regions and seas of the model become the
@@ -66,9 +66,8 @@ export function partitionFieldsFromGeography(fields, geography, options = {}) {
66
66
  });
67
67
  }
68
68
  const whole = { y0: 0, y1: height };
69
- for (const range of geography.ranges) {
70
- if (range.profile !== 'wall' && range.barrier !== 'impassable')
71
- continue;
69
+ const walls = geography.ranges.filter((range) => range.profile === 'wall' || range.barrier === 'impassable');
70
+ for (const range of walls) {
72
71
  forEachPolylinePixel(range.path, grid, whole, (x, y) => {
73
72
  for (let dy = -WALL_HALF_WIDTH; dy <= WALL_HALF_WIDTH; dy++)
74
73
  for (let dx = -WALL_HALF_WIDTH; dx <= WALL_HALF_WIDTH; dx++) {
@@ -81,7 +80,57 @@ export function partitionFieldsFromGeography(fields, geography, options = {}) {
81
80
  }
82
81
  });
83
82
  }
84
- return { ...fields, regionId, barrier, regions: table };
83
+ const wallSide = walls.length === 0 ? undefined : wallSideField(walls, grid, options.stripRows ?? 256);
84
+ return {
85
+ ...fields,
86
+ regionId,
87
+ barrier,
88
+ ...(wallSide === undefined ? {} : { wallSide }),
89
+ regions: table,
90
+ };
91
+ }
92
+ /**
93
+ * Reach of a wall's side field in pixels: past the barrier band the synthesis draws for it (the
94
+ * range footprint, displaced a little by the crest wander), so every band pixel has a side.
95
+ */
96
+ function wallReachPx(range, width) {
97
+ let halfWidthPx = 0;
98
+ for (const half of range.path.halfWidth)
99
+ halfWidthPx = Math.max(halfWidthPx, half * width);
100
+ return Math.min(WALL_REACH_LIMIT_PX, Math.ceil(3 * halfWidthPx) + 8);
101
+ }
102
+ const WALL_REACH_LIMIT_PX = 128;
103
+ /**
104
+ * The side of the nearest wall line for every pixel within its reach (`WALL_SIDE`). Beyond the
105
+ * ends of an open line there is no side, so provinces may join around the end of a wall.
106
+ */
107
+ function wallSideField(walls, grid, stripRows) {
108
+ const { width } = grid;
109
+ const side = new Uint8Array(width * grid.height);
110
+ const nearest = new Float32Array(width * grid.height).fill(Infinity);
111
+ for (const strip of rowStrips(grid, stripRows)) {
112
+ const band = createBandStrip(grid, strip);
113
+ for (const range of walls) {
114
+ clearBandStrip(band);
115
+ rasterizeBandStrip(range.path, grid, strip, wallReachPx(range, width), band);
116
+ const open = !range.path.closed;
117
+ for (let cell = 0; cell < band.distance.length; cell++) {
118
+ const distance = band.distance[cell];
119
+ if (distance === Infinity)
120
+ continue;
121
+ const t = band.t[cell];
122
+ if (open && (t <= 0 || t >= 1))
123
+ continue;
124
+ const p = strip.y0 * width + cell;
125
+ if (distance >= nearest[p])
126
+ continue;
127
+ nearest[p] = distance;
128
+ const s = band.side[cell];
129
+ side[p] = s === 0 ? WALL_SIDE.line : s < 0 ? WALL_SIDE.left : WALL_SIDE.right;
130
+ }
131
+ }
132
+ }
133
+ return side;
85
134
  }
86
135
  /** Strength each model-drawn line of the terrain synthesis gives the partition's barrier plane. */
87
136
  const TERRAIN_LINE_STRENGTH = [
@@ -1,6 +1,6 @@
1
1
  import { ServiceError } from '../core/result.js';
2
2
  import { assembleWorldProvinces, assertProvinceMaskFeasible } from './world-provinces.js';
3
- import { assertPartitionFields, PARTITION_KIND, PARTITION_TERRAIN } from './partition-fields.js';
3
+ import { assertPartitionFields, PARTITION_KIND, PARTITION_TERRAIN, WALL_SIDE, } from './partition-fields.js';
4
4
  import { PARTITION_PROVINCE_ERROR } from './partition-tuning.js';
5
5
  import { hash32, placeSeeds, STEP_UNIT, unit32, weightedWatershed } from './partition-watershed.js';
6
6
  /**
@@ -454,34 +454,111 @@ function splitAcrossLines(fields, labels, minPixels, queue) {
454
454
  }
455
455
  sizes.push(tail);
456
456
  }
457
- // Line pixels join the smallest-numbered neighbouring piece of the same province.
458
- for (let pass = 0; pass < 8; pass++) {
459
- let changed = false;
457
+ // A wall's barrier band can be many pixels wide. Its pixels go to the nearest piece on their
458
+ // own side of the wall line, whatever its province (a pixel on the line to either side), so the
459
+ // province border runs on the line, where the crossings look for it, never at the far edge of
460
+ // the band or along a strip that one piece pushed down the band.
461
+ const side = fields.wallSide;
462
+ const inWall = (p) => side !== undefined && side[p] !== WALL_SIDE.none;
463
+ const joins = (p, q) => {
464
+ const sp = side[p];
465
+ const sq = side[q];
466
+ return sp === WALL_SIDE.none || sq === WALL_SIDE.none || sp === sq || sp === WALL_SIDE.line;
467
+ };
468
+ const straddles = (p, q) => {
469
+ if (side === undefined)
470
+ return false;
471
+ const sp = side[p];
472
+ const sq = side[q];
473
+ return sp !== WALL_SIDE.none && sq !== WALL_SIDE.none && sp !== sq;
474
+ };
475
+ const neighboursOf = (p) => {
476
+ const x = p % width;
477
+ return [
478
+ x > 0 ? p - 1 : p + width - 1,
479
+ x + 1 < width ? p + 1 : p - width + 1,
480
+ p >= width ? p - width : -1,
481
+ p + width < total ? p + width : -1,
482
+ ];
483
+ };
484
+ // Other line pixels (rivers, and walls without a side field) join the smallest-numbered
485
+ // neighbouring piece of the same province.
486
+ const joinLines = () => {
487
+ let any = false;
488
+ for (let pass = 0; pass < 8; pass++) {
489
+ let changed = false;
490
+ for (let p = 0; p < total; p++) {
491
+ if (piece[p] !== -1 || kind[p] !== LAND || inWall(p))
492
+ continue;
493
+ let best = -1;
494
+ for (const q of neighboursOf(p))
495
+ if (q >= 0 &&
496
+ piece[q] >= 0 &&
497
+ labels[q] === labels[p] &&
498
+ (best === -1 || piece[q] < best))
499
+ best = piece[q];
500
+ if (best >= 0) {
501
+ piece[p] = best;
502
+ sizes[best]++;
503
+ changed = true;
504
+ }
505
+ }
506
+ if (!changed)
507
+ break;
508
+ any = true;
509
+ }
510
+ return any;
511
+ };
512
+ // Wall pixels: a breadth-first fill from the pieces, which takes the province of the piece.
513
+ const fillWalls = () => {
514
+ if (side === undefined)
515
+ return false;
516
+ let tail = 0;
460
517
  for (let p = 0; p < total; p++) {
461
- if (piece[p] !== -1 || kind[p] !== LAND)
518
+ if (piece[p] !== -1 || kind[p] !== LAND || !inWall(p))
462
519
  continue;
463
- const x = p % width;
464
520
  let best = -1;
465
- for (const q of [
466
- x > 0 ? p - 1 : p + width - 1,
467
- x + 1 < width ? p + 1 : p - width + 1,
468
- p >= width ? p - width : -1,
469
- p + width < total ? p + width : -1,
470
- ])
471
- if (q >= 0 &&
472
- piece[q] >= 0 &&
473
- labels[q] === labels[p] &&
474
- (best === -1 || piece[q] < best))
521
+ let from = -1;
522
+ for (const q of neighboursOf(p))
523
+ if (q >= 0 && piece[q] >= 0 && joins(p, q) && (best === -1 || piece[q] < best)) {
475
524
  best = piece[q];
476
- if (best >= 0) {
477
- piece[p] = best;
478
- sizes[best]++;
479
- changed = true;
480
- }
525
+ from = q;
526
+ }
527
+ if (best < 0)
528
+ continue;
529
+ queue[tail++] = p;
530
+ piece[p] = -2 - from;
531
+ }
532
+ // Assigned after the scan, so the first ring does not depend on the scan order.
533
+ for (let index = 0; index < tail; index++) {
534
+ const p = queue[index];
535
+ const from = -2 - piece[p];
536
+ piece[p] = piece[from];
537
+ labels[p] = labels[from];
538
+ sizes[piece[p]]++;
539
+ }
540
+ let head = 0;
541
+ while (head < tail) {
542
+ const p = queue[head++];
543
+ for (const q of neighboursOf(p))
544
+ if (q >= 0 && piece[q] === -1 && kind[q] === LAND && inWall(q) && joins(q, p)) {
545
+ piece[q] = piece[p];
546
+ labels[q] = labels[p];
547
+ sizes[piece[p]]++;
548
+ queue[tail++] = q;
549
+ }
550
+ }
551
+ return tail > 0;
552
+ };
553
+ if (side === undefined)
554
+ joinLines();
555
+ else
556
+ for (let round = 0; round < 8; round++) {
557
+ const lines = joinLines();
558
+ const walls = fillWalls();
559
+ if (!lines && !walls)
560
+ break;
481
561
  }
482
- if (!changed)
483
- break;
484
- }
485
562
  for (let p = 0; p < total; p++)
486
563
  if (piece[p] === -1 && kind[p] === LAND) {
487
564
  piece[p] = sizes.length;
@@ -504,6 +581,9 @@ function splitAcrossLines(fields, labels, minPixels, queue) {
504
581
  for (const q of [x + 1 < width ? p + 1 : -1, p + width < total ? p + width : -1]) {
505
582
  if (q < 0 || kind[q] !== LAND || labels[q] !== labels[p] || piece[q] === piece[p])
506
583
  continue;
584
+ // A small piece never joins a piece across a wall line.
585
+ if (straddles(p, q))
586
+ continue;
507
587
  const a = piece[p];
508
588
  const b = piece[q];
509
589
  if (sizes[a] < minPixels && (best[a] === -1 || sizes[b] > sizes[best[a]]))
@@ -735,6 +815,7 @@ export function partitionProvinces(input) {
735
815
  kind,
736
816
  ...(usesRegions ? { group: fields.regionId } : {}),
737
817
  line: lines,
818
+ ...(fields.wallSide === undefined ? {} : { wallSide: fields.wallSide }),
738
819
  }, labels);
739
820
  return { provinces, barrier, statistics: provinceStatistics(provinces, expected), notes };
740
821
  }