hoi4-agent-tools 4.6.4 → 4.7.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.
- package/CHANGELOG.md +22 -5
- package/dist/hoi4_agent_tools/core/artifacts.js +9 -2
- package/dist/hoi4_agent_tools/core/changed-summary.js +41 -0
- package/dist/hoi4_agent_tools/core/engine-client.js +273 -0
- package/dist/hoi4_agent_tools/core/job-worker-host.js +5 -1
- package/dist/hoi4_agent_tools/core/operation-result.js +24 -5
- package/dist/hoi4_agent_tools/focus/compact.js +197 -18
- package/dist/hoi4_agent_tools/focus/engine-layout.js +201 -0
- package/dist/hoi4_agent_tools/focus/job-operations.js +3 -1
- package/dist/hoi4_agent_tools/focus/layout.js +3 -2
- package/dist/hoi4_agent_tools/focus/quality/branches.js +32 -0
- package/dist/hoi4_agent_tools/focus/quality/calibration.js +364 -0
- package/dist/hoi4_agent_tools/focus/quality/delta.js +85 -0
- package/dist/hoi4_agent_tools/focus/quality/focus-quality-calibration.json +2265 -0
- package/dist/hoi4_agent_tools/focus/quality/graph.js +170 -0
- package/dist/hoi4_agent_tools/focus/quality/index.js +24 -0
- package/dist/hoi4_agent_tools/focus/quality/inline-images.js +132 -0
- package/dist/hoi4_agent_tools/focus/quality/metrics.js +424 -0
- package/dist/hoi4_agent_tools/focus/quality/orthogonal.js +202 -0
- package/dist/hoi4_agent_tools/focus/quality/positions.js +41 -0
- package/dist/hoi4_agent_tools/focus/quality/schematic.js +241 -0
- package/dist/hoi4_agent_tools/focus/quality/scorecard.js +549 -0
- package/dist/hoi4_agent_tools/focus/quality/stored-calibration.js +7 -0
- package/dist/hoi4_agent_tools/focus/quality/tool-output.js +113 -0
- package/dist/hoi4_agent_tools/focus/quality/types.js +5 -0
- package/dist/hoi4_agent_tools/focus/tool-operations.js +206 -22
- package/dist/hoi4_agent_tools/focus/tool-support.js +1 -1
- package/dist/hoi4_agent_tools/map/references.js +26 -1
- package/dist/hoi4_agent_tools/map/render.js +29 -3
- package/dist/hoi4_agent_tools/map/service.js +3 -0
- package/dist/hoi4_agent_tools/map/tool-operations.js +5 -0
- package/dist/hoi4_agent_tools/mcp/server/instructions.js +1 -1
- package/dist/hoi4_agent_tools/mcp/tools/focus.js +76 -4
- package/dist/hoi4_agent_tools/reference/game-text.js +109 -0
- package/dist/hoi4_agent_tools/reference/ranking.js +60 -2
- package/dist/hoi4_agent_tools/reference/service.js +92 -21
- package/dist/hoi4_agent_tools/schemas/focus-requests.js +64 -7
- package/dist/hoi4_agent_tools/schemas/focus.js +121 -6
- package/dist/hoi4_agent_tools/version.js +1 -1
- package/docs/configuration.md +17 -17
- package/docs/focus.md +100 -4
- package/docs/map.md +5 -2
- package/docs/reference.md +1 -1
- package/docs/research/reference-benchmark.md +111 -1
- package/docs/setup.md +1 -1
- package/docs/tools.md +5 -5
- package/docs/troubleshooting.md +12 -11
- package/npm-shrinkwrap.json +2 -2
- package/package.json +2 -1
- package/schemas/configuration.schema.json +1 -1
- package/schemas/continuous-focus-palette.schema.json +1 -1
- package/schemas/custom-weighted-pool.schema.json +1 -1
- package/schemas/decision-inspect-input.schema.json +1 -1
- package/schemas/error-log-input.schema.json +1 -1
- package/schemas/event-feature-manifest.schema.json +1 -1
- package/schemas/focus-plan.schema.json +146 -120
- package/schemas/focus-planning-sidecar.schema.json +15 -7
- package/schemas/geography-model.schema.json +1 -1
- package/schemas/gui-animation-source.schema.json +1 -1
- package/schemas/gui-helper.schema.json +1 -1
- package/schemas/gui-scenario.schema.json +1 -1
- package/schemas/helper-expansion-request.schema.json +1 -1
- package/schemas/helper-expansion-summary.schema.json +1 -1
- package/schemas/impact-inspect-input.schema.json +1 -1
- package/schemas/map-operation.schema.json +1 -1
- package/schemas/mechanic-test-input.schema.json +1 -1
- package/schemas/mod-index-input.schema.json +1 -1
- package/schemas/operation-result.schema.json +1 -1
- package/schemas/package-check-input.schema.json +1 -1
- package/schemas/package-manifest.schema.json +1 -1
- package/schemas/probability-analysis-result.schema.json +1 -1
- package/schemas/probability-compare-input.schema.json +1 -1
- package/schemas/probability-evaluate-input.schema.json +1 -1
- package/schemas/probability-inspect-input.schema.json +1 -1
- package/schemas/probability-render-input.schema.json +1 -1
- package/schemas/probability-scenario-set.schema.json +1 -1
- package/schemas/probability-sequence-input.schema.json +1 -1
- package/schemas/probability-simulate-input.schema.json +1 -1
- package/schemas/probability-sweep-input.schema.json +1 -1
- package/schemas/reference-context-input.schema.json +1 -1
- package/schemas/reference-read-input.schema.json +1 -1
- package/schemas/reference-search-input.schema.json +1 -1
- package/schemas/reference-sheets.schema.json +1 -1
- package/schemas/scenario-suite.schema.json +1 -1
- package/schemas/scenario-test-input.schema.json +1 -1
- package/schemas/script-validate-input.schema.json +1 -1
- package/schemas/shared-scenario.schema.json +1 -1
- package/schemas/source-lookup-input.schema.json +1 -1
- package/server.json +2 -2
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { registerLegacyTaskTools } from '../server/legacy-task-tools.js';
|
|
2
2
|
import { z } from 'zod/v4';
|
|
3
3
|
import { computeFocusVisualRevisions as computeCoreFocusVisualRevisions, } from '../../focus/tool-operations.js';
|
|
4
|
-
import { focusLayoutMetricsSchema } from '../../schemas/focus.js';
|
|
4
|
+
import { focusLayoutDeltaSchema, focusLayoutMetricsSchema, focusLayoutQualitySchema, } from '../../schemas/focus.js';
|
|
5
5
|
import { focusInspectRequestSchema, focusRenderRequestSchema, focusRewriteRequestSchema, } from '../../schemas/focus-requests.js';
|
|
6
6
|
import { nonNegativeIntegerSchema, renderHashesSchema, sha256Schema, } from '../server/output-schemas.js';
|
|
7
7
|
import { strictOperationResultSchema } from '../server/result.js';
|
|
@@ -9,6 +9,7 @@ const focusInspectOutputSchema = strictOperationResultSchema(z
|
|
|
9
9
|
.object({
|
|
10
10
|
mode: z.enum(['national', 'continuous']),
|
|
11
11
|
revision: sha256Schema,
|
|
12
|
+
layoutVerdict: z.enum(['blocked', 'revise', 'review', 'pass']).optional(),
|
|
12
13
|
treeCount: nonNegativeIntegerSchema,
|
|
13
14
|
paletteCount: nonNegativeIntegerSchema,
|
|
14
15
|
trees: z
|
|
@@ -29,6 +30,8 @@ const focusInspectOutputSchema = strictOperationResultSchema(z
|
|
|
29
30
|
layoutHash: sha256Schema,
|
|
30
31
|
layoutDecisionCount: nonNegativeIntegerSchema,
|
|
31
32
|
layoutMetrics: focusLayoutMetricsSchema,
|
|
33
|
+
layoutQuality: focusLayoutQualitySchema.optional(),
|
|
34
|
+
layoutDelta: focusLayoutDeltaSchema.optional(),
|
|
32
35
|
diagnosticCount: nonNegativeIntegerSchema,
|
|
33
36
|
scenarioSummary: z
|
|
34
37
|
.object({
|
|
@@ -64,6 +67,28 @@ const focusRenderOutputSchema = strictOperationResultSchema(z.discriminatedUnion
|
|
|
64
67
|
hashes: renderHashesSchema,
|
|
65
68
|
width: nonNegativeIntegerSchema,
|
|
66
69
|
height: nonNegativeIntegerSchema,
|
|
70
|
+
layoutQuality: focusLayoutQualitySchema.optional(),
|
|
71
|
+
inlineImages: z
|
|
72
|
+
.array(z
|
|
73
|
+
.object({
|
|
74
|
+
kind: z.enum(['overview', 'branch', 'focus', 'problem']),
|
|
75
|
+
label: z.string().max(300),
|
|
76
|
+
focusIds: z.array(z.string().max(256)).max(50),
|
|
77
|
+
region: z
|
|
78
|
+
.object({
|
|
79
|
+
minimumX: z.number().int(),
|
|
80
|
+
maximumX: z.number().int(),
|
|
81
|
+
minimumY: z.number().int(),
|
|
82
|
+
maximumY: z.number().int(),
|
|
83
|
+
})
|
|
84
|
+
.strict(),
|
|
85
|
+
width: nonNegativeIntegerSchema,
|
|
86
|
+
height: nonNegativeIntegerSchema,
|
|
87
|
+
bytes: nonNegativeIntegerSchema,
|
|
88
|
+
})
|
|
89
|
+
.strict())
|
|
90
|
+
.max(6)
|
|
91
|
+
.optional(),
|
|
67
92
|
})
|
|
68
93
|
.strict(),
|
|
69
94
|
z
|
|
@@ -93,6 +118,42 @@ const focusDriftOutputSchema = z
|
|
|
93
118
|
planChanged: z.boolean(),
|
|
94
119
|
})
|
|
95
120
|
.strict();
|
|
121
|
+
const engineShiftOutputSchema = z
|
|
122
|
+
.object({
|
|
123
|
+
fromX: z.number().int(),
|
|
124
|
+
columns: z.number().int().min(1),
|
|
125
|
+
direction: z.enum(['right', 'left']),
|
|
126
|
+
focusIds: z.array(z.string().max(256)),
|
|
127
|
+
})
|
|
128
|
+
.strict();
|
|
129
|
+
/** What the focus layout engine did (layoutMode engine or placement). */
|
|
130
|
+
const focusEngineLayoutOutputSchema = z
|
|
131
|
+
.object({
|
|
132
|
+
operation: z.enum(['layout', 'insert']),
|
|
133
|
+
status: z.literal('ok'),
|
|
134
|
+
hashes: z
|
|
135
|
+
.object({
|
|
136
|
+
layout: sha256Schema.nullable(),
|
|
137
|
+
untouched: sha256Schema,
|
|
138
|
+
prerequisites: sha256Schema,
|
|
139
|
+
exclusions: sha256Schema,
|
|
140
|
+
})
|
|
141
|
+
.strict(),
|
|
142
|
+
metrics: z
|
|
143
|
+
.object({
|
|
144
|
+
columns: nonNegativeIntegerSchema,
|
|
145
|
+
rows: nonNegativeIntegerSchema,
|
|
146
|
+
orthogonalCrossings: nonNegativeIntegerSchema,
|
|
147
|
+
stemsThroughPlaques: nonNegativeIntegerSchema,
|
|
148
|
+
mergedBars: nonNegativeIntegerSchema,
|
|
149
|
+
})
|
|
150
|
+
.strict(),
|
|
151
|
+
movedFocusIds: z.array(z.string().max(256)).max(100),
|
|
152
|
+
movedFocusCount: nonNegativeIntegerSchema,
|
|
153
|
+
shifted: z.array(engineShiftOutputSchema).optional(),
|
|
154
|
+
binarySource: z.enum(['environment', 'package']),
|
|
155
|
+
})
|
|
156
|
+
.strict();
|
|
96
157
|
const focusPlanOutputSchema = strictOperationResultSchema(z.discriminatedUnion('mode', [
|
|
97
158
|
z
|
|
98
159
|
.object({
|
|
@@ -102,6 +163,17 @@ const focusPlanOutputSchema = strictOperationResultSchema(z.discriminatedUnion('
|
|
|
102
163
|
created: z.boolean(),
|
|
103
164
|
execution: z.enum(['applied', 'blocked', 'unchanged']),
|
|
104
165
|
layoutHash: sha256Schema,
|
|
166
|
+
layoutQuality: focusLayoutQualitySchema.optional(),
|
|
167
|
+
layoutDelta: focusLayoutDeltaSchema.optional(),
|
|
168
|
+
compactOutcome: z
|
|
169
|
+
.object({
|
|
170
|
+
outcome: z.literal('nothing_to_improve'),
|
|
171
|
+
reason: z.enum(['verdict_pass', 'no_better_candidate', 'candidates_regress']),
|
|
172
|
+
blockedBy: z.array(z.string().max(64)).max(10),
|
|
173
|
+
})
|
|
174
|
+
.strict()
|
|
175
|
+
.optional(),
|
|
176
|
+
engine: focusEngineLayoutOutputSchema.optional(),
|
|
105
177
|
fileCount: nonNegativeIntegerSchema,
|
|
106
178
|
artifactCount: nonNegativeIntegerSchema,
|
|
107
179
|
})
|
|
@@ -135,7 +207,7 @@ export const focusTaskTools = [
|
|
|
135
207
|
{
|
|
136
208
|
name: 'hoi4.focus_inspect',
|
|
137
209
|
title: 'Inspect focus trees',
|
|
138
|
-
description: '
|
|
210
|
+
description: 'Check a focus tree\'s structure and layout. Returns blocking errors, a layout verdict (pass, review, revise, blocked) with the metrics behind it, a fix for each failing metric and next actions. Revise or blocked means the tree is not finished, however clean its structure; review is advisory, so look at hoi4.focus_render. Example: {"treeId":"my_focus_tree"}. The full report is a linked resource.',
|
|
139
211
|
inputSchema: focusInspectRequestSchema,
|
|
140
212
|
outputSchema: focusInspectOutputSchema,
|
|
141
213
|
annotations: artifactProducing,
|
|
@@ -143,7 +215,7 @@ export const focusTaskTools = [
|
|
|
143
215
|
{
|
|
144
216
|
name: 'hoi4.focus_render',
|
|
145
217
|
title: 'Preview a focus tree or continuous palette',
|
|
146
|
-
description: '
|
|
218
|
+
description: 'Render a focus tree in the in-game style (right-angle connectors) and return it inline, with close-ups of the worst places; cropBranchIds and cropFocusIds add more. Look before you judge a layout: metrics cannot see composition. Also exports PNG with icons, HTML, SVG and JSON as linked artifacts. Example: {"relativePath":"common/national_focus/my_tree.txt","treeId":"my_focus_tree"}.',
|
|
147
219
|
inputSchema: focusRenderRequestSchema,
|
|
148
220
|
outputSchema: focusRenderOutputSchema,
|
|
149
221
|
annotations: artifactProducing,
|
|
@@ -151,7 +223,7 @@ export const focusTaskTools = [
|
|
|
151
223
|
{
|
|
152
224
|
name: 'hoi4.focus_rewrite',
|
|
153
225
|
title: 'Build or arrange a focus tree',
|
|
154
|
-
description: 'Create focus trees and
|
|
226
|
+
description: 'Create or repair a focus tree or palette. New trees: lanes and position mode auto; x/y only for exact anchors. layoutMode compact repairs a layout (compactFocusIds picks a branch, pinnedFocusIds keeps neighbours); engine lays out with the Rust engine; placement adds focuses, moving no others; both need hoi4-engine. Keeps prerequisites and rewards. Returns files, layout verdict and delta. Example: {"relativePath":"common/national_focus/my_tree.txt","treeId":"my_focus_tree","layoutMode":"compact"}.',
|
|
155
227
|
inputSchema: focusRewriteRequestSchema,
|
|
156
228
|
outputSchema: focusPlanOutputSchema,
|
|
157
229
|
annotations: {
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import { readFile, realpath, stat } from 'node:fs/promises';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { sha256Bytes } from '../core/canonical.js';
|
|
4
|
+
import { isWithin } from '../core/workspace.js';
|
|
5
|
+
/**
|
|
6
|
+
* The words a player reads for script commands and modifiers.
|
|
7
|
+
*
|
|
8
|
+
* The game's English localisation names each command's tooltip after it: `TRIGGER_IS_COASTAL`
|
|
9
|
+
* reads "Is coastal", `TRIGGER_HAS_IDEA_COUNTRY` reads "Has national spirit", and
|
|
10
|
+
* `MODIFIER_SUPPLY_CONSUMPTION_FACTOR` reads "Supply Consumption". These are the words a
|
|
11
|
+
* modder uses to describe the command, so search adds them to the command's entries.
|
|
12
|
+
*/
|
|
13
|
+
const files = ['effects_l_english.yml', 'triggers_l_english.yml', 'modifiers_l_english.yml'];
|
|
14
|
+
const MAX_FILE_BYTES = 2_000_000;
|
|
15
|
+
const entry = /^\s*([A-Za-z0-9_.]+):\d*\s*"(.*)"\s*(?:#.*)?$/u;
|
|
16
|
+
// Negated and descriptive variants of a key describe the same command.
|
|
17
|
+
const keyNoise = /(?:^|_)(?:NOT|NO|YES|TT|DESC|TOOLTIP|DETAILED|HEADER)(?=_|$)/gu;
|
|
18
|
+
const empty = { revision: 'none', texts: new Map() };
|
|
19
|
+
const cache = new Map();
|
|
20
|
+
/** Plain words of a localisation value, without formatting codes or placeholders. */
|
|
21
|
+
export function plainLocalisation(value) {
|
|
22
|
+
return value
|
|
23
|
+
.replaceAll('\\n', ' ')
|
|
24
|
+
.replace(/\$[^$]*\$/gu, ' ')
|
|
25
|
+
.replace(/§.|£\S*/gu, ' ')
|
|
26
|
+
.replace(/\[[^\]]*\]|@\S*/gu, ' ')
|
|
27
|
+
.replace(/\s+/gu, ' ')
|
|
28
|
+
.trim();
|
|
29
|
+
}
|
|
30
|
+
export async function readGameText(gameRoot) {
|
|
31
|
+
if (gameRoot === undefined)
|
|
32
|
+
return empty;
|
|
33
|
+
let root;
|
|
34
|
+
try {
|
|
35
|
+
root = await realpath(path.join(gameRoot, 'localisation', 'english'));
|
|
36
|
+
}
|
|
37
|
+
catch {
|
|
38
|
+
return empty;
|
|
39
|
+
}
|
|
40
|
+
if (!isWithin(await realpath(gameRoot), root))
|
|
41
|
+
return empty;
|
|
42
|
+
const stamps = [];
|
|
43
|
+
const paths = [];
|
|
44
|
+
for (const name of files) {
|
|
45
|
+
try {
|
|
46
|
+
const file = path.join(root, name);
|
|
47
|
+
const metadata = await stat(file);
|
|
48
|
+
if (!metadata.isFile() || metadata.size > MAX_FILE_BYTES)
|
|
49
|
+
continue;
|
|
50
|
+
stamps.push(`${name}:${metadata.size}:${metadata.mtimeMs}:${metadata.ino}`);
|
|
51
|
+
paths.push(file);
|
|
52
|
+
}
|
|
53
|
+
catch {
|
|
54
|
+
// A missing file leaves its commands without in-game text.
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
const stamp = stamps.join('|');
|
|
58
|
+
const known = cache.get(root);
|
|
59
|
+
if (known?.stamp === stamp)
|
|
60
|
+
return known.text;
|
|
61
|
+
const texts = new Map();
|
|
62
|
+
const hashes = [];
|
|
63
|
+
for (const file of paths) {
|
|
64
|
+
const bytes = await readFile(file);
|
|
65
|
+
hashes.push(sha256Bytes(bytes));
|
|
66
|
+
const content = bytes.toString('utf8');
|
|
67
|
+
for (const line of (content.charCodeAt(0) === 0xfeff ? content.slice(1) : content).split(/\r?\n/u)) {
|
|
68
|
+
const match = entry.exec(line);
|
|
69
|
+
const prefix = match === null ? null : /^(?:EFFECT|TRIGGER|MODIFIER)_/u.exec(match[1]);
|
|
70
|
+
if (match === null || prefix === null)
|
|
71
|
+
continue;
|
|
72
|
+
const key = match[1]
|
|
73
|
+
.slice(prefix[0].length)
|
|
74
|
+
.replace(keyNoise, '')
|
|
75
|
+
.replace(/__+/gu, '_')
|
|
76
|
+
.replace(/^_|_$/gu, '')
|
|
77
|
+
.toLowerCase();
|
|
78
|
+
const value = plainLocalisation(match[2]);
|
|
79
|
+
if (key.length === 0 || value.length === 0)
|
|
80
|
+
continue;
|
|
81
|
+
const list = texts.get(key) ?? [];
|
|
82
|
+
list.push(value);
|
|
83
|
+
texts.set(key, list);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
const text = { revision: sha256Bytes(Buffer.from(hashes.join('\n'), 'utf8')), texts };
|
|
87
|
+
cache.set(root, { stamp, text });
|
|
88
|
+
return text;
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* The game texts for each command name: an exact key, or the longest command that a key
|
|
92
|
+
* extends at an underscore (`has_idea_country` describes `has_idea`).
|
|
93
|
+
*/
|
|
94
|
+
export function commandTexts(commands, text) {
|
|
95
|
+
const result = new Map();
|
|
96
|
+
for (const [key, values] of text.texts) {
|
|
97
|
+
let name = key;
|
|
98
|
+
while (!commands.has(name)) {
|
|
99
|
+
const cut = name.lastIndexOf('_');
|
|
100
|
+
if (cut <= 0)
|
|
101
|
+
break;
|
|
102
|
+
name = name.slice(0, cut);
|
|
103
|
+
}
|
|
104
|
+
if (!commands.has(name))
|
|
105
|
+
continue;
|
|
106
|
+
result.set(name, [...(result.get(name) ?? []), ...values]);
|
|
107
|
+
}
|
|
108
|
+
return result;
|
|
109
|
+
}
|
|
@@ -166,6 +166,47 @@ export function sectionTerms(title, heading, lines) {
|
|
|
166
166
|
: /^[A-Z][A-Z0-9]*(?:_[A-Z0-9]+)+$/u.test(heading.trim())
|
|
167
167
|
? 'define'
|
|
168
168
|
: undefined,
|
|
169
|
+
role: commandRole(title, heading.trim()),
|
|
170
|
+
};
|
|
171
|
+
}
|
|
172
|
+
function commandRole(title, heading) {
|
|
173
|
+
if (!/^[a-z][a-z0-9_]*$/u.test(heading))
|
|
174
|
+
return undefined;
|
|
175
|
+
const page = title.toLowerCase();
|
|
176
|
+
if (page.includes('dynamic variables'))
|
|
177
|
+
return 'variable';
|
|
178
|
+
if (heading.startsWith('on_'))
|
|
179
|
+
return 'on_action';
|
|
180
|
+
if (page.startsWith('trigger'))
|
|
181
|
+
return 'trigger';
|
|
182
|
+
if (page.startsWith('effect'))
|
|
183
|
+
return 'effect';
|
|
184
|
+
return 'other';
|
|
185
|
+
}
|
|
186
|
+
/** A question that starts with one of these asks for a condition; with these, for an effect. */
|
|
187
|
+
const conditionWords = new Set(['check', 'whether', 'is', 'has', 'does', 'if', 'condition']);
|
|
188
|
+
const actionWords = new Set(('add give make set remove change create increase decrease raise lower reduce grant declare ' +
|
|
189
|
+
'annex move start spawn build rename switch kill transfer fire hide run pick free put queue ' +
|
|
190
|
+
'improve tell gain lose destroy release puppet end apply load swap upgrade unlock').split(' '));
|
|
191
|
+
const timingWords = new Set(['when', 'whenever', 'happens', 'happen', 'after', 'once']);
|
|
192
|
+
/** A command of another kind than the question asks for keeps this share of its score. */
|
|
193
|
+
const intentPenalty = 0.6;
|
|
194
|
+
function questionIntent(normalized) {
|
|
195
|
+
const raw = normalized.match(tokenPattern) ?? [];
|
|
196
|
+
const first = raw.find((word) => !['how', 'to', 'i', 'can', 'do', 'a', 'the'].includes(word));
|
|
197
|
+
const onAction = raw.some((word) => timingWords.has(word)) || /on[ _]actions?/u.test(normalized);
|
|
198
|
+
return {
|
|
199
|
+
role:
|
|
200
|
+
// "Run an effect when ..." asks for the moment, not for an effect.
|
|
201
|
+
onAction || first === undefined || first.includes('_')
|
|
202
|
+
? undefined
|
|
203
|
+
: conditionWords.has(first)
|
|
204
|
+
? 'trigger'
|
|
205
|
+
: actionWords.has(first)
|
|
206
|
+
? 'effect'
|
|
207
|
+
: undefined,
|
|
208
|
+
onAction,
|
|
209
|
+
variable: raw.some((word) => word.startsWith('variable')),
|
|
169
210
|
};
|
|
170
211
|
}
|
|
171
212
|
/** Script names abbreviate counts as `num_`, as in `num_divisions` or `num_of_factories`. */
|
|
@@ -175,13 +216,19 @@ const titleWeight = 0.5;
|
|
|
175
216
|
const bodyWeight = 1;
|
|
176
217
|
const saturation = 1.2;
|
|
177
218
|
const lengthNormalization = 0.75;
|
|
219
|
+
/** Words other copies of the same command use, per occurrence, relative to body text. */
|
|
220
|
+
const cardWeight = 0.5;
|
|
178
221
|
/** Corpus statistics for one immutable inventory of sections. */
|
|
179
222
|
export class RankingIndex {
|
|
180
223
|
entries;
|
|
224
|
+
cards;
|
|
181
225
|
#documentFrequency = new Map();
|
|
182
226
|
#averageBodyLength;
|
|
183
|
-
constructor(entries
|
|
227
|
+
constructor(entries,
|
|
228
|
+
/** For a command entry, the words of its other documentation and in-game text. */
|
|
229
|
+
cards = new Map()) {
|
|
184
230
|
this.entries = entries;
|
|
231
|
+
this.cards = cards;
|
|
185
232
|
let total = 0;
|
|
186
233
|
for (const entry of entries) {
|
|
187
234
|
total += entry.bodyLength;
|
|
@@ -221,6 +268,7 @@ export class RankingIndex {
|
|
|
221
268
|
normalized,
|
|
222
269
|
identifiers: new Set(terms.map(({ term }) => term).filter((term) => term.includes('_'))),
|
|
223
270
|
wants: {
|
|
271
|
+
...questionIntent(normalized),
|
|
224
272
|
console: words.some((word) => word === 'console' || word.startsWith('command')),
|
|
225
273
|
define: words.some((word) => word.startsWith('define')) || /\b[A-Z]{2,}_[A-Z]/u.test(query),
|
|
226
274
|
},
|
|
@@ -236,7 +284,8 @@ export class RankingIndex {
|
|
|
236
284
|
for (const { term, idf, weight } of plan.terms) {
|
|
237
285
|
const weighted = headingWeight * (entry.heading.get(term) ?? 0) +
|
|
238
286
|
titleWeight * (entry.title.get(term) ?? 0) +
|
|
239
|
-
(bodyWeight * (entry.body.get(term) ?? 0)) / lengthFactor
|
|
287
|
+
(bodyWeight * (entry.body.get(term) ?? 0)) / lengthFactor +
|
|
288
|
+
cardWeight * (this.cards.get(entry)?.get(term) ?? 0);
|
|
240
289
|
if (weighted === 0)
|
|
241
290
|
continue;
|
|
242
291
|
matched++;
|
|
@@ -270,6 +319,15 @@ export class RankingIndex {
|
|
|
270
319
|
score *= 0.7;
|
|
271
320
|
if (entry.specialty === 'define' && !plan.wants.define)
|
|
272
321
|
score *= 0.6;
|
|
322
|
+
{
|
|
323
|
+
const { role } = entry;
|
|
324
|
+
if (role === 'on_action' && !plan.wants.onAction)
|
|
325
|
+
score *= intentPenalty;
|
|
326
|
+
else if (role === 'variable' && !plan.wants.variable)
|
|
327
|
+
score *= intentPenalty;
|
|
328
|
+
else if (plan.wants.role !== undefined && role !== undefined && role !== plan.wants.role)
|
|
329
|
+
score *= intentPenalty;
|
|
330
|
+
}
|
|
273
331
|
return score;
|
|
274
332
|
}
|
|
275
333
|
/** Extra credit for query words that appear next to each other in the section. */
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { statSync } from 'node:fs';
|
|
1
2
|
import { realpath } from 'node:fs/promises';
|
|
2
3
|
import path from 'node:path';
|
|
3
4
|
import { globFiles } from '../core/file-glob.js';
|
|
@@ -8,7 +9,8 @@ import { prepareSource, verifySource, readBoundedFile, } from '../core/scanner.j
|
|
|
8
9
|
import { decodeSource } from '../core/source/encoding.js';
|
|
9
10
|
import { activeKnownMistakes } from './known-mistakes.js';
|
|
10
11
|
import { readBoundedJsonLines } from './lines.js';
|
|
11
|
-
import {
|
|
12
|
+
import { commandTexts, readGameText } from './game-text.js';
|
|
13
|
+
import { RankingIndex, sectionTerms, textTerms } from './ranking.js';
|
|
12
14
|
const MAX_FILES = 512;
|
|
13
15
|
const MAX_FILE_BYTES = 2_000_000;
|
|
14
16
|
const MAX_TOTAL_BYTES = 32_000_000;
|
|
@@ -34,6 +36,10 @@ export function publicReferenceSection(section) {
|
|
|
34
36
|
const { lines: _lines, terms: _terms, ...citation } = section;
|
|
35
37
|
return citation;
|
|
36
38
|
}
|
|
39
|
+
/** An unchanged stamp lets a repeated query reuse the hashed revision without rereading. */
|
|
40
|
+
function fileStamp(metadata) {
|
|
41
|
+
return `${metadata.size}:${metadata.mtimeMs}:${metadata.ctimeMs}:${metadata.ino}:${metadata.dev}`;
|
|
42
|
+
}
|
|
37
43
|
/** Up to three non-empty lines from `first`, trimmed to the 300-character excerpt bound. */
|
|
38
44
|
function snippet(lines, first = 0) {
|
|
39
45
|
return lines
|
|
@@ -120,6 +126,21 @@ function sectionize(root, filePath, content, revision) {
|
|
|
120
126
|
...rows.map((row) => section(row.heading, row.start, row.start + 1)),
|
|
121
127
|
];
|
|
122
128
|
}
|
|
129
|
+
/** The kit's HOI4 wiki folder, and the name it had before the kit renamed it. */
|
|
130
|
+
const WIKI_FOLDER = 'hoi4_wiki';
|
|
131
|
+
const LEGACY_WIKI_FOLDER = 'paradox_wiki';
|
|
132
|
+
/** `hoi4_wiki/` when the mod has it, otherwise the older `paradox_wiki/` of a mod the kit has not updated. */
|
|
133
|
+
function defaultWikiRoot(modRoot) {
|
|
134
|
+
const current = path.join(modRoot, WIKI_FOLDER);
|
|
135
|
+
try {
|
|
136
|
+
if (statSync(current).isDirectory())
|
|
137
|
+
return current;
|
|
138
|
+
}
|
|
139
|
+
catch {
|
|
140
|
+
// Not there: fall back to the legacy name, which is reported unavailable when absent too.
|
|
141
|
+
}
|
|
142
|
+
return path.join(modRoot, LEGACY_WIKI_FOLDER);
|
|
143
|
+
}
|
|
123
144
|
function sourceRoots(workspace) {
|
|
124
145
|
const gameRoot = workspace.gameRoot ?? (workspace.registration.kind === 'game' ? workspace.modRoot : undefined);
|
|
125
146
|
return [
|
|
@@ -135,9 +156,9 @@ function sourceRoots(workspace) {
|
|
|
135
156
|
]),
|
|
136
157
|
{
|
|
137
158
|
kind: 'wiki',
|
|
138
|
-
root: workspace.wikiRoot ??
|
|
159
|
+
root: workspace.wikiRoot ?? defaultWikiRoot(workspace.modRoot),
|
|
139
160
|
patterns: ['**/*.md'],
|
|
140
|
-
authority: '
|
|
161
|
+
authority: 'HOI4 wiki (kit)',
|
|
141
162
|
},
|
|
142
163
|
{
|
|
143
164
|
kind: 'script_doc',
|
|
@@ -202,6 +223,34 @@ const gameDocNames = {
|
|
|
202
223
|
],
|
|
203
224
|
ai: ['common/ai_strategy/_documentation', 'documentation/triggers_documentation'],
|
|
204
225
|
};
|
|
226
|
+
const commandHeading = /^[a-z][a-z0-9_]*$/u;
|
|
227
|
+
/**
|
|
228
|
+
* For each entry about one command, the words the game shows players for it: the installed
|
|
229
|
+
* documentation says "check if state is coastal" and the tooltip "Is coastal"; a modifier
|
|
230
|
+
* entry gains its in-game name, such as "Supply Consumption". Console commands and defines
|
|
231
|
+
* gain nothing.
|
|
232
|
+
*/
|
|
233
|
+
function commandCards(sections, gameText) {
|
|
234
|
+
const commands = new Set(sections
|
|
235
|
+
.filter(({ source, heading }) => source === 'game_doc' && commandHeading.test(heading.trim()))
|
|
236
|
+
.map(({ heading }) => heading.trim()));
|
|
237
|
+
const spoken = new Map();
|
|
238
|
+
for (const [name, texts] of commandTexts(commands, gameText)) {
|
|
239
|
+
const card = new Map();
|
|
240
|
+
for (const term of texts.flatMap((text) => textTerms(text)))
|
|
241
|
+
card.set(term, Math.min((card.get(term) ?? 0) + 1, 3));
|
|
242
|
+
spoken.set(name, card);
|
|
243
|
+
}
|
|
244
|
+
const cards = new Map();
|
|
245
|
+
for (const section of sections) {
|
|
246
|
+
if (section.terms.specialty !== undefined || section.terms.navigation)
|
|
247
|
+
continue;
|
|
248
|
+
const card = spoken.get(section.heading.trim());
|
|
249
|
+
if (card !== undefined)
|
|
250
|
+
cards.set(section.terms, card);
|
|
251
|
+
}
|
|
252
|
+
return cards;
|
|
253
|
+
}
|
|
205
254
|
/** A workspace-private, read-only reference index over explicitly known local roots. */
|
|
206
255
|
export class ReferenceService {
|
|
207
256
|
#cache = new Map();
|
|
@@ -304,7 +353,13 @@ export class ReferenceService {
|
|
|
304
353
|
coverage[root.kind].files++;
|
|
305
354
|
admittedSources.push(source);
|
|
306
355
|
}
|
|
356
|
+
const keyOf = (source) => `${root.kind}:${canonicalRoot}:${source.canonicalPath}`;
|
|
307
357
|
const reads = await Promise.allSettled(admittedSources.map(async (source) => {
|
|
358
|
+
const known = this.#cache.get(keyOf(source));
|
|
359
|
+
if (known?.stamp === fileStamp(source.metadata)) {
|
|
360
|
+
await verifySource(readRoot, source);
|
|
361
|
+
return known;
|
|
362
|
+
}
|
|
308
363
|
const content = await readBoundedFile(source.handle, source.metadata.size, signal);
|
|
309
364
|
await verifySource(readRoot, source);
|
|
310
365
|
if (content.length !== source.metadata.size)
|
|
@@ -318,17 +373,26 @@ export class ReferenceService {
|
|
|
318
373
|
for (const [index, read] of reads.entries()) {
|
|
319
374
|
if (read.status !== 'fulfilled')
|
|
320
375
|
continue;
|
|
321
|
-
const
|
|
322
|
-
const
|
|
323
|
-
const key =
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
376
|
+
const source = admittedSources[index];
|
|
377
|
+
const canonical = source.canonicalPath;
|
|
378
|
+
const key = keyOf(source);
|
|
379
|
+
let cached;
|
|
380
|
+
if (Buffer.isBuffer(read.value)) {
|
|
381
|
+
const content = read.value;
|
|
382
|
+
const revision = sha256Bytes(content);
|
|
383
|
+
const previous = this.#cache.get(key);
|
|
384
|
+
cached =
|
|
385
|
+
previous?.revision === revision
|
|
386
|
+
? { ...previous, stamp: fileStamp(source.metadata) }
|
|
387
|
+
: {
|
|
388
|
+
revision,
|
|
389
|
+
bytes: content.length,
|
|
390
|
+
stamp: fileStamp(source.metadata),
|
|
391
|
+
sections: sectionize(root, canonical, referenceText(content), revision),
|
|
392
|
+
};
|
|
393
|
+
}
|
|
394
|
+
else
|
|
395
|
+
cached = read.value;
|
|
332
396
|
this.retain(key, cached);
|
|
333
397
|
const admitted = cached.sections.slice(0, MAX_SECTIONS - sections.length);
|
|
334
398
|
if (admitted.length < cached.sections.length)
|
|
@@ -346,7 +410,7 @@ export class ReferenceService {
|
|
|
346
410
|
}
|
|
347
411
|
async search(workspace, input, signal) {
|
|
348
412
|
const inventory = await this.inventory(workspace, signal, input.sources);
|
|
349
|
-
const { ranked: matches, describe } = this.rank(inventory.sections, input.query);
|
|
413
|
+
const { ranked: matches, describe } = this.rank(inventory.sections, input.query, await this.gameText(workspace));
|
|
350
414
|
const results = matches.slice(0, input.limit).map((match) => {
|
|
351
415
|
const { section, score, excerpt, matchLine } = describe(match);
|
|
352
416
|
return { ...this.publicSection(section), score, excerpt, matchLine };
|
|
@@ -367,8 +431,8 @@ export class ReferenceService {
|
|
|
367
431
|
};
|
|
368
432
|
}
|
|
369
433
|
/** One index per distinct set of section revisions; IDF depends on the whole inventory. */
|
|
370
|
-
rankingIndex(sections) {
|
|
371
|
-
const parts = [];
|
|
434
|
+
rankingIndex(sections, gameText) {
|
|
435
|
+
const parts = [`game-text\0${gameText.revision}`];
|
|
372
436
|
let previous;
|
|
373
437
|
for (const section of sections) {
|
|
374
438
|
if (previous?.path !== section.path || previous.revision !== section.revision)
|
|
@@ -382,7 +446,7 @@ export class ReferenceService {
|
|
|
382
446
|
this.#indexes.set(key, cached);
|
|
383
447
|
return cached;
|
|
384
448
|
}
|
|
385
|
-
const index = new RankingIndex(sections.map(({ terms }) => terms));
|
|
449
|
+
const index = new RankingIndex(sections.map(({ terms }) => terms), commandCards(sections, gameText));
|
|
386
450
|
this.#indexes.set(key, index);
|
|
387
451
|
while (this.#indexes.size > 4) {
|
|
388
452
|
const oldest = this.#indexes.keys().next().value;
|
|
@@ -392,8 +456,8 @@ export class ReferenceService {
|
|
|
392
456
|
}
|
|
393
457
|
return index;
|
|
394
458
|
}
|
|
395
|
-
rank(sections, question) {
|
|
396
|
-
const index = this.rankingIndex(sections);
|
|
459
|
+
rank(sections, question, gameText) {
|
|
460
|
+
const index = this.rankingIndex(sections, gameText);
|
|
397
461
|
const plan = index.plan(question);
|
|
398
462
|
const scored = [];
|
|
399
463
|
for (const section of sections) {
|
|
@@ -485,7 +549,9 @@ export class ReferenceService {
|
|
|
485
549
|
async context(workspace, input, signal) {
|
|
486
550
|
const inventory = await this.inventory(workspace, signal);
|
|
487
551
|
const wanted = surfaceNames[input.surface];
|
|
488
|
-
const ranking = input.question === undefined
|
|
552
|
+
const ranking = input.question === undefined
|
|
553
|
+
? undefined
|
|
554
|
+
: this.rank(inventory.sections, input.question, await this.gameText(workspace));
|
|
489
555
|
const ranked = ranking?.ranked ?? [];
|
|
490
556
|
const required = [];
|
|
491
557
|
const missing = [];
|
|
@@ -552,6 +618,11 @@ export class ReferenceService {
|
|
|
552
618
|
})),
|
|
553
619
|
};
|
|
554
620
|
}
|
|
621
|
+
async gameText(workspace) {
|
|
622
|
+
const gameRoot = workspace.gameRoot ??
|
|
623
|
+
(workspace.registration.kind === 'game' ? workspace.modRoot : undefined);
|
|
624
|
+
return readGameText(gameRoot);
|
|
625
|
+
}
|
|
555
626
|
publicSection(section) {
|
|
556
627
|
return publicReferenceSection(section);
|
|
557
628
|
}
|