hoi4-agent-tools 4.10.0 → 4.11.1

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 (74) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/dist/hoi4_agent_tools/core/operation-result.js +51 -11
  3. package/dist/hoi4_agent_tools/core/workspace.js +22 -7
  4. package/dist/hoi4_agent_tools/decision/service.js +13 -1
  5. package/dist/hoi4_agent_tools/impact/service.js +4 -1
  6. package/dist/hoi4_agent_tools/map/gameplay/crossings.js +55 -16
  7. package/dist/hoi4_agent_tools/map/partition-fields.js +14 -0
  8. package/dist/hoi4_agent_tools/map/partition-geography.js +55 -6
  9. package/dist/hoi4_agent_tools/map/partition-provinces.js +105 -24
  10. package/dist/hoi4_agent_tools/map/relief/hydrology.js +9 -0
  11. package/dist/hoi4_agent_tools/map/relief/macro-relief.js +21 -1
  12. package/dist/hoi4_agent_tools/map/relief/painted-relief.js +8 -5
  13. package/dist/hoi4_agent_tools/map/world-provinces.js +36 -19
  14. package/dist/hoi4_agent_tools/mcp/resources/register-modern.js +11 -4
  15. package/dist/hoi4_agent_tools/mcp/resources/register.js +7 -0
  16. package/dist/hoi4_agent_tools/mcp/server/argument-errors.js +1 -0
  17. package/dist/hoi4_agent_tools/mcp/tools/analysis.js +12 -0
  18. package/dist/hoi4_agent_tools/mcp/tools/reference.js +12 -3
  19. package/dist/hoi4_agent_tools/package-check/service.js +14 -1
  20. package/dist/hoi4_agent_tools/reference/operations.js +35 -6
  21. package/dist/hoi4_agent_tools/reference/service.js +118 -14
  22. package/dist/hoi4_agent_tools/reference/skill-resource.js +74 -0
  23. package/dist/hoi4_agent_tools/reference/skills.js +278 -0
  24. package/dist/hoi4_agent_tools/schemas/reference.js +34 -2
  25. package/dist/hoi4_agent_tools/schemas/skill.js +72 -0
  26. package/dist/hoi4_agent_tools/version.js +1 -1
  27. package/docs/configuration.md +3 -3
  28. package/docs/map.md +16 -16
  29. package/docs/reference.md +27 -1
  30. package/docs/tools.md +101 -86
  31. package/engine/bin/manifest.json +1 -1
  32. package/engine/bin/win32-x64/hoi4-engine.exe +0 -0
  33. package/npm-shrinkwrap.json +2 -2
  34. package/package.json +2 -1
  35. package/schemas/configuration.schema.json +1 -1
  36. package/schemas/continuous-focus-palette.schema.json +1 -1
  37. package/schemas/custom-weighted-pool.schema.json +1 -1
  38. package/schemas/decision-inspect-input.schema.json +1 -1
  39. package/schemas/error-log-input.schema.json +1 -1
  40. package/schemas/event-feature-manifest.schema.json +1 -1
  41. package/schemas/focus-plan.schema.json +1 -1
  42. package/schemas/focus-planning-sidecar.schema.json +1 -1
  43. package/schemas/geography-model.schema.json +1 -1
  44. package/schemas/gui-animation-source.schema.json +1 -1
  45. package/schemas/gui-helper.schema.json +1 -1
  46. package/schemas/gui-scenario.schema.json +1 -1
  47. package/schemas/helper-expansion-request.schema.json +1 -1
  48. package/schemas/helper-expansion-summary.schema.json +1 -1
  49. package/schemas/impact-inspect-input.schema.json +1 -1
  50. package/schemas/map-operation.schema.json +1 -1
  51. package/schemas/mechanic-test-input.schema.json +1 -1
  52. package/schemas/mod-index-input.schema.json +1 -1
  53. package/schemas/operation-result.schema.json +1 -1
  54. package/schemas/package-check-input.schema.json +1 -1
  55. package/schemas/package-manifest.schema.json +1 -1
  56. package/schemas/probability-analysis-result.schema.json +1 -1
  57. package/schemas/probability-compare-input.schema.json +1 -1
  58. package/schemas/probability-evaluate-input.schema.json +1 -1
  59. package/schemas/probability-inspect-input.schema.json +1 -1
  60. package/schemas/probability-render-input.schema.json +1 -1
  61. package/schemas/probability-scenario-set.schema.json +1 -1
  62. package/schemas/probability-sequence-input.schema.json +1 -1
  63. package/schemas/probability-simulate-input.schema.json +1 -1
  64. package/schemas/probability-sweep-input.schema.json +1 -1
  65. package/schemas/reference-context-input.schema.json +1 -1
  66. package/schemas/reference-read-input.schema.json +3 -3
  67. package/schemas/reference-search-input.schema.json +1 -1
  68. package/schemas/reference-sheets.schema.json +1 -1
  69. package/schemas/scenario-suite.schema.json +1 -1
  70. package/schemas/scenario-test-input.schema.json +1 -1
  71. package/schemas/script-validate-input.schema.json +1 -1
  72. package/schemas/shared-scenario.schema.json +1 -1
  73. package/schemas/source-lookup-input.schema.json +1 -1
  74. package/server.json +2 -2
