hoi4-agent-tools 4.11.1 → 4.13.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 (116) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/README.md +3 -3
  3. package/dist/bin/setup.js +38 -0
  4. package/dist/bin/stdio.js +12 -10
  5. package/dist/hoi4_agent_tools/core/configuration.js +29 -0
  6. package/dist/hoi4_agent_tools/core/domain-tools.js +4 -0
  7. package/dist/hoi4_agent_tools/core/engine-check.js +87 -0
  8. package/dist/hoi4_agent_tools/core/engine-client.js +1 -1
  9. package/dist/hoi4_agent_tools/core/engine.js +18 -2
  10. package/dist/hoi4_agent_tools/core/job-operation-registration.js +2 -0
  11. package/dist/hoi4_agent_tools/core/job-store.js +1 -1
  12. package/dist/hoi4_agent_tools/focus/native-effects.js +1 -1
  13. package/dist/hoi4_agent_tools/localisation/job-operations.js +42 -0
  14. package/dist/hoi4_agent_tools/localisation/write-diff.js +96 -0
  15. package/dist/hoi4_agent_tools/localisation/write-format.js +329 -0
  16. package/dist/hoi4_agent_tools/localisation/write-operations.js +213 -0
  17. package/dist/hoi4_agent_tools/localisation/write-plan.js +557 -0
  18. package/dist/hoi4_agent_tools/map/gameplay/crossing-validation.js +17 -0
  19. package/dist/hoi4_agent_tools/map/model.js +31 -1
  20. package/dist/hoi4_agent_tools/map/operations.js +37 -8
  21. package/dist/hoi4_agent_tools/map/references.js +87 -0
  22. package/dist/hoi4_agent_tools/map/relief/hydrology.js +7 -2
  23. package/dist/hoi4_agent_tools/map/relief/terrain-synthesis.js +1 -0
  24. package/dist/hoi4_agent_tools/map/service.js +13 -4
  25. package/dist/hoi4_agent_tools/map/tool-operations.js +6 -0
  26. package/dist/hoi4_agent_tools/map/world-edge.js +0 -25
  27. package/dist/hoi4_agent_tools/map/world.js +181 -64
  28. package/dist/hoi4_agent_tools/mcp/plugins.js +74 -0
  29. package/dist/hoi4_agent_tools/mcp/server/argument-errors.js +5 -0
  30. package/dist/hoi4_agent_tools/mcp/server/create-modern-operations.js +15 -21
  31. package/dist/hoi4_agent_tools/mcp/server/create.js +5 -1
  32. package/dist/hoi4_agent_tools/mcp/server/request-lifecycle.js +10 -2
  33. package/dist/hoi4_agent_tools/mcp/server/task-tool-catalog.js +2 -0
  34. package/dist/hoi4_agent_tools/mcp/server/tool-profiles.js +83 -0
  35. package/dist/hoi4_agent_tools/mcp/tools/localisation-write.js +21 -0
  36. package/dist/hoi4_agent_tools/mcp/tools/reference.js +34 -0
  37. package/dist/hoi4_agent_tools/mcp/transports/http.js +6 -1
  38. package/dist/hoi4_agent_tools/mcp/transports/negotiated-stdio.js +64 -6
  39. package/dist/hoi4_agent_tools/probability/model.js +4 -4
  40. package/dist/hoi4_agent_tools/reference/compat-patch.js +555 -0
  41. package/dist/hoi4_agent_tools/reference/compat.js +255 -0
  42. package/dist/hoi4_agent_tools/reference/docs-pack.js +164 -0
  43. package/dist/hoi4_agent_tools/reference/docs-pack.json +339 -0
  44. package/dist/hoi4_agent_tools/reference/documented-commands.js +26 -0
  45. package/dist/hoi4_agent_tools/reference/error-explain.js +235 -0
  46. package/dist/hoi4_agent_tools/reference/error-explanations.json +262 -0
  47. package/dist/hoi4_agent_tools/reference/error-log.js +30 -10
  48. package/dist/hoi4_agent_tools/reference/mod-health.js +255 -0
  49. package/dist/hoi4_agent_tools/reference/mod-index.js +63 -65
  50. package/dist/hoi4_agent_tools/reference/operations.js +435 -21
  51. package/dist/hoi4_agent_tools/reference/script-guard.js +109 -0
  52. package/dist/hoi4_agent_tools/reference/service.js +58 -20
  53. package/dist/hoi4_agent_tools/runtime.js +17 -2
  54. package/dist/hoi4_agent_tools/schemas/compat.js +153 -0
  55. package/dist/hoi4_agent_tools/schemas/localisation-write.js +154 -0
  56. package/dist/hoi4_agent_tools/schemas/map.js +5 -1
  57. package/dist/hoi4_agent_tools/schemas/mod-tools.js +50 -0
  58. package/dist/hoi4_agent_tools/schemas/modder-tools.js +191 -0
  59. package/dist/hoi4_agent_tools/version.js +1 -1
  60. package/docs/configuration.md +14 -11
  61. package/docs/development.md +2 -0
  62. package/docs/jobs.md +3 -1
  63. package/docs/map.md +8 -4
  64. package/docs/reference.md +47 -5
  65. package/docs/research/probability-adapter-evidence.md +11 -1
  66. package/docs/setup.md +23 -3
  67. package/docs/tools.md +18 -4
  68. package/docs/troubleshooting.md +1 -1
  69. package/engine/bin/darwin-arm64/hoi4-engine +0 -0
  70. package/engine/bin/linux-arm64/hoi4-engine +0 -0
  71. package/engine/bin/linux-x64/hoi4-engine +0 -0
  72. package/engine/bin/manifest.json +8 -8
  73. package/engine/bin/win32-x64/hoi4-engine.exe +0 -0
  74. package/npm-shrinkwrap.json +2 -2
  75. package/package.json +1 -1
  76. package/schemas/configuration.schema.json +181 -138
  77. package/schemas/continuous-focus-palette.schema.json +1 -1
  78. package/schemas/custom-weighted-pool.schema.json +1 -1
  79. package/schemas/decision-inspect-input.schema.json +1 -1
  80. package/schemas/error-log-input.schema.json +1 -1
  81. package/schemas/event-feature-manifest.schema.json +1 -1
  82. package/schemas/focus-plan.schema.json +1 -1
  83. package/schemas/focus-planning-sidecar.schema.json +1 -1
  84. package/schemas/geography-model.schema.json +1 -1
  85. package/schemas/gui-animation-source.schema.json +1 -1
  86. package/schemas/gui-helper.schema.json +1 -1
  87. package/schemas/gui-scenario.schema.json +1 -1
  88. package/schemas/helper-expansion-request.schema.json +1 -1
  89. package/schemas/helper-expansion-summary.schema.json +1 -1
  90. package/schemas/impact-inspect-input.schema.json +1 -1
  91. package/schemas/map-operation.schema.json +153 -139
  92. package/schemas/mechanic-test-input.schema.json +1 -1
  93. package/schemas/mod-index-input.schema.json +1 -1
  94. package/schemas/operation-result.schema.json +1 -1
  95. package/schemas/package-check-input.schema.json +1 -1
  96. package/schemas/package-manifest.schema.json +1 -1
  97. package/schemas/probability-analysis-result.schema.json +1 -1
  98. package/schemas/probability-compare-input.schema.json +1 -1
  99. package/schemas/probability-evaluate-input.schema.json +1 -1
  100. package/schemas/probability-inspect-input.schema.json +1 -1
  101. package/schemas/probability-render-input.schema.json +1 -1
  102. package/schemas/probability-scenario-set.schema.json +1 -1
  103. package/schemas/probability-sequence-input.schema.json +1 -1
  104. package/schemas/probability-simulate-input.schema.json +1 -1
  105. package/schemas/probability-sweep-input.schema.json +1 -1
  106. package/schemas/reference-context-input.schema.json +1 -1
  107. package/schemas/reference-read-input.schema.json +1 -1
  108. package/schemas/reference-search-input.schema.json +1 -1
  109. package/schemas/reference-sheets.schema.json +1 -1
  110. package/schemas/scenario-suite.schema.json +1 -1
  111. package/schemas/scenario-test-input.schema.json +1 -1
  112. package/schemas/script-validate-input.schema.json +1 -1
  113. package/schemas/shared-scenario.schema.json +1 -1
  114. package/schemas/source-lookup-input.schema.json +1 -1
  115. package/server.json +2 -2
  116. package/dist/hoi4_agent_tools/mcp/tools/chaosx.js +0 -509
