hoi4-agent-tools 2.3.0 → 2.3.3

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 (38) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/dist/bin/stdio.js +4 -0
  3. package/dist/hoi4_agent_tools/event/algorithms.js +178 -1
  4. package/dist/hoi4_agent_tools/event/graph.js +24 -9
  5. package/dist/hoi4_agent_tools/event/limits.js +4 -1
  6. package/dist/hoi4_agent_tools/event/service.js +182 -45
  7. package/dist/hoi4_agent_tools/mcp/tools/chaosx.js +480 -0
  8. package/dist/hoi4_agent_tools/mcp/tools/technology.js +4 -1
  9. package/dist/hoi4_agent_tools/runtime.js +109 -7
  10. package/dist/hoi4_agent_tools/technology/graph.js +30 -3
  11. package/dist/hoi4_agent_tools/technology/queries.js +70 -3
  12. package/dist/hoi4_agent_tools/technology/service.js +38 -2
  13. package/dist/hoi4_agent_tools/version.js +1 -1
  14. package/docs/events.md +2 -2
  15. package/docs/setup.md +2 -0
  16. package/docs/technology.md +4 -2
  17. package/package.json +3 -1
  18. package/schemas/configuration.schema.json +1 -1
  19. package/schemas/continuous-focus-palette.schema.json +1 -1
  20. package/schemas/custom-weighted-pool.schema.json +1 -1
  21. package/schemas/event-feature-manifest.schema.json +1 -1
  22. package/schemas/focus-plan.schema.json +1 -1
  23. package/schemas/focus-planning-sidecar.schema.json +1 -1
  24. package/schemas/gui-animation-source.schema.json +1 -1
  25. package/schemas/gui-helper.schema.json +1 -1
  26. package/schemas/gui-scenario.schema.json +1 -1
  27. package/schemas/map-operation.schema.json +1 -1
  28. package/schemas/operation-result.schema.json +1 -1
  29. package/schemas/probability-analysis-result.schema.json +1 -1
  30. package/schemas/probability-compare-input.schema.json +1 -1
  31. package/schemas/probability-evaluate-input.schema.json +1 -1
  32. package/schemas/probability-inspect-input.schema.json +1 -1
  33. package/schemas/probability-render-input.schema.json +1 -1
  34. package/schemas/probability-scenario-set.schema.json +1 -1
  35. package/schemas/probability-sequence-input.schema.json +1 -1
  36. package/schemas/probability-simulate-input.schema.json +1 -1
  37. package/schemas/probability-sweep-input.schema.json +1 -1
  38. package/server.json +2 -2
