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,13 +1,11 @@
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';
1
+ import { z } from 'zod/v4';
2
+ import { callSourceQuery, callWritePlan, replacementSchema, } from '../script-write/engine-plan.js';
6
3
  /**
7
4
  * The edit behind `hoi4.event_write` (issue 159): add, replace or remove one event block of an
8
- * `events/*.txt` file and nothing else. Every byte outside the touched block, the other events,
9
- * unrelated top-level entries, comments, the newline style and the encoding, comes back exactly as it
10
- * was read, and a layout the edit cannot place safely is refused with the reason, not guessed.
5
+ * `events/*.txt` file and nothing else. The engine plans it (`hoi4-script-write`, ADR 0089): every
6
+ * byte outside the touched block, the other events, unrelated top-level entries, comments, the
7
+ * newline style and the encoding come back as they were read, and a layout the edit cannot place
8
+ * safely is refused with the reason, not guessed.
11
9
  */
12
10
  export const EVENT_KINDS = [
13
11
  'country_event',
@@ -20,108 +18,24 @@ export const EVENT_ID_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*\.[0-9]+$/u;
20
18
  export function namespaceOf(id) {
21
19
  return id.slice(0, id.indexOf('.'));
22
20
  }
23
- function fail(code, message, details) {
24
- throw new ServiceError(code, message, details);
25
- }
26
- function isKind(key) {
27
- return EVENT_KINDS.includes(key);
28
- }
29
- /** Every top-level event block of the document that has an `id`. */
30
- function definitions(document) {
31
- const found = [];
32
- for (const event of assignments(document.root)) {
33
- const kind = event.key.value;
34
- if (!isKind(kind) || event.value.type !== 'block')
35
- continue;
36
- const id = assignments(event.value, 'id')[0];
37
- if (id?.value.type === 'scalar')
38
- found.push({ event, kind, id: id.value.value });
39
- }
40
- return found;
41
- }
42
- function namespaces(document) {
43
- return assignments(document.root, 'add_namespace');
44
- }
45
- /** One level of indentation, read from the file's own events, tabs when it has none. */
46
- function indentUnit(located, text) {
47
- for (const { event } of located) {
48
- if (event.value.type !== 'block')
49
- continue;
50
- const first = event.value.entries[0];
51
- if (first === undefined)
52
- continue;
53
- const inner = lineIndent(text, first.start);
54
- const outer = lineIndent(text, event.start);
55
- if (inner.length > outer.length && inner.startsWith(outer))
56
- return inner.slice(outer.length);
57
- }
58
- return '\t';
59
- }
60
- /** The body, checked on its own as the block it will become, and its own `id` when it has one. */
61
- function checkedBody(kind, id, body) {
62
- const probe = parseClausewitz(Buffer.from(`${kind} = {\n${body}\n}\n`, 'utf8'), 'event-body');
63
- const only = probe.root.entries;
64
- const single = only.length === 1 && only[0]?.type === 'assignment' && only[0].key.value === kind;
65
- if (hasBlockingDiagnostics(probe.diagnostics) || !single || only[0]?.type !== 'assignment')
66
- fail('EVENT_WRITE_BODY_INVALID', 'The body must be the text between the braces of one event: balanced braces and no definition of its own', { diagnosticCodes: probe.diagnostics.map(({ code }) => code) });
67
- if (only[0].value.type !== 'block' || only[0].value.entries.length === 0)
68
- fail('EVENT_WRITE_BODY_INVALID', 'The body of an event cannot be empty');
69
- const own = assignments(only[0].value, 'id');
70
- if (own.length > 1)
71
- fail('EVENT_WRITE_BODY_INVALID', 'The body names an id more than once');
72
- if (own[0] !== undefined && (own[0].value.type !== 'scalar' || own[0].value.value !== id))
73
- fail('EVENT_WRITE_ID_MISMATCH', `The body has its own id, which is not ${id}; leave id out of the body, the tool writes it`, { id });
74
- return own.length === 1 ? [] : [`id = ${id}`];
75
- }
76
- function definitionTexts(document, skip) {
77
- const byId = new Map();
78
- for (const { event, id } of definitions(document)) {
79
- if (event.start === skip?.start)
80
- continue;
81
- byId.set(id, [...(byId.get(id) ?? []), document.text.slice(event.start, event.end)]);
82
- }
83
- return byId;
84
- }
85
- function checkRequest(input) {
86
- if (!EVENT_ID_PATTERN.test(input.id))
87
- fail('EVENT_WRITE_ID_INVALID', `${JSON.stringify(input.id)} is not a valid event id; it is a namespace, a dot and a number, as in my_events.1`, { id: input.id });
88
- if (input.operation === 'remove' && input.body !== undefined)
89
- fail('EVENT_WRITE_BODY_UNEXPECTED', 'remove takes no body');
90
- if (input.operation !== 'remove' && (input.body === undefined || input.body.trim() === ''))
91
- fail('EVENT_WRITE_BODY_REQUIRED', `${input.operation} needs the body of the event`);
92
- if (input.operation !== 'add' && input.createNamespace === true)
93
- fail('EVENT_WRITE_NAMESPACE_UNEXPECTED', 'createNamespace applies to add only');
94
- }
95
- /** The event block text at `indent`, with `id` first. */
96
- function blockText(kind, id, body, idLine, indent, unit, newline) {
97
- const inner = indent + unit;
98
- const lines = [
99
- ...idLine.map((line) => `${inner}${line}`),
100
- indentedBody(body, inner, newline),
101
- ].join(newline);
102
- return `${indent}${kind} = {${newline}${lines}${newline}${indent}}`;
103
- }
104
- function assertWritten(document, edits, path, skip) {
105
- const bytes = applyReplacements(document, edits);
106
- const written = parseClausewitz(bytes, path);
107
- if (hasBlockingDiagnostics(written.diagnostics))
108
- fail('EVENT_WRITE_RESULT_INVALID', 'The edit would leave the file with syntax errors', {
109
- diagnosticCodes: written.diagnostics.map(({ code }) => code),
110
- });
111
- const before = definitionTexts(document, skip);
112
- const afterTexts = definitionTexts(written, undefined);
113
- let untouched = 0;
114
- for (const [id, texts] of before) {
115
- const now = afterTexts.get(id) ?? [];
116
- for (const text of texts)
117
- if (now.includes(text))
118
- untouched += 1;
119
- else
120
- fail('EVENT_WRITE_RESULT_INVALID', `The edit would change ${id}, which it must not touch`, {
121
- id,
122
- });
123
- }
124
- return { bytes, after: written.text, untouched };
21
+ const planSchema = z.object({
22
+ operation: z.enum(['add', 'replace', 'remove']),
23
+ id: z.string(),
24
+ kind: z.enum(EVENT_KINDS),
25
+ path: z.string(),
26
+ edits: z.array(replacementSchema),
27
+ untouchedDefinitions: z.number().int().nonnegative(),
28
+ namespaceAdded: z.boolean(),
29
+ });
30
+ async function plan(path, input, source) {
31
+ const answer = await callWritePlan({
32
+ op: 'event_write.plan',
33
+ path,
34
+ input: { ...input },
35
+ ...(source === undefined ? {} : { source }),
36
+ result: planSchema,
37
+ });
38
+ return { ...answer.result, text: answer.text, bytes: answer.bytes, diff: answer.diff };
125
39
  }
126
40
  /**
127
41
  * The plan that creates a new `events` file holding the namespace line and one new event, for
@@ -129,176 +43,12 @@ function assertWritten(document, edits, path, skip) {
129
43
  * own event files do.
130
44
  */
131
45
  export function planNewEventFile(path, input) {
132
- checkRequest(input);
133
- if (input.operation !== 'add')
134
- fail('EVENT_WRITE_FILE_NOT_FOUND', `${path} does not exist, and only add can create a file`);
135
- const kind = input.kind ?? 'country_event';
136
- const idLine = checkedBody(kind, input.id, input.body);
137
- const namespaceAdded = input.namespaceDeclared !== true;
138
- if (namespaceAdded && input.createNamespace !== true)
139
- fail('EVENT_WRITE_NAMESPACE_MISSING', `No mod file declares the namespace ${namespaceOf(input.id)}; pass createNamespace: true to write add_namespace`, { namespace: namespaceOf(input.id) });
140
- const text = [
141
- ...(namespaceAdded ? [`add_namespace = ${namespaceOf(input.id)}`, ''] : []),
142
- blockText(kind, input.id, input.body, idLine, '', '\t', '\n'),
143
- '',
144
- ].join('\n');
145
- const written = parseClausewitz(Buffer.from(text, 'utf8'), path);
146
- if (hasBlockingDiagnostics(written.diagnostics))
147
- fail('EVENT_WRITE_RESULT_INVALID', 'The new file would have syntax errors', {
148
- diagnosticCodes: written.diagnostics.map(({ code }) => code),
149
- });
150
- return {
151
- operation: 'add',
152
- id: input.id,
153
- kind,
154
- path,
155
- text,
156
- bytes: Buffer.from(text, 'utf8'),
157
- edits: [{ start: 0, end: 0, text, description: `create ${path} with ${input.id}` }],
158
- diff: unifiedTextDiff('', text, `a/${path}`, `b/${path}`, { context: DIFF_CONTEXT_LINES }),
159
- untouchedDefinitions: 0,
160
- namespaceAdded,
161
- };
46
+ return plan(path, input, undefined);
162
47
  }
163
48
  export function planEventWrite(source, input) {
164
- checkRequest(input);
165
- const document = parseClausewitz(source.bytes, source.path);
166
- if (hasBlockingDiagnostics(document.diagnostics))
167
- fail('EVENT_WRITE_SOURCE_INVALID', 'The source has syntax errors and cannot be edited safely', {
168
- path: source.path,
169
- diagnosticCodes: document.diagnostics.map(({ code }) => code),
170
- });
171
- const text = document.text;
172
- const newline = document.newline;
173
- const located = definitions(document);
174
- const unit = indentUnit(located, text);
175
- const existing = located.filter(({ id }) => id === input.id);
176
- const edits = [];
177
- let skip;
178
- let kind;
179
- let namespaceAdded = false;
180
- if (input.operation === 'add') {
181
- kind = input.kind ?? 'country_event';
182
- if (existing.length > 0)
183
- fail('EVENT_WRITE_DUPLICATE_ID', `${input.id} is already defined in this file`, {
184
- id: input.id,
185
- line: existing[0]?.event.key.token.line,
186
- });
187
- const idLine = checkedBody(kind, input.id, input.body);
188
- const declaredHere = namespaces(document).some(({ value }) => value.type === 'scalar' && value.value === namespaceOf(input.id));
189
- if (!declaredHere && input.namespaceDeclared !== true) {
190
- if (input.createNamespace !== true)
191
- fail('EVENT_WRITE_NAMESPACE_MISSING', `No mod file declares the namespace ${namespaceOf(input.id)}; pass createNamespace: true to write add_namespace`, { namespace: namespaceOf(input.id) });
192
- namespaceAdded = true;
193
- const lines = namespaces(document);
194
- const last = lines.at(-1);
195
- const first = document.root.entries[0];
196
- if (last !== undefined) {
197
- const lineEndAt = text.indexOf('\n', last.end);
198
- const at = lineEndAt === -1 ? text.length : lineEndAt + 1;
199
- edits.push({
200
- start: at,
201
- end: at,
202
- text: `${lineEndAt === -1 ? newline : ''}add_namespace = ${namespaceOf(input.id)}${newline}`,
203
- description: `declare the namespace ${namespaceOf(input.id)}`,
204
- });
205
- }
206
- else if (first !== undefined) {
207
- const at = text.lastIndexOf('\n', first.start - 1) + 1;
208
- edits.push({
209
- start: at,
210
- end: at,
211
- text: `add_namespace = ${namespaceOf(input.id)}${newline}${newline}`,
212
- description: `declare the namespace ${namespaceOf(input.id)}`,
213
- });
214
- }
215
- }
216
- const block = blockText(kind, input.id, input.body, idLine, '', unit, newline);
217
- const lead = text === '' ? '' : `${text.endsWith('\n') ? '' : newline}${newline}`;
218
- edits.push({
219
- start: text.length,
220
- end: text.length,
221
- text: `${lead}${block}${newline}`,
222
- description: `add ${input.id}`,
223
- });
224
- if (namespaceAdded && document.root.entries.length === 0)
225
- edits.splice(0, edits.length, {
226
- start: text.length,
227
- end: text.length,
228
- text: `${text === '' ? '' : newline}add_namespace = ${namespaceOf(input.id)}${newline}${newline}${block}${newline}`,
229
- description: `add ${input.id} and declare its namespace`,
230
- });
231
- }
232
- else {
233
- if (existing.length === 0)
234
- fail('EVENT_WRITE_NOT_FOUND', `${input.id} is not defined in this file`, { id: input.id });
235
- if (existing.length > 1)
236
- fail('EVENT_WRITE_DUPLICATE_ID', `${input.id} is defined ${existing.length} times in this file`, { id: input.id, lines: existing.map(({ event }) => event.key.token.line) });
237
- const found = existing[0];
238
- kind = found.kind;
239
- if (input.kind !== undefined && input.kind !== kind)
240
- fail('EVENT_WRITE_KIND_MISMATCH', `${input.id} is a ${kind}, and changing the kind of an event is not supported`, { id: input.id, kind });
241
- skip = found.event;
242
- if (input.operation === 'replace') {
243
- const idLine = checkedBody(kind, input.id, input.body);
244
- const indent = lineIndent(text, found.event.start);
245
- edits.push({
246
- start: found.event.start,
247
- end: found.event.end,
248
- text: blockText(kind, input.id, input.body, idLine, indent, unit, newline).slice(indent.length),
249
- description: `replace ${input.id}`,
250
- });
251
- }
252
- else {
253
- const lineStart = text.lastIndexOf('\n', found.event.start - 1) + 1;
254
- const lineEndAt = text.indexOf('\n', found.event.end);
255
- const lineEnd = lineEndAt === -1 ? text.length : lineEndAt + 1;
256
- const alone = /^[ \t]*$/u.test(text.slice(lineStart, found.event.start)) &&
257
- /^[ \t]*\r?$/u.test(text.slice(found.event.end, lineEndAt === -1 ? text.length : lineEndAt));
258
- if (!alone) {
259
- edits.push({
260
- start: found.event.start,
261
- end: found.event.end,
262
- text: '',
263
- description: `remove ${input.id}`,
264
- });
265
- }
266
- else {
267
- // A blank line that only separated this event from the one before it goes with it.
268
- const before = text.slice(0, lineStart);
269
- const blankBefore = /(?:^|\n)[ \t]*\r?\n$/u.test(before) && before.length > 0;
270
- const after = text.slice(lineEnd);
271
- const nextIsBlank = /^[ \t]*\r?(?:\n|$)/u.test(after);
272
- let start = lineStart;
273
- if (blankBefore && (nextIsBlank || after === ''))
274
- start = before.lastIndexOf('\n', before.length - 2) + 1;
275
- edits.push({ start, end: lineEnd, text: '', description: `remove ${input.id}` });
276
- }
277
- }
278
- }
279
- const { bytes, after, untouched } = assertWritten(document, edits, source.path, skip);
280
- return {
281
- operation: input.operation,
282
- id: input.id,
283
- kind,
284
- path: source.path,
285
- text: after,
286
- bytes,
287
- edits,
288
- diff: unifiedTextDiff(text, after, `a/${source.path}`, `b/${source.path}`, {
289
- context: DIFF_CONTEXT_LINES,
290
- }),
291
- untouchedDefinitions: untouched,
292
- namespaceAdded,
293
- };
49
+ return plan(source.path, input, source.bytes);
294
50
  }
295
51
  /** The ids of the events in a source, and the namespaces it declares. */
296
- export function eventFileContents(source) {
297
- const document = parseClausewitz(source.bytes, source.path);
298
- if (hasBlockingDiagnostics(document.diagnostics))
299
- return { ids: [], namespaces: [] };
300
- return {
301
- ids: definitions(document).map(({ id }) => id),
302
- namespaces: namespaces(document).flatMap(({ value }) => value.type === 'scalar' ? [value.value] : []),
303
- };
52
+ export async function eventFileContents(source) {
53
+ return callSourceQuery('event_write.contents', source.path, source.bytes, z.object({ ids: z.array(z.string()), namespaces: z.array(z.string()) }));
304
54
  }
@@ -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 { focusInspectRequestSchema, focusRenderRequestSchema, focusRewriteRequestSchema, } from '../schemas/focus-requests.js';
@@ -9,7 +9,7 @@ const wireResult = z.record(z.string(), z.json());
9
9
  /** Registers read-only focus operations without invoking transport handlers. */
10
10
  export function registerFocusJobs(operations, engine) {
11
11
  const workbench = new FocusWorkbench(engine.resolver, engine.transactions, engine.artifacts);
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();
@@ -496,24 +496,14 @@ export class GuiAssetCatalog {
496
496
  .resize(width, height, { fit: 'fill', kernel: 'nearest' })
497
497
  .raw()
498
498
  .toBuffer();
499
- let alphaVaries = false;
500
- const firstAlpha = maskPixels[3] ?? 255;
501
- for (let offset = 7; offset < maskPixels.length; offset += 4) {
502
- if (maskPixels[offset] !== firstAlpha) {
503
- alphaVaries = true;
504
- break;
505
- }
506
- }
499
+ // The game's masked flag shader takes only the mask's alpha (`OutColor.a = MaskColor.a`);
500
+ // its colour is ignored, so a black mask with full alpha shows the whole flag.
507
501
  const alphaMask = Buffer.alloc(maskPixels.length);
508
502
  for (let offset = 0; offset < maskPixels.length; offset += 4) {
509
503
  alphaMask[offset] = 255;
510
504
  alphaMask[offset + 1] = 255;
511
505
  alphaMask[offset + 2] = 255;
512
- alphaMask[offset + 3] = alphaVaries
513
- ? maskPixels[offset + 3]
514
- : Math.round(maskPixels[offset] * 0.2126 +
515
- maskPixels[offset + 1] * 0.7152 +
516
- maskPixels[offset + 2] * 0.0722);
506
+ alphaMask[offset + 3] = maskPixels[offset + 3];
517
507
  }
518
508
  composites.push({
519
509
  input: await sharp(alphaMask, {
@@ -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 { guiInspectRequestSchema, guiRenderRequestSchema, guiRewriteRequestSchema, } from '../schemas/gui-requests.js';
@@ -9,7 +9,7 @@ const wireResult = z.record(z.string(), z.json());
9
9
  /** Registers read-only GUI operations without invoking transport handlers. */
10
10
  export function registerGuiJobs(operations, engine) {
11
11
  const studio = new ScriptedGuiStudio(engine);
12
- const lifetime = new IdleCacheLifetime(() => studio.clearCaches());
12
+ const lifetime = idleCacheLifetime(engine, () => studio.clearCaches());
13
13
  function register(name, schema, normalize, execute) {
14
14
  operations.registerRead(name, schema, async (input, context) => {
15
15
  const release = lifetime.begin();
@@ -5,7 +5,7 @@ import { ServiceError } from '../core/result.js';
5
5
  import { nativeWindowState } from './native-state.js';
6
6
  import { GuiAssetCatalog } from './assets.js';
7
7
  import { GUI_GRAPH_MAX_EDGES, GUI_GRAPH_MAX_ELEMENTS, GUI_GRAPH_MAX_NODES, GUI_SCENE_MAX_DEPTH, GUI_SCENE_MAX_ELEMENTS, GUI_SCENE_MAX_TEXT_CHARACTERS, GUI_SCENE_MAX_TEXT_LAYOUT_OPERATIONS, GUI_SCENE_MAX_WORK, GUI_TEXT_MAX_CHARACTERS, GUI_TEXT_MAX_MISSING_GLYPH_SAMPLES, } from './limits.js';
8
- import { guiElementAttributeFidelity } from './source-graph.js';
8
+ import { guiElementAttributeFidelity, guiTextLooksLikeLocalisationKey } from './source-graph.js';
9
9
  import { emptyFidelityReport, fidelityCategories } from './types.js';
10
10
  import { ClausewitzEvaluationDefinitions } from '../core/clausewitz-evaluation.js';
11
11
  import { evaluateGuiCondition, guiConditionScenario } from './scenario-conditions.js';
@@ -215,9 +215,7 @@ function resolveTokenText(value, scenario, localisation, rowValues) {
215
215
  const localised = scenario.localisation[value] ?? localisation.get(value);
216
216
  let text = localised ?? value;
217
217
  assertTextLength(text, 'GUI resolved localisation');
218
- if (localised === undefined &&
219
- /^[A-Za-z0-9_.-]+$/u.test(value) &&
220
- (value.includes('_') || value === value.toUpperCase()))
218
+ if (localised === undefined && guiTextLooksLikeLocalisationKey(value))
221
219
  missingLocalisation = true;
222
220
  const expandTokens = (input, stack, depth) => replaceTextBounded(input, /\$([A-Za-z0-9_.-]+)\$/gu, (match) => {
223
221
  const key = match[1] ?? '';
@@ -389,7 +389,8 @@ function renderMaskedShield(element, textures) {
389
389
  if (mask?.supported !== true || mask.dataUri === undefined)
390
390
  return renderSpriteImage(sprite, rect, textures);
391
391
  const id = `gui-mask-${sha256Bytes(element.id).slice(0, 20)}`;
392
- return `<defs><mask id="${id}" maskUnits="userSpaceOnUse" ${rectAttributes(rect)}>${textures.use(mask.dataUri, rect)}</mask></defs>${textures.use(sprite.dataUri, rect, ` mask="url(#${id})"`)}`;
392
+ // Alpha, not luminance: the game's masked shader keeps only the mask's alpha.
393
+ return `<defs><mask id="${id}" maskUnits="userSpaceOnUse" style="mask-type:alpha" ${rectAttributes(rect)}>${textures.use(mask.dataUri, rect)}</mask></defs>${textures.use(sprite.dataUri, rect, ` mask="url(#${id})"`)}`;
393
394
  }
394
395
  function renderElementSprite(element, textures) {
395
396
  if (element.sprite?.supported !== true || element.sprite.dataUri === undefined)
@@ -1149,6 +1149,10 @@ function linkGraph(nodes, edges, elements, sprites, fonts, scriptedGuis, scripte
1149
1149
  !isStaticGuiLocalisationReference(value))
1150
1150
  continue;
1151
1151
  const entry = localisationByKey.get(value);
1152
+ // The game shows a text that matches no key as it is written, so a text that is not in key
1153
+ // form ("Title text here!", "--") is plain text, not a missing localisation key.
1154
+ if (entry === undefined && !guiTextLooksLikeLocalisationKey(value))
1155
+ continue;
1152
1156
  addEdge(edges, 'uses_localisation', element.id, entry === undefined ? `localisation:${value}` : deterministicId('gui_loc', entry), entry !== undefined, { field: key, key: value }, element.location);
1153
1157
  }
1154
1158
  }
@@ -1231,6 +1235,18 @@ function localisationAttributeValue(attributes, name) {
1231
1235
  return value;
1232
1236
  return undefined;
1233
1237
  }
1238
+ /**
1239
+ * Whether a GUI text that matches no localisation entry still reads as a key. The game looks a
1240
+ * static text up as a key and draws the text itself when nothing matches, without an error.
1241
+ * Only a text in the form of a key (the characters a localisation file allows in a key, at least
1242
+ * one letter, and an underscore or all capitals, as `MY_WINDOW_TITLE` or `OK`) is reported as a
1243
+ * missing key; anything else (`Title text here!`, `--`, `close`) is drawn literally.
1244
+ */
1245
+ export function guiTextLooksLikeLocalisationKey(value) {
1246
+ return (/^[A-Za-z0-9_.-]+$/u.test(value) &&
1247
+ /[A-Za-z]/u.test(value) &&
1248
+ (value.includes('_') || value === value.toUpperCase()));
1249
+ }
1234
1250
  function isStaticGuiLocalisationReference(value) {
1235
1251
  const trimmed = value.trim();
1236
1252
  return !(trimmed.startsWith('[') && trimmed.endsWith(']'));
@@ -331,6 +331,36 @@ function selectedElements(graph, windowName, additionalTemplateNames = []) {
331
331
  }
332
332
  return [...selected.values()];
333
333
  }
334
+ const definitionReferenceKinds = new Set(['uses_sprite', 'uses_font', 'static_fallback']);
335
+ /**
336
+ * A window graph keeps whole .gui files, so it also holds the other windows of the selected
337
+ * window's file, and it keeps every script file. The graph checks the references of all of them.
338
+ * Adds the .gfx file of every sprite and font that a kept source names and the full inventory
339
+ * resolves, so a sprite of a sibling window, a sprite a defined_text returns or a static
340
+ * fallback is not reported as missing because its .gfx file was left out of the window graph.
341
+ */
342
+ function keepReferencedDefinitionSources(graph, selectedPaths) {
343
+ const definitionPaths = new Map();
344
+ for (const { id, sourcePath } of [...graph.sprites, ...graph.fonts])
345
+ definitionPaths.set(id, sourcePath);
346
+ const nodePaths = new Map(graph.nodes.map(({ id, path: nodePath }) => [id, nodePath]));
347
+ const kept = (id) => {
348
+ const nodePath = nodePaths.get(id);
349
+ return (nodePath !== undefined && (!/\.(?:gui|gfx)$/iu.test(nodePath) || selectedPaths.has(nodePath)));
350
+ };
351
+ const references = graph.edges.filter(({ kind, resolved, to }) => resolved && definitionReferenceKinds.has(kind) && definitionPaths.has(to));
352
+ let added = true;
353
+ while (added) {
354
+ added = false;
355
+ for (const edge of references) {
356
+ const target = definitionPaths.get(edge.to);
357
+ if (selectedPaths.has(target) || !kept(edge.from))
358
+ continue;
359
+ selectedPaths.add(target);
360
+ added = true;
361
+ }
362
+ }
363
+ }
334
364
  function assertTargetWindowAvailable(graph, windowName) {
335
365
  if (graph.elements.some(({ name }) => name === windowName))
336
366
  return;
@@ -1177,6 +1207,7 @@ export class ScriptedGuiStudio {
1177
1207
  if (namedFonts.has(font.name) ||
1178
1208
  font.assetPaths.some((value) => referenceVariants(value).some((variant) => assetPaths.has(variant.toLowerCase()))))
1179
1209
  selectedPaths.add(font.sourcePath);
1210
+ keepReferencedDefinitionSources(definitions.graph, selectedPaths);
1180
1211
  const files = mergeScannedFiles(definitions.files.filter((file) => !/\.(?:gui|gfx)$/iu.test(file.relativePath) || selectedPaths.has(file.displayPath)), referenced, fontPages);
1181
1212
  await stage('Resolving selected GUI assets');
1182
1213
  const scanned = this.graphForFiles(files, `window:${workspaceId}:${windowName}`, additionalLocalisationKeys);
@@ -36,7 +36,7 @@ function newIdeaFilePath(file) {
36
36
  return path;
37
37
  }
38
38
  /** The file the operation writes: the one named, the one that defines the idea, or the one with the category. */
39
- function targetFile(snapshot, input) {
39
+ async function targetFile(snapshot, input) {
40
40
  const files = modIdeaFiles(snapshot);
41
41
  if (input.file !== undefined) {
42
42
  const named = files.find(({ relativePath }) => normalized(relativePath) === normalized(input.file));
@@ -61,7 +61,8 @@ function targetFile(snapshot, input) {
61
61
  if (input.category === undefined)
62
62
  fail('IDEA_WRITE_CATEGORY_REQUIRED', 'add needs the category block the idea goes in');
63
63
  const category = input.category;
64
- const holding = files.filter(({ bytes, relativePath }) => ideaCategories({ bytes, path: relativePath }).includes(category));
64
+ const categoriesByFile = await Promise.all(files.map(({ bytes, relativePath }) => ideaCategories({ bytes, path: relativePath })));
65
+ const holding = files.filter((_, index) => categoriesByFile[index].includes(category));
65
66
  if (holding.length === 0) {
66
67
  if (input.createCategory === true) {
67
68
  if (files.length === 1)
@@ -72,9 +73,7 @@ function targetFile(snapshot, input) {
72
73
  }
73
74
  fail('IDEA_WRITE_CATEGORY_NOT_FOUND', `No common/ideas file of the mod has a ${category} category; pass createCategory: true to create it`, {
74
75
  category,
75
- categories: [
76
- ...new Set(files.flatMap(({ bytes, relativePath }) => ideaCategories({ bytes, path: relativePath }))),
77
- ],
76
+ categories: [...new Set(categoriesByFile.flat())],
78
77
  });
79
78
  }
80
79
  if (holding.length > 1)
@@ -110,7 +109,7 @@ function referencesOf(id, body) {
110
109
  }
111
110
  export async function computeIdeaWrite(engine, input, context, applied) {
112
111
  const snapshot = await engine.scan(context.workspaceId, { patterns: WRITE_PATTERNS }, context.principal, context.signal);
113
- const target = targetFile(snapshot, input);
112
+ const target = await targetFile(snapshot, input);
114
113
  const planInput = {
115
114
  operation: input.operation,
116
115
  id: input.id,
@@ -122,7 +121,7 @@ export async function computeIdeaWrite(engine, input, context, applied) {
122
121
  let plan;
123
122
  if ('file' in target) {
124
123
  file = target.file;
125
- plan = planIdeaWrite({ bytes: file.bytes, path: file.relativePath }, planInput);
124
+ plan = await planIdeaWrite({ bytes: file.bytes, path: file.relativePath }, planInput);
126
125
  }
127
126
  else {
128
127
  const inMod = snapshot.index
@@ -133,7 +132,7 @@ export async function computeIdeaWrite(engine, input, context, applied) {
133
132
  id: input.id,
134
133
  path: inMod.path,
135
134
  });
136
- plan = planNewIdeaFile(target.newPath, planInput);
135
+ plan = await planNewIdeaFile(target.newPath, planInput);
137
136
  }
138
137
  const missing = { localisation: [], picture: [] };
139
138
  const diagnostics = [];