hoi4-agent-tools 4.12.0 → 4.14.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 (96) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/README.md +3 -3
  3. package/dist/bin/setup.js +38 -0
  4. package/dist/bin/stdio.js +5 -1
  5. package/dist/hoi4_agent_tools/core/configuration.js +16 -0
  6. package/dist/hoi4_agent_tools/core/domain-tools.js +4 -0
  7. package/dist/hoi4_agent_tools/core/engine-check.js +87 -0
  8. package/dist/hoi4_agent_tools/core/engine-client.js +1 -1
  9. package/dist/hoi4_agent_tools/core/job-operation-registration.js +2 -0
  10. package/dist/hoi4_agent_tools/localisation/job-operations.js +42 -0
  11. package/dist/hoi4_agent_tools/localisation/write-diff.js +96 -0
  12. package/dist/hoi4_agent_tools/localisation/write-format.js +329 -0
  13. package/dist/hoi4_agent_tools/localisation/write-operations.js +213 -0
  14. package/dist/hoi4_agent_tools/localisation/write-plan.js +557 -0
  15. package/dist/hoi4_agent_tools/map/gameplay/crossing-validation.js +17 -0
  16. package/dist/hoi4_agent_tools/map/model.js +31 -1
  17. package/dist/hoi4_agent_tools/map/operations.js +2 -1
  18. package/dist/hoi4_agent_tools/map/world-edge.js +0 -25
  19. package/dist/hoi4_agent_tools/map/world.js +124 -34
  20. package/dist/hoi4_agent_tools/mcp/server/argument-errors.js +5 -0
  21. package/dist/hoi4_agent_tools/mcp/server/create-modern-operations.js +8 -3
  22. package/dist/hoi4_agent_tools/mcp/server/create.js +5 -1
  23. package/dist/hoi4_agent_tools/mcp/server/request-lifecycle.js +10 -2
  24. package/dist/hoi4_agent_tools/mcp/server/task-tool-catalog.js +2 -0
  25. package/dist/hoi4_agent_tools/mcp/server/tool-profiles.js +83 -0
  26. package/dist/hoi4_agent_tools/mcp/tools/localisation-write.js +21 -0
  27. package/dist/hoi4_agent_tools/mcp/tools/reference.js +34 -0
  28. package/dist/hoi4_agent_tools/mcp/transports/http.js +6 -1
  29. package/dist/hoi4_agent_tools/reference/compat-patch.js +555 -0
  30. package/dist/hoi4_agent_tools/reference/compat.js +255 -0
  31. package/dist/hoi4_agent_tools/reference/docs-pack.js +164 -0
  32. package/dist/hoi4_agent_tools/reference/docs-pack.json +339 -0
  33. package/dist/hoi4_agent_tools/reference/documented-commands.js +26 -0
  34. package/dist/hoi4_agent_tools/reference/error-explain.js +235 -0
  35. package/dist/hoi4_agent_tools/reference/error-explanations.json +262 -0
  36. package/dist/hoi4_agent_tools/reference/error-log.js +30 -10
  37. package/dist/hoi4_agent_tools/reference/mod-health.js +255 -0
  38. package/dist/hoi4_agent_tools/reference/operations.js +435 -21
  39. package/dist/hoi4_agent_tools/reference/script-guard.js +109 -0
  40. package/dist/hoi4_agent_tools/reference/service.js +58 -20
  41. package/dist/hoi4_agent_tools/runtime.js +11 -0
  42. package/dist/hoi4_agent_tools/schemas/compat.js +153 -0
  43. package/dist/hoi4_agent_tools/schemas/localisation-write.js +154 -0
  44. package/dist/hoi4_agent_tools/schemas/map.js +13 -1
  45. package/dist/hoi4_agent_tools/schemas/modder-tools.js +191 -0
  46. package/dist/hoi4_agent_tools/version.js +1 -1
  47. package/docs/configuration.md +4 -1
  48. package/docs/jobs.md +2 -1
  49. package/docs/map.md +4 -2
  50. package/docs/reference.md +45 -5
  51. package/docs/setup.md +23 -3
  52. package/docs/tools.md +16 -1
  53. package/engine/bin/manifest.json +1 -1
  54. package/engine/bin/win32-x64/hoi4-engine.exe +0 -0
  55. package/npm-shrinkwrap.json +2 -2
  56. package/package.json +1 -1
  57. package/schemas/configuration.schema.json +140 -113
  58. package/schemas/continuous-focus-palette.schema.json +1 -1
  59. package/schemas/custom-weighted-pool.schema.json +1 -1
  60. package/schemas/decision-inspect-input.schema.json +1 -1
  61. package/schemas/error-log-input.schema.json +1 -1
  62. package/schemas/event-feature-manifest.schema.json +1 -1
  63. package/schemas/focus-plan.schema.json +1 -1
  64. package/schemas/focus-planning-sidecar.schema.json +1 -1
  65. package/schemas/geography-model.schema.json +1 -1
  66. package/schemas/gui-animation-source.schema.json +1 -1
  67. package/schemas/gui-helper.schema.json +1 -1
  68. package/schemas/gui-scenario.schema.json +1 -1
  69. package/schemas/helper-expansion-request.schema.json +1 -1
  70. package/schemas/helper-expansion-summary.schema.json +1 -1
  71. package/schemas/impact-inspect-input.schema.json +1 -1
  72. package/schemas/map-operation.schema.json +170 -139
  73. package/schemas/mechanic-test-input.schema.json +1 -1
  74. package/schemas/mod-index-input.schema.json +1 -1
  75. package/schemas/operation-result.schema.json +1 -1
  76. package/schemas/package-check-input.schema.json +1 -1
  77. package/schemas/package-manifest.schema.json +1 -1
  78. package/schemas/probability-analysis-result.schema.json +1 -1
  79. package/schemas/probability-compare-input.schema.json +1 -1
  80. package/schemas/probability-evaluate-input.schema.json +1 -1
  81. package/schemas/probability-inspect-input.schema.json +1 -1
  82. package/schemas/probability-render-input.schema.json +1 -1
  83. package/schemas/probability-scenario-set.schema.json +1 -1
  84. package/schemas/probability-sequence-input.schema.json +1 -1
  85. package/schemas/probability-simulate-input.schema.json +1 -1
  86. package/schemas/probability-sweep-input.schema.json +1 -1
  87. package/schemas/reference-context-input.schema.json +1 -1
  88. package/schemas/reference-read-input.schema.json +1 -1
  89. package/schemas/reference-search-input.schema.json +1 -1
  90. package/schemas/reference-sheets.schema.json +1 -1
  91. package/schemas/scenario-suite.schema.json +1 -1
  92. package/schemas/scenario-test-input.schema.json +1 -1
  93. package/schemas/script-validate-input.schema.json +1 -1
  94. package/schemas/shared-scenario.schema.json +1 -1
  95. package/schemas/source-lookup-input.schema.json +1 -1
  96. package/server.json +2 -2
