hoi4-agent-tools 4.16.0 → 4.18.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 (109) hide show
  1. package/CHANGELOG.md +41 -0
  2. package/README.md +1 -0
  3. package/dist/hoi4_agent_tools/core/analysis-checkpoints.js +11 -4
  4. package/dist/hoi4_agent_tools/core/engine-client.js +30 -1
  5. package/dist/hoi4_agent_tools/core/engine.js +56 -27
  6. package/dist/hoi4_agent_tools/core/managed-outputs.js +54 -3
  7. package/dist/hoi4_agent_tools/core/operation-result.js +37 -6
  8. package/dist/hoi4_agent_tools/core/scanner.js +148 -7
  9. package/dist/hoi4_agent_tools/core/server-state.js +50 -2
  10. package/dist/hoi4_agent_tools/core/source/localisation.js +7 -1
  11. package/dist/hoi4_agent_tools/event/compare.js +47 -13
  12. package/dist/hoi4_agent_tools/event/operations.js +111 -20
  13. package/dist/hoi4_agent_tools/focus/importer.js +2 -5
  14. package/dist/hoi4_agent_tools/focus/lint.js +2 -5
  15. package/dist/hoi4_agent_tools/focus/model.js +19 -0
  16. package/dist/hoi4_agent_tools/focus/tool-operations.js +16 -1
  17. package/dist/hoi4_agent_tools/focus/tool-support.js +14 -0
  18. package/dist/hoi4_agent_tools/map/appearance-validation.js +6 -1
  19. package/dist/hoi4_agent_tools/map/border-quality-input.js +57 -8
  20. package/dist/hoi4_agent_tools/map/border-quality.js +15 -6
  21. package/dist/hoi4_agent_tools/map/engine-raster.js +160 -0
  22. package/dist/hoi4_agent_tools/map/limits.js +13 -0
  23. package/dist/hoi4_agent_tools/map/model.js +9 -8
  24. package/dist/hoi4_agent_tools/map/natural-lands.js +902 -0
  25. package/dist/hoi4_agent_tools/map/operations.js +266 -23
  26. package/dist/hoi4_agent_tools/map/partition-provinces.js +6 -2
  27. package/dist/hoi4_agent_tools/map/partition-tuning.js +37 -0
  28. package/dist/hoi4_agent_tools/map/service.js +25 -12
  29. package/dist/hoi4_agent_tools/map/territory-operations.js +180 -3
  30. package/dist/hoi4_agent_tools/map/territory-quality.js +72 -5
  31. package/dist/hoi4_agent_tools/map/territory.js +63 -2
  32. package/dist/hoi4_agent_tools/map/tool-operations.js +79 -3
  33. package/dist/hoi4_agent_tools/map/validation.js +23 -3
  34. package/dist/hoi4_agent_tools/map/water.js +13 -10
  35. package/dist/hoi4_agent_tools/map/world-outputs.js +41 -26
  36. package/dist/hoi4_agent_tools/map/world.js +51 -1
  37. package/dist/hoi4_agent_tools/mcp/tools/map.js +52 -0
  38. package/dist/hoi4_agent_tools/mcp/tools/reference.js +3 -3
  39. package/dist/hoi4_agent_tools/mcp/tools/technology.js +25 -1
  40. package/dist/hoi4_agent_tools/reference/closure.js +65 -0
  41. package/dist/hoi4_agent_tools/reference/command-phrases.json +7899 -1127
  42. package/dist/hoi4_agent_tools/reference/mod-index.js +14 -5
  43. package/dist/hoi4_agent_tools/reference/operations.js +38 -21
  44. package/dist/hoi4_agent_tools/reference/ranking.js +77 -2
  45. package/dist/hoi4_agent_tools/reference/script-validation.js +4 -2
  46. package/dist/hoi4_agent_tools/reference/service.js +45 -2
  47. package/dist/hoi4_agent_tools/reference/source-lookup.js +43 -121
  48. package/dist/hoi4_agent_tools/runtime.js +27 -11
  49. package/dist/hoi4_agent_tools/schemas/lenient-arguments.js +7 -1
  50. package/dist/hoi4_agent_tools/schemas/map-requests.js +29 -1
  51. package/dist/hoi4_agent_tools/schemas/map.js +103 -2
  52. package/dist/hoi4_agent_tools/schemas/mod-tools.js +49 -0
  53. package/dist/hoi4_agent_tools/schemas/reference.js +1 -1
  54. package/dist/hoi4_agent_tools/schemas/script-validation.js +57 -3
  55. package/dist/hoi4_agent_tools/technology/operations.js +5 -0
  56. package/dist/hoi4_agent_tools/technology/queries.js +54 -0
  57. package/dist/hoi4_agent_tools/version.js +1 -1
  58. package/docs/configuration.md +1 -1
  59. package/docs/map.md +67 -23
  60. package/docs/research/reference-benchmark.md +64 -0
  61. package/docs/tools.md +20 -20
  62. package/docs/troubleshooting.md +4 -0
  63. package/engine/bin/darwin-arm64/hoi4-engine +0 -0
  64. package/engine/bin/linux-arm64/hoi4-engine +0 -0
  65. package/engine/bin/linux-x64/hoi4-engine +0 -0
  66. package/engine/bin/manifest.json +8 -8
  67. package/engine/bin/win32-x64/hoi4-engine.exe +0 -0
  68. package/npm-shrinkwrap.json +2 -2
  69. package/package.json +5 -3
  70. package/schemas/configuration.schema.json +1 -1
  71. package/schemas/continuous-focus-palette.schema.json +1 -1
  72. package/schemas/custom-weighted-pool.schema.json +1 -1
  73. package/schemas/decision-inspect-input.schema.json +1 -1
  74. package/schemas/error-log-input.schema.json +1 -1
  75. package/schemas/event-feature-manifest.schema.json +1 -1
  76. package/schemas/focus-plan.schema.json +1 -1
  77. package/schemas/focus-planning-sidecar.schema.json +1 -1
  78. package/schemas/geography-model.schema.json +1 -1
  79. package/schemas/gui-animation-source.schema.json +1 -1
  80. package/schemas/gui-helper.schema.json +1 -1
  81. package/schemas/gui-scenario.schema.json +1 -1
  82. package/schemas/helper-expansion-request.schema.json +1 -1
  83. package/schemas/helper-expansion-summary.schema.json +1 -1
  84. package/schemas/impact-inspect-input.schema.json +1 -1
  85. package/schemas/map-operation.schema.json +1087 -815
  86. package/schemas/mechanic-test-input.schema.json +1 -1
  87. package/schemas/mod-index-input.schema.json +1 -1
  88. package/schemas/operation-result.schema.json +1 -1
  89. package/schemas/package-check-input.schema.json +1 -1
  90. package/schemas/package-manifest.schema.json +1 -1
  91. package/schemas/probability-analysis-result.schema.json +1 -1
  92. package/schemas/probability-compare-input.schema.json +1 -1
  93. package/schemas/probability-evaluate-input.schema.json +1 -1
  94. package/schemas/probability-inspect-input.schema.json +1 -1
  95. package/schemas/probability-render-input.schema.json +1 -1
  96. package/schemas/probability-scenario-set.schema.json +1 -1
  97. package/schemas/probability-sequence-input.schema.json +1 -1
  98. package/schemas/probability-simulate-input.schema.json +1 -1
  99. package/schemas/probability-sweep-input.schema.json +1 -1
  100. package/schemas/reference-context-input.schema.json +1 -1
  101. package/schemas/reference-read-input.schema.json +1 -1
  102. package/schemas/reference-search-input.schema.json +2 -2
  103. package/schemas/reference-sheets.schema.json +1 -1
  104. package/schemas/scenario-suite.schema.json +1 -1
  105. package/schemas/scenario-test-input.schema.json +1 -1
  106. package/schemas/script-validate-input.schema.json +7 -1
  107. package/schemas/shared-scenario.schema.json +1 -1
  108. package/schemas/source-lookup-input.schema.json +1 -1
  109. package/server.json +2 -2