@@ -0,0 +1,557 @@
1
+ import { lstat, readdir, readFile, realpath } from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { compareCodeUnits, sha256Bytes } from '../core/canonical.js';
4
+ import { runEngineCommand } from '../core/engine-client.js';
5
+ import { ServiceError } from '../core/result.js';
6
+ import { SOURCE_MAX_BYTES } from '../core/source/limits.js';
7
+ import { isWithin } from '../core/workspace.js';
8
+ import { localisationEngineResponseSchema } from '../schemas/localisation.js';
9
+ import { LOCALISATION_LANGUAGES, } from '../schemas/localisation-write.js';
10
+ import { appendEntries, classifyLine, decodeLocBytes, detectStyle, documentChanged, encodeLocDocument, endsWithLoneBackslash, escapeLocText, formatEntryLine, newLocDocument, NEW_FILE_STYLE, repairValue, scanDocument, } from './write-format.js';
11
+ // ---------------------------------------------------------------------------------------------
12
+ // Paths
13
+ const MAX_FILES = 20_000;
14
+ const MAX_DEPTH = 16;
15
+ const LAYER_FILE_LIMIT = 16 * 1024 * 1024;
16
+ function invalidPath(field, value, message) {
17
+ return new ServiceError('LOCALISATION_PATH_INVALID', `${field}: ${message}`, {
18
+ field,
19
+ path: value.slice(0, 200),
20
+ });
21
+ }
22
+ /**
23
+ * A mod-relative path under `localisation/`, normalised to forward slashes. Absolute paths,
24
+ * drive letters, parent segments, NUL bytes and anything outside `localisation/` are refused.
25
+ */
26
+ export function normalizeLocalisationPath(value, field) {
27
+ if (value.includes('\0'))
28
+ throw invalidPath(field, value, 'contains a NUL byte');
29
+ if (/^[A-Za-z]:/u.test(value) || value.startsWith('/') || value.startsWith('\\'))
30
+ throw invalidPath(field, value, 'must be relative to the mod, not an absolute path');
31
+ const parts = value
32
+ .replaceAll('\\', '/')
33
+ .split('/')
34
+ .filter((part) => part !== '' && part !== '.');
35
+ if (parts.includes('..'))
36
+ throw invalidPath(field, value, 'parent segments (..) are not allowed');
37
+ if (parts[0] !== 'localisation')
38
+ throw invalidPath(field, value, "must be inside the mod's localisation/ folder");
39
+ for (const part of parts)
40
+ if (!/^[A-Za-z0-9_. -]+$/u.test(part) || /[. ]$/u.test(part))
41
+ throw invalidPath(field, value, `"${part.slice(0, 80)}" is not a usable file or folder name`);
42
+ return parts.join('/');
43
+ }
44
+ function languageFileSuffix(language) {
45
+ return `_l_${language}.yml`;
46
+ }
47
+ function languageOfFile(relativePath) {
48
+ const match = /_l_([a-z_]+)\.yml$/iu.exec(relativePath);
49
+ const language = match?.[1]?.toLowerCase();
50
+ return language !== undefined && LOCALISATION_LANGUAGES.includes(language)
51
+ ? language
52
+ : null;
53
+ }
54
+ function inReplaceFolder(relativePath) {
55
+ return relativePath.split('/').slice(1, -1).includes('replace');
56
+ }
57
+ async function walkYml(directory, relative, depth, out, signal) {
58
+ signal?.throwIfAborted();
59
+ if (depth > MAX_DEPTH)
60
+ return;
61
+ let entries;
62
+ try {
63
+ entries = await readdir(directory, { withFileTypes: true });
64
+ }
65
+ catch (error) {
66
+ if (error.code === 'ENOENT')
67
+ return;
68
+ throw error;
69
+ }
70
+ entries.sort((a, b) => compareCodeUnits(a.name, b.name));
71
+ for (const entry of entries) {
72
+ // A link could lead out of the folder; the localisation tree is plain files and folders.
73
+ if (entry.isSymbolicLink())
74
+ continue;
75
+ const next = `${relative}/${entry.name}`;
76
+ if (entry.isDirectory())
77
+ await walkYml(path.join(directory, entry.name), next, depth + 1, out, signal);
78
+ else if (entry.isFile() && entry.name.toLowerCase().endsWith('.yml')) {
79
+ out.push(next);
80
+ if (out.length > MAX_FILES)
81
+ throw new ServiceError('LOCALISATION_TOO_MANY_FILES', `The localisation folder holds more than ${MAX_FILES} files`);
82
+ }
83
+ }
84
+ }
85
+ async function localisationFolder(rootPath) {
86
+ const folder = path.join(rootPath, 'localisation');
87
+ let status;
88
+ try {
89
+ status = await lstat(folder);
90
+ }
91
+ catch (error) {
92
+ if (error.code === 'ENOENT')
93
+ return undefined;
94
+ throw error;
95
+ }
96
+ if (status.isSymbolicLink() || !status.isDirectory())
97
+ return undefined;
98
+ const real = await realpath(folder);
99
+ return isWithin(rootPath, real) ? folder : undefined;
100
+ }
101
+ async function readModFiles(workspace, signal) {
102
+ const files = new Map();
103
+ const folder = await localisationFolder(workspace.modRoot);
104
+ if (folder === undefined)
105
+ return files;
106
+ const paths = [];
107
+ await walkYml(folder, 'localisation', 0, paths, signal);
108
+ for (const relative of paths) {
109
+ signal?.throwIfAborted();
110
+ const absolute = path.join(workspace.modRoot, ...relative.split('/'));
111
+ const status = await lstat(absolute);
112
+ const language = languageOfFile(relative);
113
+ const base = { path: relative, language, replace: inReplaceFolder(relative) };
114
+ if (status.size > SOURCE_MAX_BYTES) {
115
+ files.set(relative, {
116
+ ...base,
117
+ bytes: undefined,
118
+ sha256: undefined,
119
+ tooLarge: true,
120
+ document: undefined,
121
+ scan: undefined,
122
+ });
123
+ continue;
124
+ }
125
+ const bytes = await readFile(absolute);
126
+ const document = decodeLocBytes(bytes);
127
+ files.set(relative, {
128
+ ...base,
129
+ bytes,
130
+ sha256: sha256Bytes(bytes),
131
+ tooLarge: false,
132
+ document,
133
+ scan: document === undefined ? undefined : scanDocument(document),
134
+ });
135
+ }
136
+ return files;
137
+ }
138
+ /** Which of `wanted` the game, its DLC or a dependency define in `language`. */
139
+ async function keysFromOtherLayers(workspace, language, wanted, signal) {
140
+ const found = new Set();
141
+ if (wanted.size === 0)
142
+ return found;
143
+ const suffix = languageFileSuffix(language);
144
+ for (const root of workspace.roots) {
145
+ if (root.kind !== 'game' && root.kind !== 'dlc' && root.kind !== 'dependency')
146
+ continue;
147
+ const folder = await localisationFolder(root.path);
148
+ if (folder === undefined)
149
+ continue;
150
+ const paths = [];
151
+ await walkYml(folder, 'localisation', 0, paths, signal);
152
+ for (const relative of paths) {
153
+ if (!relative.toLowerCase().endsWith(suffix))
154
+ continue;
155
+ signal?.throwIfAborted();
156
+ const absolute = path.join(root.path, ...relative.split('/'));
157
+ const status = await lstat(absolute);
158
+ if (status.size > LAYER_FILE_LIMIT)
159
+ continue;
160
+ const text = (await readFile(absolute)).toString('utf8');
161
+ for (const match of text.matchAll(/^[ \t]*([A-Za-z0-9_.-]+):/gmu)) {
162
+ const key = match[1];
163
+ if (wanted.has(key))
164
+ found.add(key);
165
+ }
166
+ }
167
+ }
168
+ return found;
169
+ }
170
+ class WorkSet {
171
+ mod;
172
+ files = new Map();
173
+ constructor(mod) {
174
+ this.mod = mod;
175
+ }
176
+ existing(relative) {
177
+ const known = this.files.get(relative);
178
+ if (known !== undefined)
179
+ return known;
180
+ const file = this.mod.get(relative);
181
+ if (file?.document === undefined || file.bytes === undefined)
182
+ return undefined;
183
+ const work = {
184
+ path: relative,
185
+ document: file.document,
186
+ before: file.bytes,
187
+ changes: [],
188
+ };
189
+ this.files.set(relative, work);
190
+ return work;
191
+ }
192
+ create(relative) {
193
+ const work = {
194
+ path: relative,
195
+ document: newLocDocument(),
196
+ before: null,
197
+ changes: [{ kind: 'create_file' }],
198
+ };
199
+ this.files.set(relative, work);
200
+ return work;
201
+ }
202
+ planned() {
203
+ return [...this.files.values()]
204
+ .filter(({ document }) => documentChanged(document))
205
+ .sort((a, b) => compareCodeUnits(a.path, b.path))
206
+ .map((work) => ({
207
+ path: work.path,
208
+ action: work.before === null ? 'create' : 'update',
209
+ document: work.document,
210
+ before: work.before,
211
+ after: encodeLocDocument(work.document),
212
+ changes: work.changes,
213
+ }));
214
+ }
215
+ }
216
+ function emptyPlan(mod) {
217
+ return {
218
+ files: [],
219
+ skipped: [],
220
+ unfixable: [],
221
+ notes: [],
222
+ consulted: [...mod.values()]
223
+ .filter((file) => file.sha256 !== undefined)
224
+ .map((file) => ({ path: file.path, sha256: file.sha256 })),
225
+ counts: {
226
+ keysAdded: 0,
227
+ keysReplaced: 0,
228
+ keysOverridden: 0,
229
+ bomsAdded: 0,
230
+ quotesFixed: 0,
231
+ keysCopied: 0,
232
+ },
233
+ };
234
+ }
235
+ function modFolderName(workspace) {
236
+ const name = path.basename(workspace.modRoot).replace(/[^A-Za-z0-9_.-]+/gu, '_');
237
+ return name.replace(/^[._-]+/u, '') || 'mod';
238
+ }
239
+ function defaultTargetPath(workspace, language, replace) {
240
+ const name = modFolderName(workspace);
241
+ return replace
242
+ ? `localisation/${language}/replace/${name}_replace${languageFileSuffix(language)}`
243
+ : `localisation/${language}/${name}${languageFileSuffix(language)}`;
244
+ }
245
+ /** The file to append to: the mod's file with the most keys for the language, else a new one. */
246
+ function pickTarget(workspace, mod, language, replace) {
247
+ let best;
248
+ for (const file of [...mod.values()].sort((a, b) => compareCodeUnits(a.path, b.path))) {
249
+ if (file.language !== language || file.replace !== replace)
250
+ continue;
251
+ if (!file.scan?.headers.some((header) => header.language === language))
252
+ continue;
253
+ const count = file.scan.entries.filter((entry) => entry.language === language).length;
254
+ if (best === undefined || count > best.count)
255
+ best = { path: file.path, count };
256
+ }
257
+ if (best !== undefined)
258
+ return { path: best.path, create: false };
259
+ const fallback = defaultTargetPath(workspace, language, replace);
260
+ if (mod.has(fallback))
261
+ throw new ServiceError('LOCALISATION_TARGET_UNSUITABLE', `${fallback} exists but cannot take new keys (not valid UTF-8 or no l_${language}: header); run mode "fix" first or pass file`, { path: fallback });
262
+ return { path: fallback, create: true };
263
+ }
264
+ export async function planAdd(options, input) {
265
+ const { workspace, signal } = options;
266
+ const language = input.language;
267
+ const entries = input.entries ?? [];
268
+ let explicit;
269
+ if (input.file !== undefined) {
270
+ explicit = normalizeLocalisationPath(input.file, 'file');
271
+ if (!explicit.endsWith(languageFileSuffix(language)) || explicit.split('/').length < 2)
272
+ throw invalidPath('file', input.file, `must be a localisation/ path ending in ${languageFileSuffix(language)}`);
273
+ }
274
+ const mod = await readModFiles(workspace, signal);
275
+ const plan = emptyPlan(mod);
276
+ const work = new WorkSet(mod);
277
+ const definitions = new Map();
278
+ for (const file of mod.values()) {
279
+ if (file.language !== language || file.scan === undefined)
280
+ continue;
281
+ for (const scanned of file.scan.entries) {
282
+ if (scanned.language !== language)
283
+ continue;
284
+ const list = definitions.get(scanned.entry.key) ?? [];
285
+ list.push({
286
+ path: file.path,
287
+ lineIndex: scanned.lineIndex,
288
+ value: scanned.entry.value,
289
+ prefix: scanned.entry.prefix,
290
+ tail: scanned.entry.tail,
291
+ });
292
+ definitions.set(scanned.entry.key, list);
293
+ }
294
+ }
295
+ const undefinedInMod = new Set(entries.filter(({ key }) => !definitions.has(key)).map(({ key }) => key));
296
+ const elsewhere = await keysFromOtherLayers(workspace, language, undefinedInMod, signal);
297
+ const fresh = [];
298
+ for (const entry of entries) {
299
+ const raw = escapeLocText(entry.text);
300
+ if (endsWithLoneBackslash(raw)) {
301
+ plan.skipped.push({
302
+ key: entry.key,
303
+ reason: 'the text ends with a backslash that would escape the closing quote',
304
+ });
305
+ continue;
306
+ }
307
+ const existing = definitions.get(entry.key);
308
+ if (existing === undefined) {
309
+ fresh.push({ key: entry.key, raw, override: elsewhere.has(entry.key) });
310
+ continue;
311
+ }
312
+ const differing = existing.filter(({ value }) => value !== raw);
313
+ if (differing.length === 0) {
314
+ plan.skipped.push({
315
+ key: entry.key,
316
+ reason: 'unchanged: the mod already defines it with this text',
317
+ });
318
+ continue;
319
+ }
320
+ if (!input.replace) {
321
+ const first = differing[0];
322
+ plan.skipped.push({
323
+ key: entry.key,
324
+ reason: `defined in ${first.path}:${first.lineIndex + 1} with different text; set replace to true to rewrite it`,
325
+ });
326
+ continue;
327
+ }
328
+ for (const definition of differing) {
329
+ const target = work.existing(definition.path);
330
+ if (target === undefined)
331
+ continue;
332
+ const line = target.document.lines[definition.lineIndex];
333
+ line.content = `${definition.prefix}"${raw}"${definition.tail}`;
334
+ target.changes.push({ kind: 'replace_key', key: entry.key, line: definition.lineIndex + 1 });
335
+ plan.counts.keysReplaced += 1;
336
+ }
337
+ }
338
+ // Group the new keys by target file, keeping the request's order.
339
+ const groups = new Map();
340
+ const targetOf = (override) => {
341
+ if (explicit !== undefined) {
342
+ const file = mod.get(explicit);
343
+ if (file === undefined)
344
+ return { path: explicit, create: true };
345
+ const scan = file.scan;
346
+ if (scan === undefined)
347
+ throw new ServiceError('LOCALISATION_FILE_ENCODING', `${explicit} is not valid UTF-8 or UTF-16; run mode "fix" or recreate it before adding keys`, { path: explicit });
348
+ if (scan.headers.length > 0 && !scan.headers.some((header) => header.language === language))
349
+ throw new ServiceError('LOCALISATION_FILE_HEADER', `${explicit} has no l_${language}: header`, { path: explicit });
350
+ return { path: explicit, create: false };
351
+ }
352
+ return pickTarget(workspace, mod, language, override);
353
+ };
354
+ for (const item of fresh) {
355
+ const target = targetOf(item.override);
356
+ const group = groups.get(target.path) ?? { create: target.create, items: [] };
357
+ group.items.push(item);
358
+ groups.set(target.path, group);
359
+ }
360
+ const overridePaths = new Set();
361
+ for (const [targetPath, group] of [...groups].sort(([a], [b]) => compareCodeUnits(a, b))) {
362
+ const file = group.create ? work.create(targetPath) : work.existing(targetPath);
363
+ const style = group.create ? NEW_FILE_STYLE : detectStyle(file.document);
364
+ const lines = appendEntries(file.document, language, group.items.map(({ key, raw }) => formatEntryLine(style, key, raw)));
365
+ for (const [index, item] of group.items.entries()) {
366
+ file.changes.push({
367
+ kind: item.override ? 'override_key' : 'add_key',
368
+ key: item.key,
369
+ line: lines[index],
370
+ });
371
+ if (item.override) {
372
+ plan.counts.keysOverridden += 1;
373
+ overridePaths.add(targetPath);
374
+ }
375
+ else
376
+ plan.counts.keysAdded += 1;
377
+ }
378
+ if (!group.create && file.document.target === 'utf8')
379
+ plan.notes.push(`${targetPath} has no byte order mark, so the game ignores it; run mode "fix".`);
380
+ }
381
+ if (plan.counts.keysOverridden > 0) {
382
+ const names = fresh.filter(({ override }) => override).map(({ key }) => key);
383
+ const inReplace = [...overridePaths].every((target) => inReplaceFolder(target));
384
+ plan.notes.push(`${names.length} key(s) are defined by the game or a dependency (${names.slice(0, 5).join(', ')}${names.length > 5 ? ', ...' : ''}): the new entries override them${inReplace ? ' from a replace folder, which the game loads with priority' : `, but ${[...overridePaths].join(', ')} is not in a replace folder, so the game may keep its own text and list the key twice in text.log`}.`);
385
+ }
386
+ plan.files = work.planned();
387
+ return plan;
388
+ }
389
+ // ---------------------------------------------------------------------------------------------
390
+ // Mode fix
391
+ export async function planFix(options, input) {
392
+ const { workspace, signal } = options;
393
+ const fixes = new Set(input.fixes);
394
+ const mod = await readModFiles(workspace, signal);
395
+ const plan = emptyPlan(mod);
396
+ const work = new WorkSet(mod);
397
+ // `paths` limit which files change. A path is a file or a folder under localisation/.
398
+ const filters = (input.paths ?? []).map((value) => ({
399
+ value,
400
+ path: normalizeLocalisationPath(value, 'paths'),
401
+ }));
402
+ const allowed = (relative) => filters.length === 0 ||
403
+ filters.some(({ path: filter }) => relative === filter || relative.startsWith(`${filter}/`));
404
+ for (const filter of filters)
405
+ if (![...mod.keys()].some((candidate) => candidate === filter.path || candidate.startsWith(`${filter.path}/`)))
406
+ plan.unfixable.push({
407
+ kind: 'path',
408
+ path: filter.path,
409
+ reason: 'no localisation file matches this path',
410
+ });
411
+ for (const file of [...mod.values()].sort((a, b) => compareCodeUnits(a.path, b.path))) {
412
+ if (!allowed(file.path) || (!fixes.has('bom') && !fixes.has('quotes')))
413
+ continue;
414
+ if (file.document === undefined) {
415
+ plan.unfixable.push({
416
+ kind: 'encoding',
417
+ path: file.path,
418
+ reason: file.tooLarge
419
+ ? 'the file is larger than the supported size'
420
+ : 'the file is not valid UTF-8 or UTF-16, so its encoding is unclear',
421
+ });
422
+ continue;
423
+ }
424
+ const target = work.existing(file.path);
425
+ const document = target.document;
426
+ if (fixes.has('bom') && document.lines.length > 0 && document.encoding !== 'utf8-bom') {
427
+ document.target = 'utf8-bom';
428
+ target.changes.push({ kind: document.encoding === 'utf8' ? 'add_bom' : 'reencode_utf16' });
429
+ plan.counts.bomsAdded += 1;
430
+ }
431
+ if (fixes.has('quotes') && file.language !== null) {
432
+ for (const [index, line] of document.lines.entries()) {
433
+ const kind = classifyLine(line.content);
434
+ if (kind.kind !== 'broken')
435
+ continue;
436
+ const repair = repairValue(kind, document.lines[index + 1]?.content);
437
+ if (repair.fixed) {
438
+ line.content = repair.content;
439
+ target.changes.push({ kind: 'fix_quote', key: kind.key, line: index + 1 });
440
+ plan.counts.quotesFixed += 1;
441
+ }
442
+ else
443
+ plan.unfixable.push({
444
+ kind: 'quote',
445
+ path: file.path,
446
+ key: kind.key,
447
+ reason: `line ${index + 1}: ${repair.reason}`,
448
+ });
449
+ }
450
+ }
451
+ }
452
+ if (fixes.has('missing_languages'))
453
+ await planMissingLanguages(options, mod, work, plan, allowed);
454
+ plan.files = work.planned();
455
+ return plan;
456
+ }
457
+ async function planMissingLanguages(options, mod, work, plan, allowed) {
458
+ const { workspace, signal } = options;
459
+ // The mod's English keys in file order; the first definition of a key wins.
460
+ const english = new Map();
461
+ const defined = new Map();
462
+ for (const file of [...mod.values()].sort((a, b) => compareCodeUnits(a.path, b.path))) {
463
+ if (file.language === null || file.scan === undefined)
464
+ continue;
465
+ for (const scanned of file.scan.entries) {
466
+ if (scanned.language !== file.language)
467
+ continue;
468
+ const keys = defined.get(file.language) ?? new Set();
469
+ keys.add(scanned.entry.key);
470
+ defined.set(file.language, keys);
471
+ if (file.language === 'english' && !english.has(scanned.entry.key))
472
+ english.set(scanned.entry.key, { value: scanned.entry.value, replace: file.replace });
473
+ }
474
+ }
475
+ if (english.size > 0) {
476
+ for (const language of LOCALISATION_LANGUAGES) {
477
+ if (language === 'english')
478
+ continue;
479
+ const have = defined.get(language) ?? new Set();
480
+ // A language the mod supports holds at least a quarter of its English keys
481
+ // (the rule hoi4.localisation_inspect uses).
482
+ if (have.size * 4 < english.size)
483
+ continue;
484
+ const missing = [...english].filter(([key]) => !have.has(key));
485
+ if (missing.length === 0)
486
+ continue;
487
+ // The game's own translation of a key the mod overrides in English must not be hidden.
488
+ const elsewhere = await keysFromOtherLayers(workspace, language, new Set(missing.map(([key]) => key)), signal);
489
+ for (const replace of [false, true]) {
490
+ const items = missing.filter(([key, info]) => info.replace === replace && !elsewhere.has(key));
491
+ if (items.length === 0)
492
+ continue;
493
+ const target = pickTarget(workspace, mod, language, replace);
494
+ if (!allowed(target.path))
495
+ continue;
496
+ const file = target.create ? work.create(target.path) : work.existing(target.path);
497
+ const style = target.create ? NEW_FILE_STYLE : detectStyle(file.document);
498
+ const lines = appendEntries(file.document, language, items.map(([key, info]) => formatEntryLine(style, key, info.value)));
499
+ for (const [index, [key]] of items.entries())
500
+ file.changes.push({ kind: 'copy_missing_key', key, line: lines[index] });
501
+ plan.counts.keysCopied += items.length;
502
+ }
503
+ }
504
+ }
505
+ const report = await (options.undefinedKeys ?? (() => engineUndefinedKeys(workspace, signal)))();
506
+ if (report.available) {
507
+ for (const item of report.keys)
508
+ plan.unfixable.push({
509
+ kind: 'undefined_key',
510
+ ...(item.path === undefined ? {} : { path: item.path }),
511
+ key: item.key,
512
+ reason: 'script uses this key and no language defines it; the fixer never invents text, so use mode "add" with the text',
513
+ });
514
+ if (report.total > report.keys.length)
515
+ plan.notes.push(`${report.total} keys are used by script and defined nowhere; the first ${report.keys.length} are listed.`);
516
+ }
517
+ else
518
+ plan.notes.push(`Keys that script uses and no language defines were not checked: the engine is unavailable (${report.reason}).`);
519
+ }
520
+ async function engineUndefinedKeys(workspace, signal) {
521
+ try {
522
+ const result = await runEngineCommand('localisation', {
523
+ ...(workspace.gameRoot === undefined ? {} : { game: workspace.gameRoot }),
524
+ mod: workspace.modRoot,
525
+ dependencies: workspace.dependencyRoots,
526
+ includeDlc: workspace.dlcLayers.length > 0,
527
+ mode: 'audit',
528
+ limit: 50,
529
+ }, localisationEngineResponseSchema, { timeoutMs: 120_000, ...(signal === undefined ? {} : { signal }) });
530
+ if (!result.available)
531
+ return { available: false, reason: result.reason };
532
+ if (result.outcome === 'invalid_request')
533
+ return { available: false, reason: result.error.code };
534
+ const audit = result.response.audit;
535
+ const keys = (audit?.problems ?? [])
536
+ .filter(({ code, key }) => code === 'LOC_KEY_UNDEFINED' && key !== null)
537
+ .map(({ key, path: problemPath }) => ({
538
+ key: key,
539
+ ...(problemPath !== '' &&
540
+ !path.isAbsolute(problemPath) &&
541
+ !/^[A-Za-z]:/u.test(problemPath) &&
542
+ problemPath.length <= 1024
543
+ ? { path: problemPath.replaceAll('\\', '/') }
544
+ : {}),
545
+ }));
546
+ return {
547
+ available: true,
548
+ keys,
549
+ total: Math.max(keys.length, audit?.counts.LOC_KEY_UNDEFINED ?? 0),
550
+ };
551
+ }
552
+ catch (error) {
553
+ if (signal?.aborted === true)
554
+ throw error;
555
+ return { available: false, reason: 'engine_error' };
556
+ }
557
+ }
@@ -143,6 +143,14 @@ function* checkRows(index, report) {
143
143
  const impassable = index.adjacencies.filter(({ type }) => type === 'impassable');
144
144
  const isolated = [];
145
145
  const nonLand = [];
146
+ const seamOnly = raster.seamOnlyPairs ?? new Set();
147
+ const acrossSeam = [];
148
+ for (const row of index.adjacencies) {
149
+ if (row.from < 0 || row.to < 0)
150
+ continue;
151
+ if (seamOnly.has(`${Math.min(row.from, row.to)}:${Math.max(row.from, row.to)}`))
152
+ acrossSeam.push(`${row.from}-${row.to}`);
153
+ }
146
154
  for (const row of impassable) {
147
155
  const from = index.definitionsById.get(row.from);
148
156
  const to = index.definitionsById.get(row.to);
@@ -154,6 +162,15 @@ function* checkRows(index, report) {
154
162
  nonLand.push(`${row.from}-${row.to}`);
155
163
  }
156
164
  yield;
165
+ // The engine does not wrap adjacencies: it draws a row between provinces that touch only across
166
+ // the seam as a crossing line through the whole map (seen in the game, 8 November 2026).
167
+ if (acrossSeam.length > 0)
168
+ report({
169
+ code: 'MAP_ADJACENCY_ACROSS_SEAM',
170
+ severity: 'error',
171
+ message: `${acrossSeam.length} adjacency row(s) join provinces that touch only across the wrapping seam; the game draws each as a line across the whole map. Close the seam with impassable land instead`,
172
+ details: { rows: bounded(acrossSeam), count: acrossSeam.length },
173
+ });
157
174
  // The base game has one such row among 93, so a stray row is information and a pattern a warning.
158
175
  if (isolated.length > 0)
159
176
  report({
@@ -1018,15 +1018,44 @@ export function buildProvinceRaster(bitmap, definitionsByColor, definitionsById)
1018
1018
  }
1019
1019
  }
1020
1020
  const adjacency = new Map();
1021
+ const seamPairs = new Set();
1021
1022
  for (let y = 0; y < bitmap.height; y += 1) {
1022
1023
  for (let x = 0; x < bitmap.width; x += 1) {
1023
1024
  const current = provinceIds[y * bitmap.width + x] ?? -1;
1024
1025
  const rightX = x === bitmap.width - 1 ? 0 : x + 1;
1025
- addNeighbor(adjacency, current, provinceIds[y * bitmap.width + rightX] ?? -1);
1026
+ const right = provinceIds[y * bitmap.width + rightX] ?? -1;
1027
+ if (rightX === 0 && current >= 0 && right >= 0 && current !== right)
1028
+ seamPairs.add(`${Math.min(current, right)}:${Math.max(current, right)}`);
1029
+ addNeighbor(adjacency, current, right);
1026
1030
  if (y + 1 < bitmap.height)
1027
1031
  addNeighbor(adjacency, current, provinceIds[(y + 1) * bitmap.width + x] ?? -1);
1028
1032
  }
1029
1033
  }
1034
+ // A seam pair that also touches inside the map is an ordinary neighbour.
1035
+ const seamOnlyPairs = new Set();
1036
+ if (seamPairs.size > 0) {
1037
+ const inside = new Set();
1038
+ for (let y = 0; y < bitmap.height; y += 1)
1039
+ for (let x = 0; x < bitmap.width; x += 1) {
1040
+ const current = provinceIds[y * bitmap.width + x] ?? -1;
1041
+ if (current < 0)
1042
+ continue;
1043
+ const neighbours = [
1044
+ x + 1 < bitmap.width ? (provinceIds[y * bitmap.width + x + 1] ?? -1) : -1,
1045
+ y + 1 < bitmap.height ? (provinceIds[(y + 1) * bitmap.width + x] ?? -1) : -1,
1046
+ ];
1047
+ for (const other of neighbours) {
1048
+ if (other < 0 || other === current)
1049
+ continue;
1050
+ const key = `${Math.min(current, other)}:${Math.max(current, other)}`;
1051
+ if (seamPairs.has(key))
1052
+ inside.add(key);
1053
+ }
1054
+ }
1055
+ for (const key of seamPairs)
1056
+ if (!inside.has(key))
1057
+ seamOnlyPairs.add(key);
1058
+ }
1030
1059
  const geometry = new Map();
1031
1060
  for (const [id, value] of accumulators) {
1032
1061
  geometry.set(id, {
@@ -1058,6 +1087,7 @@ export function buildProvinceRaster(bitmap, definitionsByColor, definitionsById)
1058
1087
  height: bitmap.height,
1059
1088
  provinceIds,
1060
1089
  adjacency,
1090
+ seamOnlyPairs,
1061
1091
  geometry,
1062
1092
  unknownColors: [...unknown.values()].sort((left, right) => compareCodeUnits(rgbKey(left.color), rgbKey(right.color))),
1063
1093
  unknownColorCount,