@@ -1,18 +1,30 @@
1
+ import { realpath, stat } from 'node:fs/promises';
2
+ import path from 'node:path';
1
3
  import { hashCanonical } from '../core/canonical.js';
2
4
  import { parseClausewitz } from '../core/source/index.js';
3
5
  import { requireOperationScope, resolveOperationWorkspaceForSource, } from '../core/operation-context.js';
4
- import { emptyServiceResult } from '../core/result.js';
6
+ import { emptyServiceResult, ServiceError } from '../core/result.js';
7
+ import { globFiles } from '../core/file-glob.js';
8
+ import { checkedLayerName, runEngineCheck } from '../core/engine-check.js';
5
9
  import { toolResult } from '../core/operation-result.js';
6
10
  import { referenceContextRequestSchema, referenceReadRequestSchema, referenceSearchRequestSchema, sourceLookupRequestSchema, } from '../schemas/reference.js';
7
11
  import { ReferenceService } from './service.js';
8
12
  import { sourceLookup } from './source-lookup.js';
9
13
  import { scriptValidateDataSchema, scriptValidateRequestSchema, } from '../schemas/script-validation.js';
10
14
  import { identifierArgumentCommands, validateScript, } from './script-validation.js';
11
- import { modChangedAfter, readErrorLog } from './error-log.js';
15
+ import { categoryHints, errorLogPattern, modChangedAfter, readErrorLog } from './error-log.js';
16
+ import { errorExplanations, explainErrors } from './error-explain.js';
17
+ import { documentedNames } from './documented-commands.js';
18
+ import { explainErrorRequestSchema, modHealthDataSchema, modHealthRequestSchema, scriptGuardDataSchema, scriptGuardRequestSchema, } from '../schemas/modder-tools.js';
19
+ import { guardedFiles, inventedNames } from './script-guard.js';
20
+ import { rankProblems } from './mod-health.js';
12
21
  import { modIndex } from './mod-index.js';
13
22
  import { listSkills, loadSkill } from './skills.js';
14
23
  import { skillDataSchema, skillRequestSchema } from '../schemas/skill.js';
15
24
  import { inspectLocalisation } from '../localisation/inspect.js';
25
+ import { checkModCompatibility } from './compat.js';
26
+ import { checkPatchCompatibility } from './compat-patch.js';
27
+ import { compatCheckDataSchema, compatCheckRequestSchema, } from '../schemas/compat.js';
16
28
  import { inspectIdeas } from '../ideas/inspect.js';
17
29
  import { ideaInspectDataSchema, ideaInspectRequestSchema } from '../schemas/ideas.js';
18
30
  import { inspectAssets, inspectSystem, inspectUnits } from '../system/inspect.js';