@@ -3,8 +3,11 @@ import { runEngineCommand } from '../core/engine-client.js';
3
3
  import { ServiceError } from '../core/result.js';
4
4
  import { readModDescriptor } from '../core/workspace.js';
5
5
  import { modIndexEngineResponseSchema, } from '../schemas/mod-tools.js';
6
- const MAX_NAMESPACES = 200;
7
- const MAX_FOLDERS = 60;
6
+ // An overview answers inline in about 8 KB (issue 66): the busiest namespaces and folders, with a
7
+ // prefix filter for the rest. A namespace line is about 80 bytes and a folder line about 60.
8
+ const MAX_NAMESPACES = 50;
9
+ const MAX_FILTERED_NAMESPACES = 100;
10
+ const MAX_FOLDERS = 25;
8
11
  /** A cold index of the game, its DLC and a large mod. */
9
12
  const MOD_INDEX_TIMEOUT_MS = 180_000;
10
13
  const MOD_INDEX_REQUEST_SCHEMA = 'hoi4-mod-index-request/1';
@@ -78,7 +81,13 @@ export async function modIndex(engine, workspaceId, input, principal, signal) {
78
81
  };
79
82
  }
80
83
  const answer = await runModIndex(engine, workspaceId, { mode: 'overview', rootKinds: input.layer === 'mod' ? ['mod'] : SOURCE_ROOT_KINDS }, principal, signal);
81
- const allNamespaces = [...(answer.namespaces ?? [])].sort((left, right) => left.namespace.localeCompare(right.namespace, 'en'));
84
+ // `namespace` or `prefix` narrows the list to the namespaces that start with it.
85
+ const filter = input.prefix ?? input.namespace;
86
+ const matching = (answer.namespaces ?? []).filter(({ namespace }) => filter === undefined || namespace.startsWith(filter));
87
+ const shownNamespaces = [...matching]
88
+ .sort((left, right) => right.events - left.events || left.namespace.localeCompare(right.namespace, 'en'))
89
+ .slice(0, filter === undefined ? MAX_NAMESPACES : MAX_FILTERED_NAMESPACES)
90
+ .sort((left, right) => left.namespace.localeCompare(right.namespace, 'en'));
82
91
  const modRoot = engine.resolver
83
92
  .get(workspaceId, principal)
84
93
  .roots.find(({ kind }) => kind === 'mod')?.path;
@@ -93,7 +102,7 @@ export async function modIndex(engine, workspaceId, input, principal, signal) {
93
102
  folders: [...(answer.folders ?? [])]
94
103
  .sort((left, right) => right.files - left.files || left.folder.localeCompare(right.folder))
95
104
  .slice(0, MAX_FOLDERS),
96
- namespaces: allNamespaces.slice(0, MAX_NAMESPACES),
97
- omittedNamespaces: Math.max(0, allNamespaces.length - MAX_NAMESPACES),
105
+ namespaces: shownNamespaces,
106
+ omittedNamespaces: matching.length - shownNamespaces.length,
98
107
  };
99
108
  }
@@ -10,6 +10,7 @@ import { toolResult } from '../core/operation-result.js';
10
10
  import { referenceContextRequestSchema, referenceReadRequestSchema, referenceSearchRequestSchema, sourceLookupRequestSchema, } from '../schemas/reference.js';
