hoi4-agent-tools 4.20.2 → 4.21.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 (99) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/dist/bin/stdio.js +5 -2
  3. package/dist/hoi4_agent_tools/characters/write-operations.js +2 -2
  4. package/dist/hoi4_agent_tools/characters/write-plan.js +21 -205
  5. package/dist/hoi4_agent_tools/core/artifacts-engine.js +272 -0
  6. package/dist/hoi4_agent_tools/core/configuration.js +6 -0
  7. package/dist/hoi4_agent_tools/core/engine.js +77 -17
  8. package/dist/hoi4_agent_tools/core/idle-cache-lifetime.js +7 -0
  9. package/dist/hoi4_agent_tools/core/operation-tasks.js +3 -1
  10. package/dist/hoi4_agent_tools/core/transactions.js +6 -0
  11. package/dist/hoi4_agent_tools/core/workspace.js +130 -19
  12. package/dist/hoi4_agent_tools/decision/write-operations.js +7 -8
  13. package/dist/hoi4_agent_tools/decision/write-plan.js +25 -245
  14. package/dist/hoi4_agent_tools/doctrine/write-operations.js +2 -2
  15. package/dist/hoi4_agent_tools/doctrine/write-plan.js +21 -180
  16. package/dist/hoi4_agent_tools/event/graph.js +3 -3
  17. package/dist/hoi4_agent_tools/event/job-operations.js +2 -2
  18. package/dist/hoi4_agent_tools/event/write-job-operations.js +2 -2
  19. package/dist/hoi4_agent_tools/event/write-operations.js +9 -10
  20. package/dist/hoi4_agent_tools/event/write-plan.js +28 -278
  21. package/dist/hoi4_agent_tools/focus/job-operations.js +2 -2
  22. package/dist/hoi4_agent_tools/gui/assets.js +3 -13
  23. package/dist/hoi4_agent_tools/gui/job-operations.js +2 -2
  24. package/dist/hoi4_agent_tools/gui/layout.js +2 -4
  25. package/dist/hoi4_agent_tools/gui/renderer.js +2 -1
  26. package/dist/hoi4_agent_tools/gui/source-graph.js +16 -0
  27. package/dist/hoi4_agent_tools/gui/studio.js +31 -0
  28. package/dist/hoi4_agent_tools/ideas/write-operations.js +7 -8
  29. package/dist/hoi4_agent_tools/ideas/write-plan.js +24 -304
  30. package/dist/hoi4_agent_tools/map/engine-validation.js +230 -0
  31. package/dist/hoi4_agent_tools/map/job-operations.js +2 -2
  32. package/dist/hoi4_agent_tools/map/model.js +17 -3
  33. package/dist/hoi4_agent_tools/map/validation.js +12 -18
  34. package/dist/hoi4_agent_tools/mcp/server/create-modern-operations.js +9 -0
  35. package/dist/hoi4_agent_tools/mcp/server/request-lifecycle.js +4 -0
  36. package/dist/hoi4_agent_tools/mcp/server/startup-failure.js +19 -0
  37. package/dist/hoi4_agent_tools/mcp/transports/negotiated-stdio.js +24 -16
  38. package/dist/hoi4_agent_tools/probability/job-operations.js +2 -2
  39. package/dist/hoi4_agent_tools/runtime.js +85 -19
  40. package/dist/hoi4_agent_tools/schemas/transaction.js +3 -2
  41. package/dist/hoi4_agent_tools/script-write/engine-plan.js +45 -0
  42. package/dist/hoi4_agent_tools/technology/engine-graph.js +156 -0
  43. package/dist/hoi4_agent_tools/technology/job-operations.js +2 -2
  44. package/dist/hoi4_agent_tools/technology/operations.js +1 -2
  45. package/dist/hoi4_agent_tools/technology/service.js +30 -59
  46. package/dist/hoi4_agent_tools/technology/source-analysis.js +3 -1
  47. package/dist/hoi4_agent_tools/technology/write-job-operations.js +2 -2
  48. package/dist/hoi4_agent_tools/technology/write-operations.js +2 -2
  49. package/dist/hoi4_agent_tools/technology/write-plan.js +21 -207
  50. package/dist/hoi4_agent_tools/version.js +1 -1
  51. package/docs/configuration.md +11 -10
  52. package/docs/troubleshooting.md +11 -11
  53. package/engine/bin/darwin-arm64/hoi4-engine +0 -0
  54. package/engine/bin/linux-arm64/hoi4-engine +0 -0
  55. package/engine/bin/linux-x64/hoi4-engine +0 -0
  56. package/engine/bin/manifest.json +8 -8
  57. package/engine/bin/win32-x64/hoi4-engine.exe +0 -0
  58. package/npm-shrinkwrap.json +2 -2
  59. package/package.json +2 -2
  60. package/schemas/configuration.schema.json +143 -134
  61. package/schemas/continuous-focus-palette.schema.json +1 -1
  62. package/schemas/custom-weighted-pool.schema.json +1 -1
  63. package/schemas/decision-inspect-input.schema.json +1 -1
  64. package/schemas/error-log-input.schema.json +1 -1
  65. package/schemas/event-feature-manifest.schema.json +1 -1
  66. package/schemas/focus-plan.schema.json +1 -1
  67. package/schemas/focus-planning-sidecar.schema.json +1 -1
  68. package/schemas/geography-model.schema.json +1 -1
  69. package/schemas/gui-animation-source.schema.json +1 -1
  70. package/schemas/gui-helper.schema.json +1 -1
  71. package/schemas/gui-scenario.schema.json +1 -1
  72. package/schemas/helper-expansion-request.schema.json +1 -1
  73. package/schemas/helper-expansion-summary.schema.json +1 -1
  74. package/schemas/impact-inspect-input.schema.json +1 -1
  75. package/schemas/map-operation.schema.json +1 -1
  76. package/schemas/mechanic-test-input.schema.json +1 -1
  77. package/schemas/mod-index-input.schema.json +1 -1
  78. package/schemas/operation-result.schema.json +1 -1
  79. package/schemas/package-check-input.schema.json +1 -1
  80. package/schemas/package-manifest.schema.json +1 -1
  81. package/schemas/probability-analysis-result.schema.json +1 -1
  82. package/schemas/probability-compare-input.schema.json +1 -1
  83. package/schemas/probability-evaluate-input.schema.json +1 -1
  84. package/schemas/probability-inspect-input.schema.json +1 -1
  85. package/schemas/probability-render-input.schema.json +1 -1
  86. package/schemas/probability-scenario-set.schema.json +1 -1
  87. package/schemas/probability-sequence-input.schema.json +1 -1
  88. package/schemas/probability-simulate-input.schema.json +1 -1
  89. package/schemas/probability-sweep-input.schema.json +1 -1
  90. package/schemas/reference-context-input.schema.json +1 -1
  91. package/schemas/reference-read-input.schema.json +1 -1
  92. package/schemas/reference-search-input.schema.json +1 -1
  93. package/schemas/reference-sheets.schema.json +1 -1
  94. package/schemas/scenario-suite.schema.json +1 -1
  95. package/schemas/scenario-test-input.schema.json +1 -1
  96. package/schemas/script-validate-input.schema.json +1 -1
  97. package/schemas/shared-scenario.schema.json +1 -1
  98. package/schemas/source-lookup-input.schema.json +1 -1
  99. package/server.json +2 -2
