hoi4-agent-tools 4.16.0 → 4.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (101) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/README.md +1 -0
  3. package/dist/hoi4_agent_tools/core/analysis-checkpoints.js +11 -4
  4. package/dist/hoi4_agent_tools/core/engine-client.js +30 -1
  5. package/dist/hoi4_agent_tools/core/engine.js +56 -27
  6. package/dist/hoi4_agent_tools/core/managed-outputs.js +54 -3
  7. package/dist/hoi4_agent_tools/core/scanner.js +148 -7
  8. package/dist/hoi4_agent_tools/core/server-state.js +50 -2
  9. package/dist/hoi4_agent_tools/core/source/localisation.js +7 -1
  10. package/dist/hoi4_agent_tools/event/compare.js +47 -13
  11. package/dist/hoi4_agent_tools/focus/importer.js +2 -5
  12. package/dist/hoi4_agent_tools/focus/lint.js +2 -5
  13. package/dist/hoi4_agent_tools/focus/model.js +19 -0
  14. package/dist/hoi4_agent_tools/focus/tool-operations.js +16 -1
  15. package/dist/hoi4_agent_tools/focus/tool-support.js +14 -0
  16. package/dist/hoi4_agent_tools/map/appearance-validation.js +6 -1
  17. package/dist/hoi4_agent_tools/map/engine-raster.js +160 -0
  18. package/dist/hoi4_agent_tools/map/model.js +9 -8
  19. package/dist/hoi4_agent_tools/map/operations.js +20 -5
  20. package/dist/hoi4_agent_tools/map/partition-provinces.js +6 -2
  21. package/dist/hoi4_agent_tools/map/partition-tuning.js +37 -0
  22. package/dist/hoi4_agent_tools/map/service.js +25 -12
  23. package/dist/hoi4_agent_tools/map/territory-operations.js +114 -3
  24. package/dist/hoi4_agent_tools/map/territory-quality.js +39 -0
  25. package/dist/hoi4_agent_tools/map/territory.js +63 -2
  26. package/dist/hoi4_agent_tools/map/tool-operations.js +27 -1
  27. package/dist/hoi4_agent_tools/map/validation.js +23 -3
  28. package/dist/hoi4_agent_tools/map/water.js +13 -10
  29. package/dist/hoi4_agent_tools/map/world-outputs.js +41 -26
  30. package/dist/hoi4_agent_tools/map/world.js +51 -1
  31. package/dist/hoi4_agent_tools/mcp/tools/map.js +23 -0
  32. package/dist/hoi4_agent_tools/mcp/tools/reference.js +2 -2
  33. package/dist/hoi4_agent_tools/mcp/tools/technology.js +25 -1
  34. package/dist/hoi4_agent_tools/reference/closure.js +65 -0
  35. package/dist/hoi4_agent_tools/reference/command-phrases.json +7899 -1127
  36. package/dist/hoi4_agent_tools/reference/operations.js +38 -21
  37. package/dist/hoi4_agent_tools/reference/ranking.js +77 -2
  38. package/dist/hoi4_agent_tools/reference/script-validation.js +4 -2
  39. package/dist/hoi4_agent_tools/reference/service.js +45 -2
  40. package/dist/hoi4_agent_tools/reference/source-lookup.js +43 -121
  41. package/dist/hoi4_agent_tools/runtime.js +27 -11
  42. package/dist/hoi4_agent_tools/schemas/lenient-arguments.js +7 -1
  43. package/dist/hoi4_agent_tools/schemas/map.js +33 -0
  44. package/dist/hoi4_agent_tools/schemas/mod-tools.js +49 -0
  45. package/dist/hoi4_agent_tools/schemas/reference.js +1 -1
  46. package/dist/hoi4_agent_tools/schemas/script-validation.js +57 -3
  47. package/dist/hoi4_agent_tools/technology/operations.js +5 -0
  48. package/dist/hoi4_agent_tools/technology/queries.js +54 -0
  49. package/dist/hoi4_agent_tools/version.js +1 -1
  50. package/docs/configuration.md +1 -1
  51. package/docs/map.md +13 -11
  52. package/docs/research/reference-benchmark.md +64 -0
  53. package/docs/tools.md +20 -20
  54. package/docs/troubleshooting.md +4 -0
  55. package/engine/bin/darwin-arm64/hoi4-engine +0 -0
  56. package/engine/bin/linux-arm64/hoi4-engine +0 -0
  57. package/engine/bin/linux-x64/hoi4-engine +0 -0
  58. package/engine/bin/manifest.json +8 -8
  59. package/engine/bin/win32-x64/hoi4-engine.exe +0 -0
  60. package/npm-shrinkwrap.json +2 -2
  61. package/package.json +5 -3
  62. package/schemas/configuration.schema.json +1 -1
  63. package/schemas/continuous-focus-palette.schema.json +1 -1
  64. package/schemas/custom-weighted-pool.schema.json +1 -1
  65. package/schemas/decision-inspect-input.schema.json +1 -1
  66. package/schemas/error-log-input.schema.json +1 -1
  67. package/schemas/event-feature-manifest.schema.json +1 -1
  68. package/schemas/focus-plan.schema.json +1 -1
  69. package/schemas/focus-planning-sidecar.schema.json +1 -1
  70. package/schemas/geography-model.schema.json +1 -1
  71. package/schemas/gui-animation-source.schema.json +1 -1
  72. package/schemas/gui-helper.schema.json +1 -1
  73. package/schemas/gui-scenario.schema.json +1 -1
  74. package/schemas/helper-expansion-request.schema.json +1 -1
  75. package/schemas/helper-expansion-summary.schema.json +1 -1
  76. package/schemas/impact-inspect-input.schema.json +1 -1
  77. package/schemas/map-operation.schema.json +817 -728
  78. package/schemas/mechanic-test-input.schema.json +1 -1
  79. package/schemas/mod-index-input.schema.json +1 -1
  80. package/schemas/operation-result.schema.json +1 -1
  81. package/schemas/package-check-input.schema.json +1 -1
  82. package/schemas/package-manifest.schema.json +1 -1
  83. package/schemas/probability-analysis-result.schema.json +1 -1
  84. package/schemas/probability-compare-input.schema.json +1 -1
  85. package/schemas/probability-evaluate-input.schema.json +1 -1
  86. package/schemas/probability-inspect-input.schema.json +1 -1
  87. package/schemas/probability-render-input.schema.json +1 -1
  88. package/schemas/probability-scenario-set.schema.json +1 -1
  89. package/schemas/probability-sequence-input.schema.json +1 -1
  90. package/schemas/probability-simulate-input.schema.json +1 -1
  91. package/schemas/probability-sweep-input.schema.json +1 -1
  92. package/schemas/reference-context-input.schema.json +1 -1
  93. package/schemas/reference-read-input.schema.json +1 -1
  94. package/schemas/reference-search-input.schema.json +2 -2
  95. package/schemas/reference-sheets.schema.json +1 -1
  96. package/schemas/scenario-suite.schema.json +1 -1
  97. package/schemas/scenario-test-input.schema.json +1 -1
  98. package/schemas/script-validate-input.schema.json +7 -1
  99. package/schemas/shared-scenario.schema.json +1 -1
  100. package/schemas/source-lookup-input.schema.json +1 -1
  101. package/server.json +2 -2