11
11
  import { ReferenceService } from './service.js';
12
12
  import { sourceLookup } from './source-lookup.js';
13
+ import { checkClosure, closureMessage } from './closure.js';
13
14
  import { scriptValidateDataSchema, scriptValidateRequestSchema, } from '../schemas/script-validation.js';
14
15
  import { identifierArgumentCommands, validateScript, } from './script-validation.js';
15
16
  import { categoryHints, errorLogPattern, modChangedAfter, readErrorLog } from './error-log.js';
@@ -405,32 +406,46 @@ export class ReferenceToolService {
405
406
  passed: checked.valid === true,
406
407
  checks: [
407
408
  {
408
- id: 'script-command-checks',
409
+ id: checked.closure === undefined ? 'script-command-checks' : 'mod-closure',
409
410
  passed: checked.valid === true,
410
- message: checked.valid === true
411
- ? 'Syntax, native command kinds and declared scopes match the selected documentation'
412
- : checked.valid === false
413
- ? 'Script checks found an error'
414
- : `Script checks are partial: ${(checked.partialReasons ?? ['coverage is unresolved']).join('; ')}`,
411
+ message: checked.closure !== undefined
412
+ ? `${closureMessage(checked.closure)}${checked.valid === null ? `; partial: ${(checked.partialReasons ?? ['coverage is unresolved']).join('; ')}` : ''}`
413
+ : checked.valid === true
414
+ ? 'Syntax, native command kinds and declared scopes match the selected documentation'
415
+ : checked.valid === false
416
+ ? 'Script checks found an error'
417
+ : `Script checks are partial: ${(checked.partialReasons ?? ['coverage is unresolved']).join('; ')}`,
415
418
  },
416
419
  ],
417
420
  };