@@ -1,103 +1,22 @@
1
- import { indentedBody, lineIndent } from '../core/block-edit.js';
2
- import { hasBlockingDiagnostics } from '../core/diagnostics.js';
3
- import { DIFF_CONTEXT_LINES, unifiedTextDiff } from '../core/diff.js';
4
- import { ServiceError } from '../core/result.js';
5
- import { applyReplacements, assignments, parseClausewitz, } from '../core/source/index.js';
6
- const ID_PATTERN = /^[A-Za-z_][A-Za-z0-9_.-]*$/u;
7
- function fail(code, message, details) {
8
- throw new ServiceError(code, message, details);
9
- }
10
- /** Every `ideas = { <category> = { <id> = { ... } } }` definition of the document. */
11
- function definitions(document) {
12
- const found = [];
13
- for (const ideas of assignments(document.root, 'ideas')) {
14
- if (ideas.value.type !== 'block')
15
- continue;
16
- for (const category of assignments(ideas.value)) {
17
- if (category.value.type !== 'block')
18
- continue;
19
- for (const idea of assignments(category.value)) {
20
- if (idea.value.type !== 'block')
21
- continue;
22
- found.push({
23
- idea,
24
- category,
25
- categoryBlock: category.value,
26
- });
27
- }
28
- }
29
- }
30
- return found;
31
- }
32
- function categoryBlocks(document) {
33
- return assignments(document.root, 'ideas').flatMap((ideas) => ideas.value.type === 'block'
34
- ? assignments(ideas.value).filter(({ value }) => value.type === 'block')
35
- : []);
36
- }
37
- /** One level of indentation, read from the file's own ideas, tabs when it has none. */
38
- function indentUnit(document, located) {
39
- for (const { idea, category } of located) {
40
- const outer = lineIndent(document.text, category.start);
41
- const inner = lineIndent(document.text, idea.start);
42
- if (inner.length > outer.length && inner.startsWith(outer))
43
- return inner.slice(outer.length);
44
- }
45
- return '\t';
46
- }
47
- /** The body, checked on its own as the block it will become. */
48
- function assertBodyIsOneBlock(id, body) {
49
- const probe = parseClausewitz(Buffer.from(`${id} = {\n${body}\n}\n`, 'utf8'), 'idea-body');
50
- const only = probe.root.entries;
51
- const single = only.length === 1 && only[0]?.type === 'assignment' && only[0].key.value === id;
52
- if (hasBlockingDiagnostics(probe.diagnostics) || !single || only[0]?.type !== 'assignment')
53
- fail('IDEA_WRITE_BODY_INVALID', 'The body must be the text between the braces of one idea: balanced braces and no definition of its own', { diagnosticCodes: probe.diagnostics.map(({ code }) => code) });
54
- if (only[0].value.type !== 'block' || only[0].value.entries.length === 0)
55
- fail('IDEA_WRITE_BODY_INVALID', 'The body of an idea cannot be empty');
56
- }
57
- function definitionTexts(document, skip) {
58
- const byKey = new Map();
59
- for (const { idea, category } of definitions(document)) {
60
- if (idea.start === skip?.start)
61
- continue;
62
- const key = `${category.key.value}:${idea.key.value}`;
63
- byKey.set(key, [...(byKey.get(key) ?? []), document.text.slice(idea.start, idea.end)]);
64
- }
65
- return byKey;
66
- }
67
- /**
68
- * The edit that adds a category block holding the new idea to the file's single `ideas` block, for
69
- * `createCategory: true`.
70
- */
71
- function categoryCreation(document, input, unit) {
72
- const wanted = input.category;
73
- if (!ID_PATTERN.test(wanted))
74
- fail('IDEA_WRITE_CATEGORY_INVALID', `${JSON.stringify(wanted)} is not a valid category name`, {
75
- category: wanted,
76
- });
77
- const text = document.text;
78
- const newline = document.newline;
79
- const ideasBlocks = assignments(document.root, 'ideas').filter(({ value }) => value.type === 'block');
80
- if (ideasBlocks.length !== 1)
81
- fail('IDEA_WRITE_LAYOUT_UNSUPPORTED', ideasBlocks.length === 0
82
- ? 'The file has no ideas block to put a new category in'
83
- : `The file has ${ideasBlocks.length} ideas blocks, so the new category has no single place`, { blocks: ideasBlocks.length });
84
- const ideas = ideasBlocks[0];
85
- const block = ideas.value;
86
- const close = block.close;
87
- if (close === undefined)
88
- fail('IDEA_WRITE_LAYOUT_UNSUPPORTED', 'The ideas block has no closing brace');
89
- const closeLineStart = text.lastIndexOf('\n', close.start - 1) + 1;
90
- if (!/^[ \t]*$/u.test(text.slice(closeLineStart, close.start)))
91
- fail('IDEA_WRITE_LAYOUT_UNSUPPORTED', 'The closing brace of the ideas block shares its line with other text', { line: close.line });
92
- const categoryIndent = lineIndent(text, ideas.start) + unit;
93
- const ideaIndent = categoryIndent + unit;
94
- const ideaText = `${ideaIndent}${input.id} = {${newline}${indentedBody(input.body, ideaIndent + unit, newline)}${newline}${ideaIndent}}${newline}`;
95
- return {
96
- start: closeLineStart,
97
- end: closeLineStart,
98
- text: `${block.entries.length > 0 ? newline : ''}${categoryIndent}${wanted} = {${newline}${ideaText}${categoryIndent}}${newline}`,
99
- description: `add ${input.id} in the new category ${wanted}`,
100
- };
1
+ import { z } from 'zod/v4';
2
+ import { callSourceQuery, callWritePlan, replacementSchema, } from '../script-write/engine-plan.js';
3
+ const planSchema = z.object({
4
+ operation: z.enum(['add', 'replace', 'remove']),
5
+ id: z.string(),
6
+ category: z.string(),
7
+ path: z.string(),
8
+ edit: replacementSchema,
9
+ untouchedDefinitions: z.number().int().nonnegative(),
10
+ });
11
+ async function plan(path, input, source) {
12
+ const answer = await callWritePlan({
13
+ op: 'idea_write.plan',
14
+ path,
15
+ input: { ...input },
16
+ ...(source === undefined ? {} : { source }),
17
+ result: planSchema,
18
+ });
19
+ return { ...answer.result, text: answer.text, bytes: answer.bytes, diff: answer.diff };
101
20
  }
102
21
  /**
103
22
  * The plan that creates a new `common/ideas` file holding one new idea in one category, for
@@ -105,212 +24,13 @@ function categoryCreation(document, input, unit) {
105
24
  * game's own ideas files do.
106
25
  */
107
26
  export function planNewIdeaFile(path, input) {
108
- if (!ID_PATTERN.test(input.id))
109
- fail('IDEA_WRITE_ID_INVALID', `${JSON.stringify(input.id)} is not a valid idea id`, {
110
- id: input.id,
111
- });
112
- if (input.operation !== 'add')
113
- fail('IDEA_WRITE_FILE_NOT_FOUND', `${path} does not exist, and only add can create a file`);
114
- if (input.category === undefined || !ID_PATTERN.test(input.category))
115
- fail('IDEA_WRITE_CATEGORY_REQUIRED', 'a new file needs the category block the idea goes in');
116
- if (input.body === undefined || input.body.trim() === '')
117
- fail('IDEA_WRITE_BODY_REQUIRED', 'add needs the body of the idea');
118
- assertBodyIsOneBlock(input.id, input.body);
119
- const text = [
120
- 'ideas = {',
121
- `\t${input.category} = {`,
122
- `\t\t${input.id} = {`,
123
- indentedBody(input.body, '\t\t\t', '\n'),
124
- '\t\t}',
125
- '\t}',
126
- '}',
127
- '',
128
- ].join('\n');
129
- const written = parseClausewitz(Buffer.from(text, 'utf8'), path);
130
- if (hasBlockingDiagnostics(written.diagnostics))
131
- fail('IDEA_WRITE_RESULT_INVALID', 'The new file would have syntax errors', {
132
- diagnosticCodes: written.diagnostics.map(({ code }) => code),
133
- });
134
- return {
135
- operation: 'add',
136
- id: input.id,
137
- category: input.category,
138
- path,
139
- text,
140
- bytes: Buffer.from(text, 'utf8'),
141
- edit: {
142
- start: 0,
143
- end: 0,
144
- text,
145
- description: `create ${path} with ${input.id}`,
146
- },
147
- diff: unifiedTextDiff('', text, `a/${path}`, `b/${path}`, { context: DIFF_CONTEXT_LINES }),
148
- untouchedDefinitions: 0,
149
- };
27
+ return plan(path, input, undefined);
150
28
  }
151
29
  export function planIdeaWrite(source, input) {
152
- if (!ID_PATTERN.test(input.id))
153
- fail('IDEA_WRITE_ID_INVALID', `${JSON.stringify(input.id)} is not a valid idea id`, {
154
- id: input.id,
155
- });
156
- if (input.operation === 'remove' && input.body !== undefined)
157
- fail('IDEA_WRITE_BODY_UNEXPECTED', 'remove takes no body');
158
- if (input.operation !== 'remove' && (input.body === undefined || input.body.trim() === ''))
159
- fail('IDEA_WRITE_BODY_REQUIRED', `${input.operation} needs the body of the idea`);
160
- const document = parseClausewitz(source.bytes, source.path);
161
- if (hasBlockingDiagnostics(document.diagnostics))
162
- fail('IDEA_WRITE_SOURCE_INVALID', 'The source has syntax errors and cannot be edited safely', {
163
- path: source.path,
164
- diagnosticCodes: document.diagnostics.map(({ code }) => code),
165
- });
166
- const text = document.text;
167
- const newline = document.newline;
168
- const located = definitions(document);
169
- if (input.body !== undefined)
170
- assertBodyIsOneBlock(input.id, input.body);
171
- const unit = indentUnit(document, located);
172
- const existing = located.filter(({ idea }) => idea.key.value === input.id);
173
- let edit;
174
- let category;
175
- let skip;
176
- if (input.operation === 'add') {
177
- if (existing.length > 0)
178
- fail('IDEA_WRITE_DUPLICATE_ID', `${input.id} is already defined in this file`, {
179
- id: input.id,
180
- category: existing[0]?.category.key.value,
181
- line: existing[0]?.idea.key.token.line,
182
- });
183
- if (input.category === undefined)
184
- fail('IDEA_WRITE_CATEGORY_REQUIRED', 'add needs the category block the idea goes in');
185
- const wanted = input.category;
186
- const matching = categoryBlocks(document).filter(({ key }) => key.value === wanted);
187
- if (matching.length === 0 && input.createCategory !== true)
188
- fail('IDEA_WRITE_CATEGORY_NOT_FOUND', `The file has no ${wanted} category; pass createCategory: true to create it`, {
189
- category: wanted,
190
- categories: [...new Set(categoryBlocks(document).map(({ key }) => key.value))],
191
- });
192
- if (matching.length > 1)
193
- fail('IDEA_WRITE_CATEGORY_AMBIGUOUS', `The file has ${matching.length} ${wanted} categories`, {
194
- category: wanted,
195
- lines: matching.map(({ key }) => key.token.line),
196
- });
197
- if (matching.length === 0) {
198
- edit = categoryCreation(document, input, unit);
199
- }
200
- else {
201
- const target = matching[0];
202
- const block = target.value;
203
- const close = block.close;
204
- if (close === undefined)
205
- fail('IDEA_WRITE_LAYOUT_UNSUPPORTED', `The ${wanted} category has no closing brace`);
206
- const closeLineStart = text.lastIndexOf('\n', close.start - 1) + 1;
207
- if (!/^[ \t]*$/u.test(text.slice(closeLineStart, close.start)))
208
- fail('IDEA_WRITE_LAYOUT_UNSUPPORTED', `The closing brace of ${wanted} shares its line with other text, so the new idea has no line to go on`, { category: wanted, line: close.line });
209
- const categoryIndent = lineIndent(text, target.start);
210
- const ideaIndent = categoryIndent + unit;
211
- const hasSiblings = block.entries.length > 0;
212
- const ideaText = `${ideaIndent}${input.id} = {${newline}${indentedBody(input.body, ideaIndent + unit, newline)}${newline}${ideaIndent}}${newline}`;
213
- edit = {
214
- start: closeLineStart,
215
- end: closeLineStart,
216
- text: `${hasSiblings ? newline : ''}${ideaText}`,
217
- description: `add ${input.id} to ${wanted}`,
218
- };
219
- }
220
- category = wanted;
221
- }
222
- else {
223
- if (existing.length === 0)
224
- fail('IDEA_WRITE_NOT_FOUND', `${input.id} is not defined in this file`, { id: input.id });
225
- if (existing.length > 1)
226
- fail('IDEA_WRITE_DUPLICATE_ID', `${input.id} is defined ${existing.length} times in this file`, {
227
- id: input.id,
228
- lines: existing.map(({ idea }) => idea.key.token.line),
229
- });
230
- const found = existing[0];
231
- category = found.category.key.value;
232
- if (input.category !== undefined && input.category !== category)
233
- fail('IDEA_WRITE_CATEGORY_MISMATCH', `${input.id} is in ${category}, and moving an idea to another category is not supported`, { id: input.id, category });
234
- skip = found.idea;
235
- const ideaIndent = lineIndent(text, found.idea.start);
236
- if (input.operation === 'replace') {
237
- edit = {
238
- start: found.idea.start,
239
- end: found.idea.end,
240
- text: `${input.id} = {${newline}${indentedBody(input.body, ideaIndent + unit, newline)}${newline}${ideaIndent}}`,
241
- description: `replace ${input.id}`,
242
- };
243
- }
244
- else {
245
- const lineStart = text.lastIndexOf('\n', found.idea.start - 1) + 1;
246
- const lineEndAt = text.indexOf('\n', found.idea.end);
247
- const lineEnd = lineEndAt === -1 ? text.length : lineEndAt + 1;
248
- const alone = /^[ \t]*$/u.test(text.slice(lineStart, found.idea.start)) &&
249
- /^[ \t]*\r?$/u.test(text.slice(found.idea.end, lineEndAt === -1 ? text.length : lineEndAt));
250
- if (!alone) {
251
- edit = {
252
- start: found.idea.start,
253
- end: found.idea.end,
254
- text: '',
255
- description: `remove ${input.id}`,
256
- };
257
- }
258
- else {
259
- // A blank line that only separated this idea from the one before it goes with it.
260
- const before = text.slice(0, lineStart);
261
- const blankBefore = /(?:^|\n)[ \t]*\r?\n$/u.test(before) && before.length > 0;
262
- const after = text.slice(lineEnd);
263
- const nextIsBlankOrClose = /^[ \t]*(?:\r?\n|\})/u.test(after) || after === '';
264
- let start = lineStart;
265
- if (blankBefore && nextIsBlankOrClose) {
266
- const previousLineStart = before.lastIndexOf('\n', before.length - 2) + 1;
267
- start = previousLineStart;
268
- }
269
- edit = { start, end: lineEnd, text: '', description: `remove ${input.id}` };
270
- }
271
- }
272
- }
273
- const bytes = applyReplacements(document, [edit]);
274
- const after = text.slice(0, edit.start) + edit.text + text.slice(edit.end);
275
- const written = parseClausewitz(bytes, source.path);
276
- if (hasBlockingDiagnostics(written.diagnostics))
277
- fail('IDEA_WRITE_RESULT_INVALID', 'The edit would leave the file with syntax errors', {
278
- diagnosticCodes: written.diagnostics.map(({ code }) => code),
279
- });
280
- const before = definitionTexts(document, skip);
281
- const afterTexts = definitionTexts(written, undefined);
282
- let untouched = 0;
283
- for (const [key, texts] of before) {
284
- const now = afterTexts.get(key) ?? [];
285
- for (const textOfIdea of texts)
286
- if (now.includes(textOfIdea))
287
- untouched += 1;
288
- else
289
- fail('IDEA_WRITE_RESULT_INVALID', `The edit would change ${key}, which it must not touch`, {
290
- key,
291
- });
292
- }
293
- const now = written.text;
294
- if (now !== after)
295
- fail('IDEA_WRITE_RESULT_INVALID', 'The written file does not match the planned edit');
296
- return {
297
- operation: input.operation,
298
- id: input.id,
299
- category,
300
- path: source.path,
301
- text: after,
302
- bytes,
303
- edit,
304
- diff: unifiedTextDiff(text, after, `a/${source.path}`, `b/${source.path}`, {
305
- context: DIFF_CONTEXT_LINES,
306
- }),
307
- untouchedDefinitions: untouched,
308
- };
30
+ return plan(source.path, input, source.bytes);
309
31
  }
