hoi4-agent-tools 4.20.3 → 4.22.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 (140) hide show
  1. package/CHANGELOG.md +40 -0
  2. package/README.md +2 -0
  3. package/dist/bin/setup.js +1 -0
  4. package/dist/bin/stdio.js +1 -0
  5. package/dist/hoi4_agent_tools/characters/write-operations.js +2 -2
  6. package/dist/hoi4_agent_tools/characters/write-plan.js +21 -205
  7. package/dist/hoi4_agent_tools/common-write/documented-lists.js +62 -0
  8. package/dist/hoi4_agent_tools/common-write/limits.js +35 -0
  9. package/dist/hoi4_agent_tools/common-write/paths.js +17 -0
  10. package/dist/hoi4_agent_tools/common-write/write-job-operations.js +42 -0
  11. package/dist/hoi4_agent_tools/common-write/write-operations.js +360 -0
  12. package/dist/hoi4_agent_tools/common-write/write-plan.js +34 -0
  13. package/dist/hoi4_agent_tools/core/artifacts-engine.js +272 -0
  14. package/dist/hoi4_agent_tools/core/configuration.js +6 -0
  15. package/dist/hoi4_agent_tools/core/domain-tools.js +8 -0
  16. package/dist/hoi4_agent_tools/core/engine.js +67 -21
  17. package/dist/hoi4_agent_tools/core/idle-cache-lifetime.js +7 -0
  18. package/dist/hoi4_agent_tools/core/job-controls.js +12 -2
  19. package/dist/hoi4_agent_tools/core/job-executor.js +8 -7
  20. package/dist/hoi4_agent_tools/core/job-operation-registration.js +4 -0
  21. package/dist/hoi4_agent_tools/core/job-store.js +97 -5
  22. package/dist/hoi4_agent_tools/core/job-worker-host.js +2 -2
  23. package/dist/hoi4_agent_tools/core/operation-result.js +118 -33
  24. package/dist/hoi4_agent_tools/core/operation-tasks.js +4 -2
  25. package/dist/hoi4_agent_tools/core/transactions.js +6 -0
  26. package/dist/hoi4_agent_tools/core/workspace.js +25 -2
  27. package/dist/hoi4_agent_tools/country/job-operations.js +42 -0
  28. package/dist/hoi4_agent_tools/country/write-operations.js +646 -0
  29. package/dist/hoi4_agent_tools/country/write-plan.js +28 -0
  30. package/dist/hoi4_agent_tools/decision/write-operations.js +7 -8
  31. package/dist/hoi4_agent_tools/decision/write-plan.js +25 -245
  32. package/dist/hoi4_agent_tools/doctrine/write-operations.js +2 -2
  33. package/dist/hoi4_agent_tools/doctrine/write-plan.js +21 -180
  34. package/dist/hoi4_agent_tools/event/graph.js +3 -3
  35. package/dist/hoi4_agent_tools/event/job-operations.js +2 -2
  36. package/dist/hoi4_agent_tools/event/write-job-operations.js +2 -2
  37. package/dist/hoi4_agent_tools/event/write-operations.js +9 -10
  38. package/dist/hoi4_agent_tools/event/write-plan.js +28 -278
  39. package/dist/hoi4_agent_tools/focus/job-operations.js +2 -2
  40. package/dist/hoi4_agent_tools/gui/assets.js +3 -13
  41. package/dist/hoi4_agent_tools/gui/job-operations.js +2 -2
  42. package/dist/hoi4_agent_tools/gui/layout.js +2 -4
  43. package/dist/hoi4_agent_tools/gui/renderer.js +2 -1
  44. package/dist/hoi4_agent_tools/gui/source-graph.js +16 -0
  45. package/dist/hoi4_agent_tools/gui/studio.js +31 -0
  46. package/dist/hoi4_agent_tools/ideas/write-operations.js +7 -8
  47. package/dist/hoi4_agent_tools/ideas/write-plan.js +24 -304
  48. package/dist/hoi4_agent_tools/map/engine-validation.js +230 -0
  49. package/dist/hoi4_agent_tools/map/job-operations.js +2 -2
  50. package/dist/hoi4_agent_tools/map/landmass-source.js +42 -0
  51. package/dist/hoi4_agent_tools/map/landmass.js +190 -0
  52. package/dist/hoi4_agent_tools/map/model.js +17 -3
  53. package/dist/hoi4_agent_tools/map/operations.js +20 -6
  54. package/dist/hoi4_agent_tools/map/references.js +6 -3
  55. package/dist/hoi4_agent_tools/map/service.js +88 -8
  56. package/dist/hoi4_agent_tools/map/validation.js +12 -18
  57. package/dist/hoi4_agent_tools/mcp/server/argument-errors.js +2 -0
  58. package/dist/hoi4_agent_tools/mcp/server/create-modern-operations.js +1 -1
  59. package/dist/hoi4_agent_tools/mcp/server/create.js +4 -0
  60. package/dist/hoi4_agent_tools/mcp/server/task-tool-catalog.js +4 -0
  61. package/dist/hoi4_agent_tools/mcp/tools/common-write.js +21 -0
  62. package/dist/hoi4_agent_tools/mcp/tools/country-write.js +21 -0
  63. package/dist/hoi4_agent_tools/mcp/tools/map.js +1 -1
  64. package/dist/hoi4_agent_tools/mcp/transports/http.js +2 -0
  65. package/dist/hoi4_agent_tools/mcp/transports/negotiated-stdio.js +24 -16
  66. package/dist/hoi4_agent_tools/probability/job-operations.js +2 -2
  67. package/dist/hoi4_agent_tools/runtime.js +83 -3
  68. package/dist/hoi4_agent_tools/schemas/character-write.js +5 -1
  69. package/dist/hoi4_agent_tools/schemas/common-write.js +74 -0
  70. package/dist/hoi4_agent_tools/schemas/country-write.js +206 -0
  71. package/dist/hoi4_agent_tools/schemas/decision-write.js +5 -1
  72. package/dist/hoi4_agent_tools/schemas/doctrine-write.js +5 -1
  73. package/dist/hoi4_agent_tools/schemas/event-write.js +5 -1
  74. package/dist/hoi4_agent_tools/schemas/idea-write.js +5 -1
  75. package/dist/hoi4_agent_tools/schemas/landmass.js +129 -0
  76. package/dist/hoi4_agent_tools/schemas/localisation-write.js +10 -1
  77. package/dist/hoi4_agent_tools/schemas/map-requests.js +1 -1
  78. package/dist/hoi4_agent_tools/schemas/map.js +2 -0
  79. package/dist/hoi4_agent_tools/schemas/tech-write.js +5 -1
  80. package/dist/hoi4_agent_tools/script-write/engine-plan.js +45 -0
  81. package/dist/hoi4_agent_tools/technology/engine-graph.js +156 -0
  82. package/dist/hoi4_agent_tools/technology/job-operations.js +2 -2
  83. package/dist/hoi4_agent_tools/technology/operations.js +1 -2
  84. package/dist/hoi4_agent_tools/technology/service.js +30 -59
  85. package/dist/hoi4_agent_tools/technology/write-job-operations.js +2 -2
  86. package/dist/hoi4_agent_tools/technology/write-operations.js +2 -2
  87. package/dist/hoi4_agent_tools/technology/write-plan.js +21 -207
  88. package/dist/hoi4_agent_tools/version.js +1 -1
  89. package/docs/configuration.md +11 -10
  90. package/docs/jobs.md +2 -2
  91. package/docs/setup.md +1 -0
  92. package/docs/tools.md +16 -2
  93. package/docs/troubleshooting.md +11 -11
  94. package/engine/bin/darwin-arm64/hoi4-engine +0 -0
  95. package/engine/bin/linux-arm64/hoi4-engine +0 -0
  96. package/engine/bin/linux-x64/hoi4-engine +0 -0
  97. package/engine/bin/manifest.json +8 -8
  98. package/engine/bin/win32-x64/hoi4-engine.exe +0 -0
  99. package/npm-shrinkwrap.json +43 -19
  100. package/package.json +2 -2
  101. package/schemas/configuration.schema.json +143 -134
  102. package/schemas/continuous-focus-palette.schema.json +1 -1
  103. package/schemas/custom-weighted-pool.schema.json +1 -1
  104. package/schemas/decision-inspect-input.schema.json +1 -1
  105. package/schemas/error-log-input.schema.json +1 -1
  106. package/schemas/event-feature-manifest.schema.json +1 -1
  107. package/schemas/focus-plan.schema.json +1 -1
  108. package/schemas/focus-planning-sidecar.schema.json +1 -1
  109. package/schemas/geography-model.schema.json +1 -1
  110. package/schemas/gui-animation-source.schema.json +1 -1
  111. package/schemas/gui-helper.schema.json +1 -1
  112. package/schemas/gui-scenario.schema.json +1 -1
  113. package/schemas/helper-expansion-request.schema.json +1 -1
  114. package/schemas/helper-expansion-summary.schema.json +1 -1
  115. package/schemas/impact-inspect-input.schema.json +1 -1
  116. package/schemas/map-operation.schema.json +354 -1
  117. package/schemas/mechanic-test-input.schema.json +1 -1
  118. package/schemas/mod-index-input.schema.json +1 -1
  119. package/schemas/operation-result.schema.json +1 -1
  120. package/schemas/package-check-input.schema.json +1 -1
  121. package/schemas/package-manifest.schema.json +1 -1
  122. package/schemas/probability-analysis-result.schema.json +1 -1
  123. package/schemas/probability-compare-input.schema.json +1 -1
  124. package/schemas/probability-evaluate-input.schema.json +1 -1
  125. package/schemas/probability-inspect-input.schema.json +1 -1
  126. package/schemas/probability-render-input.schema.json +1 -1
  127. package/schemas/probability-scenario-set.schema.json +1 -1
  128. package/schemas/probability-sequence-input.schema.json +1 -1
  129. package/schemas/probability-simulate-input.schema.json +1 -1
  130. package/schemas/probability-sweep-input.schema.json +1 -1
  131. package/schemas/reference-context-input.schema.json +1 -1
  132. package/schemas/reference-read-input.schema.json +1 -1
  133. package/schemas/reference-search-input.schema.json +1 -1
  134. package/schemas/reference-sheets.schema.json +1 -1
  135. package/schemas/scenario-suite.schema.json +1 -1
  136. package/schemas/scenario-test-input.schema.json +1 -1
  137. package/schemas/script-validate-input.schema.json +1 -1
  138. package/schemas/shared-scenario.schema.json +1 -1
  139. package/schemas/source-lookup-input.schema.json +1 -1
  140. package/server.json +2 -2