package/CHANGELOG.md CHANGED
@@ -2,6 +2,21 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ ## 4.11.1 - 2026-11-07
6
+
7
+ - Close impassable walls in generated maps, and keep pass saddles and point river mouths that a 4.10.0 `create_world` lost.
8
+ - 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.
9
+ - `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`.
10
+ - 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`.
11
+
12
+ ## 4.11.0 - 2026-11-07
13
+
14
+ - 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.
15
+ - Smaller answers (maintainer decision R-4). The reference tools (`reference_search`, `reference_read`, `reference_context`, `source_lookup`, `script_validate`, `error_log`, `mod_index` and the `*_inspect` tools beside them), which agents call most, leave out `filesScanned`, `proposedFiles`, `changedFiles`, `diagnostics`, `artifacts` and `blockers` when they are empty, and `validation.checks` when there are none. An absent list means an empty one, and the advertised output schema marks them optional for every tool. The other tools keep the full envelope for now. A `reference_search` or `reference_context` hit names its file under its source's folder (`wiki:event_modding.md`, `game_doc:documentation/effects_documentation.md`) instead of an absolute path, carries a 16-character id and a 12-character revision instead of two 64-character hashes, leaves out the source's authority line, and repeats the page title only when it differs from the heading. `reference_read` accepts these short forms and still accepts the full ones. A stale revision is still caught. When no mod is selected, `WORKSPACE_CONTEXT_NOT_FOUND` and `WORKSPACE_CONTEXT_REQUIRED` list the mod folder names (`modFolders`) and one line that says what to pass (`fix`), instead of opaque workspace ids. A `workspaceId` that names a mod folder now matches in any letter case and with spaces, as the folder appears in a file manager.
16
+ - Generate the tool tables and example calls in `docs/tools.md` from `tools/list` (#109, M-5). `npm run docs:tools` rewrites them, and `tests/integration/tool-docs.test.ts` fails when the page drifts from the tool definitions, when two tools share a name, when a tool has no section, or when a description has no example call. The first run added the missing `hoi4.asset_inspect` row, updated four example calls that no longer matched their descriptions, and dropped three second calls that no description carries.
17
+ - More answers come inline, with less unrelated noise (part of #66). `package_check` names every item that is not present in `data.notPresent` (category, id, status, reason and path, up to 32), so the answer needs no report. `filesScanned` of `package_check`, of a `decision_inspect` inspection or comparison, and of `impact_inspect` now lists the files that hold the checked items, the decision or the symbol and its consumers, instead of the first twelve files of the workspace. The tools list budget in the discovery test moves from 80 to 84 KiB, as in #104 and #105.
18
+ - Record the 2026-11-01 head-to-head with cpntodd/HOI4-MCP in `docs/research/hoi4-mcp-head-to-head-2026-11-01.md` (part of #111, M-7). The record says that it predates the accuracy fixes and that its seeded `owner = ROOT` control was wrong ground truth, because `owner` is not a trigger.
19
+
5
20
  ## 4.10.0 - 2026-11-06
6
21
 
7
22
  - Size lake provinces: `create_world.partitionTuning.lakeArea` (default 6,000 pixels, capped at the largest province the map allows) sets the area of a lake province, so a drawn lake no larger than it stays one province.
@@ -12,6 +27,7 @@
12
27
  - `MAP_REALM_CUT_OFF` and `MAP_REALM_ENCLOSED` warn when impassable land or borders cut a realm apart or box it in.
13
28
  - `EVENT_TARGET_READ_BEFORE_SAVE` no longer reports correct script (#60). A `has_event_target` or `has_global_event_target` check tests whether a target exists. Without a visible producer it is now the design warning `EVENT_GATE_WITHOUT_WRITER`, not a probable defect. A read that such a check guards in the same event, focus or decision is not reported. Names built in a `meta_effect` or with `$parameter$`s are no longer cut at their first bracket. Names far into a long block are read in full instead of being cut at the display limit. The event graph now reads shared and joint focuses and the `completion_reward_joint_originator` and `completion_reward_joint_member` rewards, where vanilla saves `SSB_leader`. On Chaos Redux with vanilla 1.19.4.1 the findings drop from 33 to 2. Both remaining ones are real: vanilla reads `demanded_prov_target` in `events/Generic.txt` and saves it nowhere.
14
29
  - Check the hand-kept game data against the installed build (#70). The probability adapters were re-checked on 1.19.4.1: five of the six documentation files they rest on are byte-identical to 1.19.2.0, and the two AI strategy sections they use say the same, so the target moves to `Operation Postern 1.19.4.1 (f584)` and the adapter version to `hoi4-1.19.4.1.v1`. A result on another build now carries the warning `PROBABILITY_GAME_BUILD_UNVERIFIED` instead of only recording `workspace_observed` in its metadata. The nightly game-update watcher lists the adapters or the native-effects list under "Checked against another build" on every run while their pin differs from the installed build, not only on the night the build changes.
30
+ - Keep the kit wiki's maintenance text out of reference answers. `hoi4.reference_search`, `hoi4.reference_read` and `hoi4.reference_context` never index `LICENSE.txt`, `SOURCES.json` (or `SOURCES.md`) and `manifest.json` (or `manifest.md`) in the wiki folder, whatever their extension, and no longer serve HTML comments from Markdown sources. Kit wiki pages from before the kit made them lean carry `<!-- kit:begin ... -->` markers, and a search excerpt could open with one. A comment is blanked outside code fences and inline code, and every line is kept, so cited line numbers still match the file. On the 163 hand-checked questions of the discovery benchmark the kit's lean wiki answers as well as before (131 rather than 130 within five results) and the median reply is 9 percent smaller.
15
31
 
16
32
  ## 4.9.0 - 2026-11-05
17
33
 
@@ -57,22 +57,61 @@ const compactPublicOperationResultSchema = z
57
57
  status: z.enum(['ok', 'blocked', 'error']),
58
58
  code: z.string(),
59
59
  workspaceId: z.string(),
60
- filesScanned: z.array(z.unknown()),
61
- proposedFiles: z.array(z.unknown()),
62
- changedFiles: z.array(z.unknown()),
63
- diagnostics: z.array(z.unknown()).max(MAX_INLINE_DIAGNOSTICS),
64
- artifacts: z.array(z.unknown()).max(MAX_INLINE_ARTIFACT_LINKS),
60
+ filesScanned: z.array(z.unknown()).optional(),
61
+ proposedFiles: z.array(z.unknown()).optional(),
62
+ changedFiles: z.array(z.unknown()).optional(),
63
+ diagnostics: z.array(z.unknown()).max(MAX_INLINE_DIAGNOSTICS).optional(),
64
+ artifacts: z.array(z.unknown()).max(MAX_INLINE_ARTIFACT_LINKS).optional(),
65
65
  validation: z.unknown(),
66
- blockers: z.array(z.unknown()),
66
+ blockers: z.array(z.unknown()).optional(),
67
67
  data: z.object({}).catchall(z.unknown()),
68
68
  })
69
69
  .strict();
70
+ /**
71
+ * Collections a compact tool result leaves out when they are empty. The reference tools answer
72
+ * most often, so their answers do not repeat six empty lists; an absent list is empty.
73
+ */
74
+ const OMITTED_WHEN_EMPTY = [
75
+ 'filesScanned',
76
+ 'proposedFiles',
77
+ 'changedFiles',
78
+ 'diagnostics',
79
+ 'artifacts',
80
+ 'blockers',
81
+ ];
82
+ /** The published envelope: the same fields, with empty collections and empty checks optional. */
83
+ const publicOperationResultBaseSchema = operationResultBaseSchema
84
+ .partial({
85
+ filesScanned: true,
86
+ proposedFiles: true,
87
+ changedFiles: true,
88
+ diagnostics: true,
89
+ artifacts: true,
90
+ blockers: true,
91
+ })
92
+ .extend({ validation: validationSummarySchema.partial({ checks: true }) })
93
+ .strict();
94
+ /** Drop the empty collections and empty validation checks from a structured result. */
95
+ export function withoutEmptyCollections(structured) {
96
+ const omitted = new Set(OMITTED_WHEN_EMPTY);
97
+ const result = Object.fromEntries(Object.entries(structured).filter(([key, value]) => !(omitted.has(key) && Array.isArray(value) && value.length === 0)));
98
+ const validation = result.validation;
99
+ if (validation !== null &&
100
+ typeof validation === 'object' &&
101
+ 'checks' in validation &&
102
+ Array.isArray(validation.checks) &&
103
+ validation.checks.length === 0) {
104
+ const { checks: _checks, ...rest } = validation;
105
+ result.validation = rest;
106
+ }
107
+ return result;
108
+ }
70
109
  /**
71
110
  * Advertise one compact operation envelope while retaining exact per-tool runtime validation.
72
111
  * The generic operation-result schema remains available for stored envelopes.
73
112
  */
74
113
  export function strictOperationResultSchema(successDataSchema) {
75
- const exactSchema = operationResultBaseSchema
114
+ const exactSchema = publicOperationResultBaseSchema
76
115
  .extend({ data: z.union([emptyToolDataSchema, successDataSchema]) })
77
116
  .strict();
78
117
  return compactPublicOperationResultSchema.superRefine((value, context) => {
@@ -421,8 +460,9 @@ function compactDescriptions(unfiltered) {
421
460
  })),
422
461
  };
423
462
  }
424
- function buildToolResult(selected, imageCount = 0) {
425
- const structuredContent = operationResultSchema.parse(selected);
463
+ function buildToolResult(selected, imageCount = 0, compact = false) {
464
+ const parsed = operationResultSchema.parse(selected);
465
+ const structuredContent = compact ? withoutEmptyCollections(parsed) : parsed;
426
466
  const shown = selected.artifacts
427
467
  .map((artifact, order) => ({ artifact, order }))
428
468
  .sort((left, right) => linkPriority(left.artifact.mimeType) - linkPriority(right.artifact.mimeType) ||
@@ -487,10 +527,10 @@ export function toolResult(result, options = {}) {
487
527
  ? Buffer.byteLength(canonicalJson(compact), 'utf8')
488
528
  : MAX_TOOL_RESULT_BYTES + 1;
489
529
  const selected = estimatedBytes > MAX_TOOL_RESULT_BYTES ? boundedResult(compact, estimatedBytes) : compact;
490
- let output = buildToolResult(selected, images.length);
530
+ let output = buildToolResult(selected, images.length, options.compact);
491
531
  const wireBytes = Buffer.byteLength(canonicalJson(output), 'utf8');
492
532
  if (wireBytes > MAX_TOOL_RESULT_BYTES) {
493
- output = buildToolResult(boundedResult(compact, wireBytes), images.length);
533
+ output = buildToolResult(boundedResult(compact, wireBytes), images.length, options.compact);
494
534
  }
495
535
  const finalBytes = Buffer.byteLength(canonicalJson(output), 'utf8');
496
536
  if (finalBytes > MAX_TOOL_RESULT_BYTES) {
@@ -207,15 +207,23 @@ function workspaceAliases(workspace) {
207
207
  `mod_${nameSlug}`,
208
208
  ]);
209
209
  }
210
- const WORKSPACE_CONTEXT_FIX = 'Pass workspaceId with one of the listed IDs or the mod folder name, start the client in the mod folder, or set defaultWorkspace in the server configuration';
210
+ const WORKSPACE_CONTEXT_FIX = 'Pass workspaceId with a mod folder name from modFolders, start the client in the mod folder, or set defaultWorkspace in the server configuration';
211
211
  const WORKSPACE_CANDIDATE_LIMIT = 32;
212
- /** The mods a caller could name, bounded and without host paths. */
212
+ /**
213
+ * The mods a caller could name, bounded and without host paths: their folder names, which
214
+ * `workspaceId` accepts, and one line that says what to pass.
215
+ */
213
216
  function workspaceCandidates(workspaces) {
214
- const listed = workspaces.slice(0, WORKSPACE_CANDIDATE_LIMIT);
217
+ const modFolders = workspaces
218
+ .slice(0, WORKSPACE_CANDIDATE_LIMIT)
219
+ .map(({ modRoot }) => path.basename(modRoot));
220
+ const example = modFolders[0];
215
221
  return {
216
- workspaceIds: listed.map(({ id }) => id),
217
- workspaceNames: listed.map(({ name }) => name),
222
+ modFolders,
218
223
  workspaceCount: workspaces.length,
224
+ fix: example === undefined
225
+ ? 'Add a mod folder to modRoots in the server configuration'
226
+ : `Pass "workspaceId":${JSON.stringify(example)} (or another folder in modFolders)`,
219
227
  };
220
228
  }
221
229
  function requestedWorkspaceAlias(value) {
@@ -383,7 +391,7 @@ export class WorkspaceResolver {
383
391
  resolveCurrentWorkspaceId(principal) {
384
392
  const workspaces = this.list(principal).filter(({ registration }) => registration.kind === 'mod');
385
393
  if (workspaces.length === 0) {
386
- throw new ServiceError('WORKSPACE_CONTEXT_NOT_FOUND', 'No writable mod workspace is configured for the MCP server');
394
+ throw new ServiceError('WORKSPACE_CONTEXT_NOT_FOUND', 'No writable mod workspace is configured for the MCP server', workspaceCandidates(workspaces));
387
395
  }
388
396
  const currentDirectory = path.normalize(process.cwd());
389
397
  const containing = workspaces.filter((workspace) => isWithin(workspace.modRoot, currentDirectory));
@@ -455,7 +463,14 @@ export class WorkspaceResolver {
455
463
  if (this.#byId.has(workspaceId))
456
464
  return workspaceId;
457
465
  const alias = requestedWorkspaceAlias(workspaceId);
458
- const matches = this.list(principal).filter((workspace) => workspace.registration.kind === 'mod' && workspaceAliases(workspace).has(alias));
466
+ // A folder name as the file manager shows it ("My Mod") names the same mod as its slug.
467
+ const slug = workspaceAliasSlug(alias);
468
+ const matches = this.list(principal).filter((workspace) => {
469
+ if (workspace.registration.kind !== 'mod')
470
+ return false;
471
+ const aliases = workspaceAliases(workspace);
472
+ return aliases.has(alias) || (slug !== '' && aliases.has(slug));
473
+ });
459
474
  if (matches.length === 1)
460
475
  return matches[0].id;
461
476
  if (matches.length > 1) {
@@ -226,7 +226,19 @@ export class DecisionAnalyzer {
226
226
  result.code = complete ? 'DECISION_ANALYZED' : 'DECISION_ANALYZED_PARTIAL';
227
227
  result.artifacts = [publicArtifactLink(artifact)];
228
228
  result.proposedFiles = overlay?.changes.map(({ path }) => path).slice(0, 64) ?? [];
229
- setInlineFilesScanned(result, before.files.map(({ displayPath }) => displayPath));
229
+ // A decision's own files answer an inspection; an inventory spans the workspace (#66).
230
+ setInlineFilesScanned(result, input.mode === 'inventory'
231
+ ? before.files.map(({ displayPath }) => displayPath)
232
+ : [
233
+ ...new Set(inventory.decisions
234
+ .filter(({ id }) => id === input.id)
235
+ .flatMap(({ path, category }) => [
236
+ path,
237
+ ...inventory.categories
238
+ .filter((entry) => entry.id === category)
239
+ .map((entry) => entry.path),
240
+ ])),
241
+ ]);
230
242
  result.validation = {
231
243
  passed: complete,
232
244
  checks: [
@@ -125,7 +125,10 @@ export class ImpactAnalyzer {
125
125
  result.code = complete ? 'IMPACT_ANALYZED' : 'IMPACT_ANALYZED_PARTIAL';
126
126
  result.artifacts = [publicArtifactLink(artifact)];
127
127
  result.proposedFiles = overlay?.changes.map(({ path }) => path).slice(0, 64) ?? [];
128
- setInlineFilesScanned(result, before.files.map(({ displayPath }) => displayPath));
128
+ // The seed files and the files of the consumers, not the first files of the workspace (#66).
129
+ setInlineFilesScanned(result, [
130
+ ...new Set([...(query.changedFiles ?? []), ...suiteGraph.affectedFiles]),
131
+ ]);
129
132
  result.validation = {
130
133
  passed: complete,
131
134
  checks: [
@@ -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;
@@ -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
  }
@@ -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 }