418
- result.diagnostics = checked.findings
419
- .filter(({ status }) => status !== 'supported')
420
- .slice(0, 20)
421
- .map((finding) => ({
422
- code: finding.code,
423
- severity: finding.status === 'error' ? 'error' : 'warning',
424
- category: 'validation',
425
- message: finding.message,
426
- details: {
427
- command: finding.command,
428
- kind: finding.kind,
429
- scope: finding.scope,
430
- line: finding.line,
431
- column: finding.column,
432
- },
421
+ const closureDiagnostics = (checked.closure?.kinds ?? [])
422
+ .filter(({ unresolved, unknown }) => unresolved > 0 || unknown > 0)
423
+ .map(({ kind, resolved, unresolved, unknown }) => ({
424
+ code: unresolved > 0 ? 'CLOSURE_UNRESOLVED_REFERENCES' : 'CLOSURE_UNKNOWN_REFERENCES',
425
+ severity: unresolved > 0 ? 'error' : 'warning',
426
+ category: 'reference',
427
+ message: `${kind}: ${resolved} resolved, ${unresolved} unresolved, ${unknown} unknown`,
428
+ details: { kind, resolved, unresolved, unknown },
433
429
  }));
430
+ result.diagnostics = [
431
+ ...closureDiagnostics,
432
+ ...checked.findings
433
+ .filter(({ status }) => status !== 'supported')
434
+ .slice(0, 20)
435
+ .map((finding) => ({
436
+ code: finding.code,
437
+ severity: finding.status === 'error' ? 'error' : 'warning',
438
+ category: 'validation',
439
+ message: finding.message,
440
+ details: {
441
+ command: finding.command,
442
+ kind: finding.kind,
443
+ scope: finding.scope,
444
+ line: finding.line,
445
+ column: finding.column,
446
+ },
447
+ })),
448
+ ].slice(0, 20);
434
449
  while (Buffer.byteLength(JSON.stringify(result.diagnostics), 'utf8') > 4096 &&
435
450
  result.diagnostics.length > 1)
436
451
  result.diagnostics.pop();
@@ -673,6 +688,8 @@ export class ReferenceToolService {
673
688
  : checkPatchCompatibility(workspace, input, signal);
674
689
  }
675
690
  async validateScript(workspaceId, workspace, request, principal, signal) {
691
+ if (request.closure === true)
692
+ return checkClosure(this.engine, workspaceId, principal, signal);
676
693
  // Every file check of the supported families shares one scan, so checking files across
677
694
  // folders reuses one snapshot and its incremental index; other folders add their own.
678
695
  const scan = (extra) => this.engine.scan(workspaceId, { patterns: [...fileCheckPatterns, ...extra] }, principal, signal);
@@ -168,8 +168,23 @@ export function sectionTerms(title, heading, lines) {
168
168
  : undefined,
169
169
  role: commandRole(title, heading.trim()),
170
170
  verb: commandRole(title, heading.trim()) === undefined ? undefined : heading.trim().split('_')[0],
171
+ connectors: commandRole(title, heading.trim()) === undefined
172
+ ? []
173
+ : [
174
+ ...new Set(heading
175
+ .trim()
176
+ .split('_')
177
+ .slice(1)
178
+ .filter((part) => connectorWords.has(part))),
179
+ ],
171
180
  };
172
181
  }
182
+ /**
183
+ * Command names carry relations in little words: `has_war_with`, `is_owned_by`,
184
+ * `num_of_factories`. A question that says "at war with" names them, and the content words
185
+ * of the question alone cannot tell `has_war_with` from `has_annex_war_goal`.
186
+ */
187
+ const connectorWords = new Set(['with', 'by', 'of', 'from', 'to', 'in', 'on', 'for', 'against']);
173
188
  function commandRole(title, heading) {
174
189
  if (!/^[a-z][a-z0-9_]*$/u.test(heading))
175
190
  return undefined;
@@ -232,9 +247,49 @@ function questionIntent(normalized) {
232
247
  direction: first === undefined ? undefined : questionDirection.get(first),
233
248
  };
234
249
  }
250
+ /**
251
+ * Words players use for what the scripts call something else: a "national spirit" is an idea, a
252
+ * "vassal" a puppet, a state "with access to the sea" is coastal. Each question word adds the
253
+ * script words beside it, at a lower weight than the words the question itself uses.
254
+ */
255
+ const scriptWords = new Map(Object.entries({
256
+ sea: ['coast', 'coastal', 'naval'],
257
+ ocean: ['sea', 'naval', 'coastal'],
258
+ temporary: ['timed', 'days', 'duration'],
259
+ temporarily: ['timed', 'days', 'duration'],
260
+ hide: ['visible', 'hidden'],
261
+ hiding: ['visible', 'hidden'],
262
+ invisible: ['visible', 'hidden'],
263
+ fighting: ['war'],
264
+ fight: ['war'],
265
+ vassal: ['puppet', 'subject'],
266
+ vassals: ['puppet', 'subject'],
267
+ spirit: ['idea'],
268
+ owner: ['owned', 'controller'],
269
+ ownership: ['owned'],
270
+ random: ['chance'],
271
+ randomly: ['chance'],
272
+ percent: ['chance'],
273
+ monthly: ['month'],
274
+ yearly: ['year'],
275
+ daily: ['day'],
276
+ tech: ['technology'],
277
+ free: ['release', 'independent'],
278
+ independence: ['release', 'puppet'],
279
+ conquer: ['occupied', 'control'],
280
+ capture: ['occupied', 'control'],
281
+ ally: ['faction', 'alliance'],
282
+ allies: ['faction', 'alliance'],
283
+ requirement: ['trigger', 'allow'],
284
+ unlock: ['available', 'allow'],
285
+ }).map(([word, words]) => [stemTerm(word), words.map((entry) => stemTerm(entry))]));
286
+ /** What an added script word counts for next to a word the question itself uses. */
287
+ const scriptWordWeight = 0.7;
235
288
  /** Script names abbreviate counts as `num_`, as in `num_divisions` or `num_of_factories`. */
236
289
  const countWords = new Set(['count', 'number', 'amount', 'many', 'much']);
237
290
  const headingWeight = 4;
291
+ /** What a command name's little word is worth when the question says it and names every other word. */
292
+ const connectorBonus = 3;
238
293
  const titleWeight = 0.5;
239
294
  const bodyWeight = 1;
240
295
  const saturation = 1.2;
@@ -279,6 +334,10 @@ export class RankingIndex {
279
334
  }
280
335
  if (words.some((word) => countWords.has(word)) && !weights.has('num'))
281
336
  weights.set('num', 0.6);
337
+ for (const word of words)
338
+ for (const added of scriptWords.get(stemTerm(word)) ?? [])
339
+ if (this.#documentFrequency.has(added) && !weights.has(added))
340
+ weights.set(added, scriptWordWeight);
282
341
  const terms = [...weights].map(([term, weight]) => ({ term, idf: this.idf(term), weight }));
283
342
  const plain = sequence.filter((term) => !term.includes('_'));
284
343
  const pairs = [...new Set(plain.slice(1).map((term, index) => `${plain[index]} ${term}`))].map((pair) => {
@@ -289,6 +348,7 @@ export class RankingIndex {
289
348
  terms,
290
349
  pairs,
291
350
  normalized,
351
+ spoken: new Set(normalized.replace(/'s\b/gu, '').match(tokenPattern) ?? []),
292
352
  identifiers: new Set(terms.map(({ term }) => term).filter((term) => term.includes('_'))),
293
353
  wants: {
294
354
  ...questionIntent(normalized),
@@ -325,8 +385,14 @@ export class RankingIndex {
325
385
  return undefined;
326
386
  const headingText = heading.trim().toLowerCase();
327
387
  // An exact heading is the answer; authority, not incidental wording, orders duplicates.
328
- if (headingText === plan.normalized)
329
- return 1000;
388
+ // A console command, a define or a variable of the same name answers only a question that
389
+ // asks for one, so a trigger or an effect of that name stays ahead of it.
390
+ if (headingText === plan.normalized) {
391
+ const unwanted = (entry.specialty === 'console' && !plan.wants.console) ||
392
+ (entry.specialty === 'define' && !plan.wants.define) ||
393
+ (entry.role === 'variable' && !plan.wants.variable);
394
+ return unwanted ? 600 : 1000;
395
+ }
330
396
  else if (plan.identifiers.has(headingText))
331
397
  score += 40;
332
398
  // A short heading whose every word the question names is usually the topic itself.
@@ -340,6 +406,15 @@ export class RankingIndex {
340
406
  const fraction = covered.length / entry.headingWords.length;
341
407
  score += fraction * fraction * covered.reduce((sum, word) => sum + this.idf(word), 0) * 0.6;
342
408
  }
409
+ // A little word of the command's name that the question also says ("at war with" for
410
+ // `has_war_with`) is worth more than the content words the commands share.
411
+ if (entry.connectors.length > 0 && entry.headingWords.length > 0) {
412
+ const covered = entry.headingWords.filter((word) => plan.terms.some(({ term }) => term === word));
413
+ if (covered.length === entry.headingWords.length) {
414
+ const said = entry.connectors.filter((word) => plan.spoken.has(word)).length;
415
+ score += said * connectorBonus;
416
+ }
417
+ }
343
418
  if (entry.navigation)
344
419
  score *= 0.25;
345
420
  if (entry.specialty === 'console' && !plan.wants.console)
@@ -34,6 +34,8 @@ const identifierArguments = {
34
34
  unit_leader_event: { value: 'event', fields: { id: 'event' } },
35
35
  operative_leader_event: { value: 'event', fields: { id: 'event' } },
36
36
  };
37
+ /** What an unknown id does in game, so a warning still reads as a bug in the modder's file. */
38
+ const UNKNOWN_ID_IN_GAME = '; the game loads the file, but this command does nothing';
37
39
  export const identifierArgumentCommands = new Set(Object.keys(identifierArguments));
38
40
  /** Values that are computed or substituted, so their target cannot be read from source. */
39
41
  const dynamicValue = /[[\]$@:]|^(?:yes|no)$/u;
@@ -362,7 +364,7 @@ export async function validateScript(references, workspace, input, signal, file,
362
364
  code: 'SCRIPT_ARGUMENT_UNKNOWN_ID',
363
365
  // The game loads the file and the command does nothing, as vanilla's own dangling ids show.
364
366
  status: identifiers.complete ? 'warning' : 'unresolved',
365
- message: `${entry.key.value} names ${target} ${value.slice(0, 256)}, which ${identifiers.complete ? 'no loaded file defines' : 'the indexed files do not define (the index is incomplete)'}`,
367
+ message: `${entry.key.value} names ${target} ${value.slice(0, 256)}, which ${identifiers.complete ? `no loaded file defines${UNKNOWN_ID_IN_GAME}` : 'the indexed files do not define (the index is incomplete)'}`,
366
368
  suggestions,
367
369
  });
368
370
  }
@@ -495,7 +497,7 @@ export async function validateScript(references, workspace, input, signal, file,
495
497
  code: other === undefined ? 'SCRIPT_COMMAND_UNRESOLVED' : 'SCRIPT_COMMAND_WRONG_KIND',
496
498
  status: other === undefined ? 'unresolved' : 'error',
497
499
  message: other === undefined
498
- ? 'Not documented as a native command in the selected source; inspect scripted helpers or declare the scope binding'
500
+ ? `Not documented as a native command in the selected source; inspect scripted helpers or declare the scope binding${suggestions.length === 0 ? '' : `. Did you mean ${suggestions.join(', ')}?`}`
499
501
  : `Documented as a ${kind === 'effect' ? 'trigger' : 'effect'}, not a ${kind}`,
500
502
  suggestions,
501
503
  ...(other === undefined ? {} : { reference: other.reference }),
@@ -57,6 +57,45 @@ function referenceHit(section) {
57
57
  function fileStamp(metadata) {
58
58
  return `${metadata.size}:${metadata.mtimeMs}:${metadata.ctimeMs}:${metadata.ino}:${metadata.dev}`;
59
59
  }
60
+ /**
61
+ * The meaning of an installed-documentation command in one line, with the scopes it works in:
62
+ * "COUNTRY: Adds an idea to the country for a number of days". The game's text puts the
63
+ * description inside a code fence below the scope lines and stops it with "Example"; a line that
64
+ * only looks like script is not a meaning, so such an entry keeps the plain excerpt.
65
+ */
66
+ function commandSummary(lines) {
67
+ let scopes;
68
+ for (const raw of lines.slice(1)) {
69
+ const line = raw.trim();
70
+ const scope = /^\*\s*Supported Scopes:\s*(.+)$/iu.exec(line);
71
+ if (scope !== null) {
72
+ scopes = scope[1].trim();
73
+ continue;
74
+ }
75
+ if (line === '' || line.startsWith('```') || line.startsWith('*'))
76
+ continue;
77
+ if (/^(?:examples?|usage)\b/iu.test(line) || /[={}]\s*$|^[a-z_][a-z0-9_]*\s*=/u.test(line))
78
+ return undefined;
79
+ const meaning = line.replace(/\s+/gu, ' ').slice(0, 200);
80
+ return scopes === undefined ? meaning : `${scopes}: ${meaning}`;
81
+ }
82
+ return undefined;
83
+ }
84
+ /**
85
+ * The meaning of a wiki table row: its description cell, without the markup. The wiki tables of
86
+ * effects, triggers and modifiers keep the name, arguments, example and then the description.
87
+ */
88
+ function rowSummary(row) {
89
+ const cells = row.split('|').map((cell) => cell.trim());
90
+ const description = cells[4];
91
+ if (description === undefined || description.length < 8)
92
+ return undefined;
93
+ return description
94
+ .replace(/<br\s*\/?>/giu, ' ')
95
+ .replace(/[`*]/gu, '')
96
+ .replace(/\s+/gu, ' ')
97
+ .slice(0, 200);
98
+ }
60
99
  /** Up to three non-empty lines from `first`, trimmed to the 300-character excerpt bound. */
61
100
  function snippet(lines, first = 0) {
62
101
  return lines
@@ -332,7 +371,7 @@ const commandHeading = /^[a-z][a-z0-9_]*$/u;
332
371
  * Plain-word phrasings count this many times a game text word, because they name the
333
372
  * command the way a question does rather than the way a tooltip labels it.
334
373
  */
335
- const PHRASE_WEIGHT = 4;
374
+ const PHRASE_WEIGHT = 2;
336
375
  let phraseTerms;
337
376
  /**
338
377
  * The terms of `command-phrases.json`: four plain-word phrasings of each documented effect,
@@ -672,7 +711,11 @@ export class ReferenceService {
672
711
  return {
673
712
  section,
674
713
  score,
675
- excerpt: snippet(section.lines, offset),
714
+ excerpt: (section.source === 'game_doc' && section.terms.role !== undefined
715
+ ? commandSummary(section.lines)
716
+ : section.source === 'wiki' && section.lines.length === 1
717
+ ? rowSummary(section.lines[0])
718
+ : undefined) ?? snippet(section.lines, offset),
676
719
  matchLine: section.startLine + offset,
677
720
  };
678
721
  },
@@ -8,13 +8,10 @@ import { decodeSource } from '../core/source/encoding.js';
8
8
  import { sourceLookupEngineResponseSchema } from '../schemas/mod-tools.js';
9
9
  import { modIndexEngineRequest, SOURCE_ROOT_KINDS } from './mod-index.js';
10
10
  import { readBoundedJsonLines } from './lines.js';
11
- import { IMPACT_SEMANTIC_MAX_REFERENCES, scanImpactSemanticReferences, } from '../core/impact-semantic.js';
12
11
  import { parseClausewitz } from '../core/source/parser.js';
13
12
  import { positionAt } from '../core/source/lexer.js';
14
13
  import { navigateSource } from './source-navigation.js';
15
14
  import { locatePatterns, locateSource } from './source-locate.js';
16
- import { nearestNames } from './suggestions.js';
17
- const semanticCache = new WeakMap();
18
15
  /** The lines, or the nested navigation, of one matched definition. */
19
16
  function describeDefinition(entry, source, index, input, navigating) {
20
17
  const start = entry.startLine;
@@ -96,8 +93,8 @@ function nearestOf(candidates) {
96
93
  .slice(0, 5)
97
94
  .map(({ id }) => id);
98
95
  }
99
- function notFound(symbol, kind, suggestions) {
100
- return new ServiceError('SYMBOL_NOT_FOUND', `No indexed file defines ${symbol.slice(0, 256)}${kind === undefined ? '' : ` as a ${kind}`}${suggestions.length === 0 ? '' : `; did you mean ${suggestions.join(', ')}?`}`, { symbol: symbol.slice(0, 256), suggestions });
96
+ function notFound(symbol, kind, suggestions, usesToo) {
97
+ return new ServiceError('SYMBOL_NOT_FOUND', `No indexed file defines${usesToo ? ' or uses' : ''} ${symbol.slice(0, 256)}${kind === undefined ? '' : ` as a ${kind}`}${suggestions.length === 0 ? '' : `; did you mean ${suggestions.join(', ')}?`}`, { symbol: symbol.slice(0, 256), suggestions });
101
98
  }
102
99
  /**
103
100
  * The first line of a definition's assignment in a parsed file. The engine names a definition by
@@ -169,6 +166,9 @@ async function lookupFromEngine(engine, workspaceId, input, symbol, patterns, pr
169
166
  symbol,
170
167
  ...(input.kind === undefined ? {} : { kind: input.kind }),
171
168
  maxDefinitions: navigating ? 1 : input.maxDefinitions,
169
+ ...(input.includeReferences
170
+ ? { includeReferences: true, maxReferences: input.maxReferences }
171
+ : {}),
172
172
  }, sourceLookupEngineResponseSchema, { timeoutMs: SOURCE_LOOKUP_TIMEOUT_MS, ...(signal === undefined ? {} : { signal }) });
173
173
  if (!answered.available)
174
174
  throw new ServiceError('ENGINE_UNAVAILABLE', answered.message, { reason: answered.reason });
@@ -181,9 +181,10 @@ async function lookupFromEngine(engine, workspaceId, input, symbol, patterns, pr
181
181
  if (navigating && response.kindCount > 1)
182
182
  throw new ServiceError('SOURCE_KIND_AMBIGUOUS', 'Nested navigation requires kind when the identifier has multiple symbol kinds');
183
183
  const suggestions = nearestOf(response.suggestionCandidates);
184
- // A complete index that does not define the symbol answers not-found, never an empty success.
185
- if (response.definitionCount === 0 && response.complete)
186
- throw notFound(symbol, input.kind, suggestions);
184
+ // A complete index that neither defines nor uses the symbol answers not-found, never an empty
185
+ // success.
186
+ if (response.definitionCount === 0 && response.referenceCount === 0 && response.complete)
187
+ throw notFound(symbol, input.kind, suggestions, input.includeReferences);
187
188
  const definitions = await Promise.all(response.definitions.map(async (entry, index) => {
188
189
  const bytes = await readScannedFile(engine, workspaceId, entry.absolutePath, entry.sha256, principal);
189
190
  return describeDefinition({
@@ -208,12 +209,22 @@ async function lookupFromEngine(engine, workspaceId, input, symbol, patterns, pr
208
209
  definitionsTruncated: response.definitionCount > definitions.length,
209
210
  ...(response.definitionCount === 0 ? { suggestions } : {}),
210
211
  definitions,
211
- references: [],
212
- referencesIncluded: false,
213
- referenceCount: 0,
214
- referencesTruncated: false,
215
- referencesComplete: false,
216
- unresolvedReferenceCount: 0,
212
+ references: response.references.map(({ kind, from, toKind, path, line }) => ({
213
+ kind,
214
+ from,
215
+ toKind,
216
+ path,
217
+ line,
218
+ })),
219
+ referencesIncluded: input.includeReferences,
220
+ referenceCount: response.referenceCount,
221
+ referencesTruncated: response.referenceCount > response.references.length,
222
+ referencesComplete: input.includeReferences &&
223
+ response.complete &&
224
+ response.semanticComplete &&
225
+ response.unresolvedReferenceCount === 0 &&
226
+ response.referenceCount <= response.references.length,
227
+ unresolvedReferenceCount: input.includeReferences ? response.unresolvedReferenceCount : 0,
217
228
  });
218
229
  }
219
230
  /** A cold index of the game, its DLC and a large mod. */
@@ -244,116 +255,27 @@ export async function sourceLookup(engine, workspaceId, input, principal, signal
244
255
  : input.includeReferences || input.kind === undefined
245
256
  ? undefined
246
257
  : narrowPatterns[input.kind];
247
- const locating = input.path !== undefined && input.line !== undefined;
248
- if (!locating && input.symbol !== undefined && !input.includeReferences)
258
+ const { path: sourcePath, line: sourceLine } = input;
259
+ if (sourcePath === undefined || sourceLine === undefined) {
260
+ if (input.symbol === undefined)
261
+ throw new ServiceError('SOURCE_LOOKUP_TARGET_REQUIRED', 'Provide a symbol, or path and line');
249
262
  return lookupFromEngine(engine, workspaceId, input, input.symbol, patterns, principal, signal);
250
- const snapshot = await engine.scan(workspaceId, patterns === undefined ? {} : { patterns }, principal, signal);
251
- if (input.path !== undefined && input.line !== undefined)
252
- return {
253
- sourceScope: 'source_location',
254
- revision: snapshot.revision,
255
- complete: snapshot.complete,
256
- skippedSourceCount: snapshot.skippedSourceCount,
257
- definitionCount: 0,
258
- definitionsTruncated: false,
259
- referencesIncluded: false,
260
- referenceCount: 0,
261
- referencesTruncated: false,
262
- referencesComplete: false,
263
- unresolvedReferenceCount: 0,
264
- location: locateSource(snapshot, input.path, input.line, input.column),
265
- definitions: [],
266
- references: [],
267
- };
268
- const symbol = input.symbol;
269
- if (symbol === undefined)
270
- throw new ServiceError('SOURCE_LOOKUP_TARGET_REQUIRED', 'Provide a symbol, or path and line');
271
- if (input.expectedRevision !== undefined && input.expectedRevision !== snapshot.revision) {
272
- throw new ServiceError('SOURCE_REVISION_STALE', 'Indexed source changed; look up the symbol again', { currentRevision: snapshot.revision });
273
- }
274
- const navigating = input.keyPath !== undefined || input.view === 'structure';
275
- const matchedDefinitions = snapshot.index.symbols
276
- .filter((entry) => entry.id === symbol && (input.kind === undefined || entry.kind === input.kind))
277
- .sort((left, right) => Number(left.overridden) - Number(right.overridden) || right.loadOrder - left.loadOrder);
278
- if (navigating && new Set(matchedDefinitions.map(({ kind }) => kind)).size > 1)
279
- throw new ServiceError('SOURCE_KIND_AMBIGUOUS', 'Nested navigation requires kind when the identifier has multiple symbol kinds');
280
- const definitions = matchedDefinitions
281
- .slice(0, navigating ? 1 : input.maxDefinitions)
282
- .map((entry, index) => {
283
- const source = snapshot.index.files.get(entry.path);
284
- return describeDefinition({
285
- kind: entry.kind,
286
- id: entry.id,
287
- path: entry.path,
288
- rootKind: entry.rootKind,
289
- loadOrder: entry.loadOrder,
290
- overridden: entry.overridden,
291
- sourceShadowed: entry.sourceShadowed,
292
- startLine: entry.location?.start.line,
293
- endLine: entry.location?.end.line,
294
- rangeIn: () => entry.location === undefined
295
- ? undefined
296
- : { start: entry.location.start.offset, end: entry.location.end.offset },
297
- }, source === undefined ? undefined : { bytes: source.bytes, displayPath: source.displayPath }, index, input, navigating);
298
- });
299
- let semantic = input.includeReferences ? semanticCache.get(snapshot) : undefined;
300
- if (input.includeReferences && semantic === undefined) {
301
- semantic = scanImpactSemanticReferences(snapshot, IMPACT_SEMANTIC_MAX_REFERENCES, {
302
- includeOnActions: true,
303
- });
304
- semanticCache.set(snapshot, semantic);
305
- }
306
- const referenceIdentities = new Set();
307
- const matchedReferences = input.includeReferences
308
- ? [...snapshot.index.references, ...(semantic?.references ?? [])]
309
- .filter((entry) => entry.to === symbol && (input.kind === undefined || entry.toKind === input.kind))
310
- .filter((entry) => {
311
- const key = `${entry.path}:${entry.location?.start.offset ?? 0}:${entry.toKind}:${entry.to}:${entry.kind}`;
312
- if (referenceIdentities.has(key))
313
- return false;
314
- referenceIdentities.add(key);
315
- return true;
316
- })
317
- : [];
318
- const references = matchedReferences.slice(0, input.maxReferences).map((entry) => ({
319
- kind: entry.kind,
320
- from: entry.from,
321
- toKind: entry.toKind,
322
- path: entry.path,
323
- line: entry.location?.start.line ?? null,
324
- }));
325
- // A complete index that neither defines nor uses the symbol answers not-found, never an
326
- // empty success.
327
- if (matchedDefinitions.length === 0 && matchedReferences.length === 0 && snapshot.complete) {
328
- const suggestions = nearestNames(symbol, new Set(snapshot.index.symbols
329
- .filter((entry) => input.kind === undefined || entry.kind === input.kind)
330
- .map(({ id }) => id)));
331
- throw new ServiceError('SYMBOL_NOT_FOUND', `No indexed file defines${input.includeReferences ? ' or uses' : ''} ${symbol.slice(0, 256)}${input.kind === undefined ? '' : ` as a ${input.kind}`}${suggestions.length === 0 ? '' : `; did you mean ${suggestions.join(', ')}?`}`, { symbol: symbol.slice(0, 256), suggestions });
332
263
  }
333
- return boundResult({
334
- sourceScope: scopeOf(input, patterns),
264
+ const snapshot = await engine.scan(workspaceId, patterns === undefined ? {} : { patterns }, principal, signal);
265
+ return {
266
+ sourceScope: 'source_location',
335
267
  revision: snapshot.revision,
336
268
  complete: snapshot.complete,
337
269
  skippedSourceCount: snapshot.skippedSourceCount,
338
- definitionCount: snapshot.index.symbols.filter((entry) => entry.id === symbol && (input.kind === undefined || entry.kind === input.kind)).length,
339
- definitionsTruncated: matchedDefinitions.length > definitions.length,
340
- ...(matchedDefinitions.length === 0
341
- ? {
342
- suggestions: nearestNames(symbol, new Set(snapshot.index.symbols
343
- .filter((entry) => input.kind === undefined || entry.kind === input.kind)
344
- .map(({ id }) => id))),
345
- }
346
- : {}),
347
- definitions,
348
- references,
349
- referencesIncluded: input.includeReferences,
350
- referenceCount: matchedReferences.length,
351
- referencesTruncated: matchedReferences.length > references.length,
352
- referencesComplete: input.includeReferences &&
353
- snapshot.complete &&
354
- semantic?.complete === true &&
355
- semantic.unresolved.length === 0 &&
356
- matchedReferences.length <= references.length,
357
- unresolvedReferenceCount: semantic?.unresolved.length ?? 0,
358
- });
270
+ definitionCount: 0,
271
+ definitionsTruncated: false,
272
+ referencesIncluded: false,
273
+ referenceCount: 0,
274
+ referencesTruncated: false,
275
+ referencesComplete: false,
276
+ unresolvedReferenceCount: 0,
277
+ location: locateSource(snapshot, sourcePath, sourceLine, input.column),
278
+ definitions: [],
279
+ references: [],
280
+ };
359
281
  }
@@ -196,9 +196,22 @@ function automaticWorkspaceId(modRoot) {
196
196
  .slice(0, 48);
197
197
  return `auto_${slug.length === 0 ? 'mod' : slug}`;
198
198
  }
199
- /** Build an in-memory configuration when a local agent starts inside a mod. */
200
- export async function automaticConfiguration(start = process.cwd()) {
201
- const modRoot = await findCurrentModRoot(start);
199
+ /**
200
+ * Build an in-memory configuration when a local agent starts inside a mod. With
201
+ * `allowNoMod`, a start folder outside every mod gives a configuration with no workspace
202
+ * instead of an error, so documentation search still works there.
203
+ */
204
+ export async function automaticConfiguration(start = process.cwd(), options = {}) {
205
+ let modRoot;
206
+ try {
207
+ modRoot = await findCurrentModRoot(start);
208
+ }
209
+ catch (error) {
210
+ if (options.allowNoMod !== true ||
211
+ !(error instanceof ServiceError) ||
212
+ error.code !== 'AUTO_MOD_ROOT_NOT_FOUND')
213
+ throw error;
214
+ }
202
215
  const gameRoot = await firstExistingDirectory(automaticGameRootCandidates());
203
216
  const storage = automaticStorageRoots();
204
217
  return serverConfigurationSchema.parse({
@@ -206,13 +219,15 @@ export async function automaticConfiguration(start = process.cwd()) {
206
219
  serverStateRoot: storage.serverStateRoot,
207
220
  workspaceStorageRoot: storage.workspaceStorageRoot,
208
221
  ...(gameRoot === undefined ? {} : { gameRoot }),
209
- workspaces: [
210
- {
211
- id: automaticWorkspaceId(modRoot),
212
- name: path.basename(modRoot),
213
- root: modRoot,
214
- },
215
- ],
222
+ workspaces: modRoot === undefined
223
+ ? []
224
+ : [
225
+ {
226
+ id: automaticWorkspaceId(modRoot),
227
+ name: path.basename(modRoot),
228
+ root: modRoot,
229
+ },
230
+ ],
216
231
  });
217
232
  }
218
233
  async function configurationExists(configPath) {
@@ -236,7 +251,8 @@ export async function createEngine(configPath = configurationPath(), options = {
236
251
  !(await configurationExists(configPath));
237
252
  if (!useAutomaticConfiguration)
238
253
  throw error;
239
- configuration = await automaticConfiguration();
254
+ // Outside a mod there is no workspace, and the documentation tools still answer.
255
+ configuration = await automaticConfiguration(process.cwd(), { allowNoMod: true });
240
256
  }
241
257
  // The stdio server lists the core tools unless the client or the file asks for more.
242
258
  const profiles = parseProfilesEnv(process.env[PROFILES_ENV]) ??
@@ -7,7 +7,8 @@
7
7
  * plain string or without its kind, a GUI scenario without an id, a decision inspection without
8
8
  * a scenario, a probability scenario set without ids or state, a scenario set sent as a bare
9
9
  * array, a namespace wildcard such as `chaosx.nr14.*`, a trace given `from` instead of `selector`,
10
- * and a script file check that also names the kind and scope its file already fixes.
10
+ * a script file check that also names the kind and scope its file already fixes, and a probability
11
+ * source given as a top-level `path`.
11
12
  */
12
13
  function isObject(value) {
13
14
  return typeof value === 'object' && value !== null && !Array.isArray(value);
@@ -231,6 +232,11 @@ function normalizeProbabilityArguments(args) {
231
232
  : { identifier: result.source };
232
233
  if (typeof result.candidatePool === 'string')
233
234
  result.candidatePool = [result.candidatePool];
235
+ // The description says surfaces are found by path; a top-level `path` names the source file.
236
+ if (typeof result.path === 'string' && result.source === undefined) {
237
+ const { path, ...rest } = result;
238
+ return { ...rest, source: { path } };
239
+ }
234
240
  return result;
235
241
  }
236
242
  /** Rewrite known shorthands for one tool; unknown tools and non-object arguments pass through. */