@@ -0,0 +1,646 @@
1
+ import { compareCodeUnits } from '../core/canonical.js';
2
+ import { DIFF_CONTEXT_LINES, unifiedTextDiff } from '../core/diff.js';
3
+ import { emptyServiceResult, ServiceError } from '../core/result.js';
4
+ import { decodeSource } from '../core/source/encoding.js';
5
+ import { assignments, parseClausewitz } from '../core/source/index.js';
6
+ import { autonomousResultArtifacts, } from '../core/transaction-execution.js';
7
+ import { readDependenciesFromScannedFiles, } from '../core/transactions.js';
8
+ import { computeLocalisationPlan } from '../localisation/write-operations.js';
9
+ import { documentedNames } from '../reference/documented-commands.js';
10
+ import { ReferenceService } from '../reference/service.js';
11
+ import { countryWriteDataSchema, } from '../schemas/country-write.js';
12
+ import { localisationWriteRequestSchema } from '../schemas/localisation-write.js';
13
+ import { planCountryFile, } from './write-plan.js';
14
+ const DIFF_BUDGET_BYTES = 9_000;
15
+ const MAX_INLINE_PATHS = 16;
16
+ const MAX_INLINE_ARTIFACTS = 2;
17
+ const MAX_LISTED = 30;
18
+ const MAX_REFERENCES = 20;
19
+ /** The tag count at which one measured game build overflowed its flag sheet (ADR 0069). */
20
+ const TAG_COUNT_WARNING = 439;
21
+ const TAG_FILE = /^common\/country_tags\/[^/]+\.txt$/u;
22
+ const BOOKMARK_FILE = /^common\/bookmarks\/[^/]+\.txt$/u;
23
+ const COLORS_FILE = 'common/countries/colors.txt';
24
+ /**
25
+ * A list for a refusal message. A background job keeps only a refusal's code and message, so what
26
+ * the refusal lists must be in the message too: at most 20 entries, then a count.
27
+ */
28
+ function listed(entries, total = entries.length) {
29
+ const shown = entries.slice(0, 20);
30
+ if (shown.length === 0)
31
+ return 'none';
32
+ const more = total - shown.length;
33
+ return more > 0 ? `${shown.join(', ')} and ${more} more` : shown.join(', ');
34
+ }
35
+ function fail(code, message, details) {
36
+ throw new ServiceError(code, message, details);
37
+ }
38
+ function normalized(path) {
39
+ return path.replaceAll('\\', '/').replace(/^\.\//u, '').toLowerCase();
40
+ }
41
+ /** A path the tool may create: under `folder`, ending .txt, with no empty or dot segment. */
42
+ /** Names Windows reserves for devices, with or without an extension. */
43
+ const DEVICE_NAME = /^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/iu;
44
+ /**
45
+ * A file the tool may create, `<folder>/<name>.txt` directly under `folder`: the folder in its
46
+ * canonical lower case, so a differently cased path never makes a second file on a case-sensitive
47
+ * system. A name with a character Windows refuses, a device name or a trailing dot or space is
48
+ * refused.
49
+ */
50
+ function newPathUnder(file, folder, field, what) {
51
+ const path = file.replaceAll('\\', '/').replace(/^\.\//u, '');
52
+ const name = path.slice(folder.length + 1);
53
+ if (!normalized(path).startsWith(`${folder}/`) ||
54
+ !/^[^/]+\.txt$/iu.test(name) ||
55
+ /[<>:"|?*\p{Cc}]/u.test(name) ||
56
+ DEVICE_NAME.test(name) ||
57
+ /[ .]$/u.test(name.slice(0, -4)))
58
+ fail('COUNTRY_WRITE_FILE_INVALID', `${file} is not ${what}`, { field, file });
59
+ return `${folder}/${name}`;
60
+ }
61
+ /** The longest file stem the tool writes, so the paths stay well inside Windows path limits. */
62
+ const MAX_STEM = 80;
63
+ /**
64
+ * `slug` of create_world: letters, digits, space, `_` and `-`. Like create_world, it drops every
65
+ * other character, non-ASCII letters included, so a name such as "Åland" makes the file
66
+ * `<TAG> - land.txt`; the localised name keeps every letter.
67
+ */
68
+ export function countrySlug(name) {
69
+ return name.replace(/[^A-Za-z0-9 _-]/gu, '').trim() || 'Country';
70
+ }
71
+ function active(snapshot) {
72
+ return snapshot.files.filter(({ shadowedBy }) => shadowedBy === undefined);
73
+ }
74
+ function modFiles(snapshot) {
75
+ return active(snapshot).filter(({ rootKind }) => rootKind === 'mod');
76
+ }
77
+ /** The active file at a path, from whichever layer wins. */
78
+ function activeAt(snapshot, path) {
79
+ return active(snapshot).find(({ relativePath }) => normalized(relativePath) === normalized(path));
80
+ }
81
+ function modAt(snapshot, path) {
82
+ return modFiles(snapshot).find(({ relativePath }) => normalized(relativePath) === normalized(path));
83
+ }
84
+ function tagFiles(snapshot) {
85
+ const out = [];
86
+ for (const file of active(snapshot)) {
87
+ if (!TAG_FILE.test(normalized(file.relativePath)))
88
+ continue;
89
+ const root = parseClausewitz(file.bytes, file.displayPath).root;
90
+ const entries = assignments(root);
91
+ const dynamic = entries.some((entry) => entry.key.value === 'dynamic_tags' &&
92
+ entry.value.type === 'scalar' &&
93
+ entry.value.value === 'yes');
94
+ const tags = new Map();
95
+ for (const entry of entries)
96
+ if (/^[A-Z0-9]{3}$/u.test(entry.key.value) && entry.value.type === 'scalar')
97
+ tags.set(entry.key.value, entry.value.value);
98
+ out.push({ file, dynamic, tags });
99
+ }
100
+ return out;
101
+ }
102
+ function cultures(snapshot) {
103
+ const file = activeAt(snapshot, 'common/graphicalculturetype.txt');
104
+ if (file === undefined)
105
+ return [];
106
+ const text = decodeSource(file.bytes).text.replace(/#[^\r\n]*/gu, ' ');
107
+ return [...new Set(text.split(/\s+/u).filter((word) => /^[A-Za-z0-9_]+$/u.test(word)))].sort(compareCodeUnits);
108
+ }
109
+ function ideologies(snapshot) {
110
+ const names = new Set();
111
+ for (const file of active(snapshot)) {
112
+ if (!/^common\/ideologies\/[^/]+\.txt$/u.test(normalized(file.relativePath)))
113
+ continue;
114
+ const root = parseClausewitz(file.bytes, file.displayPath).root;
115
+ for (const wrapper of assignments(root, 'ideologies'))
116
+ if (wrapper.value.type === 'block')
117
+ for (const entry of assignments(wrapper.value))
118
+ if (entry.value.type === 'block')
119
+ names.add(entry.key.value);
120
+ }
121
+ return [...names].sort(compareCodeUnits);
122
+ }
123
+ function states(snapshot) {
124
+ const ids = new Set();
125
+ for (const record of snapshot.index.findAll('state'))
126
+ if (!record.overridden && /^\d+$/u.test(record.id))
127
+ ids.add(Number(record.id));
128
+ return [...ids].sort((a, b) => a - b);
129
+ }
130
+ /** History files of a tag: the game matches `history/countries/<TAG> - <name>.txt` by its prefix. */
131
+ function historyFiles(snapshot, tag) {
132
+ return active(snapshot).filter(({ relativePath }) => {
133
+ const name = normalized(relativePath);
134
+ if (!name.startsWith('history/countries/') || !name.endsWith('.txt'))
135
+ return false;
136
+ const base = relativePath.replaceAll('\\', '/').split('/').pop() ?? '';
137
+ return new RegExp(`^${tag}(?:[ ._-]|$)`, 'u').test(base);
138
+ });
139
+ }
140
+ /** Whether a Clausewitz text names the tag as a token outside comments. */
141
+ function tokenLines(text, tag) {
142
+ const lines = [];
143
+ const token = new RegExp(`(?<![A-Za-z0-9_])${tag}(?![A-Za-z0-9_])`, 'u');
144
+ text.split(/\r\n|\r|\n/u).forEach((line, index) => {
145
+ let code = '';
146
+ let quoted = false;
147
+ for (const char of line) {
148
+ if (char === '"')
149
+ quoted = !quoted;
150
+ if (char === '#' && !quoted)
151
+ break;
152
+ code += char;
153
+ }
154
+ if (token.test(code))
155
+ lines.push(index + 1);
156
+ });
157
+ return lines;
158
+ }
159
+ function warning(code, message, details) {
160
+ return { code, severity: 'warning', category: 'reference', message, details };
161
+ }
162
+ async function reservedNames(engine, context) {
163
+ const workspace = engine.resolver.get(context.workspaceId, context.principal);
164
+ const names = await documentedNames(new ReferenceService({ docsRoot: engine.resolver.config().docsRoot }), workspace, context.signal);
165
+ if (names === undefined)
166
+ return undefined;
167
+ return [...new Set([...names.effect, ...names.trigger])]
168
+ .filter((name) => /^[a-z][a-z0-9]{2}$/u.test(name))
169
+ .map((name) => name.toUpperCase())
170
+ .sort(compareCodeUnits);
171
+ }
172
+ function engineInput(input, target, known, countryFile) {
173
+ const { history, bookmark } = input;
174
+ return {
175
+ operation: input.operation,
176
+ target,
177
+ tag: input.tag,
178
+ ...(countryFile === undefined ? {} : { countryFile }),
179
+ ...(input.graphicalCulture === undefined ? {} : { graphicalCulture: input.graphicalCulture }),
180
+ ...(input.color === undefined ? {} : { color: input.color }),
181
+ ...(input.colorUi === undefined ? {} : { colorUi: input.colorUi }),
182
+ ...(history === undefined ? {} : { history }),
183
+ ...(bookmark === undefined
184
+ ? {}
185
+ : {
186
+ bookmark: Object.fromEntries(Object.entries(bookmark).filter(([key]) => key !== 'file')),
187
+ }),
188
+ known,
189
+ };
190
+ }
191
+ /** The localisation entries the call gives, as `<TAG>`, `<TAG>_ADJ`, `<TAG>_DEF` and per ideology. */
192
+ function localisationEntries(input) {
193
+ const entries = [];
194
+ const add = (key, text) => {
195
+ if (text !== undefined)
196
+ entries.push({ key, text });
197
+ };
198
+ const adding = input.operation === 'add';
199
+ add(input.tag, input.name);
200
+ add(`${input.tag}_ADJ`, input.adjective ?? (adding ? input.name : undefined));
201
+ add(`${input.tag}_DEF`, input.definition ?? (adding ? input.name : undefined));
202
+ for (const variant of input.ideologyNames ?? []) {
203
+ add(`${input.tag}_${variant.ideology}`, variant.name);
204
+ add(`${input.tag}_${variant.ideology}_ADJ`, variant.adjective);
205
+ add(`${input.tag}_${variant.ideology}_DEF`, variant.definition);
206
+ }
207
+ return entries;
208
+ }
209
+ export async function computeCountryWrite(engine, input, context, applied) {
210
+ const tag = input.tag;
211
+ const flagNames = [
212
+ tag,
213
+ ...new Set([
214
+ ...(input.ideologyNames ?? []).map(({ ideology }) => `${tag}_${ideology}`),
215
+ ...(input.history?.politics === undefined
216
+ ? []
217
+ : [`${tag}_${input.history.politics.rulingParty}`]),
218
+ ]),
219
+ ];
220
+ const patterns = [
221
+ 'common/country_tags/*.txt',
222
+ 'common/countries/**/*.txt',
223
+ 'common/graphicalculturetype.txt',
224
+ 'common/ideologies/*.txt',
225
+ 'common/bookmarks/*.txt',
226
+ 'common/characters/**/*.txt',
227
+ 'history/countries/*.txt',
228
+ 'history/states/*.txt',
229
+ 'history/units/*.txt',
230
+ 'localisation/english/**/*.{yml,yaml}',
231
+ 'localisation/*.{yml,yaml}',
232
+ ...flagNames.flatMap((name) => ['', 'medium/', 'small/'].map((folder) => `gfx/flags/${folder}${name}.tga`)),
233
+ ];
234
+ const snapshot = await engine.scan(context.workspaceId, { patterns }, context.principal, context.signal);
235
+ const diagnostics = [];
236
+ const tagSources = tagFiles(snapshot);
237
+ const allTags = [...new Set(tagSources.flatMap(({ tags }) => [...tags.keys()]))].sort(compareCodeUnits);
238
+ const reserved = await reservedNames(engine, context);
239
+ if (reserved === undefined && input.operation === 'add')
240
+ diagnostics.push(warning('COUNTRY_WRITE_RESERVED_NAMES_UNAVAILABLE', 'The game documentation is not available, so the tag was not checked against the script names it lists', {}));
241
+ const known = {
242
+ tags: allTags,
243
+ reservedNames: reserved ?? [],
244
+ states: states(snapshot),
245
+ cultures: cultures(snapshot),
246
+ ideologies: ideologies(snapshot),
247
+ };
248
+ for (const [field, list] of [
249
+ ['states', known.states],
250
+ ['cultures', known.cultures],
251
+ ['ideologies', known.ideologies],
252
+ ])
253
+ if (list.length === 0)
254
+ diagnostics.push(warning('COUNTRY_WRITE_CHECK_SKIPPED', `No ${field} were found in the active sources, so the ${field} the call names were not checked`, { field }));
255
+ // The per-ideology names reach only the localisation writer, so their ideologies are checked here.
256
+ for (const { ideology } of input.ideologyNames ?? [])
257
+ if (known.ideologies.length > 0 && !known.ideologies.includes(ideology))
258
+ fail('COUNTRY_WRITE_IDEOLOGY_UNKNOWN', `${ideology} is not an ideology of the active common/ideologies files; they define ${listed(known.ideologies)}`, { field: 'ideologyNames', ideology, known: known.ideologies });
259
+ const declaring = tagSources.filter(({ tags }) => tags.has(tag));
260
+ const modDeclaring = declaring.filter(({ file }) => file.rootKind === 'mod');
261
+ const changes = [];
262
+ const plan = async (target, path, read, countryFile) => {
263
+ const result = await planCountryFile(path, engineInput(input, target, known, countryFile), read?.bytes);
264
+ if (result.action === 'unchanged')
265
+ return;
266
+ const before = modAt(snapshot, path);
267
+ changes.push({
268
+ plan: result,
269
+ before,
270
+ read: read !== undefined && read !== before ? read : undefined,
271
+ });
272
+ };
273
+ if (input.operation !== 'add') {
274
+ if (modDeclaring.length === 0) {
275
+ if (declaring.length > 0)
276
+ fail('COUNTRY_WRITE_NOT_IN_MOD', `${tag} is defined by ${declaring[0].file.displayPath}, not by the mod; the tool edits only the mod's countries`, { tag, path: declaring[0].file.displayPath });
277
+ fail('COUNTRY_WRITE_TAG_NOT_FOUND', `${tag} is not a country tag of the active sources`, {
278
+ tag,
279
+ });
280
+ }
281
+ }
282
+ // The tag line and the country file it points at.
283
+ const stem = input.name === undefined ? undefined : `${tag} - ${countrySlug(input.name)}`;
284
+ if (input.operation === 'add' && stem !== undefined && stem.length > MAX_STEM)
285
+ fail('COUNTRY_WRITE_FILE_INVALID', `The file name ${stem}.txt from the country name is longer than ${MAX_STEM} characters; give a shorter name and put the long form in definition`, { field: 'name', stem });
286
+ if (input.operation === 'add') {
287
+ const ownTagFiles = tagSources.filter(({ file }) => file.rootKind === 'mod');
288
+ let tagPath;
289
+ let tagRead;
290
+ if (input.tagFile !== undefined) {
291
+ tagPath = newPathUnder(input.tagFile, 'common/country_tags', 'tagFile', 'a .txt file directly under common/country_tags');
292
+ tagRead = modAt(snapshot, tagPath);
293
+ // An existing file is edited under its own spelling.
294
+ if (tagRead !== undefined)
295
+ tagPath = tagRead.relativePath;
296
+ const lower = activeAt(snapshot, tagPath);
297
+ if (tagRead === undefined && lower !== undefined)
298
+ fail('COUNTRY_WRITE_TAG_FILE_SHADOWS', `${tagPath} is a file of ${lower.rootKind === 'game' ? 'the game' : 'a dependency'}; a mod file of the same name would replace every tag it declares. Name another file`, { file: tagPath });
299
+ }
300
+ else {
301
+ const candidates = ownTagFiles.filter(({ dynamic }) => !dynamic);
302
+ if (candidates.length !== 1)
303
+ fail('COUNTRY_WRITE_TAG_FILE_REQUIRED', candidates.length === 0
304
+ ? 'The mod has no common/country_tags file; name a new one with tagFile'
305
+ : `${candidates.length} common/country_tags files of the mod declare tags; name one with tagFile: ${listed(candidates.map(({ file }) => file.relativePath))}`, { files: candidates.map(({ file }) => file.relativePath).slice(0, 20) });
306
+ tagRead = candidates[0].file;
307
+ tagPath = tagRead.relativePath;
308
+ }
309
+ // The tag plan goes first: the engine checks the tag and every value of the input there.
310
+ await plan('tags', tagPath, tagRead, `countries/${stem}.txt`);
311
+ const countryPath = `common/countries/${stem}.txt`;
312
+ if (activeAt(snapshot, countryPath) !== undefined)
313
+ fail('COUNTRY_WRITE_FILE_EXISTS', `${countryPath} already exists`, { path: countryPath });
314
+ const existingHistory = historyFiles(snapshot, tag);
315
+ if (existingHistory.length > 0)
316
+ fail('COUNTRY_WRITE_FILE_EXISTS', `${existingHistory[0].displayPath} already holds the history of ${tag}`, { path: existingHistory[0].displayPath });
317
+ await plan('country', countryPath, undefined);
318
+ }
319
+ else {
320
+ const value = modDeclaring[0].tags.get(tag);
321
+ const path = `common/${value.replaceAll('\\', '/')}`;
322
+ const file = modAt(snapshot, path);
323
+ if (input.operation === 'remove') {
324
+ // Another tag may point at the same country file; deleting the mod's file would break that country.
325
+ const sharing = [
326
+ ...new Set(tagSources
327
+ .flatMap(({ tags }) => [...tags])
328
+ .filter(([other, target]) => other !== tag && normalized(`common/${target}`) === normalized(path))
329
+ .map(([other]) => other)),
330
+ ].sort(compareCodeUnits);
331
+ if (file !== undefined && sharing.length > 0)
332
+ fail('COUNTRY_WRITE_COUNTRY_FILE_SHARED', `${path} is also the country file of ${listed(sharing)}, so removing ${tag} cannot delete it; point ${tag} at its own file first`, { tag, path, tags: sharing });
333
+ for (const declared of modDeclaring)
334
+ await plan('tags', declared.file.relativePath, declared.file);
335
+ if (file !== undefined)
336
+ await plan('country', file.relativePath, file);
337
+ else
338
+ diagnostics.push(warning('COUNTRY_WRITE_COUNTRY_FILE_KEPT', `The country file of ${tag}, ${path}, is not a file of the mod, so remove leaves it as it is`, { tag, path }));
339
+ }
340
+ else if (input.graphicalCulture !== undefined || input.color !== undefined) {
341
+ if (file === undefined)
342
+ fail('COUNTRY_WRITE_NOT_IN_MOD', `The country file of ${tag}, ${path}, is not a file of the mod`, { tag, path });
343
+ await plan('country', path, file);
344
+ }
345
+ }
346
+ // The colours entry: the mod's colors.txt, or a copy of the active one so its entries stay.
347
+ const colorsActive = activeAt(snapshot, COLORS_FILE);
348
+ const colorsMod = modAt(snapshot, COLORS_FILE);
349
+ if (input.operation === 'add' || input.color !== undefined || input.colorUi !== undefined) {
350
+ await plan('colors', colorsMod?.relativePath ?? COLORS_FILE, colorsActive);
351
+ if (colorsMod === undefined && colorsActive !== undefined)
352
+ diagnostics.push({
353
+ code: 'COUNTRY_WRITE_COLORS_COPIED',
354
+ severity: 'info',
355
+ category: 'validation',
356
+ message: `The mod had no ${COLORS_FILE}; it gets a copy of ${colorsActive.displayPath} with the new entry, so the other countries keep their colours`,
357
+ details: { from: colorsActive.displayPath },
358
+ });
359
+ }
360
+ else if (input.operation === 'remove' && colorsMod !== undefined)
361
+ await plan('colors', colorsMod.relativePath, colorsMod);
362
+ // The history file.
363
+ if (input.operation === 'add')
364
+ await plan('history', `history/countries/${stem}.txt`, undefined);
365
+ else {
366
+ const own = historyFiles(snapshot, tag).filter(({ rootKind }) => rootKind === 'mod');
367
+ if (input.operation === 'remove')
368
+ for (const file of own)
369
+ await plan('history', file.relativePath, file);
370
+ else if (input.history !== undefined) {
371
+ if (own.length !== 1)
372
+ fail(own.length === 0 ? 'COUNTRY_WRITE_NOT_IN_MOD' : 'COUNTRY_WRITE_LAYOUT_UNSUPPORTED', own.length === 0
373
+ ? `The mod has no history/countries file for ${tag}`
374
+ : `${own.length} history files of the mod belong to ${tag}`, { tag, files: own.map(({ relativePath }) => relativePath) });
375
+ await plan('history', own[0].relativePath, own[0]);
376
+ }
377
+ }
378
+ // The bookmark.
379
+ if (input.bookmark !== undefined && input.operation !== 'remove') {
380
+ const path = newPathUnder(input.bookmark.file, 'common/bookmarks', 'bookmark.file', 'a .txt file directly under common/bookmarks');
381
+ const read = activeAt(snapshot, path);
382
+ if (read === undefined && input.bookmark.create === undefined)
383
+ fail('COUNTRY_WRITE_BOOKMARK_NOT_FOUND', `${path} does not exist; give bookmark.create to make a new bookmark there`, { file: path });
384
+ await plan('bookmark', modAt(snapshot, path)?.relativePath ?? path, read);
385
+ }
386
+ else if (input.operation === 'remove') {
387
+ for (const file of modFiles(snapshot))
388
+ if (BOOKMARK_FILE.test(normalized(file.relativePath)) &&
389
+ tokenLines(decodeSource(file.bytes).text, tag).length > 0)
390
+ await plan('bookmark', file.relativePath, file);
391
+ }
392
+ // Localisation, in the same transaction.
393
+ const entries = input.operation === 'remove' ? [] : localisationEntries(input);
394
+ let localisation;
395
+ if (entries.length > 0) {
396
+ localisation = await computeLocalisationPlan(engine, localisationWriteRequestSchema.parse({
397
+ mode: 'add',
398
+ entries,
399
+ replace: input.operation === 'update',
400
+ }), {
401
+ workspaceId: context.workspaceId,
402
+ ...(context.principal === undefined ? {} : { principal: context.principal }),
403
+ ...(context.signal === undefined ? {} : { signal: context.signal }),
404
+ });
405
+ for (const skipped of localisation.skipped)
406
+ diagnostics.push(warning('COUNTRY_WRITE_LOCALISATION_KEPT', `${skipped.key} already has text, which add keeps; update replaces it`, { key: skipped.key, reason: skipped.reason }));
407
+ }
408
+ // Warnings: what the country refers to and the mod does not have.
409
+ const missing = {
410
+ flags: [],
411
+ localisation: [],
412
+ characters: [],
413
+ oob: [],
414
+ };
415
+ const localisationKept = [];
416
+ if (input.operation !== 'remove') {
417
+ const haveFlag = (path) => activeAt(snapshot, path) !== undefined;
418
+ for (const name of flagNames)
419
+ for (const folder of ['', 'medium/', 'small/']) {
420
+ const path = `gfx/flags/${folder}${name}.tga`;
421
+ // Per-ideology flags fall back to the plain flag, so only a missing plain flag is certain to show.
422
+ if (!haveFlag(path))
423
+ missing.flags.push(path);
424
+ }
425
+ if (missing.flags.length > 0)
426
+ diagnostics.push(warning('COUNTRY_WRITE_FLAG_MISSING', `${missing.flags.length} flag file(s) of ${tag} are missing; the game shows a blank flag where no plain ${tag} flag exists. Draw them with an image tool; this tool never draws placeholder art`, { paths: missing.flags.slice(0, MAX_LISTED) }));
427
+ const given = new Set(entries.map(({ key }) => key));
428
+ const textKeys = [
429
+ ...(input.operation === 'add' ? [tag, `${tag}_ADJ`, `${tag}_DEF`] : []),
430
+ ...(input.bookmark?.history === undefined ? [] : [input.bookmark.history]),
431
+ ];
432
+ for (const key of textKeys)
433
+ if (!given.has(key) && snapshot.index.find('localisation', `l_english:${key}`) === undefined)
434
+ missing.localisation.push(key);
435
+ if (missing.localisation.length > 0)
436
+ diagnostics.push(warning('COUNTRY_WRITE_LOCALISATION_MISSING', `No English text is defined for ${missing.localisation.join(', ')}; hoi4.localisation_write adds it`, { keys: missing.localisation.slice(0, MAX_LISTED) }));
437
+ for (const character of input.history?.recruitCharacters ?? [])
438
+ if (snapshot.index.find('leader', character) === undefined)
439
+ missing.characters.push(character);
440
+ if (missing.characters.length > 0)
441
+ diagnostics.push(warning('COUNTRY_WRITE_CHARACTER_UNDEFINED', `${missing.characters.join(', ')} ${missing.characters.length === 1 ? 'is' : 'are'} not defined; hoi4.character_write adds characters`, { characters: missing.characters }));
442
+ const oob = input.history?.oob;
443
+ if (oob !== undefined && activeAt(snapshot, `history/units/${oob}.txt`) === undefined) {
444
+ missing.oob.push(`history/units/${oob}.txt`);
445
+ diagnostics.push(warning('COUNTRY_WRITE_OOB_MISSING', `history/units/${oob}.txt does not exist, so the country starts without the units it names`, { path: `history/units/${oob}.txt` }));
446
+ }
447
+ if (input.operation === 'add' && allTags.length + 1 > TAG_COUNT_WARNING)
448
+ diagnostics.push(warning('COUNTRY_WRITE_TAG_COUNT_HIGH', `The active sources will declare ${allTags.length + 1} tags; one measured game build overflowed its flag sheet above ${TAG_COUNT_WARNING}`, { tags: allTags.length + 1, threshold: TAG_COUNT_WARNING }));
449
+ }
450
+ else {
451
+ for (const key of [tag, `${tag}_ADJ`, `${tag}_DEF`])
452
+ if (snapshot.index.find('localisation', `l_english:${key}`) !== undefined)
453
+ localisationKept.push(key);
454
+ await refuseStillReferenced(engine, context, tag, changes);
455
+ }
456
+ const files = summarize(changes, localisation);
457
+ const data = countryWriteDataSchema.parse({
458
+ operation: input.operation,
459
+ tag,
460
+ applied,
461
+ files,
462
+ missing: {
463
+ flags: missing.flags.slice(0, MAX_LISTED),
464
+ localisation: missing.localisation.slice(0, MAX_LISTED),
465
+ characters: missing.characters.slice(0, MAX_LISTED),
466
+ oob: missing.oob,
467
+ },
468
+ localisationKept,
469
+ });
470
+ return { changes, localisation, data, diagnostics };
471
+ }
472
+ /** Every mod file that still names the tag once the plan is applied blocks the removal. */
473
+ async function refuseStillReferenced(engine, context, tag, changes) {
474
+ const snapshot = await engine.scanFiles(context.workspaceId, { patterns: ['common/**/*.txt', 'history/**/*.txt', 'events/**/*.txt'], rootKinds: ['mod'] }, context.principal, context.signal);
475
+ const planned = new Map(changes.map(({ plan }) => [normalized(plan.path), plan]));
476
+ const references = [];
477
+ let total = 0;
478
+ for (const file of snapshot.files) {
479
+ if (file.shadowedBy !== undefined)
480
+ continue;
481
+ const change = planned.get(normalized(file.relativePath));
482
+ if (change?.action === 'delete')
483
+ continue;
484
+ const text = decodeSource(change?.bytes ?? file.bytes).text;
485
+ for (const line of tokenLines(text, tag)) {
486
+ total += 1;
487
+ if (references.length < MAX_REFERENCES)
488
+ references.push({ path: file.displayPath, line });
489
+ }
490
+ }
491
+ if (total > 0)
492
+ fail('COUNTRY_WRITE_STILL_REFERENCED', `${total} line(s) of other mod files still name ${tag}; change or remove them first: ${listed(references.map(({ path, line }) => `${path}:${line}`), total)}`, { tag, total, references });
493
+ }
494
+ function summarize(changes, localisation) {
495
+ const files = changes.map(({ plan, before }) => ({
496
+ path: plan.path,
497
+ action: plan.action === 'delete' ? 'delete' : before === undefined ? 'create' : 'modify',
498
+ diff: plan.diff,
499
+ }));
500
+ for (const file of localisation?.files ?? []) {
501
+ const before = file.before === null ? '' : decodeSource(file.before).text;
502
+ files.push({
503
+ path: file.path,
504
+ action: file.action === 'create' ? 'create' : 'modify',
505
+ diff: unifiedTextDiff(before, decodeSource(file.after).text, `a/${file.path}`, `b/${file.path}`, {
506
+ context: DIFF_CONTEXT_LINES,
507
+ }),
508
+ });
509
+ }
510
+ let budget = DIFF_BUDGET_BYTES;
511
+ return files.slice(0, MAX_INLINE_PATHS).map((file) => {
512
+ const fits = file.diff.length <= budget;
513
+ const diff = fits ? file.diff : `${file.diff.slice(0, Math.max(0, budget))}\n`;
514
+ budget = Math.max(0, budget - file.diff.length);
515
+ return { ...file, diff, diffTruncated: !fits };
516
+ });
517
+ }
518
+ function resultFor(workspaceId, data, outcome) {
519
+ const result = emptyServiceResult(workspaceId, data);
520
+ result.code =
521
+ outcome === 'preview'
522
+ ? 'COUNTRY_WRITE_PREVIEW'
523
+ : outcome === 'applied'
524
+ ? 'COUNTRY_WRITE_APPLIED'
525
+ : outcome === 'unchanged'
526
+ ? 'COUNTRY_WRITE_UNCHANGED'
527
+ : 'COUNTRY_WRITE_BLOCKED';
528
+ result.status = outcome === 'blocked' ? 'blocked' : 'ok';
529
+ result.proposedFiles = data.files.map(({ path }) => path).slice(0, MAX_INLINE_PATHS);
530
+ return result;
531
+ }
532
+ /** `apply: false`: the diff of every file the call would change, and nothing written. */
533
+ export async function previewCountryWrite(engine, input, context) {
534
+ await context.progress?.(0, 2, "Reading the mod's countries");
535
+ const computed = await computeCountryWrite(engine, input, context, false);
536
+ const unchanged = computed.data.files.length === 0;
537
+ const result = resultFor(context.workspaceId, computed.data, unchanged ? 'unchanged' : 'preview');
538
+ result.diagnostics = computed.diagnostics.slice(0, 20);
539
+ await context.progress?.(2, 2, 'Country preview ready');
540
+ return result;
541
+ }
542
+ /** `apply: true`: the same plans, as one validated transaction for atomic replacement. */
543
+ export async function prepareCountryWrite(engine, input, context) {
544
+ await context.progress?.(0, 3, "Reading the mod's countries");
545
+ const { changes, localisation, data, diagnostics } = await computeCountryWrite(engine, input, context, true);
546
+ if (data.files.length === 0) {
547
+ const result = resultFor(context.workspaceId, { ...data, applied: false }, 'unchanged');
548
+ result.diagnostics = diagnostics.slice(0, 20);
549
+ return { readOnlyPreview: result };
550
+ }
551
+ const operationId = `country-${input.operation}`;
552
+ const proposed = [
553
+ ...changes.map(({ plan }) => ({
554
+ relativePath: plan.path,
555
+ content: plan.action === 'delete' ? null : plan.bytes,
556
+ operationIds: [operationId],
557
+ mediaType: 'text/plain',
558
+ })),
559
+ ...(localisation?.files ?? []).map((file) => ({
560
+ relativePath: file.path,
561
+ content: file.after,
562
+ operationIds: [operationId],
563
+ mediaType: 'text/plain',
564
+ })),
565
+ ];
566
+ const workspace = engine.resolver.get(context.workspaceId, context.principal);
567
+ const modRoot = workspace.roots.find((root) => root.kind === 'mod');
568
+ const dependencies = readDependenciesFromScannedFiles(changes.flatMap(({ before, read }) => [before, read].filter((file) => file !== undefined)));
569
+ for (const consulted of localisation?.consulted ?? [])
570
+ dependencies.push({
571
+ rootKind: 'mod',
572
+ loadOrder: modRoot?.loadOrder ?? 0,
573
+ relativePath: consulted.path,
574
+ sha256: consulted.sha256,
575
+ });
576
+ await context.progress?.(1, 3, 'Preparing the country transaction');
577
+ const transaction = await engine.transactions.plan({
578
+ workspaceId: context.workspaceId,
579
+ ...(context.principal === undefined ? {} : { principal: context.principal }),
580
+ operationKind: 'country-changes',
581
+ operations: [
582
+ {
583
+ id: operationId,
584
+ kind: operationId,
585
+ summary: `${input.operation} ${input.tag}`,
586
+ data: { tag: input.tag },
587
+ },
588
+ ],
589
+ changes: proposed,
590
+ readDependencies: dependencies,
591
+ validate: (bytesByPath, signal) => {
592
+ signal?.throwIfAborted();
593
+ const matches = proposed.every(({ relativePath, content }) => {
594
+ const bytes = bytesByPath.get(relativePath);
595
+ if (content === null)
596
+ return bytes === null;
597
+ return (bytes !== undefined && bytes !== null && Buffer.from(bytes).equals(Buffer.from(content)));
598
+ });
599
+ return Promise.resolve({
600
+ diagnostics: matches
601
+ ? []
602
+ : [
603
+ {
604
+ code: 'COUNTRY_WRITE_TRANSACTION_BYTES_MISMATCH',
605
+ severity: 'blocker',
606
+ category: 'validation',
607
+ message: 'Transaction dry-run bytes differ from the planned country files',
608
+ },
609
+ ],
610
+ checks: [
611
+ {
612
+ id: 'country-proposed-bytes-match',
613
+ passed: matches,
614
+ message: matches
615
+ ? 'Transaction bytes exactly match the planned country files'
616
+ : 'Transaction bytes differ from the planned country files',
617
+ },
618
+ ],
619
+ });
620
+ },
621
+ ...(context.signal === undefined ? {} : { signal: context.signal }),
622
+ });
623
+ await context.progress?.(2, 3, 'Country change prepared for journaled application');
624
+ return { transaction, recipe: { data, diagnostics } };
625
+ }
626
+ export function completeCountryWrite(workspaceId, execution, recipe) {
627
+ const parsed = recipe;
628
+ const data = countryWriteDataSchema.parse({
629
+ ...parsed.data,
630
+ applied: execution.outcome === 'applied',
631
+ });
632
+ const transaction = execution.transaction;
633
+ const result = resultFor(workspaceId, data, execution.outcome);
634
+ result.status = transaction.validation.passed ? 'ok' : 'blocked';
635
+ result.changedFiles = transaction.appliedFiles.slice(0, MAX_INLINE_PATHS);
636
+ const hard = transaction.diagnostics.filter(({ severity }) => severity === 'error' || severity === 'blocker');
637
+ result.diagnostics = [...hard, ...parsed.diagnostics].slice(0, 20);
638
+ result.artifacts = autonomousResultArtifacts(execution).slice(0, MAX_INLINE_ARTIFACTS);
639
+ result.validation = transaction.validation;
640
+ result.blockers = hard.slice(0, 20).map(({ code, message, details }) => ({
641
+ code,
642
+ message,
643
+ ...(details === undefined ? {} : { details }),
644
+ }));
645
+ return result;
646
+ }
@@ -0,0 +1,28 @@
1
+ import { z } from 'zod/v4';
2
+ import { callWritePlan, replacementSchema, } from '../script-write/engine-plan.js';
3
+ const planSchema = z.object({
4
+ operation: z.enum(['add', 'update', 'remove']),
5
+ target: z.enum(['tags', 'country', 'colors', 'history', 'bookmark']),
6
+ tag: z.string(),
7
+ path: z.string(),
8
+ action: z.enum(['create', 'modify', 'delete', 'unchanged']),
9
+ edits: z.array(replacementSchema),
10
+ });
11
+ /** The plan of one file: `source` is its bytes, absent when the call creates it. */
12
+ export async function planCountryFile(path, input, source) {
13
+ const answer = await callWritePlan({
14
+ op: 'country_write.plan',
15
+ path,
16
+ input: { ...input },
17
+ ...(source === undefined ? {} : { source }),
18
+ result: planSchema,
19
+ });
20
+ return {
21
+ target: answer.result.target,
22
+ path: answer.result.path,
23
+ action: answer.result.action,
24
+ edits: answer.result.edits,
25
+ bytes: answer.bytes,
26
+ diff: answer.diff,
27
+ };
28
+ }