@@ -47,6 +47,53 @@ async function assertNoLinkComponents(absolutePath) {
47
47
  }
48
48
  }
49
49
  }
50
+ /**
51
+ * A link only the superuser can create or change: owned by root, in a root-owned directory that
52
+ * neither group nor others can write. macOS ships `/var`, `/tmp` and `/etc` as such links into
53
+ * `/private`, so `$TMPDIR` (`/var/folders/...`) always has one. Windows has no such rule.
54
+ */
55
+ export function isTrustedSystemLink(facts, platform = process.platform) {
56
+ return (platform !== 'win32' &&
57
+ facts.linkUid === 0 &&
58
+ facts.parentUid === 0 &&
59
+ (facts.parentMode & 0o022) === 0);
60
+ }
61
+ /**
62
+ * Replace the leading components that pass through trusted system links with their real paths,
63
+ * so a state root such as `/var/folders/.../state` becomes `/private/var/folders/.../state`. A
64
+ * link anyone else could change stays in the path and is refused by `assertNoLinkComponents`.
65
+ */
66
+ async function resolveTrustedSystemLinks(absolutePath) {
67
+ const parsed = path.parse(absolutePath);
68
+ const segments = absolutePath.slice(parsed.root.length).split(path.sep).filter(Boolean);
69
+ let cursor = parsed.root;
70
+ for (let index = 0; index < segments.length; index += 1) {
71
+ const candidate = path.join(cursor, segments[index]);
72
+ let metadata;
73
+ try {
74
+ metadata = await lstat(candidate);
75
+ }
76
+ catch (error) {
77
+ if (isNotFound(error))
78
+ return path.join(candidate, ...segments.slice(index + 1));
79
+ throw error;
80
+ }
81
+ if (!metadata.isSymbolicLink()) {
82
+ cursor = candidate;
83
+ continue;
84
+ }
85
+ const parent = await lstat(cursor);
86
+ if (!isTrustedSystemLink({
87
+ linkUid: metadata.uid,
88
+ parentUid: parent.uid,
89
+ parentMode: parent.mode,
90
+ })) {
91
+ return absolutePath;
92
+ }
93
+ cursor = path.normalize(await realpath(candidate));
94
+ }
95
+ return cursor;
96
+ }
50
97
  async function assertPrivateFile(filePath, expectedBytes) {
51
98
  let metadata;
52
99
  try {
@@ -100,10 +147,11 @@ export class ServerState {
100
147
  this.journalKey = journalKey;
101
148
  }
102
149
  static async create(requestedRoot) {
103
- const absoluteRoot = path.normalize(requestedRoot);
104
- if (!path.isAbsolute(absoluteRoot)) {
150
+ const normalizedRoot = path.normalize(requestedRoot);
151
+ if (!path.isAbsolute(normalizedRoot)) {
105
152
  throw stateError('SERVER_STATE_ROOT_INVALID', 'Server state root must be absolute');
106
153
  }
154
+ const absoluteRoot = await resolveTrustedSystemLinks(normalizedRoot);
107
155
  await assertNoLinkComponents(absoluteRoot);
108
156
  await mkdir(absoluteRoot, { recursive: true, mode: 0o700 });
109
157
  await assertNoLinkComponents(absoluteRoot);
@@ -4,6 +4,12 @@ import { SourceDiagnosticCollector } from './limits.js';
4
4
  import { SOURCE_ENTRY_LIMIT, SOURCE_LINE_LIMIT, SOURCE_MAX_BYTES } from './limits.js';
5
5
  const languagePattern = /^\s*(l_[a-z_]+):\s*(?:#.*)?$/u;
6
6
  const entryPattern = /^\s*([A-Za-z0-9_.-]+):(?:(\d+)\s+|\s*)"((?:\\.|[^"\\])*)"\s*(?:#.*)?$/u;
7
+ /**
8
+ * A value with quotes inside it, as in `k:0 "He said "hi" now"`. The game reads from the first quote
9
+ * to the last one on the line: the installed game's own localisation has 400 such lines, and mods
10
+ * use them freely. Tried only when `entryPattern` does not match.
11
+ */
12
+ const innerQuotePattern = /^\s*([A-Za-z0-9_.-]+):(?:(\d+)\s+|\s*)"(.*)"\s*$/u;
7
13
  function decodeLocalisationValue(value) {
8
14
  let result = '';
9
15
  for (let index = 0; index < value.length; index += 1) {
@@ -114,7 +120,7 @@ export function parseLocalisation(bytes, sourcePath) {
114
120
  lineNumber += 1;
115
121
  continue;
116
122
  }
117
- const match = entryPattern.exec(line);
123
+ const match = entryPattern.exec(line) ?? innerQuotePattern.exec(line);
118
124
  if (match === null) {
119
125
  diagnosticCollector.add(() => ({
120
126
  code: 'LOCALISATION_MALFORMED_LINE',
@@ -33,6 +33,42 @@ function semanticStateAccess(access) {
33
33
  conditions: access.conditions.map(semanticCondition),
34
34
  };
35
35
  }
36
+ /**
37
+ * Edges and state accesses share their condition objects: every effect inside an option
38
+ * carries the option's guards. Hashing each condition once and naming it by its digest keeps
39
+ * the hash a function of the same semantic content while the bytes hashed stay proportional
40
+ * to the distinct conditions. On a large mod the inline form hashed about 3 GB per graph.
41
+ */
42
+ const conditionDigests = new WeakMap();
43
+ function conditionDigest(condition) {
44
+ let digest = conditionDigests.get(condition);
45
+ if (digest === undefined) {
46
+ digest = hashCanonical(semanticCondition(condition));
47
+ conditionDigests.set(condition, digest);
48
+ }
49
+ return digest;
50
+ }
51
+ function edgeHash(edge) {
52
+ return hashCanonical({
53
+ ...edge,
54
+ location: { path: edge.location.path },
55
+ conditions: edge.conditions.map(conditionDigest),
56
+ provenance: edge.provenance.map(({ role, location }) => ({
57
+ role,
58
+ location: { path: location.path },
59
+ })),
60
+ weight: edge.weight === undefined
61
+ ? undefined
62
+ : { ...edge.weight, modifiers: edge.weight.modifiers.map(conditionDigest) },
63
+ });
64
+ }
65
+ function stateAccessHash(access) {
66
+ return hashCanonical({
67
+ ...access,
68
+ location: { path: access.location.path },
69
+ conditions: access.conditions.map(conditionDigest),
70
+ });
71
+ }
36
72
  function semanticIssue(issue) {
37
73
  return {
38
74
  ...issue,
@@ -57,11 +93,11 @@ function semanticUnresolved(item) {
57
93
  })),
58
94
  };
59
95
  }
60
- function semanticCollectionHash(domain, values, identity, semantic, signal) {
96
+ function semanticCollectionHash(domain, values, identity, hash, signal) {
61
97
  const records = values.map((value, index) => {
62
98
  if ((index & 255) === 0)
63
99
  signal?.throwIfAborted();
64
- return { id: identity(value), hash: hashCanonical(semantic(value)) };
100
+ return { id: identity(value), hash: hash(value) };
65
101
  });
66
102
  records.sort((left, right) => compareCodeUnits(left.id, right.id) || compareCodeUnits(left.hash, right.hash));
67
103
  const digest = createHash('sha256');
@@ -83,13 +119,13 @@ function semanticCollectionHash(domain, values, identity, semantic, signal) {
83
119
  function graphHash(graph, signal) {
84
120
  signal?.throwIfAborted();
85
121
  return hashCanonical({
86
- schema: 'event-semantic-graph-hash.v2',
87
- nodes: semanticCollectionHash('nodes', graph.nodes, ({ id }) => id, semanticNode, signal),
88
- edges: semanticCollectionHash('edges', graph.edges, ({ id }) => id, semanticEdge, signal),
89
- stateAccesses: semanticCollectionHash('state-accesses', graph.stateAccesses, ({ id }) => id, semanticStateAccess, signal),
90
- stateLinks: semanticCollectionHash('state-links', graph.stateLinks, ({ id }) => id, (value) => value, signal),
91
- issues: semanticCollectionHash('issues', graph.issues, issueId, semanticIssue, signal),
92
- unresolved: semanticCollectionHash('unresolved', graph.unresolved, ({ id }) => id, semanticUnresolved, signal),
122
+ schema: 'event-semantic-graph-hash.v3',
123
+ nodes: semanticCollectionHash('nodes', graph.nodes, ({ id }) => id, (node) => hashCanonical(semanticNode(node)), signal),
124
+ edges: semanticCollectionHash('edges', graph.edges, ({ id }) => id, edgeHash, signal),
125
+ stateAccesses: semanticCollectionHash('state-accesses', graph.stateAccesses, ({ id }) => id, stateAccessHash, signal),
126
+ stateLinks: semanticCollectionHash('state-links', graph.stateLinks, ({ id }) => id, (value) => hashCanonical(value), signal),
127
+ issues: semanticCollectionHash('issues', graph.issues, issueId, (issue) => hashCanonical(semanticIssue(issue)), signal),
128
+ unresolved: semanticCollectionHash('unresolved', graph.unresolved, ({ id }) => id, (item) => hashCanonical(semanticUnresolved(item)), signal),
93
129
  });
94
130
  }
95
131
  function mapById(values, signal) {
@@ -198,8 +234,7 @@ export function compareEventGraphs(before, after, signal) {
198
234
  .filter((id) => {
199
235
  check();
200
236
  const current = afterEdges.get(id);
201
- return (current !== undefined &&
202
- hashCanonical(semanticEdge(beforeEdges.get(id))) !== hashCanonical(semanticEdge(current)));
237
+ return current !== undefined && edgeHash(beforeEdges.get(id)) !== edgeHash(current);
203
238
  })
204
239
  .sort(compareCodeUnits);
205
240
  const addedStateAccessIds = [...afterStateAccesses.keys()]
@@ -219,8 +254,7 @@ export function compareEventGraphs(before, after, signal) {
219
254
  check();
220
255
  const current = afterStateAccesses.get(id);
221
256
  return (current !== undefined &&
222
- hashCanonical(semanticStateAccess(beforeStateAccesses.get(id))) !==
223
- hashCanonical(semanticStateAccess(current)));
257
+ stateAccessHash(beforeStateAccesses.get(id)) !== stateAccessHash(current));
224
258
  })
225
259
  .sort(compareCodeUnits);
226
260
  const addedStateLinkIds = [...afterStateLinks.keys()]
@@ -1,6 +1,6 @@
1
1
  import { compareCodeUnits, sha256Bytes } from '../core/canonical.js';
2
2
  import { assignments, firstScalar, nodeLocation, } from '../core/source/index.js';
3
- import { FOCUS_PLAN_SCHEMA_VERSION, FOCUS_COST_CONSTANT_PATTERN, focusPlanHash, } from './model.js';
3
+ import { FOCUS_PLAN_SCHEMA_VERSION, FOCUS_COST_CONSTANT_PATTERN, focusPlanHash, referenceCatalogSet, } from './model.js';
4
4
  import { nativeFocusEffectKeys } from './native-effects.js';
5
5
  const knownTreeKeys = new Set([
6
6
  'id',
@@ -123,10 +123,7 @@ const scopeKeys = new Set([
123
123
  'target',
124
124
  ]);
125
125
  function catalogValues(options, kind) {
126
- const values = options.references?.[kind];
127
- if (values === undefined)
128
- return new Set();
129
- return values instanceof Set ? values : new Set(values);
126
+ return referenceCatalogSet(options.references?.[kind]) ?? new Set();
130
127
  }
131
128
  function isFormableDecision(target, options) {
132
129
  if (catalogValues(options, 'formable').has(target))
@@ -5,7 +5,7 @@ import { ServiceError } from '../core/result.js';
5
5
  import { flattenFocusConnectorCurve, focusConnectorCurve, focusConnectorPolylinesIntersect, focusNodesVisiblyOverlap, } from './geometry.js';
6
6
  import { layoutFocusTree } from './layout.js';
7
7
  import { FOCUS_CYCLE_SAMPLE_MAX, FOCUS_DIAGNOSTIC_MAX, FOCUS_GRAPH_MAX_DEPTH, FOCUS_GRAPH_MAX_EDGES, FOCUS_GRAPH_MAX_NODES, FOCUS_LINT_WORK_MAX, FOCUS_PAIR_COMPARISON_MAX, } from './limits.js';
8
- import { layoutNodeMap, } from './model.js';
8
+ import { layoutNodeMap, referenceCatalogSet, } from './model.js';
9
9
  export function lintContinuousFocusPalette(plan) {
10
10
  if (plan.focuses.length > FOCUS_GRAPH_MAX_NODES) {
11
11
  return [
@@ -69,10 +69,7 @@ function prerequisiteIds(focus) {
69
69
  return focus.prerequisites.groups.flatMap(({ focusIds }) => focusIds);
70
70
  }
71
71
  function referenceSet(catalog, kind) {
72
- const values = catalog?.[kind];
73
- if (values === undefined)
74
- return undefined;
75
- return values instanceof Set ? values : new Set(values);
72
+ return referenceCatalogSet(catalog?.[kind]);
76
73
  }
77
74
  function referenceSymbolKind(kind) {
78
75
  switch (kind) {
@@ -2,6 +2,25 @@ import { hashCanonical } from '../core/canonical.js';
2
2
  export const FOCUS_PLAN_SCHEMA_VERSION = 1;
3
3
  /** A source-safe Clausewitz file constant such as `@focus_cost_standard`. */
4
4
  export const FOCUS_COST_CONSTANT_PATTERN = /^@[A-Za-z_][A-Za-z0-9_]*$/u;
5
+ const referenceSets = new WeakMap();
6
+ /**
7
+ * One catalog kind as a set. A catalog arrives as arrays of every identifier in the game and
8
+ * the mod, and the importer and the lint ask for it once per focus or per assignment, so the
9
+ * conversion is cached per array instead of repeated tens of thousands of times per call.
10
+ */
11
+ export function referenceCatalogSet(values) {
12
+ if (values === undefined)
13
+ return undefined;
14
+ if (values instanceof Set)
15
+ return values;
16
+ const array = values;
17
+ let cached = referenceSets.get(array);
18
+ if (cached === undefined) {
19
+ cached = new Set(array);
20
+ referenceSets.set(array, cached);
21
+ }
22
+ return cached;
23
+ }
5
24
  function withoutTransientFields(value) {
6
25
  if (Array.isArray(value))
7
26
  return value.map(withoutTransientFields);
@@ -29,6 +29,21 @@ const focusRewriteRecipeSchema = z
29
29
  filesScanned: z.array(z.string().min(1).max(4096)),
30
30
  })
31
31
  .strict();
32
+ /**
33
+ * The focus files an inspect call reads. A call that names a tree but no file reads only the files
34
+ * that define that tree: importing every focus file of the game to keep one tree took tens of
35
+ * seconds. A tree the index does not know falls back to every file, so the not-found answer is
36
+ * unchanged.
37
+ */
38
+ function filesForInspect(snapshot, active, relativePath, treeId) {
39
+ if (relativePath !== undefined)
40
+ return active.filter((file) => file.relativePath === relativePath);
41
+ if (treeId === undefined)
42
+ return active;
43
+ const definingPaths = new Set(snapshot.index.findAll('focus_tree', treeId).map(({ path }) => path));
44
+ const defining = active.filter((file) => definingPaths.has(file.displayPath));
45
+ return defining.length === 0 ? active : defining;
46
+ }
32
47
  export async function computeFocusVisualRevisions(engine, context, workspaceId, snapshot, selectors) {
33
48
  const workspace = engine.resolver.get(workspaceId, context.principal);
34
49
  const paletteImport = continuousPalettes(snapshot);
@@ -576,7 +591,7 @@ export async function inspectFocus(engine, workbench, input, context) {
576
591
  await context.progress(3, 3, 'Continuous focus inspection complete');
577
592
  return { result, sourceRevision: snapshot.revision };
578
593
  }
579
- const selectedFiles = activeFocusFiles(snapshot, workspace.registration.roots.focus).filter((file) => input.relativePath === undefined || file.relativePath === input.relativePath);
594
+ const selectedFiles = filesForInspect(snapshot, activeFocusFiles(snapshot, workspace.registration.roots.focus), input.relativePath, input.treeId);
580
595
  if (selectedFiles.length === 0)
581
596
  throw new ServiceError('FOCUS_SOURCE_NOT_FOUND', 'No active focus source matched the request');
582
597
  const selectedSidecarFiles = selectedFiles.flatMap((file) => {
@@ -98,7 +98,21 @@ export function focusImportOptions(snapshot) {
98
98
  : { nativeEffects: snapshot.documentedEffects.names }),
99
99
  };
100
100
  }
101
+ const referenceCatalogs = new WeakMap();
102
+ /**
103
+ * The identifiers of every decision, event, idea and helper in the game and the mod. A scan lists
104
+ * tens of thousands, and one call asks for the catalog once per imported file, so it is built once
105
+ * per scan.
106
+ */
101
107
  export function referenceCatalog(snapshot) {
108
+ const cached = referenceCatalogs.get(snapshot);
109
+ if (cached !== undefined)
110
+ return cached;
111
+ const built = buildReferenceCatalog(snapshot);
112
+ referenceCatalogs.set(snapshot, built);
113
+ return built;
114
+ }
115
+ function buildReferenceCatalog(snapshot) {
102
116
  const identifiers = (kind) => [
103
117
  ...new Set(snapshot.index
104
118
  .findAll(kind)
@@ -161,7 +161,12 @@ function* validateHeightmap(index, raster, report, options) {
161
161
  }
162
162
  const { width, height, kind } = raster;
163
163
  const hasLake = kind.includes(LAKE);
164
- const distance = hasLake ? landDistanceField(kind, width, height) : undefined;
164
+ // Only "farther than the bank allowance" is asked, so the search stops one step past it: a
165
+ // pixel it does not reach holds the limit, which is past the allowance as before. The full
166
+ // field (limit 255) flooded every sea pixel of the map.
167
+ const distance = hasLake
168
+ ? landDistanceField(kind, width, height, LAKE_BANK_ALLOWANCE_PX + 1)
169
+ : undefined;
165
170
  let lakePixels = 0;
166
171
  let landBelow = 0;
167
172
  let seaAbove = 0;
@@ -0,0 +1,160 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
3
+ import { tmpdir } from 'node:os';
4
+ import path from 'node:path';
5
+ import { z } from 'zod/v4';
6
+ import { compareCodeUnits } from '../core/canonical.js';
7
+ import { locateEngineBinary } from '../core/engine-client.js';
8
+ import { ServiceError } from '../core/result.js';
9
+ import { rgbKey } from './bmp.js';
10
+ /**
11
+ * The province raster from the shared Rust engine (`hoi4-engine map-provinces`, ADR 0084): the
12
+ * province of every pixel, each province's extent, the neighbour graph, seam-only pairs, colours
13
+ * without a definition, coastal provinces and the geometry checks' parts, holes and thin runs.
14
+ * The engine reproduces `buildProvinceRaster` and the TypeScript geometry checks exactly,
15
+ * iteration order included; `scripts/map-raster-parity.ts` compares them on real maps.
16
+ *
17
+ * The call is synchronous because the map model is built in one synchronous pass. It sends the
18
+ * decoded bitmap's bytes and pixel offsets and reads one frame back. A missing engine is
19
+ * `ENGINE_UNAVAILABLE`; nothing falls back to TypeScript.
20
+ */
21
+ export const MAP_PROVINCES_REQUEST_SCHEMA = 'hoi4-map-provinces-request/1';
22
+ const MAP_PROVINCES_TIMEOUT_MS = 120_000;
23
+ const RESPONSE_JSON_MAX_BYTES = 256 * 1024 * 1024;
24
+ const count = z.number().int().min(0);
25
+ const id = z.number().int();
26
+ const responseSchema = z
27
+ .object({
28
+ schema: z.literal('hoi4-map-provinces/1'),
29
+ width: count,
30
+ height: count,
31
+ geometry: z.array(z.tuple([id, count, count, count, count, count, count, count])),
32
+ adjacency: z.array(z.tuple([id, z.array(id)])),
33
+ seamOnlyPairs: z.array(z.tuple([id, id])),
34
+ unknownColors: z.array(z.tuple([count, count, count, count])),
35
+ unknownColorCount: count,
36
+ coastal: z.array(id),
37
+ components: z.array(z.tuple([id, count])),
38
+ holes: z.array(z.tuple([id, z.number().int()])),
39
+ thin: z.array(id),
40
+ })
41
+ .strict();
42
+ const frameSchema = z.union([
43
+ z.object({ ok: z.literal(true), result: z.unknown(), payload: count }).strict(),
44
+ z
45
+ .object({
46
+ ok: z.literal(false),
47
+ error: z.looseObject({ code: z.string(), message: z.string() }),
48
+ })
49
+ .strict(),
50
+ ]);
51
+ function packed(key) {
52
+ const [r, g, b] = key.split(',').map(Number);
53
+ return ((r ?? 0) << 16) | ((g ?? 0) << 8) | (b ?? 0);
54
+ }
55
+ export function engineProvinceRaster(bitmap, definitionsByColor, definitionsById) {
56
+ const located = locateEngineBinary();
57
+ if (!('path' in located))
58
+ throw new ServiceError('ENGINE_UNAVAILABLE', located.message, { reason: located.reason });
59
+ const header = `${JSON.stringify({
60
+ schema: MAP_PROVINCES_REQUEST_SCHEMA,
61
+ width: bitmap.width,
62
+ height: bitmap.height,
63
+ topDown: bitmap.topDown,
64
+ bitsPerPixel: bitmap.bitsPerPixel,
65
+ pixelOffset: bitmap.pixelOffset,
66
+ rowStride: bitmap.rowStride,
67
+ palette: bitmap.palette.map(({ r, g, b }) => [r, g, b]),
68
+ colors: [...definitionsByColor].map(([key, definition]) => [packed(key), definition.id]),
69
+ types: [...definitionsById].map(([provinceId, definition]) => [provinceId, definition.type]),
70
+ payload: bitmap.bytes.length,
71
+ })}\n`;
72
+ const script = /\.(?:c|m)?js$/iu.test(located.path);
73
+ // The frames go through files, not the child's pipes: a synchronous call that wrote hundreds of
74
+ // kilobytes to stdin and read as much from stdout hung until its timeout on macOS runners.
75
+ const directory = mkdtempSync(path.join(tmpdir(), 'hoi4-map-provinces-'));
76
+ const inputPath = path.join(directory, 'request');
77
+ const outputPath = path.join(directory, 'answer');
78
+ let child;
79
+ let stdout;
80
+ try {
81
+ writeFileSync(inputPath, Buffer.concat([Buffer.from(header, 'utf8'), bitmap.bytes]));
82
+ const args = ['map-provinces', '--input', inputPath, '--output', outputPath];
83
+ child = spawnSync(script ? process.execPath : located.path, script ? [located.path, ...args] : args, {
84
+ stdio: ['ignore', 'ignore', 'pipe'],
85
+ maxBuffer: RESPONSE_JSON_MAX_BYTES,
86
+ timeout: MAP_PROVINCES_TIMEOUT_MS,
87
+ windowsHide: true,
88
+ shell: false,
89
+ });
90
+ stdout = existsSync(outputPath) ? readFileSync(outputPath) : Buffer.alloc(0);
91
+ }
92
+ finally {
93
+ rmSync(directory, { recursive: true, force: true });
94
+ }
95
+ const unavailable = (message) => new ServiceError('ENGINE_UNAVAILABLE', message, { reason: 'invalid_output' });
96
+ if (child.error !== undefined)
97
+ throw new ServiceError('ENGINE_UNAVAILABLE', `hoi4-engine map-provinces: ${child.error.message}`, {
98
+ reason: 'spawn_failed',
99
+ });
100
+ const newline = stdout.indexOf(0x0a);
101
+ if (newline < 0)
102
+ throw unavailable(`hoi4-engine map-provinces gave no answer (exit ${child.status ?? 'none'}): ${child.stderr.toString('utf8').slice(-300)}`);
103
+ const frame = frameSchema.safeParse(JSON.parse(stdout.subarray(0, newline).toString('utf8')));
104
+ if (!frame.success)
105
+ throw unavailable('hoi4-engine map-provinces answered an unknown frame');
106
+ if (!frame.data.ok) {
107
+ const { code, message, ...details } = frame.data.error;
108
+ // The engine names a bad palette index the way BmpImage.rgbAt does.
109
+ if (code === 'MAP_BMP_PALETTE_INDEX_INVALID')
110
+ throw new ServiceError(code, message, details);
111
+ throw new ServiceError('MAP_ENGINE_REQUEST_INVALID', message, { code });
112
+ }
113
+ const response = responseSchema.safeParse(frame.data.result);
114
+ const payload = stdout.subarray(newline + 1);
115
+ if (!response.success ||
116
+ response.data.width !== bitmap.width ||
117
+ response.data.height !== bitmap.height ||
118
+ payload.length !== frame.data.payload ||
119
+ payload.length !== bitmap.width * bitmap.height * 4)
120
+ throw unavailable('hoi4-engine map-provinces answered out of shape');
121
+ const result = response.data;
122
+ // Copied so the ids are aligned, whatever offset the payload has in the output buffer.
123
+ const provinceIds = new Int32Array(payload.buffer.slice(payload.byteOffset, payload.byteOffset + payload.length));
124
+ const geometry = new Map();
125
+ for (const [provinceId, pixelCount, minX, minY, maxX, maxY, sumX, sumY] of result.geometry)
126
+ geometry.set(provinceId, {
127
+ id: provinceId,
128
+ pixelCount,
129
+ minX,
130
+ minY,
131
+ maxX,
132
+ maxY,
133
+ centerX: sumX / pixelCount,
134
+ centerY: sumY / pixelCount,
135
+ });
136
+ const color = (rgb) => ({ r: (rgb >> 16) & 0xff, g: (rgb >> 8) & 0xff, b: rgb & 0xff });
137
+ return {
138
+ width: result.width,
139
+ height: result.height,
140
+ provinceIds,
141
+ adjacency: new Map(result.adjacency.map(([provinceId, others]) => [provinceId, new Set(others)])),
142
+ seamOnlyPairs: new Set(result.seamOnlyPairs.map(([low, high]) => `${low}:${high}`)),
143
+ geometry,
144
+ unknownColors: result.unknownColors
145
+ .map(([rgb, pixels, firstX, firstY]) => ({
146
+ color: color(rgb),
147
+ count: pixels,
148
+ firstX,
149
+ firstY,
150
+ }))
151
+ .sort((left, right) => compareCodeUnits(rgbKey(left.color), rgbKey(right.color))),
152
+ unknownColorCount: result.unknownColorCount,
153
+ coastalProvinceIds: new Set(result.coastal),
154
+ topology: {
155
+ components: new Map(result.components),
156
+ holes: new Map(result.holes),
157
+ thin: new Set(result.thin),
158
+ },
159
+ };
160
+ }
@@ -1,11 +1,11 @@
1
1
  import { compareCodeUnits } from '../core/canonical.js';
2
2
  import path from 'node:path';
3
- import { SymbolIndex } from '../core/index.js';
4
3
  import { assertRenderDimensions } from '../core/render-budget.js';
5
4
  import { addMapDiagnostic, addMapDiagnostics } from './diagnostic-limit.js';
6
5
  import { ServiceError } from '../core/result.js';
7
6
  import { assignments, assertSourceEncodingPreserved, childBlocks, decodeSource, encodeSource, firstScalar, nodeLocation, parseClausewitz, parseLocalisation, } from '../core/source/index.js';
8
7
  import { BmpImage, rgbKey } from './bmp.js';
8
+ import { engineProvinceRaster } from './engine-raster.js';
9
9
  const defaultMapIndexSourceRoots = {
10
10
  map: ['map'],
11
11
  states: ['history/states'],
@@ -966,6 +966,10 @@ function addNeighbor(adjacency, left, right) {
966
966
  adjacency.set(left, leftSet);
967
967
  adjacency.set(right, rightSet);
968
968
  }
969
+ /**
970
+ * The TypeScript raster, kept as the reference the engine's (`engineProvinceRaster`, ADR 0084)
971
+ * is checked against in tests and `scripts/map-raster-parity.ts`. The map model uses the engine.
972
+ */
969
973
  export function buildProvinceRaster(bitmap, definitionsByColor, definitionsById) {
970
974
  assertRenderDimensions(bitmap.width, bitmap.height, 'map province raster', {
971
975
  maximumPixels: MAP_PROVINCE_ENGINE_MAX_PIXELS,
@@ -1098,8 +1102,6 @@ export class MapWorkspaceIndex {
1098
1102
  /** Every scanned root file, including entries shadowed by a higher-load-order root. */
1099
1103
  sourceFiles;
1100
1104
  sourceRoots;
1101
- /** Shared cross-domain symbol/reference authority for these exact source bytes. */
1102
- sharedIndex;
1103
1105
  activeFiles;
1104
1106
  earliestBookmark;
1105
1107
  diagnostics = [];
@@ -1182,9 +1184,8 @@ export class MapWorkspaceIndex {
1182
1184
  const color = this.#heightmap.palette[index];
1183
1185
  return (color === undefined ? index : color.r) / 10;
1184
1186
  }
1185
- constructor(files, sourceRoots = defaultMapIndexSourceRoots, sharedIndex = SymbolIndex.build(files)) {
1187
+ constructor(files, sourceRoots = defaultMapIndexSourceRoots) {
1186
1188
  this.sourceFiles = [...files];
1187
- this.sharedIndex = sharedIndex;
1188
1189
  this.sourceRoots = {
1189
1190
  map: sourceRoots.map.map(normalizeConfiguredRoot),
1190
1191
  states: sourceRoots.states.map(normalizeConfiguredRoot),
@@ -1243,7 +1244,7 @@ export class MapWorkspaceIndex {
1243
1244
  }
1244
1245
  }
1245
1246
  if (this.provinceBitmap !== undefined) {
1246
- this.raster = buildProvinceRaster(this.provinceBitmap, this.definitionsByColor, this.definitionsById);
1247
+ this.raster = engineProvinceRaster(this.provinceBitmap, this.definitionsByColor, this.definitionsById);
1247
1248
  }
1248
1249
  const stateFiles = this.activeFiles.all.filter((file) => inConfiguredRoot(file.relativePath, this.sourceRoots.states));
1249
1250
  const activeStatePaths = new Set(stateFiles.map(({ displayPath }) => displayPath));
@@ -1440,8 +1441,8 @@ export class MapWorkspaceIndex {
1440
1441
  });
1441
1442
  }
1442
1443
  }
1443
- static build(files, sourceRoots = defaultMapIndexSourceRoots, sharedIndex = SymbolIndex.build(files)) {
1444
- return new MapWorkspaceIndex(files, sourceRoots, sharedIndex);
1444
+ static build(files, sourceRoots = defaultMapIndexSourceRoots) {
1445
+ return new MapWorkspaceIndex(files, sourceRoots);
1445
1446
  }
1446
1447
  provinceAtMapCoordinate(x, z) {
1447
1448
  if (this.raster === undefined)
@@ -12,7 +12,7 @@ import { resolveEdge } from './world-edge.js';
12
12
  import { DEFAULT_AUTO_STRAIT_GAP_PX } from './gameplay/crossings.js';
13
13
  import { planMapPositions, planSupplyRebuild } from './derived.js';
14
14
  import { buildWorldContext, countryTagCatalog, WORLD_COUNTRY_TAG_FILE, } from './world-context.js';
15
- import { planWorldOutputs, refreshWorldOutputs, WORLD_OUTPUT_MANIFEST } from './world-outputs.js';
15
+ import { planWorldOutputs, refreshWorldOutputs, WORLD_OUTPUT_MANIFEST, } from './world-outputs.js';
16
16
  import { resolvePartitionMode } from './partition.js';
17
17
  import { applyAssignTerritory, applyRepartitionStates, } from './territory-operations.js';
18
18
  import { unsupportedGeographyParts } from './relief/index.js';
@@ -746,7 +746,7 @@ export function indexWithProposedChanges(base, changes, replacedRoots = []) {
746
746
  if (change.content !== null)
747
747
  files.push(syntheticFile(change.relativePath, Buffer.from(change.content), maximumLoadOrder));
748
748
  }
749
- return MapWorkspaceIndex.build(files, base.sourceRoots, base.sharedIndex.rebuild(files));
749
+ return MapWorkspaceIndex.build(files, base.sourceRoots);
750
750
  }
751
751
  export function addChange(changes, relativePath, content, operationId, mediaType) {
752
752
  const key = normalizeRelative(relativePath);
@@ -3750,6 +3750,14 @@ function applyRegenerateMapPositions(base, changes, operation) {
3750
3750
  for (const file of planMapPositions(index, operation))
3751
3751
  addChange(changes, file.relativePath, file.content, operation.id, 'text/plain');
3752
3752
  }
3753
+ /** The map, state and localisation roots a world of this workspace records its outputs under. */
3754
+ function worldOutputRoots(base) {
3755
+ return {
3756
+ mapRoot: base.sourceRoots.map[0] ?? 'map',
3757
+ stateRoots: base.sourceRoots.states,
3758
+ localisationRoots: base.sourceRoots.localisation,
3759
+ };
3760
+ }
3753
3761
  function worldOutputsRefreshedDiagnostic(refresh) {
3754
3762
  return {
3755
3763
  code: 'MAP_WORLD_OUTPUTS_REFRESHED',
@@ -3757,12 +3765,15 @@ function worldOutputsRefreshedDiagnostic(refresh) {
3757
3765
  category: 'map',
3758
3766
  message: `The world output inventory records the new bytes of ${refresh.refreshed.length} output(s) this request wrote` +
3759
3767
  (refresh.dropped.length > 0 ? ` and drops ${refresh.dropped.length} it deleted` : '') +
3768
+ (refresh.added.length > 0 ? `, and adds ${refresh.added.length} it created` : '') +
3760
3769
  (refresh.keptEdited.length > 0
3761
3770
  ? `; ${refresh.keptEdited.length} output(s) were edited before this request and keep their recorded hash, so the next create_world still refuses them (record_world_outputs adopts them)`
3762
3771
  : ''),
3763
3772
  details: {
3764
3773
  refreshed: refresh.refreshed.length,
3765
3774
  dropped: refresh.dropped.length,
3775
+ added: refresh.added.length,
3776
+ addedPaths: refresh.added.slice(0, 200),
3766
3777
  keptEdited: refresh.keptEdited.slice(0, 200),
3767
3778
  keptEditedCount: refresh.keptEdited.length,
3768
3779
  },
@@ -3773,7 +3784,7 @@ function worldOutputsRefreshedDiagnostic(refresh) {
3773
3784
  * the next create_world takes them as the world's own. Recorded files that are gone are dropped.
3774
3785
  */
3775
3786
  function applyRecordWorldOutputs(base, changes, operation) {
3776
- const refresh = refreshWorldOutputs(base.sourceFiles, proposedChanges(changes), true);
3787
+ const refresh = refreshWorldOutputs(base.sourceFiles, proposedChanges(changes), worldOutputRoots(base), { adoptAll: true, adoptUnrecorded: operation.adoptUnrecorded !== false });
3777
3788
  if (refresh === undefined)
3778
3789
  throw new ServiceError('MAP_WORLD_OUTPUTS_MISSING', `The workspace has no world output inventory (${WORLD_OUTPUT_MANIFEST}) to record; only a mod written by create_world has one`);
3779
3790
  if (refresh.content !== undefined)
@@ -3783,13 +3794,17 @@ function applyRecordWorldOutputs(base, changes, operation) {
3783
3794
  severity: 'info',
3784
3795
  category: 'map',
3785
3796
  operationId: operation.id,
3786
- message: `The world output inventory now records the current bytes of its outputs: ${refresh.refreshed.length} refreshed, ${refresh.unchanged.length} unchanged, ${refresh.dropped.length} dropped because the file is gone`,
3797
+ message: `The world output inventory now records the current bytes of its outputs: ${refresh.refreshed.length} refreshed, ${refresh.unchanged.length} unchanged, ${refresh.dropped.length} dropped because the file is gone${refresh.unscanned.length > 0 ? `, ${refresh.unscanned.length} kept unread` : ''}${operation.adoptUnrecorded !== false ? `, ${refresh.added.length} added that it lacked` : ''}`,
3787
3798
  details: {
3788
3799
  refreshed: refresh.refreshed.length,
3789
3800
  unchanged: refresh.unchanged.length,
3790
3801
  dropped: refresh.dropped.length,
3802
+ added: refresh.added.length,
3803
+ unscanned: refresh.unscanned.length,
3804
+ unscannedPaths: refresh.unscanned.slice(0, 200),
3791
3805
  refreshedPaths: refresh.refreshed.slice(0, 200),
3792
3806
  droppedPaths: refresh.dropped.slice(0, 200),
3807
+ addedPaths: refresh.added.slice(0, 200),
3793
3808
  },
3794
3809
  };
3795
3810
  }
@@ -4006,7 +4021,7 @@ function* planMapOperationSteps(base, operations, signal, context = {}) {
4006
4021
  }
4007
4022
  // The tool's own later edits of world outputs must never read as hand edits at the next
4008
4023
  // create_world, in this request or a later one.
4009
- const refresh = refreshWorldOutputs(base.sourceFiles, proposedChanges(changes));
4024
+ const refresh = refreshWorldOutputs(base.sourceFiles, proposedChanges(changes), worldOutputRoots(base));
4010
4025
  if (refresh?.content !== undefined) {
4011
4026
  const [first, ...rest] = refresh.operationIds;
4012
4027
  addChange(changes, WORLD_OUTPUT_MANIFEST, refresh.content, first, 'application/json');
@@ -1,7 +1,7 @@
1
1
  import { ServiceError } from '../core/result.js';
2
2
  import { assembleWorldProvinces, assertProvinceMaskFeasible } from './world-provinces.js';
3
3
  import { assertPartitionFields, PARTITION_KIND, PARTITION_TERRAIN, WALL_SIDE, } from './partition-fields.js';
4
- import { PARTITION_PROVINCE_ERROR } from './partition-tuning.js';
4
+ import { areaRowFactor, PARTITION_PROVINCE_ERROR } from './partition-tuning.js';
5
5
  import { hash32, placeSeeds, STEP_UNIT, unit32, weightedWatershed } from './partition-watershed.js';
6
6
  /**
7
7
  * Feature-aware provinces (ADR 0058). The land is cut by a marker-controlled watershed whose
@@ -343,7 +343,11 @@ function planAreas(fields, tuning, coastDistance, seaDistance) {
343
343
  : area > t.maxProvincePixels
344
344
  ? t.maxProvincePixels
345
345
  : area;
346
- const land = (pixel) => clampArea(landRaw(pixel) * landScale);
346
+ // areaByRow applies after the scale to the base area, so rows with factor 1 keep their sizes.
347
+ const rowFactor = new Float64Array(height);
348
+ for (let y = 0; y < height; y += 1)
349
+ rowFactor[y] = areaRowFactor(t.areaByRow, y, height);
350
+ const land = (pixel) => clampArea(landRaw(pixel) * landScale * rowFactor[Math.floor(pixel / width)]);
347
351
  const sea = (pixel) => kind[pixel] === LAKE ? t.lakeArea : clampArea(seaRaw(pixel) * seaScale);
348
352
  let minLand = Infinity;
349
353
  let minSea = Infinity;