@@ -55,8 +67,12 @@ const schemas = {
55
67
  'hoi4.source_lookup': sourceLookupRequestSchema,
56
68
  'hoi4.script_validate': scriptValidateRequestSchema,
57
69
  'hoi4.error_log': errorLogRequestSchema,
70
+ 'hoi4.explain_error': explainErrorRequestSchema,
71
+ 'hoi4.mod_health': modHealthRequestSchema,
72
+ 'hoi4.script_guard': scriptGuardRequestSchema,
58
73
  'hoi4.mod_index': modIndexRequestSchema,
59
74
  'hoi4.localisation_inspect': localisationInspectRequestSchema,
75
+ 'hoi4.compat_check': compatCheckRequestSchema,
60
76
  'hoi4.idea_inspect': ideaInspectRequestSchema,
61
77
  'hoi4.system_inspect': systemInspectRequestSchema,
62
78
  'hoi4.unit_inspect': unitInspectRequestSchema,
@@ -70,6 +86,14 @@ const ASSET_INFORMATION = new Set([
70
86
  'ASSET_TEXTURE_EMPTY',
71
87
  'ASSET_FLAG_SIZE_CLOSE',
72
88
  ]);
89
+ function isDocumentationTool(name) {
90
+ return (name === 'hoi4.reference_search' ||
91
+ name === 'hoi4.reference_read' ||
92
+ name === 'hoi4.reference_context');
93
+ }
94
+ /** The workspace id of an answer from the documentation alone, and a request for one. */
95
+ export const DOCS_WORKSPACE_ID = 'docs';
96
+ const FETCH_DOCS_FIX = 'Run `hoi4-agent-tools-setup --fetch-docs` once to install the HOI4 wiki pages for documentation search';
73
97
  export function isReferenceTool(name) {
74
98
  return Object.hasOwn(schemas, name);
75
99
  }
@@ -80,15 +104,39 @@ export class ReferenceToolService {
80
104
  references;
81
105
  constructor(engine) {
82
106
  this.engine = engine;
83
- const cached = sharedReferences.get(engine) ?? new ReferenceService();
107
+ const cached = sharedReferences.get(engine) ??
108
+ new ReferenceService({ docsRoot: engine.resolver.config().docsRoot });
84
109
  sharedReferences.set(engine, cached);
85
110
  this.references = cached;
86
111
  }
87
112
  async call(name, input, context, signal) {
88
113
  requireOperationScope(context, 'hoi4:read');
89
114
  const parsed = schemas[name].parse(input);
115
+ if (isDocumentationTool(name) && parsed.workspaceId === DOCS_WORKSPACE_ID) {
116
+ const target = await this.documentationTarget();
117
+ if (target === undefined)
118
+ throw new ServiceError('REFERENCE_DOCUMENTATION_UNAVAILABLE', `Documentation without a mod needs the game folder (gameRoot) or the docs pack. ${FETCH_DOCS_FIX}`);
119
+ return this.documentationOnly(name, parsed, target, signal);
120
+ }
90
121
  // A validated file names its mod when the client's roots and working directory do not.
91
- const workspaceId = await resolveOperationWorkspaceForSource(this.engine, context, parsed.workspaceId, name === 'hoi4.script_validate' ? scriptValidateRequestSchema.parse(parsed).path : undefined, signal);
122
+ let workspaceId;
123
+ try {
124
+ workspaceId = await resolveOperationWorkspaceForSource(this.engine, context, parsed.workspaceId, name === 'hoi4.script_validate'
125
+ ? scriptValidateRequestSchema.parse(parsed).path
126
+ : undefined, signal);
127
+ }
128
+ catch (error) {
129
+ // Documentation does not need a mod: with none selected it comes from the game and the pack.
130
+ if (!isDocumentationTool(name) ||
131
+ parsed.workspaceId !== 'current' ||
132
+ !(error instanceof ServiceError) ||
133
+ !['WORKSPACE_CONTEXT_NOT_FOUND', 'WORKSPACE_CONTEXT_REQUIRED'].includes(error.code))
134
+ throw error;
135
+ const target = await this.documentationTarget();
136
+ if (target === undefined)
137
+ throw new ServiceError(error.code, `${error.message}. ${FETCH_DOCS_FIX}`, error.details);
138
+ return this.documentationOnly(name, parsed, target, signal);
139
+ }
92
140
  const workspace = this.engine.resolver.get(workspaceId, context.principal);
93
141
  const data = name === 'hoi4.reference_search'
94
142
  ? await this.references.searchHits(workspace, referenceSearchRequestSchema.parse(parsed), signal)
@@ -98,24 +146,69 @@ export class ReferenceToolService {
98
146
  ? await this.references.contextHits(workspace, referenceContextRequestSchema.parse(parsed), signal)
99
147
  : name === 'hoi4.error_log'
100
148
  ? await readErrorLog(workspace, errorLogRequestSchema.parse(parsed), this.engine.resolver.config().gameUserRoot, signal)
101
- : name === 'hoi4.mod_index'
102
- ? await modIndex(this.engine, workspaceId, modIndexRequestSchema.parse(parsed), context.principal, signal)
103
- : name === 'hoi4.script_validate'
104
- ? await this.validateScript(workspaceId, workspace, scriptValidateRequestSchema.parse(parsed), context.principal, signal)
105
- : name === 'hoi4.idea_inspect'
106
- ? await inspectIdeas(workspace, ideaInspectRequestSchema.parse(parsed), signal)
107
- : name === 'hoi4.system_inspect'
108
- ? await inspectSystem(workspace, systemInspectRequestSchema.parse(parsed), signal)
109
- : name === 'hoi4.asset_inspect'
110
- ? await inspectAssets(workspace, assetInspectRequestSchema.parse(parsed), signal)
111
- : name === 'hoi4.unit_inspect'
112
- ? await inspectUnits(workspace, unitInspectRequestSchema.parse(parsed), signal)
113
- : name === 'hoi4.skill'
114
- ? await this.skill(workspace, skillRequestSchema.parse(parsed), signal)
115
- : name === 'hoi4.localisation_inspect'
116
- ? await inspectLocalisation(workspace, localisationInspectRequestSchema.parse(parsed), signal)
117
- : await sourceLookup(this.engine, workspaceId, sourceLookupRequestSchema.parse(parsed), context.principal, signal);
149
+ : name === 'hoi4.script_guard'
150
+ ? await this.scriptGuard(workspaceId, workspace, scriptGuardRequestSchema.parse(parsed), context.principal, signal)
151
+ : name === 'hoi4.mod_health'
152
+ ? await this.modHealth(workspaceId, workspace, modHealthRequestSchema.parse(parsed), context.principal, signal)
153
+ : name === 'hoi4.explain_error'
154
+ ? await this.explainError(workspaceId, workspace, explainErrorRequestSchema.parse(parsed), context.principal, signal)
155
+ : name === 'hoi4.mod_index'
156
+ ? await modIndex(this.engine, workspaceId, modIndexRequestSchema.parse(parsed), context.principal, signal)
157
+ : name === 'hoi4.script_validate'
158
+ ? await this.validateScript(workspaceId, workspace, scriptValidateRequestSchema.parse(parsed), context.principal, signal)
159
+ : name === 'hoi4.idea_inspect'
160
+ ? await inspectIdeas(workspace, ideaInspectRequestSchema.parse(parsed), signal)
161
+ : name === 'hoi4.system_inspect'
162
+ ? await inspectSystem(workspace, systemInspectRequestSchema.parse(parsed), signal)
163
+ : name === 'hoi4.asset_inspect'
164
+ ? await inspectAssets(workspace, assetInspectRequestSchema.parse(parsed), signal)
165
+ : name === 'hoi4.unit_inspect'
166
+ ? await inspectUnits(workspace, unitInspectRequestSchema.parse(parsed), signal)
167
+ : name === 'hoi4.compat_check'
168
+ ? await this.checkCompat(workspace, compatCheckRequestSchema.parse(parsed), context.principal, signal)
169
+ : name === 'hoi4.skill'
170
+ ? await this.skill(workspace, skillRequestSchema.parse(parsed), signal)
171
+ : name === 'hoi4.localisation_inspect'
172
+ ? await inspectLocalisation(workspace, localisationInspectRequestSchema.parse(parsed), signal)
173
+ : await sourceLookup(this.engine, workspaceId, sourceLookupRequestSchema.parse(parsed), context.principal, signal);
118
174
  const result = emptyServiceResult(workspaceId, data);
175
+ if (isDocumentationTool(name))
176
+ result.diagnostics.push(...(await this.wikiHint(data)));
177
+ if (name === 'hoi4.script_guard') {
178
+ const guard = scriptGuardDataSchema.parse(data);
179
+ result.code = 'SCRIPT_GUARD_CHECKED';
180
+ const invented = guard.counts.effect + guard.counts.trigger + guard.counts.modifier;
181
+ result.validation = {
182
+ passed: guard.verdict === 'clean',
183
+ checks: [
184
+ {
185
+ id: 'script-guard',
186
+ passed: guard.verdict === 'clean',
187
+ message: guard.verdict === 'clean'
188
+ ? `Every effect, trigger and modifier in ${guard.filesChecked} files is documented or defined`
189
+ : `${invented} names in ${guard.filesChecked} files are neither documented nor defined`,
190
+ },
191
+ ],
192
+ };
193
+ }
194
+ if (name === 'hoi4.mod_health') {
195
+ const health = modHealthDataSchema.parse(data);
196
+ result.code = 'MOD_HEALTH_CHECKED';
197
+ result.validation = {
198
+ passed: health.verdict === 'healthy',
199
+ checks: [
200
+ {
201
+ id: 'mod-health',
202
+ passed: health.verdict === 'healthy',
203
+ message: health.verdict === 'healthy'
204
+ ? 'Every audit ran and found no problem'
205
+ : health.verdict === 'incomplete'
206
+ ? 'No problem found, but an audit could not run'
207
+ : `${health.totals.problems} kinds of problem, ${health.totals.findings} findings`,
208
+ },
209
+ ],
210
+ };
211
+ }
119
212
  if (name === 'hoi4.error_log') {
120
213
  const log = errorLogDataSchema.parse(data);
121
214
  result.code = 'ERROR_LOG_READ';
@@ -268,6 +361,21 @@ export class ReferenceToolService {
268
361
  ],
269
362
  };
270
363
  }
364
+ if (name === 'hoi4.compat_check') {
365
+ const checked = compatCheckDataSchema.parse(data);
366
+ result.code = checked.mode === 'mod' ? 'COMPAT_MOD_CHECKED' : 'COMPAT_PATCH_CHECKED';
367
+ if (checked.mode === 'mod')
368
+ result.validation = {
369
+ passed: checked.verdict === 'no_conflicts',
370
+ checks: [
371
+ {
372
+ id: 'mod-compatibility',
373
+ passed: checked.verdict === 'no_conflicts',
374
+ message: checked.summary,
375
+ },
376
+ ],
377
+ };
378
+ }
271
379
  if (name === 'hoi4.localisation_inspect') {
272
380
  const inspected = localisationInspectDataSchema.parse(data);
273
381
  result.code = 'LOCALISATION_INSPECTED';
@@ -332,12 +440,238 @@ export class ReferenceToolService {
332
440
  #eventPopups = new Map();
333
441
  /** The latest player-text context of each workspace, keyed by its source files' hashes. */
334
442
  #playerText = new Map();
443
+ /**
444
+ * The documentation alone, for a call with no mod: the installed game's documentation
445
+ * (gameRoot) and the docs pack, read as one workspace that has no mod files.
446
+ */
447
+ async documentationTarget() {
448
+ const configuredGameRoot = this.engine.resolver.config().gameRoot;
449
+ // The canonical path, as every registered workspace has: the roots are compared by it.
450
+ const gameRoot = configuredGameRoot === undefined
451
+ ? undefined
452
+ : await realpath(configuredGameRoot).catch(() => configuredGameRoot);
453
+ const wiki = await this.references.docsPackWiki();
454
+ if (gameRoot === undefined && wiki === undefined)
455
+ return undefined;
456
+ return {
457
+ modRoot: gameRoot ?? path.dirname(wiki),
458
+ ...(gameRoot === undefined ? {} : { gameRoot }),
459
+ ...(wiki === undefined ? {} : { wikiRoot: wiki }),
460
+ registration: { kind: 'mod' },
461
+ };
462
+ }
463
+ async documentationOnly(name, parsed, target, signal) {
464
+ const data = name === 'hoi4.reference_search'
465
+ ? await this.references.searchHits(target, referenceSearchRequestSchema.parse(parsed), signal)
466
+ : name === 'hoi4.reference_read'
467
+ ? await this.references.read(target, referenceReadRequestSchema.parse(parsed), signal)
468
+ : await this.references.contextHits(target, referenceContextRequestSchema.parse(parsed), signal);
469
+ const result = emptyServiceResult(DOCS_WORKSPACE_ID, data);
470
+ result.diagnostics.push({
471
+ code: 'REFERENCE_DOCUMENTATION_ONLY',
472
+ severity: 'info',
473
+ category: 'configuration',
474
+ message: 'No mod is selected, so this answer comes from the game documentation and the docs pack only',
475
+ }, ...(await this.wikiHint(data)));
476
+ return toolResult(result, { compact: true });
477
+ }
478
+ /** Name the fix when no wiki was read and no docs pack is installed. */
479
+ async wikiHint(data) {
480
+ const coverage = data
481
+ .coverage?.wiki;
482
+ if (coverage === undefined ||
483
+ !coverage.unavailable ||
484
+ !coverage.included ||
485
+ !this.references.docsPackConfigured ||
486
+ (await this.references.docsPackWiki()) !== undefined)
487
+ return [];
488
+ return [
489
+ {
490
+ code: 'REFERENCE_WIKI_UNAVAILABLE',
491
+ severity: 'info',
492
+ category: 'configuration',
493
+ message: `No HOI4 wiki pages were found. ${FETCH_DOCS_FIX}`,
494
+ },
495
+ ];
496
+ }
497
+ /**
498
+ * `hoi4.mod_health`: the error log, the engine's whole-mod check and the localisation and
499
+ * asset audits run side by side; script validation then checks the files they named first,
500
+ * and the newest after them, within a time budget.
501
+ */
502
+ async modHealth(workspaceId, workspace, request, principal, signal) {
503
+ const wanted = new Set(request.checks ?? ['error_log', 'engine_check', 'script', 'localisation', 'assets']);
504
+ const timed = async (check, run) => {
505
+ if (!wanted.has(check))
506
+ return { check, status: 'skipped', ms: 0, findings: [] };
507
+ const started = performance.now();
508
+ try {
509
+ return { check, ...(await run()), ms: performance.now() - started };
510
+ }
511
+ catch (error) {
512
+ if (error.name === 'AbortError')
513
+ throw error;
514
+ const code = error instanceof ServiceError ? error.code : 'INTERNAL_ERROR';
515
+ return {
516
+ check,
517
+ status: 'unavailable',
518
+ ms: performance.now() - started,
519
+ findings: [],
520
+ note: `${code}: ${error.message}`,
521
+ };
522
+ }
523
+ };
524
+ const [errorLog, engineCheck, localisation, assets] = await Promise.all([
525
+ timed('error_log', () => this.healthErrorLog(workspace, signal)),
526
+ timed('engine_check', () => healthEngineCheck(workspace, signal)),
527
+ timed('localisation', () => healthLocalisation(workspace, signal)),
528
+ timed('assets', () => healthAssets(workspace, signal)),
529
+ ]);
530
+ // The files the other audits name are validated first.
531
+ const named = new Set([...errorLog.findings, ...engineCheck.findings].flatMap(({ path: file }) => file === undefined ? [] : [file]));
532
+ const script = await timed('script', () => this.healthScript(workspaceId, workspace, named, principal, signal));
533
+ return rankProblems([errorLog, engineCheck, script, localisation, assets], request.limit);
534
+ }
535
+ /** The mod's own entries of the last launch's error.log, grouped by what they report. */
536
+ async healthErrorLog(workspace, signal) {
537
+ const log = await readErrorLog(workspace, errorLogRequestSchema.parse({ scope: 'mod', limit: 50 }), this.engine.resolver.config().gameUserRoot, signal);
538
+ if (log.launch?.modLoaded === false)
539
+ return {
540
+ status: 'partial',
541
+ findings: [],
542
+ note: 'The last game launch did not load this mod, so its error.log says nothing about it',
543
+ };
544
+ const stale = await modChangedAfter(workspace.modRoot, Date.parse(log.log.modifiedAt), signal);
545
+ const findings = log.entries
546
+ .filter((entry) => entry.source?.layer === 'mod')
547
+ .map((entry) => {
548
+ const matched = errorExplanations.find((explanation) => explanation.regex.test(entry.message));
549
+ return {
550
+ code: `LOG_${(matched?.id ?? entry.category).toUpperCase()}`,
551
+ severity: 'error',
552
+ message: entry.message,
553
+ ...(entry.source === undefined ? {} : { path: entry.source.relativePath }),
554
+ ...(entry.source?.line === undefined ? {} : { line: entry.source.line }),
555
+ };
556
+ });
557
+ return {
558
+ status: stale === undefined ? 'ran' : 'partial',
559
+ findings,
560
+ ...(stale === undefined
561
+ ? {}
562
+ : {
563
+ note: `${stale.files} mod files changed after the log was written; relaunch the game for a current log`,
564
+ }),
565
+ describe: (_code, examples) => {
566
+ const first = examples[0].message;
567
+ const category = log.entries.find((entry) => entry.message === first)?.category ?? 'other';
568
+ return {
569
+ title: `The game reports: ${errorLogPattern(first)}`,
570
+ fix: `${categoryHints[category]} hoi4.explain_error explains each line.`,
571
+ weight: (category === 'syntax' ? 100 : 90) - (stale === undefined ? 0 : 30),
572
+ next: { tool: 'hoi4.explain_error', arguments: { line: first.slice(0, 1000) } },
573
+ };
574
+ },
575
+ };
576
+ }
577
+ /** Validate the mod's script files: the ones other audits named, then the newest. */
578
+ async healthScript(workspaceId, workspace, named, principal, signal) {
579
+ const files = await globFiles(HEALTH_SCRIPT_PATTERNS, {
580
+ cwd: workspace.modRoot,
581
+ caseSensitive: false,
582
+ ...(signal === undefined ? {} : { signal }),
583
+ });
584
+ const modified = new Map();
585
+ for (const file of files)
586
+ modified.set(file, (await stat(path.join(workspace.modRoot, file)).catch(() => undefined))?.mtimeMs ?? 0);
587
+ const ordered = [...files].sort((left, right) => Number(named.has(right)) - Number(named.has(left)) ||
588
+ modified.get(right) - modified.get(left) ||
589
+ (left < right ? -1 : 1));
590
+ const deadline = performance.now() + HEALTH_SCRIPT_BUDGET_MS;
591
+ const findings = [];
592
+ let checked = 0;
593
+ for (const file of ordered.slice(0, HEALTH_SCRIPT_MAX_FILES)) {
594
+ if (performance.now() > deadline)
595
+ break;
596
+ signal?.throwIfAborted();
597
+ const validated = await this.validateScript(workspaceId, workspace, scriptValidateRequestSchema.parse({ path: file, limit: 32 }), principal, signal);
598
+ checked += 1;
599
+ for (const finding of validated.findings)
600
+ if (finding.status === 'error' || finding.status === 'warning')
601
+ findings.push({
602
+ code: finding.code,
603
+ severity: finding.status,
604
+ message: finding.message,
605
+ path: file,
606
+ line: finding.line,
607
+ });
608
+ }
609
+ return {
610
+ status: checked === files.length ? 'ran' : 'partial',
611
+ findings,
612
+ ...(checked === files.length
613
+ ? {}
614
+ : {
615
+ note: `Checked ${checked} of ${files.length} script files within the time budget: files other audits named first, then the newest`,
616
+ }),
617
+ };
618
+ }
619
+ /**
620
+ * `hoi4.script_guard`: the engine's whole-mod check narrowed to the files an agent wrote, and
621
+ * script validation of the first of them for the names the engine does not read as commands.
622
+ */
623
+ async scriptGuard(workspaceId, workspace, request, principal, signal) {
624
+ const { files, candidates } = await guardedFiles(workspace.modRoot, request, Date.now(), signal);
625
+ if (files.length === 0)
626
+ throw new ServiceError('SCRIPT_GUARD_NO_FILES', `No script file of the mod changed in the last ${request.sinceMinutes} minutes; pass paths to name the files to check`);
627
+ const report = await runEngineCheck({
628
+ mod: workspace.modRoot,
629
+ ...(workspace.gameRoot === undefined ? {} : { game: workspace.gameRoot }),
630
+ dependencies: workspace.dependencyRoots,
631
+ includeDlc: workspace.dlcLayers.length > 0,
632
+ }, signal === undefined ? {} : { signal });
633
+ const unresolved = [];
634
+ for (const file of files.filter((candidate) => SCRIPT_FILE.test(candidate)).slice(0, 50)) {
635
+ signal?.throwIfAborted();
636
+ const validated = await this.validateScript(workspaceId, workspace, scriptValidateRequestSchema.parse({ path: file, limit: 32 }), principal, signal);
637
+ for (const finding of validated.findings)
638
+ if (finding.code === 'SCRIPT_COMMAND_UNRESOLVED' &&
639
+ finding.command !== '' &&
640
+ (finding.kind === 'effect' || finding.kind === 'trigger'))
641
+ unresolved.push({
642
+ name: finding.command,
643
+ kind: finding.kind,
644
+ path: file,
645
+ line: finding.line,
646
+ ...(finding.suggestions[0] === undefined ? {} : { suggestion: finding.suggestions[0] }),
647
+ message: `\`${finding.command}\` is neither a documented ${finding.kind} nor a scripted ${finding.kind} defined in any loaded file`,
648
+ });
649
+ }
650
+ return inventedNames(report, files, candidates, unresolved);
651
+ }
652
+ /** Explanations know the documented commands and the scripted helpers the loaded files define. */
653
+ async explainError(workspaceId, workspace, request, principal, signal) {
654
+ const snapshot = await this.engine.scan(workspaceId, { patterns: ['common/scripted_effects/**/*.txt', 'common/scripted_triggers/**/*.txt'] }, principal, signal);
655
+ const helpers = (kind) => new Set(snapshot.index.symbols.filter((symbol) => symbol.kind === kind).map(({ id }) => id));
656
+ const documented = await documentedNames(this.references, workspace, signal);
657
+ return explainErrors(request, {
658
+ workspace,
659
+ ...(documented === undefined ? {} : { documented }),
660
+ helpers: { effect: helpers('scripted_effect'), trigger: helpers('scripted_trigger') },
661
+ ...(signal === undefined ? {} : { signal }),
662
+ });
663
+ }
335
664
  /** File mode reads the scanned file and the mod's scripted helper names from one scan. */
336
665
  async skill(workspace, request, signal) {
337
666
  return request.name === undefined
338
667
  ? listSkills(workspace, signal)
339
668
  : loadSkill(workspace, { ...request, name: request.name }, signal);
340
669
  }
670
+ async checkCompat(workspace, input, principal, signal) {
671
+ return input.mode === 'mod'
672
+ ? checkModCompatibility(this.engine, workspace, input, principal, signal)
673
+ : checkPatchCompatibility(workspace, input, signal);
674
+ }
341
675
  async validateScript(workspaceId, workspace, request, principal, signal) {
342
676
  // Every file check of the supported families shares one scan, so checking files across
343
677
  // folders reuses one snapshot and its incremental index; other folders add their own.
@@ -524,3 +858,83 @@ function playerTextFamily(relativePath) {
524
858
  file.startsWith('common/national_focus/') ||
525
859
  (file.startsWith('common/decisions/') && !file.startsWith('common/decisions/categories/')));
526
860
  }
861
+ /** The script families file validation checks, in the mod's own folder. */
862
+ const HEALTH_SCRIPT_PATTERNS = [
863
+ 'events/**/*.txt',
864
+ 'common/decisions/**/*.txt',
865
+ 'common/national_focus/**/*.txt',
866
+ 'common/on_actions/**/*.txt',
867
+ 'common/scripted_effects/**/*.txt',
868
+ 'common/scripted_triggers/**/*.txt',
869
+ ];
870
+ const HEALTH_SCRIPT_BUDGET_MS = 30_000;
871
+ /** The families script validation reads, for the guard's second pass. */
872
+ const SCRIPT_FILE = /^(?:events|common\/(?:decisions|national_focus|on_actions|scripted_effects|scripted_triggers))\//u;
873
+ const HEALTH_SCRIPT_MAX_FILES = 400;
874
+ /** The engine's whole-mod check: findings in the mod's own layer. */
875
+ async function healthEngineCheck(workspace, signal) {
876
+ const report = await runEngineCheck({
877
+ mod: workspace.modRoot,
878
+ ...(workspace.gameRoot === undefined ? {} : { game: workspace.gameRoot }),
879
+ dependencies: workspace.dependencyRoots,
880
+ includeDlc: workspace.dlcLayers.length > 0,
881
+ }, signal === undefined ? {} : { signal });
882
+ const layer = checkedLayerName(report);
883
+ return {
884
+ status: 'ran',
885
+ findings: report.findings
886
+ .filter((finding) => finding.layer === layer && finding.severity !== 'info')
887
+ .map((finding) => ({
888
+ code: finding.code,
889
+ severity: finding.severity === 'error' ? 'error' : 'warning',
890
+ message: finding.message,
891
+ path: finding.path,
892
+ line: finding.line,
893
+ })),
894
+ };
895
+ }
896
+ /** The engine's localisation audit; information is not a problem players see. */
897
+ async function healthLocalisation(workspace, signal) {
898
+ const inspected = await inspectLocalisation(workspace, localisationInspectRequestSchema.parse({ mode: 'audit', limit: 2 }), signal);
899
+ const problems = (inspected.audit?.problems ?? []).filter(({ severity }) => severity === 'warning');
900
+ const codes = new Set(problems.map(({ code }) => code));
901
+ return {
902
+ status: 'ran',
903
+ findings: problems.map(({ code, message, path: file, line }) => ({
904
+ code,
905
+ severity: 'warning',
906
+ message,
907
+ path: file,
908
+ line,
909
+ })),
910
+ counts: Object.fromEntries(Object.entries(inspected.audit?.counts ?? {}).filter(([code]) => codes.has(code))),
911
+ };
912
+ }
913
+ /** The engine's sprite and flag audits, without what players would not notice. */
914
+ async function healthAssets(workspace, signal) {
915
+ const findings = [];
916
+ const counts = {};
917
+ for (const kind of ['sprite', 'flag']) {
918
+ const inspected = await inspectAssets(workspace, assetInspectRequestSchema.parse({ kind, audit: true, limit: 2 }), signal);
919
+ for (const problem of inspected.audit?.problems ?? []) {
920
+ if (problem.severity !== 'warning' || ASSET_INFORMATION.has(problem.code))
921
+ continue;
922
+ findings.push({
923
+ code: problem.code,
924
+ severity: 'warning',
925
+ message: problem.message,
926
+ path: problem.path,
927
+ line: problem.line,
928
+ });
929
+ }
930
+ for (const [code, count] of Object.entries(inspected.audit?.counts ?? {}))
931
+ if (!ASSET_INFORMATION.has(code))
932
+ counts[code] = (counts[code] ?? 0) + count;
933
+ }
934
+ const codes = new Set(findings.map(({ code }) => code));
935
+ return {
936
+ status: 'ran',
937
+ findings,
938
+ counts: Object.fromEntries(Object.entries(counts).filter(([code]) => codes.has(code))),
939
+ };
940
+ }
@@ -0,0 +1,109 @@
1
+ import { stat } from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { globFiles } from '../core/file-glob.js';
4
+ import { checkedLayerName } from '../core/engine-check.js';
5
+ import { ServiceError } from '../core/result.js';
6
+ /** The engine codes for a name that nothing documents or defines, by the kind of name. */
7
+ const INVENTED = {
8
+ REF_UNKNOWN_EFFECT: 'effect',
9
+ REF_UNKNOWN_TRIGGER: 'trigger',
10
+ LINT_UNKNOWN_MODIFIER: 'modifier',
11
+ };
12
+ /** Script and modifier files an agent writes; other files hold no effects or triggers. */
13
+ const SCRIPT_PATTERNS = ['events/**/*.txt', 'common/**/*.txt', 'history/**/*.txt'];
14
+ const MAX_FILES = 200;
15
+ const MAX_INVENTED = 40;
16
+ function normalized(relativePath) {
17
+ return relativePath.replaceAll('\\', '/').replace(/^mod:/u, '').replace(/^\.\//u, '');
18
+ }
19
+ /**
20
+ * The files to guard: the named ones, or the mod's script files changed in the last
21
+ * `sinceMinutes`. File times decide, not Git, so a mod's repository settings never run.
22
+ */
23
+ export async function guardedFiles(modRoot, input, now = Date.now(), signal) {
24
+ if (input.paths !== undefined) {
25
+ const files = [];
26
+ for (const requested of input.paths) {
27
+ const relative = normalized(requested);
28
+ const absolute = path.resolve(modRoot, relative);
29
+ if (path.isAbsolute(relative) || !absolute.startsWith(path.resolve(modRoot) + path.sep))
30
+ throw new ServiceError('SCRIPT_GUARD_PATH_OUTSIDE_MOD', `Pass paths inside the mod, such as events/my_events.txt, not ${requested}`);
31
+ const info = await stat(absolute).catch(() => undefined);
32
+ if (info?.isFile() !== true)
33
+ throw new ServiceError('SCRIPT_GUARD_FILE_NOT_FOUND', `The mod has no file ${relative}`);
34
+ files.push(relative);
35
+ }
36
+ return { files: [...new Set(files)], candidates: files.length };
37
+ }
38
+ const since = now - input.sinceMinutes * 60_000;
39
+ const all = await globFiles(SCRIPT_PATTERNS, {
40
+ cwd: modRoot,
41
+ caseSensitive: false,
42
+ ...(signal === undefined ? {} : { signal }),
43
+ });
44
+ const changed = [];
45
+ for (const file of all) {
46
+ const info = await stat(path.join(modRoot, file)).catch(() => undefined);
47
+ if (info !== undefined && info.mtimeMs >= since)
48
+ changed.push({ file, modified: info.mtimeMs });
49
+ }
50
+ changed.sort((left, right) => right.modified - left.modified);
51
+ return {
52
+ files: changed.slice(0, MAX_FILES).map(({ file }) => normalized(file)),
53
+ candidates: changed.length,
54
+ };
55
+ }
56
+ /**
57
+ * The invented names in the guarded files: the engine's findings, plus the names script
58
+ * validation could not resolve, such as a trigger compared with `>`, which the engine's check
59
+ * does not read as a command. A name both report counts once.
60
+ */
61
+ export function inventedNames(report, files, candidates, unresolved = []) {
62
+ const layer = checkedLayerName(report);
63
+ const wanted = new Set(files.map((file) => file.toLowerCase()));
64
+ const found = report.findings
65
+ .filter((finding) => INVENTED[finding.code] !== undefined &&
66
+ finding.layer === layer &&
67
+ wanted.has(normalized(finding.path).toLowerCase()))
68
+ .map((finding) => ({
69
+ name: finding.subject ?? '',
70
+ kind: INVENTED[finding.code],
71
+ path: normalized(finding.path),
72
+ line: Math.max(1, finding.line),
73
+ ...(finding.context === undefined ? {} : { context: finding.context }),
74
+ ...(finding.suggestion === undefined ? {} : { suggestion: finding.suggestion }),
75
+ message: finding.message,
76
+ }));
77
+ const seen = new Set(found.map(({ path: file, line, name }) => `${file}\0${line}\0${name}`));
78
+ for (const name of unresolved) {
79
+ const key = `${normalized(name.path)}\0${name.line}\0${name.name}`;
80
+ if (seen.has(key) || !wanted.has(normalized(name.path).toLowerCase()))
81
+ continue;
82
+ seen.add(key);
83
+ found.push({ ...name, path: normalized(name.path) });
84
+ }
85
+ found.sort((left, right) => (left.path < right.path ? -1 : left.path > right.path ? 1 : 0) || left.line - right.line);
86
+ const counts = { effect: 0, trigger: 0, modifier: 0 };
87
+ const perFile = new Map();
88
+ for (const name of found) {
89
+ counts[name.kind] += 1;
90
+ perFile.set(name.path, (perFile.get(name.path) ?? 0) + 1);
91
+ }
92
+ return {
93
+ verdict: found.length === 0 ? 'clean' : 'invented',
94
+ filesChecked: files.length,
95
+ filesOmitted: Math.max(0, candidates - files.length),
96
+ counts,
97
+ files: files.map((file) => ({ path: file, invented: perFile.get(file) ?? 0 })).slice(0, 50),
98
+ invented: found.slice(0, MAX_INVENTED).map((name) => ({
99
+ name: name.name.slice(0, 256),
100
+ kind: name.kind,
101
+ path: name.path.slice(0, 1024),
102
+ line: name.line,
103
+ ...(name.context === undefined ? {} : { context: name.context.slice(0, 256) }),
104
+ ...(name.suggestion === undefined ? {} : { suggestion: name.suggestion.slice(0, 256) }),
105
+ message: name.message.slice(0, 300),
106
+ })),
107
+ inventedOmitted: Math.max(0, found.length - MAX_INVENTED),
108
+ };
109
+ }