310
32
  /** The category blocks of a `common/ideas` file, or none when the file cannot be parsed. */
311
- export function ideaCategories(source) {
312
- const document = parseClausewitz(source.bytes, source.path);
313
- if (hasBlockingDiagnostics(document.diagnostics))
314
- return [];
315
- return [...new Set(categoryBlocks(document).map(({ key }) => key.value))];
33
+ export async function ideaCategories(source) {
34
+ const answer = await callSourceQuery('idea_write.categories', source.path, source.bytes, z.object({ categories: z.array(z.string()) }));
35
+ return answer.categories;
316
36
  }
@@ -0,0 +1,230 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import { closeSync, existsSync, mkdtempSync, openSync, 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 { callEngineOperation } from '../core/engine-operation.js';
7
+ import { locateEngineBinary } from '../core/engine-client.js';
8
+ import { ServiceError } from '../core/result.js';
9
+ import { PACKAGE_VERSION } from '../version.js';
10
+ /**
11
+ * Map validation on the engine (`map.validate`, ADR 0089 step 6, packet P13a). The engine builds
12
+ * its own map index from the scanned files of the request. A file scanned from disk goes as its
13
+ * metadata and absolute path (the scan has already checked the path against its roots): the
14
+ * engine reads it and refuses it (`MAP_SOURCE_STALE`) when its size or SHA-256 changed since the
15
+ * scan. A file held only in memory (a proposed edit, `virtual://`) goes as bytes in the payload.
16
+ * The answer comes back in the payload (`{format:'json'}`), so a large finding list never meets
17
+ * the header limit. A missing engine, an
18
+ * engine without the op or an answer out of shape is `ENGINE_UNAVAILABLE`; nothing falls back to
19
+ * TypeScript.
20
+ *
21
+ * `validateMapAsync` calls the resident engine. `validateMap` is synchronous, because the map
22
+ * model and its callers are, so it runs one `hoi4-engine serve` over request and answer files: a
23
+ * synchronous call that piped hundreds of megabytes hung on macOS runners (see engine-raster.ts).
24
+ */
25
+ export const MAP_VALIDATE_OP = 'map.validate';
26
+ /** The engine's request payload ceiling for in-memory files; a larger request is refused, never cut. */
27
+ export const MAP_ENGINE_PAYLOAD_LIMIT = 256 * 1024 * 1024;
28
+ const MAP_VALIDATE_TIMEOUT_MS = 600_000;
29
+ const location = z.looseObject({ path: z.string() });
30
+ const answerHeaderSchema = z.object({ format: z.literal('json') }).strict();
31
+ const diagnosticSchema = z
32
+ .object({
33
+ code: z.string(),
34
+ severity: z.enum(['info', 'warning', 'error', 'blocker']),
35
+ category: z.enum([
36
+ 'syntax',
37
+ 'reference',
38
+ 'layout',
39
+ 'design',
40
+ 'rendering',
41
+ 'security',
42
+ 'validation',
43
+ 'map',
44
+ 'configuration',
45
+ ]),
46
+ message: z.string(),
47
+ location: location.optional(),
48
+ related: z.array(location).optional(),
49
+ operationId: z.string().optional(),
50
+ details: z.record(z.string(), z.unknown()).optional(),
51
+ })
52
+ .strict();
53
+ export const mapValidateAnswerSchema = z
54
+ .object({
55
+ passed: z.boolean(),
56
+ diagnostics: z.array(diagnosticSchema),
57
+ checks: z.array(z.object({ id: z.string(), passed: z.boolean(), message: z.string() }).strict()),
58
+ baselineFingerprint: z.string().optional(),
59
+ })
60
+ .strict();
61
+ /** The request body and payload: every scanned file of the index, and the options. */
62
+ export function mapValidateRequest(index, options = {}) {
63
+ const chunks = [];
64
+ const files = index.sourceFiles.map((file) => {
65
+ const common = {
66
+ displayPath: file.displayPath,
67
+ relativePath: file.relativePath,
68
+ rootKind: file.rootKind,
69
+ loadOrder: file.loadOrder,
70
+ size: file.size,
71
+ sha256: file.sha256,
72
+ };
73
+ // A scanned file is read by the engine; one with no real path (a proposed edit) travels.
74
+ if (path.isAbsolute(file.absolutePath))
75
+ return { ...common, path: file.absolutePath };
76
+ chunks.push(file.bytes);
77
+ return { ...common, length: file.bytes.length };
78
+ });
79
+ const baselineBitmap = options.baseline?.provinceBitmap?.bytes;
80
+ if (baselineBitmap !== undefined)
81
+ chunks.push(baselineBitmap);
82
+ const body = {
83
+ files,
84
+ sourceRoots: index.sourceRoots,
85
+ toolVersion: PACKAGE_VERSION,
86
+ options: {
87
+ ...(options.operationId === undefined ? {} : { operationId: options.operationId }),
88
+ ...(options.expectedChangedBounds === undefined
89
+ ? {}
90
+ : { expectedChangedBounds: options.expectedChangedBounds }),
91
+ ...(options.baseline === undefined
92
+ ? {}
93
+ : {
94
+ baseline: {
95
+ stateIds: [...options.baseline.statesById.keys()],
96
+ ...(baselineBitmap === undefined
97
+ ? {}
98
+ : { provinceBitmapLength: baselineBitmap.length }),
99
+ },
100
+ }),
101
+ includeBaselineDiagnostics: options.includeBaselineDiagnostics === true,
102
+ ...(options.diagnosticLimit === undefined
103
+ ? {}
104
+ : { diagnosticLimit: options.diagnosticLimit }),
105
+ ...(options.edgeMode === undefined ? {} : { edgeMode: options.edgeMode }),
106
+ },
107
+ };
108
+ const bytes = chunks.reduce((sum, chunk) => sum + chunk.length, 0);
109
+ if (bytes > MAP_ENGINE_PAYLOAD_LIMIT)
110
+ throw new ServiceError('MAP_ENGINE_PAYLOAD_LIMIT', `The map's scanned files hold ${bytes} bytes, above the ${MAP_ENGINE_PAYLOAD_LIMIT}-byte limit of one engine request; the map is not validated in part`, { bytes, limit: MAP_ENGINE_PAYLOAD_LIMIT, files: files.length });
111
+ return { body, payload: Buffer.concat(chunks) };
112
+ }
113
+ function result(answer) {
114
+ return {
115
+ passed: answer.passed,
116
+ diagnostics: answer.diagnostics,
117
+ checks: answer.checks,
118
+ };
119
+ }
120
+ /** `map.validate` on the resident engine. */
121
+ export async function engineValidateMapAsync(index, options = {}) {
122
+ options.signal?.throwIfAborted();
123
+ const { body, payload } = mapValidateRequest(index, options);
124
+ const answer = await callEngineOperation({
125
+ op: MAP_VALIDATE_OP,
126
+ body,
127
+ payload,
128
+ result: answerHeaderSchema,
129
+ options: {
130
+ timeoutMs: MAP_VALIDATE_TIMEOUT_MS,
131
+ ...(options.signal === undefined ? {} : { signal: options.signal }),
132
+ },
133
+ });
134
+ return result(parseAnswerPayload(answer.payload));
135
+ }
136
+ function parseAnswerPayload(payload) {
137
+ let json;
138
+ try {
139
+ json = JSON.parse(payload.toString('utf8'));
140
+ }
141
+ catch {
142
+ json = undefined;
143
+ }
144
+ const parsed = mapValidateAnswerSchema.safeParse(json);
145
+ if (!parsed.success)
146
+ throw new ServiceError('ENGINE_UNAVAILABLE', 'hoi4-engine map.validate answered out of shape', {
147
+ op: MAP_VALIDATE_OP,
148
+ reason: 'invalid_response',
149
+ });
150
+ return parsed.data;
151
+ }
152
+ const frameSchema = z.union([
153
+ z.object({ id: z.number(), ok: z.literal(true), result: z.unknown() }).loose(),
154
+ z
155
+ .object({
156
+ id: z.number(),
157
+ ok: z.literal(false),
158
+ error: z.looseObject({ code: z.string(), message: z.string() }),
159
+ })
160
+ .loose(),
161
+ ]);
162
+ const TOOL_CODE = /^[A-Z][A-Z0-9_]*$/u;
163
+ /** `map.validate` on a one-shot engine, for the synchronous callers. */
164
+ export function engineValidateMapSync(index, options = {}) {
165
+ return result(engineMapOperationSync(MAP_VALIDATE_OP, mapValidateRequest(index, options), answerHeaderSchema, parseAnswerPayload));
166
+ }
167
+ /** One registered engine operation on a one-shot `hoi4-engine serve`, over files. */
168
+ export function engineMapOperationSync(op, request, schema, fromPayload) {
169
+ const located = locateEngineBinary();
170
+ if (!('path' in located))
171
+ throw new ServiceError('ENGINE_UNAVAILABLE', located.message, { reason: located.reason });
172
+ const header = `${JSON.stringify({ ...request.body, id: 1, op, payload: request.payload.length })}\n`;
173
+ const script = /\.(?:c|m)?js$/iu.test(located.path);
174
+ const directory = mkdtempSync(path.join(tmpdir(), 'hoi4-map-validate-'));
175
+ const inputPath = path.join(directory, 'request');
176
+ const outputPath = path.join(directory, 'answer');
177
+ let child;
178
+ let answer;
179
+ try {
180
+ writeFileSync(inputPath, Buffer.concat([Buffer.from(header, 'utf8'), request.payload]));
181
+ const input = openSync(inputPath, 'r');
182
+ const output = openSync(outputPath, 'w');
183
+ try {
184
+ child = spawnSync(script ? process.execPath : located.path, script ? [located.path, 'serve'] : ['serve'], {
185
+ stdio: [input, output, 'pipe'],
186
+ timeout: MAP_VALIDATE_TIMEOUT_MS,
187
+ windowsHide: true,
188
+ shell: false,
189
+ });
190
+ }
191
+ finally {
192
+ closeSync(input);
193
+ closeSync(output);
194
+ }
195
+ answer = existsSync(outputPath) ? readFileSync(outputPath) : Buffer.alloc(0);
196
+ }
197
+ finally {
198
+ rmSync(directory, { recursive: true, force: true });
199
+ }
200
+ const unavailable = (message, reason) => new ServiceError('ENGINE_UNAVAILABLE', message, { op, reason });
201
+ if (child.error !== undefined)
202
+ throw unavailable(`hoi4-engine ${op}: ${child.error.message}`, 'spawn_failed');
203
+ const newline = answer.indexOf(0x0a);
204
+ if (newline < 0)
205
+ throw unavailable(`hoi4-engine ${op} gave no answer (exit ${child.status ?? 'none'}): ${child.stderr.toString('utf8').slice(-300)}`, 'invalid_output');
206
+ let parsedFrame;
207
+ try {
208
+ parsedFrame = JSON.parse(answer.subarray(0, newline).toString('utf8'));
209
+ }
210
+ catch {
211
+ throw unavailable(`hoi4-engine ${op} answered an unreadable frame`, 'invalid_output');
212
+ }
213
+ const frame = frameSchema.safeParse(parsedFrame);
214
+ if (!frame.success)
215
+ throw unavailable(`hoi4-engine ${op} answered an unknown frame`, 'invalid_output');
216
+ if (!frame.data.ok) {
217
+ const { code, message, ...details } = frame.data.error;
218
+ if (TOOL_CODE.test(code))
219
+ throw new ServiceError(code, message, details);
220
+ throw unavailable(message, code);
221
+ }
222
+ const parsed = schema.safeParse(frame.data.result);
223
+ if (!parsed.success)
224
+ throw unavailable(`hoi4-engine ${op} answered out of shape`, 'invalid_response');
225
+ const announced = parsedFrame.payload;
226
+ const length = typeof announced === 'number' && Number.isSafeInteger(announced) ? announced : 0;
227
+ if (length < 0 || answer.length < newline + 1 + length)
228
+ throw unavailable(`hoi4-engine ${op} answered a short payload`, 'invalid_output');
229
+ return fromPayload(answer.subarray(newline + 1, newline + 1 + length));
230
+ }
@@ -1,5 +1,5 @@
1
1
  import { z } from 'zod/v4';
2
- import { IdleCacheLifetime } from '../core/idle-cache-lifetime.js';
2
+ import { idleCacheLifetime } from '../core/idle-cache-lifetime.js';
3
3
  import { errorResult, toolResult } from '../core/operation-result.js';
4
4
  import { ServiceError } from '../core/result.js';
5
5
  import { MAP_VIEW_FIELDS, mapInspectRequestSchema, mapRewriteRequestSchema, } from '../schemas/map-requests.js';
@@ -9,7 +9,7 @@ const wireResult = z.record(z.string(), z.json());
9
9
  /** Registers read-only map operations without invoking transport handlers. */
10
10
  export function registerMapJobs(operations, engine) {
11
11
  const nudger = new AgentNudger(engine);
12
- const lifetime = new IdleCacheLifetime(() => engine.releaseScanCaches());
12
+ const lifetime = idleCacheLifetime(engine, () => engine.releaseScanCaches());
13
13
  function register(name, schema, normalize, execute) {
14
14
  operations.registerRead(name, schema, async (input, context) => {
15
15
  const release = lifetime.begin();
@@ -24,12 +24,19 @@ const MAP_TEXT_FIELD_LIMIT = 10_000;
24
24
  const MAP_MODEL_MAX_SCRIPT_FILES = 5_000;
25
25
  const MAP_MODEL_MAX_SOURCE_TOKENS = 1_000_000;
26
26
  const MAP_MODEL_MAX_RECORDS = 500_000;
27
+ /**
28
+ * Building, unit and weather positions have their own ceiling (issue 172): they are fixed-size
29
+ * rows, and a mod with large position tables (Old World Blues, 533,984 records) exceeded the
30
+ * domain-record ceiling with them. The engine model (`hoi4-map`) uses the same ceilings.
31
+ */
32
+ export const MAP_MODEL_MAX_POSITION_RECORDS = 2_000_000;
27
33
  const MAP_MODEL_MAX_LOCALISATION_RECORDS = 2_000_000;
28
34
  const MAP_MODEL_MAX_MEMBERSHIP_EDGES = 1_000_000;
29
35
  class MapModelBudget {
30
36
  #documents = new Set();
31
37
  #tokens = 0;
32
38
  #records = 0;
39
+ #positionRecords = 0;
33
40
  #localisationRecords = 0;
34
41
  #membershipEdges = 0;
35
42
  assertScriptFiles(count) {
@@ -52,6 +59,13 @@ class MapModelBudget {
52
59
  this.block('domain records', this.#records, MAP_MODEL_MAX_RECORDS);
53
60
  }
54
61
  }
62
+ addPositionRecords(count) {
63
+ this.#positionRecords += count;
64
+ if (!Number.isSafeInteger(this.#positionRecords) ||
65
+ this.#positionRecords > MAP_MODEL_MAX_POSITION_RECORDS) {
66
+ this.block('position records', this.#positionRecords, MAP_MODEL_MAX_POSITION_RECORDS);
67
+ }
68
+ }
55
69
  addLocalisationRecords(count) {
56
70
  this.#localisationRecords += count;
57
71
  if (!Number.isSafeInteger(this.#localisationRecords) ||
@@ -1367,17 +1381,17 @@ export class MapWorkspaceIndex {
1367
1381
  const buildingsFile = mapFile(this.activeFiles, 'buildings.txt', this.sourceRoots.map);
1368
1382
  this.buildingPositions =
1369
1383
  buildingsFile === undefined ? [] : parseBuildingPositions(buildingsFile, this.diagnostics);
1370
- modelBudget.addRecords(this.buildingPositions.length);
1384
+ modelBudget.addPositionRecords(this.buildingPositions.length);
1371
1385
  const unitstacksFile = mapFile(this.activeFiles, 'unitstacks.txt', this.sourceRoots.map);
1372
1386
  const positionsFile = mapFile(this.activeFiles, defaultMapSelectorValue(this.defaultMapFile, 'positions', 'positions.txt'), this.sourceRoots.map);
1373
1387
  this.unitPositions = [unitstacksFile, positionsFile]
1374
1388
  .filter((file) => file !== undefined && file.size > 0)
1375
1389
  .flatMap((file) => parseUnitPositions(file, this.diagnostics));
1376
- modelBudget.addRecords(this.unitPositions.length);
1390
+ modelBudget.addPositionRecords(this.unitPositions.length);
1377
1391
  const weatherFile = mapFile(this.activeFiles, 'weatherpositions.txt', this.sourceRoots.map);
1378
1392
  this.weatherPositions =
1379
1393
  weatherFile === undefined ? [] : parseWeatherPositions(weatherFile, this.diagnostics);
1380
- modelBudget.addRecords(this.weatherPositions.length);
1394
+ modelBudget.addPositionRecords(this.weatherPositions.length);
1381
1395
  this.entityLocators = this.activeFiles.all
1382
1396
  .filter((file) => (file.rootKind === 'mod' || file.rootKind === 'fixture') &&
1383
1397
  normalizedPath(file.relativePath).endsWith('.asset') &&