@@ -0,0 +1,480 @@
1
+ import path from 'node:path';
2
+ import sharp from 'sharp';
3
+ import { z } from 'zod/v4';
4
+ import { publicArtifactLink } from '../../core/artifacts.js';
5
+ import { compareCodeUnits, hashCanonical } from '../../core/canonical.js';
6
+ import { emptyServiceResult } from '../../core/result.js';
7
+ import { RenderBudget } from '../../core/render-budget.js';
8
+ import { workspaceIdSchema } from '../../schemas/common.js';
9
+ import { GuiAssetCatalog } from '../../gui/assets.js';
10
+ import { ScriptedGuiStudio } from '../../gui/index.js';
11
+ import { buildGuiSourceGraph } from '../../gui/source-graph.js';
12
+ import { PACKAGE_VERSION } from '../../version.js';
13
+ import { compactValidatedInputSchema } from '../server/context-schemas.js';
14
+ import { nonNegativeIntegerSchema, sha256Schema } from '../server/output-schemas.js';
15
+ import { progressReporter } from '../server/progress.js';
16
+ import { errorResult, setInlineFilesScanned, strictOperationResultSchema, toolResult, } from '../server/result.js';
17
+ const countryTagSchema = z
18
+ .string()
19
+ .regex(/^[A-Z0-9]{3}$/u)
20
+ .describe('Exact HOI4 country tag selected by ChaosX');
21
+ const chaosxCountryAssetsInput = compactValidatedInputSchema(z
22
+ .object({
23
+ workspaceId: workspaceIdSchema,
24
+ countryTags: z.array(countryTagSchema).min(1).max(4),
25
+ eventId: z.number().int().min(0).max(999).optional(),
26
+ treeId: z.string().min(1).max(256).optional(),
27
+ })
28
+ .strict(), 'ChaosX-only country tags and optional event/focus identity');
29
+ const chaosxCountryAssetsOutput = strictOperationResultSchema(z
30
+ .object({
31
+ revision: sha256Schema,
32
+ countries: z
33
+ .array(z
34
+ .object({
35
+ tag: countryTagSchema,
36
+ flagArtifactName: z.string().max(128).optional(),
37
+ leaderPortraitArtifactName: z.string().max(128).optional(),
38
+ leaderSprite: z.string().max(256).optional(),
39
+ })
40
+ .strict())
41
+ .max(4),
42
+ artifactCount: nonNegativeIntegerSchema,
43
+ })
44
+ .strict());
45
+ const visualGuiSelectorSchema = z
46
+ .object({
47
+ windowName: z.string().min(1).max(256),
48
+ guiId: z.string().min(1).max(256),
49
+ })
50
+ .strict();
51
+ const chaosxVisualRevisionInput = compactValidatedInputSchema(z
52
+ .object({
53
+ workspaceId: workspaceIdSchema,
54
+ guiWindows: z.array(visualGuiSelectorSchema).min(1).max(3),
55
+ })
56
+ .strict(), 'ChaosX-only scripted-GUI selectors for fast cache revision checks');
57
+ const visualRevisionEntrySchema = z
58
+ .object({
59
+ windowName: z.string().min(1).max(256),
60
+ guiId: z.string().min(1).max(256),
61
+ revision: sha256Schema,
62
+ })
63
+ .strict();
64
+ const chaosxVisualRevisionOutput = strictOperationResultSchema(z
65
+ .object({
66
+ workspaceRevision: sha256Schema,
67
+ guiRevisions: z.array(visualRevisionEntrySchema).max(3),
68
+ dependencyFileCount: nonNegativeIntegerSchema,
69
+ })
70
+ .strict());
71
+ const artifactProducing = {
72
+ readOnlyHint: false,
73
+ destructiveHint: false,
74
+ idempotentHint: true,
75
+ openWorldHint: false,
76
+ };
77
+ const readOnly = { ...artifactProducing, readOnlyHint: true };
78
+ function activeFiles(snapshot) {
79
+ return snapshot.files.filter(({ shadowedBy }) => shadowedBy === undefined);
80
+ }
81
+ function historyFile(snapshot, tag) {
82
+ const prefix = `history/countries/${tag.toLowerCase()} `;
83
+ return activeFiles(snapshot)
84
+ .filter(({ relativePath }) => relativePath.toLowerCase().startsWith(prefix))
85
+ .sort((left, right) => {
86
+ const ownership = Number(right.rootKind === 'mod') - Number(left.rootKind === 'mod');
87
+ return (ownership ||
88
+ right.loadOrder - left.loadOrder ||
89
+ compareCodeUnits(left.displayPath, right.displayPath));
90
+ })[0];
91
+ }
92
+ function pictureFromText(file, tag, requireTagPrefix) {
93
+ const text = file.bytes.toString('utf8');
94
+ const pattern = requireTagPrefix
95
+ ? new RegExp(`\\bpicture\\s*=\\s*"?(GFX_portrait_${tag}_[A-Za-z0-9_.:-]+)"?`, 'u')
96
+ : /\bpicture\s*=\s*"?(GFX_[A-Za-z0-9_.:-]+)"?/u;
97
+ return pattern.exec(text)?.[1];
98
+ }
99
+ function eventPictureSource(snapshot, tag, eventId) {
100
+ const eventPrefix = eventId === undefined ? undefined : String(eventId).padStart(3, '0');
101
+ const candidates = activeFiles(snapshot)
102
+ .filter(({ relativePath, bytes }) => {
103
+ const normalized = relativePath.toLowerCase();
104
+ return (normalized.endsWith('.txt') &&
105
+ (normalized.startsWith('events/') || normalized.startsWith('common/scripted_effects/')) &&
106
+ bytes.includes(Buffer.from(`GFX_portrait_${tag}_`, 'utf8')));
107
+ })
108
+ .sort((left, right) => {
109
+ const leftPreferred = eventPrefix !== undefined && path.posix.basename(left.relativePath).startsWith(eventPrefix);
110
+ const rightPreferred = eventPrefix !== undefined &&
111
+ path.posix.basename(right.relativePath).startsWith(eventPrefix);
112
+ return (Number(rightPreferred) - Number(leftPreferred) ||
113
+ compareCodeUnits(left.displayPath, right.displayPath));
114
+ });
115
+ for (const file of candidates) {
116
+ const sprite = pictureFromText(file, tag, true);
117
+ if (sprite !== undefined)
118
+ return { sprite, path: file.displayPath };
119
+ }
120
+ return undefined;
121
+ }
122
+ function leaderSelection(snapshot, tag, eventId) {
123
+ const countryHistory = historyFile(snapshot, tag);
124
+ const historyPicture = countryHistory === undefined ? undefined : pictureFromText(countryHistory, tag, false);
125
+ const eventPicture = historyPicture === undefined ? eventPictureSource(snapshot, tag, eventId) : undefined;
126
+ const fallbackSprite = snapshot.index
127
+ .findAll('sprite')
128
+ .filter(({ overridden, id }) => !overridden && id.startsWith(`GFX_portrait_${tag}_`))
129
+ .sort((left, right) => compareCodeUnits(left.id, right.id))[0];
130
+ const leaderSprite = historyPicture ?? eventPicture?.sprite ?? fallbackSprite?.id;
131
+ if (leaderSprite === undefined)
132
+ return {};
133
+ const sprite = snapshot.index.find('sprite', leaderSprite);
134
+ const texture = typeof sprite?.metadata.texture === 'string' ? sprite.metadata.texture : undefined;
135
+ return {
136
+ leaderSprite,
137
+ ...(texture === undefined ? {} : { leaderTexturePath: texture }),
138
+ ...(countryHistory !== undefined
139
+ ? { discoverySourcePath: countryHistory.displayPath }
140
+ : eventPicture === undefined
141
+ ? {}
142
+ : { discoverySourcePath: eventPicture.path }),
143
+ ...(sprite === undefined ? {} : { spriteSourcePath: sprite.path }),
144
+ };
145
+ }
146
+ function flagCandidates(tag) {
147
+ return ['tga', 'dds', 'png'].flatMap((extension) => [
148
+ `gfx/flags/${tag}.${extension}`,
149
+ `gfx/flags/medium/${tag}.${extension}`,
150
+ `gfx/flags/small/${tag}.${extension}`,
151
+ ]);
152
+ }
153
+ async function rasterPng(catalog, assetPath) {
154
+ const raster = await catalog.loadRaster(assetPath);
155
+ if (!raster.supported || raster.width < 1 || raster.height < 1)
156
+ return undefined;
157
+ return sharp(raster.data, {
158
+ raw: { width: raster.width, height: raster.height, channels: 4 },
159
+ })
160
+ .png({ compressionLevel: 9, adaptiveFiltering: false, palette: false })
161
+ .toBuffer();
162
+ }
163
+ async function selectCountryAssets(engine, snapshot, workspaceId, tags, eventId, context, signal) {
164
+ const selections = tags.map((tag) => ({
165
+ tag,
166
+ ...leaderSelection(snapshot, tag, eventId),
167
+ }));
168
+ const patterns = [
169
+ ...new Set(selections.flatMap(({ tag, leaderTexturePath }) => [
170
+ ...flagCandidates(tag),
171
+ ...(leaderTexturePath === undefined ? [] : [leaderTexturePath]),
172
+ ])),
173
+ ].sort(compareCodeUnits);
174
+ const workspace = engine.resolver.get(workspaceId, context.principal);
175
+ const scannedAssets = patterns.length === 0
176
+ ? []
177
+ : await engine.scanner.scan(workspace, {
178
+ patterns,
179
+ ...(signal === undefined ? {} : { signal }),
180
+ });
181
+ const graph = buildGuiSourceGraph([], snapshot.index);
182
+ const catalog = new GuiAssetCatalog(graph, scannedAssets, new RenderBudget());
183
+ for (const selection of selections) {
184
+ const flagPath = flagCandidates(selection.tag).find((candidate) => catalog.resolveFile(candidate) !== undefined);
185
+ if (flagPath !== undefined)
186
+ selection.flagPath = flagPath;
187
+ }
188
+ return { selections, catalog };
189
+ }
190
+ function scannerPattern(displayPath) {
191
+ const separator = displayPath.indexOf(':');
192
+ return separator < 0 ? displayPath : displayPath.slice(separator + 1);
193
+ }
194
+ async function cachedGuiRevisionCurrent(engine, context, workspaceId, cached, signal) {
195
+ const expectedPaths = Object.keys(cached.sourceHashes);
196
+ if (expectedPaths.length === 0)
197
+ return true;
198
+ const workspace = engine.resolver.get(workspaceId, context.principal);
199
+ const expected = new Set(expectedPaths);
200
+ const scanned = await engine.scanner.scan(workspace, {
201
+ patterns: [...new Set(expectedPaths.map(scannerPattern))].sort(compareCodeUnits),
202
+ signal,
203
+ });
204
+ const current = Object.fromEntries(scanned
205
+ .filter(({ displayPath }) => expected.has(displayPath))
206
+ .map(({ displayPath, sha256 }) => [displayPath, sha256]));
207
+ return hashCanonical(current) === hashCanonical(cached.sourceHashes);
208
+ }
209
+ function collectNamedGuiAttributes(value, keys, output) {
210
+ if (Array.isArray(value)) {
211
+ for (const entry of value)
212
+ collectNamedGuiAttributes(entry, keys, output);
213
+ return;
214
+ }
215
+ if (typeof value !== 'object' || value === null)
216
+ return;
217
+ for (const [key, entry] of Object.entries(value)) {
218
+ if (keys.has(key) && typeof entry === 'string' && entry.length > 0)
219
+ output.add(entry);
220
+ collectNamedGuiAttributes(entry, keys, output);
221
+ }
222
+ }
223
+ function guiDependencySourceHashes(graph, selector) {
224
+ const window = [...graph.elements]
225
+ .sort((left, right) => left.definitionOrder - right.definitionOrder)
226
+ .find(({ name }) => name === selector.windowName);
227
+ if (window === undefined)
228
+ throw new Error(`GUI window not found: ${selector.windowName}`);
229
+ const scriptedGui = graph.scriptedGuis.find(({ name }) => name === selector.guiId);
230
+ if (scriptedGui === undefined)
231
+ throw new Error(`Scripted GUI not found: ${selector.guiId}`);
232
+ const nodeById = new Map(graph.nodes.map((node) => [node.id, node]));
233
+ const elementById = new Map(graph.elements.map((element) => [element.id, element]));
234
+ const spriteByName = new Map(graph.sprites.map((sprite) => [sprite.name, sprite]));
235
+ const fontByName = new Map(graph.fonts.map((font) => [font.name, font]));
236
+ const localisationByKey = new Map();
237
+ for (const localisation of graph.localisation)
238
+ if (!localisationByKey.has(localisation.key))
239
+ localisationByKey.set(localisation.key, localisation);
240
+ const outgoing = new Map();
241
+ for (const edge of graph.edges) {
242
+ if (!edge.resolved)
243
+ continue;
244
+ const targets = outgoing.get(edge.from) ?? [];
245
+ targets.push(edge.to);
246
+ outgoing.set(edge.from, targets);
247
+ }
248
+ const pending = [window.id, scriptedGui.id];
249
+ const visited = new Set();
250
+ const sourcePaths = new Set([window.sourcePath, scriptedGui.sourcePath]);
251
+ while (pending.length > 0) {
252
+ const nodeId = pending.pop();
253
+ if (nodeId === undefined || visited.has(nodeId))
254
+ continue;
255
+ visited.add(nodeId);
256
+ const node = nodeById.get(nodeId);
257
+ if (node !== undefined && graph.sourceHashes[node.path] !== undefined)
258
+ sourcePaths.add(node.path);
259
+ const element = elementById.get(nodeId);
260
+ if (element !== undefined) {
261
+ const spriteNames = new Set();
262
+ const fontNames = new Set();
263
+ const localisationKeys = new Set();
264
+ collectNamedGuiAttributes(element.attributes, new Set(['spriteType', 'quadTextureSprite']), spriteNames);
265
+ collectNamedGuiAttributes(element.attributes, new Set(['font', 'buttonFont']), fontNames);
266
+ collectNamedGuiAttributes(element.attributes, new Set(['text', 'buttonText', 'pdx_tooltip', 'pdx_tooltip_delayed', 'hint_tag']), localisationKeys);
267
+ for (const spriteName of spriteNames) {
268
+ const sprite = spriteByName.get(spriteName);
269
+ if (sprite !== undefined)
270
+ pending.push(sprite.id);
271
+ }
272
+ for (const fontName of fontNames) {
273
+ const font = fontByName.get(fontName);
274
+ if (font !== undefined)
275
+ pending.push(font.id);
276
+ }
277
+ for (const localisationKey of localisationKeys) {
278
+ const localisation = localisationByKey.get(localisationKey);
279
+ if (localisation !== undefined)
280
+ sourcePaths.add(localisation.sourcePath);
281
+ }
282
+ }
283
+ for (const target of outgoing.get(nodeId) ?? [])
284
+ pending.push(target);
285
+ }
286
+ return Object.fromEntries([...sourcePaths]
287
+ .filter((sourcePath) => graph.sourceHashes[sourcePath] !== undefined)
288
+ .sort(compareCodeUnits)
289
+ .map((sourcePath) => [sourcePath, graph.sourceHashes[sourcePath]]));
290
+ }
291
+ async function resolveGuiRevision(engine, context, studio, cache, workspaceId, selector, signal) {
292
+ const cacheKey = hashCanonical({ workspaceId, selector });
293
+ const cached = cache.get(cacheKey);
294
+ if (cached !== undefined &&
295
+ (await cachedGuiRevisionCurrent(engine, context, workspaceId, cached, signal))) {
296
+ return {
297
+ windowName: selector.windowName,
298
+ guiId: selector.guiId,
299
+ revision: cached.sourceRevision,
300
+ workspaceRevision: cached.workspaceRevision,
301
+ filesScanned: Object.keys(cached.sourceHashes).sort(compareCodeUnits),
302
+ };
303
+ }
304
+ const linted = await studio.lint({
305
+ workspaceId,
306
+ windowName: selector.windowName,
307
+ scenario: {
308
+ id: 'chaosx-visual-revision',
309
+ resolution: { width: 1920, height: 1080 },
310
+ state: 'active',
311
+ scriptedGui: { [selector.guiId]: true },
312
+ visibility: { [selector.windowName]: true, [selector.guiId]: true },
313
+ },
314
+ ...(context.principal === undefined ? {} : { principal: context.principal }),
315
+ signal,
316
+ });
317
+ const sourceHashes = guiDependencySourceHashes(linted.graph, selector);
318
+ const sourceRevision = hashCanonical({ selector, sourceHashes });
319
+ const next = {
320
+ workspaceRevision: linted.scene.sourceRevision,
321
+ sourceRevision,
322
+ sourceHashes,
323
+ };
324
+ cache.set(cacheKey, next);
325
+ return {
326
+ windowName: selector.windowName,
327
+ guiId: selector.guiId,
328
+ revision: sourceRevision,
329
+ workspaceRevision: next.workspaceRevision,
330
+ filesScanned: Object.keys(sourceHashes).sort(compareCodeUnits),
331
+ };
332
+ }
333
+ export function registerChaosxTools(server, engine, context) {
334
+ const guiStudio = new ScriptedGuiStudio(engine);
335
+ const guiRevisionCache = new Map();
336
+ server.registerTool('chaosx.visual_revision', {
337
+ title: 'Check ChaosX visual revisions',
338
+ description: 'Private ChaosX cache-coherency endpoint. Computes exact scripted-GUI source revisions without rendering PNG artifacts.',
339
+ inputSchema: chaosxVisualRevisionInput,
340
+ outputSchema: chaosxVisualRevisionOutput,
341
+ annotations: readOnly,
342
+ }, async (input, extra) => {
343
+ const workspaceId = engine.resolver.resolveWorkspaceId(input.workspaceId, context.principal);
344
+ try {
345
+ const progress = progressReporter(extra);
346
+ await progress.report(0, 2, 'Checking ChaosX scripted-GUI sources');
347
+ const resolvedGuiRevisions = [];
348
+ for (const selector of input.guiWindows)
349
+ resolvedGuiRevisions.push(await resolveGuiRevision(engine, context, guiStudio, guiRevisionCache, workspaceId, selector, progress.signal));
350
+ const filesScanned = new Set(resolvedGuiRevisions.flatMap(({ filesScanned }) => filesScanned));
351
+ const guiRevisions = resolvedGuiRevisions.map(({ windowName, guiId, revision }) => ({
352
+ windowName,
353
+ guiId,
354
+ revision,
355
+ }));
356
+ const workspaceRevision = hashCanonical(resolvedGuiRevisions.map(({ windowName, workspaceRevision: revision }) => ({
357
+ windowName,
358
+ revision,
359
+ })));
360
+ const result = emptyServiceResult(workspaceId, {
361
+ workspaceRevision,
362
+ guiRevisions,
363
+ dependencyFileCount: filesScanned.size,
364
+ });
365
+ result.code = 'CHAOSX_VISUAL_REVISION_CHECKED';
366
+ setInlineFilesScanned(result, [...filesScanned].sort(compareCodeUnits));
367
+ await progress.report(2, 2, 'ChaosX scripted-GUI revisions complete');
368
+ return toolResult(result);
369
+ }
370
+ catch (error) {
371
+ return errorResult(error, workspaceId);
372
+ }
373
+ });
374
+ server.registerTool('chaosx.focus_country_assets', {
375
+ title: 'Render ChaosX focus country assets',
376
+ description: 'Private ChaosX Discord integration endpoint. Returns country flags and leader portraits to accompany a focus-tree raster; it is not intended for coding-agent workflows.',
377
+ inputSchema: chaosxCountryAssetsInput,
378
+ outputSchema: chaosxCountryAssetsOutput,
379
+ annotations: artifactProducing,
380
+ }, async (input, extra) => {
381
+ const workspaceId = engine.resolver.resolveWorkspaceId(input.workspaceId, context.principal);
382
+ try {
383
+ const progress = progressReporter(extra);
384
+ await progress.report(0, 3, 'Resolving ChaosX country assets');
385
+ const snapshot = await engine.scan(workspaceId, {}, context.principal, progress.signal);
386
+ const tags = [...new Set(input.countryTags)];
387
+ const { selections, catalog } = await selectCountryAssets(engine, snapshot, workspaceId, tags, input.eventId, context, progress.signal);
388
+ await progress.report(1, 3, 'Rasterizing ChaosX country assets');
389
+ const writes = [];
390
+ const countries = [];
391
+ const filesScanned = new Set();
392
+ for (const selection of selections) {
393
+ const country = { tag: selection.tag };
394
+ const sourcePaths = [selection.discoverySourcePath, selection.spriteSourcePath].filter((value) => value !== undefined);
395
+ for (const sourcePath of sourcePaths)
396
+ filesScanned.add(sourcePath);
397
+ if (selection.flagPath !== undefined) {
398
+ const png = await rasterPng(catalog, selection.flagPath);
399
+ const source = catalog.resolveFile(selection.flagPath);
400
+ if (png !== undefined && source !== undefined) {
401
+ filesScanned.add(source.displayPath);
402
+ const name = `chaosx-${selection.tag}-flag.png`;
403
+ country.flagArtifactName = name;
404
+ writes.push({
405
+ name,
406
+ mimeType: 'image/png',
407
+ content: png,
408
+ provenance: {
409
+ kind: 'chaosx-country-flag',
410
+ toolVersion: PACKAGE_VERSION,
411
+ schemaVersion: 'chaosx-country-assets.v1',
412
+ sourceHashes: { [source.displayPath]: source.sha256 },
413
+ metadata: {
414
+ tag: selection.tag,
415
+ eventId: input.eventId ?? null,
416
+ treeId: input.treeId ?? null,
417
+ },
418
+ },
419
+ description: `ChaosX country flag for ${selection.tag}`,
420
+ });
421
+ }
422
+ }
423
+ if (selection.leaderTexturePath !== undefined) {
424
+ const png = await rasterPng(catalog, selection.leaderTexturePath);
425
+ const source = catalog.resolveFile(selection.leaderTexturePath);
426
+ if (png !== undefined && source !== undefined) {
427
+ filesScanned.add(source.displayPath);
428
+ const name = `chaosx-${selection.tag}-leader.png`;
429
+ country.leaderPortraitArtifactName = name;
430
+ const leaderSprite = selection.leaderSprite;
431
+ if (leaderSprite !== undefined)
432
+ country.leaderSprite = leaderSprite;
433
+ const sourceHashes = { [source.displayPath]: source.sha256 };
434
+ for (const sourcePath of sourcePaths) {
435
+ const file = snapshot.files.find(({ displayPath }) => displayPath === sourcePath);
436
+ if (file !== undefined)
437
+ sourceHashes[sourcePath] = file.sha256;
438
+ }
439
+ writes.push({
440
+ name,
441
+ mimeType: 'image/png',
442
+ content: png,
443
+ provenance: {
444
+ kind: 'chaosx-leader-portrait',
445
+ toolVersion: PACKAGE_VERSION,
446
+ schemaVersion: 'chaosx-country-assets.v1',
447
+ sourceHashes,
448
+ metadata: {
449
+ tag: selection.tag,
450
+ leaderSprite: selection.leaderSprite ?? null,
451
+ eventId: input.eventId ?? null,
452
+ treeId: input.treeId ?? null,
453
+ },
454
+ },
455
+ description: `ChaosX leader portrait for ${selection.tag}`,
456
+ });
457
+ }
458
+ }
459
+ countries.push(country);
460
+ }
461
+ const workspace = engine.resolver.get(workspaceId, context.principal);
462
+ const artifacts = writes.length === 0
463
+ ? []
464
+ : await engine.artifacts.withAtomicChunkedWrites(workspace, writes, (stored) => Promise.resolve([...stored]), progress.signal);
465
+ const result = emptyServiceResult(workspaceId, {
466
+ revision: snapshot.revision,
467
+ countries,
468
+ artifactCount: artifacts.length,
469
+ });
470
+ result.code = 'CHAOSX_COUNTRY_ASSETS_RENDERED';
471
+ setInlineFilesScanned(result, [...filesScanned].sort(compareCodeUnits));
472
+ result.artifacts = artifacts.map(publicArtifactLink);
473
+ await progress.report(3, 3, 'ChaosX country assets complete');
474
+ return toolResult(result);
475
+ }
476
+ catch (error) {
477
+ return errorResult(error, workspaceId);
478
+ }
479
+ });
480
+ }
@@ -162,6 +162,7 @@ const readOnly = {
162
162
  function graphHash(graph) {
163
163
  return hashCanonical({
164
164
  schemaVersion: graph.schemaVersion,
165
+ analysisMode: graph.analysisMode ?? 'full',
165
166
  workspaceIdentity: graph.workspaceIdentity,
166
167
  revision: graph.revision,
167
168
  statistics: graph.statistics,
@@ -192,7 +193,9 @@ function validation(graph) {
192
193
  passed: graph.complete && blocking === 0,
193
194
  message: graph.complete
194
195
  ? `${blocking} blocking technology diagnostics; full evidence is linked`
195
- : `${graph.skippedSourceCount} source(s) were skipped; full evidence is linked`,
196
+ : graph.analysisMode === 'focused'
197
+ ? 'Helper projections were deferred for this large workspace; direct evidence is linked'
198
+ : `${graph.skippedSourceCount} source(s) were skipped; full evidence is linked`,
196
199
  },
197
200
  ],
198
201
  };
@@ -1,4 +1,4 @@
1
- import { stat } from 'node:fs/promises';
1
+ import { lstat, readdir, stat } from 'node:fs/promises';
2
2
  import path from 'node:path';
3
3
  import { homedir } from 'node:os';
4
4
  import { loadConfiguration, serverConfigurationSchema, } from './core/configuration.js';
@@ -39,15 +39,117 @@ async function isFile(candidate) {
39
39
  return false;
40
40
  }
41
41
  }
42
+ /**
43
+ * Standard content directories that can be the only content in a valid local
44
+ * mod. Keep this list limited to HOI4 roots so an arbitrary project directory
45
+ * is not mistaken for a mod just because it contains a generic `common`
46
+ * folder.
47
+ */
48
+ const MOD_CONTENT_DIRECTORIES = [
49
+ 'events',
50
+ 'gfx',
51
+ 'history',
52
+ 'interface',
53
+ 'localisation',
54
+ 'localisation_synced',
55
+ 'map',
56
+ 'music',
57
+ 'portraits',
58
+ 'sound',
59
+ ];
60
+ const MOD_CONTENT_EXTENSIONS = {
61
+ events: ['.txt'],
62
+ gfx: ['.dds', '.gfx', '.png', '.tga'],
63
+ history: ['.txt'],
64
+ interface: ['.gfx', '.gui', '.txt'],
65
+ localisation: ['.yml', '.yaml'],
66
+ localisation_synced: ['.yml', '.yaml'],
67
+ map: ['.bmp', '.csv', '.map', '.txt'],
68
+ music: ['.asset', '.ogg', '.txt', '.wav'],
69
+ portraits: ['.dds', '.jpg', '.jpeg', '.png', '.tga'],
70
+ sound: ['.asset', '.ogg', '.txt', '.wav'],
71
+ };
72
+ const MOD_COMMON_DIRECTORIES = [
73
+ 'abilities',
74
+ 'ai_focuses',
75
+ 'ai_strategy',
76
+ 'ai_strategy_plans',
77
+ 'bop',
78
+ 'buildings',
79
+ 'characters',
80
+ 'continuous_focus',
81
+ 'decisions',
82
+ 'doctrines',
83
+ 'ideas',
84
+ 'mtth',
85
+ 'national_focus',
86
+ 'on_actions',
87
+ 'operations',
88
+ 'raids',
89
+ 'resistance_compliance_modifiers',
90
+ 'script_constants',
91
+ 'scripted_effects',
92
+ 'scripted_guis',
93
+ 'scripted_triggers',
94
+ 'special_projects',
95
+ 'technology_sharing',
96
+ 'technologies',
97
+ 'technology_tags',
98
+ 'units',
99
+ 'unit_tags',
100
+ ];
101
+ async function hasEntries(candidate, extensions) {
102
+ try {
103
+ const entries = await readdir(candidate, { withFileTypes: true });
104
+ return entries.some((entry) => entry.isFile() &&
105
+ (extensions === undefined ||
106
+ extensions.some((extension) => entry.name.toLowerCase().endsWith(extension))));
107
+ }
108
+ catch {
109
+ return false;
110
+ }
111
+ }
112
+ async function isRealDirectory(candidate) {
113
+ try {
114
+ const metadata = await lstat(candidate);
115
+ return metadata.isDirectory() && !metadata.isSymbolicLink();
116
+ }
117
+ catch {
118
+ return false;
119
+ }
120
+ }
121
+ async function isLikelyGameRoot(candidate) {
122
+ // Vanilla installations have an executable or launcher marker that a mod
123
+ // root should never contain. The marker check also protects a nested cwd
124
+ // such as `<game>/common` when the server is started from there.
125
+ return ((await isFile(path.join(candidate, 'hoi4.exe'))) ||
126
+ (await isFile(path.join(candidate, 'run_hoi4'))) ||
127
+ (await isFile(path.join(candidate, 'steam_appid.txt'))));
128
+ }
129
+ async function isLikelyModRoot(candidate) {
130
+ if (await isFile(path.join(candidate, 'descriptor.mod')))
131
+ return true;
132
+ if (await isLikelyGameRoot(candidate))
133
+ return false;
134
+ for (const directory of MOD_COMMON_DIRECTORIES) {
135
+ if (await isRealDirectory(path.join(candidate, 'common', directory)))
136
+ return true;
137
+ }
138
+ if (await isFile(path.join(candidate, 'common', 'combat_tactics.txt')))
139
+ return true;
140
+ for (const directory of MOD_CONTENT_DIRECTORIES) {
141
+ if ((await isRealDirectory(path.join(candidate, directory))) &&
142
+ (await hasEntries(path.join(candidate, directory), MOD_CONTENT_EXTENSIONS[directory])))
143
+ return true;
144
+ }
145
+ return false;
146
+ }
42
147
  async function findCurrentModRoot(start = process.cwd()) {
43
148
  for (let cursor = path.resolve(start);;) {
44
- if ((await isFile(path.join(cursor, 'descriptor.mod'))) ||
45
- ((await isDirectory(path.join(cursor, 'common'))) &&
46
- ((await isDirectory(path.join(cursor, 'history'))) ||
47
- (await isDirectory(path.join(cursor, 'interface'))) ||
48
- (await isDirectory(path.join(cursor, 'map')))))) {
149
+ if (await isLikelyGameRoot(cursor))
150
+ break;
151
+ if (await isLikelyModRoot(cursor))
49
152
  return cursor;
50
- }
51
153
  const parent = path.dirname(cursor);
52
154
  if (parent === cursor)
53
155
  break;