hoi4-agent-tools 4.15.0 → 4.17.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 +33 -0
- package/README.md +1 -0
- package/dist/hoi4_agent_tools/core/analysis-checkpoints.js +11 -4
- package/dist/hoi4_agent_tools/core/engine-client.js +30 -1
- package/dist/hoi4_agent_tools/core/engine.js +56 -27
- package/dist/hoi4_agent_tools/core/managed-outputs.js +153 -26
- package/dist/hoi4_agent_tools/core/scanner.js +148 -7
- package/dist/hoi4_agent_tools/core/server-state.js +50 -2
- package/dist/hoi4_agent_tools/core/source/localisation.js +7 -1
- package/dist/hoi4_agent_tools/event/compare.js +47 -13
- package/dist/hoi4_agent_tools/focus/importer.js +2 -5
- package/dist/hoi4_agent_tools/focus/lint.js +2 -5
- package/dist/hoi4_agent_tools/focus/model.js +19 -0
- package/dist/hoi4_agent_tools/focus/tool-operations.js +16 -1
- package/dist/hoi4_agent_tools/focus/tool-support.js +14 -0
- package/dist/hoi4_agent_tools/map/appearance-validation.js +6 -1
- package/dist/hoi4_agent_tools/map/engine-raster.js +160 -0
- package/dist/hoi4_agent_tools/map/model.js +9 -8
- package/dist/hoi4_agent_tools/map/operations.js +74 -2
- package/dist/hoi4_agent_tools/map/partition-provinces.js +6 -2
- package/dist/hoi4_agent_tools/map/partition-tuning.js +37 -0
- package/dist/hoi4_agent_tools/map/service.js +25 -12
- package/dist/hoi4_agent_tools/map/territory-operations.js +114 -3
- package/dist/hoi4_agent_tools/map/territory-quality.js +39 -0
- package/dist/hoi4_agent_tools/map/territory.js +63 -2
- package/dist/hoi4_agent_tools/map/tool-operations.js +27 -1
- package/dist/hoi4_agent_tools/map/validation.js +23 -3
- package/dist/hoi4_agent_tools/map/water.js +13 -10
- package/dist/hoi4_agent_tools/map/world-outputs.js +53 -25
- package/dist/hoi4_agent_tools/map/world.js +51 -1
- package/dist/hoi4_agent_tools/mcp/tools/map.js +23 -0
- package/dist/hoi4_agent_tools/mcp/tools/reference.js +2 -2
- package/dist/hoi4_agent_tools/mcp/tools/technology.js +25 -1
- package/dist/hoi4_agent_tools/reference/closure.js +65 -0
- package/dist/hoi4_agent_tools/reference/command-phrases.json +7899 -1127
- package/dist/hoi4_agent_tools/reference/operations.js +38 -21
- package/dist/hoi4_agent_tools/reference/ranking.js +77 -2
- package/dist/hoi4_agent_tools/reference/script-validation.js +4 -2
- package/dist/hoi4_agent_tools/reference/service.js +45 -2
- package/dist/hoi4_agent_tools/reference/source-lookup.js +43 -121
- package/dist/hoi4_agent_tools/runtime.js +27 -11
- package/dist/hoi4_agent_tools/schemas/lenient-arguments.js +7 -1
- package/dist/hoi4_agent_tools/schemas/map.js +41 -0
- package/dist/hoi4_agent_tools/schemas/mod-tools.js +49 -0
- package/dist/hoi4_agent_tools/schemas/reference.js +1 -1
- package/dist/hoi4_agent_tools/schemas/script-validation.js +57 -3
- package/dist/hoi4_agent_tools/technology/operations.js +5 -0
- package/dist/hoi4_agent_tools/technology/queries.js +54 -0
- package/dist/hoi4_agent_tools/version.js +1 -1
- package/docs/configuration.md +1 -1
- package/docs/map.md +14 -10
- package/docs/research/reference-benchmark.md +64 -0
- package/docs/tools.md +20 -20
- package/docs/troubleshooting.md +4 -0
- package/engine/bin/darwin-arm64/hoi4-engine +0 -0
- package/engine/bin/linux-arm64/hoi4-engine +0 -0
- package/engine/bin/linux-x64/hoi4-engine +0 -0
- package/engine/bin/manifest.json +8 -8
- package/engine/bin/win32-x64/hoi4-engine.exe +0 -0
- package/npm-shrinkwrap.json +2 -2
- package/package.json +5 -3
- 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 +1 -1
- package/schemas/focus-planning-sidecar.schema.json +1 -1
- 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 +838 -728
- 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 +2 -2
- 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 +7 -1
- package/schemas/shared-scenario.schema.json +1 -1
- package/schemas/source-lookup-input.schema.json +1 -1
- package/server.json +2 -2
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { open, realpath, stat } from 'node:fs/promises';
|
|
1
|
+
import { open, readdir, realpath, stat } from 'node:fs/promises';
|
|
2
2
|
import { createHash } from 'node:crypto';
|
|
3
3
|
import path from 'node:path';
|
|
4
4
|
import { iterateFiles } from './file-glob.js';
|
|
@@ -65,6 +65,14 @@ export async function prepareSource(root, relativePath, signal) {
|
|
|
65
65
|
throw error;
|
|
66
66
|
}
|
|
67
67
|
}
|
|
68
|
+
/** Roots that hold the installed game, which only a game update changes. */
|
|
69
|
+
function installedRoot(kind) {
|
|
70
|
+
return kind === 'game' || kind === 'dlc';
|
|
71
|
+
}
|
|
72
|
+
/** Device, file number, size and both change times: any write to the file moves one of them. */
|
|
73
|
+
function fileIdentity(metadata) {
|
|
74
|
+
return `${metadata.dev}:${metadata.ino}:${metadata.size}:${metadata.mtimeMs}:${metadata.ctimeMs}`;
|
|
75
|
+
}
|
|
68
76
|
function normalizeRelative(value) {
|
|
69
77
|
return value.replaceAll('\\', '/').replace(/^\.\//u, '');
|
|
70
78
|
}
|
|
@@ -85,11 +93,72 @@ function hiddenByReplacePath(workspace, root, relativePath) {
|
|
|
85
93
|
return candidate === normalized || candidate.startsWith(`${normalized}/`);
|
|
86
94
|
}));
|
|
87
95
|
}
|
|
96
|
+
const GAME_INVENTORY_MAX_BYTES = 96 * 1024 * 1024;
|
|
97
|
+
const GAME_INVENTORY_MAX_ENTRIES = 3;
|
|
98
|
+
/** Files the game rewrites with every patch. A game folder without the first is always walked. */
|
|
99
|
+
const GAME_VERSION_FILES = [
|
|
100
|
+
'hoi4_rev.txt',
|
|
101
|
+
'hoi4_branch.txt',
|
|
102
|
+
'clausewitz_rev.txt',
|
|
103
|
+
'checksum_manifest.txt',
|
|
104
|
+
];
|
|
105
|
+
/**
|
|
106
|
+
* The state of the installed game as its version files and top-level folders show it, or
|
|
107
|
+
* undefined when the folder does not name its version and so cannot vouch for itself.
|
|
108
|
+
* HOI4_AGENT_FULL_GAME_SCAN set to any value turns the shortcut off, for a modder who edits the
|
|
109
|
+
* game's files in place without a patch.
|
|
110
|
+
*/
|
|
111
|
+
async function gameFingerprint(rootPath, signal) {
|
|
112
|
+
if (process.env.HOI4_AGENT_FULL_GAME_SCAN !== undefined)
|
|
113
|
+
return undefined;
|
|
114
|
+
const parts = [];
|
|
115
|
+
try {
|
|
116
|
+
for (const name of GAME_VERSION_FILES) {
|
|
117
|
+
signal?.throwIfAborted();
|
|
118
|
+
const metadata = await stat(path.join(rootPath, name)).catch(() => undefined);
|
|
119
|
+
if (name === GAME_VERSION_FILES[0] && metadata === undefined)
|
|
120
|
+
return undefined;
|
|
121
|
+
parts.push(metadata === undefined
|
|
122
|
+
? `${name}:-`
|
|
123
|
+
: `${name}:${metadata.size}:${metadata.mtimeMs}:${metadata.ctimeMs}`);
|
|
124
|
+
}
|
|
125
|
+
parts.push(`.:${(await stat(rootPath)).mtimeMs}`);
|
|
126
|
+
const folders = (await readdir(rootPath, { withFileTypes: true }))
|
|
127
|
+
.filter((entry) => entry.isDirectory())
|
|
128
|
+
.map((entry) => entry.name)
|
|
129
|
+
.sort(compareCodeUnits);
|
|
130
|
+
for (const name of folders) {
|
|
131
|
+
signal?.throwIfAborted();
|
|
132
|
+
const metadata = await stat(path.join(rootPath, name)).catch(() => undefined);
|
|
133
|
+
parts.push(`${name}:${metadata?.mtimeMs ?? '-'}`);
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
catch (error) {
|
|
137
|
+
if (signal?.aborted === true)
|
|
138
|
+
throw error;
|
|
139
|
+
return undefined;
|
|
140
|
+
}
|
|
141
|
+
return parts.join('|');
|
|
142
|
+
}
|
|
143
|
+
/** The scan a game inventory answers: the root, the patterns and what mods hide from the game. */
|
|
144
|
+
function gameInventoryKey(workspace, root, options) {
|
|
145
|
+
const hidden = workspace.roots
|
|
146
|
+
.filter((owner) => (owner.kind === 'mod' || owner.kind === 'dependency') && owner.loadOrder > root.loadOrder)
|
|
147
|
+
.flatMap((owner) => owner.replacePaths.map((replacePath) => normalizeRelative(replacePath)))
|
|
148
|
+
.sort(compareCodeUnits);
|
|
149
|
+
return JSON.stringify([
|
|
150
|
+
path.resolve(root.path),
|
|
151
|
+
[...options.patterns].sort(compareCodeUnits),
|
|
152
|
+
[...(options.ignore ?? ['**/.hoi4-agent/**'])].sort(compareCodeUnits),
|
|
153
|
+
hidden,
|
|
154
|
+
]);
|
|
155
|
+
}
|
|
88
156
|
export class WorkspaceScanner {
|
|
89
157
|
serverMaxFiles;
|
|
90
158
|
serverMaxBytes;
|
|
91
159
|
serverMaxFileBytes;
|
|
92
160
|
#sourceCache = new Map();
|
|
161
|
+
#gameInventories = new Map();
|
|
93
162
|
#sourceCacheBytes = 0;
|
|
94
163
|
#sourceCacheMaxBytes;
|
|
95
164
|
constructor(serverMaxFiles = DEFAULT_SCAN_MAX_FILES, serverMaxBytes = DEFAULT_SCAN_MAX_BYTES, serverMaxFileBytes = DEFAULT_SCAN_MAX_FILE_BYTES) {
|
|
@@ -119,10 +188,24 @@ export class WorkspaceScanner {
|
|
|
119
188
|
this.#sourceCacheBytes -= oldest[1].bytes.length;
|
|
120
189
|
}
|
|
121
190
|
}
|
|
191
|
+
rememberGameInventory(key, inventory) {
|
|
192
|
+
this.#gameInventories.delete(key);
|
|
193
|
+
// The buffers are shared with the source cache, so the limit keeps this to a few focused scans.
|
|
194
|
+
if (inventory.bytes > GAME_INVENTORY_MAX_BYTES)
|
|
195
|
+
return;
|
|
196
|
+
this.#gameInventories.set(key, inventory);
|
|
197
|
+
while (this.#gameInventories.size > GAME_INVENTORY_MAX_ENTRIES) {
|
|
198
|
+
const oldest = this.#gameInventories.keys().next().value;
|
|
199
|
+
if (oldest === undefined)
|
|
200
|
+
break;
|
|
201
|
+
this.#gameInventories.delete(oldest);
|
|
202
|
+
}
|
|
203
|
+
}
|
|
122
204
|
/** Release retained source buffers after an idle MCP analysis batch. */
|
|
123
205
|
clearCaches() {
|
|
124
206
|
this.#sourceCache.clear();
|
|
125
207
|
this.#sourceCacheBytes = 0;
|
|
208
|
+
this.#gameInventories.clear();
|
|
126
209
|
}
|
|
127
210
|
/** Cache accounting used by lifecycle and regression tests. */
|
|
128
211
|
cacheUsage() {
|
|
@@ -160,8 +243,40 @@ export class WorkspaceScanner {
|
|
|
160
243
|
let enumeratedFiles = 0;
|
|
161
244
|
for (const root of roots) {
|
|
162
245
|
options.signal?.throwIfAborted();
|
|
163
|
-
//
|
|
164
|
-
//
|
|
246
|
+
// The installed game is walked file by file once. While its version files and top-level
|
|
247
|
+
// folders stay as they were, the next scan with the same patterns takes that inventory
|
|
248
|
+
// instead of opening, resolving and checking 1,400 files again. A game folder that does not
|
|
249
|
+
// name its version, or any other kind of root, is always walked.
|
|
250
|
+
const inventoryKey = root.kind === 'game' ? gameInventoryKey(workspace, root, options) : undefined;
|
|
251
|
+
const fingerprint = inventoryKey === undefined ? undefined : await gameFingerprint(root.path, options.signal);
|
|
252
|
+
const known = inventoryKey === undefined || fingerprint === undefined
|
|
253
|
+
? undefined
|
|
254
|
+
: this.#gameInventories.get(inventoryKey);
|
|
255
|
+
if (known !== undefined && known.fingerprint === fingerprint) {
|
|
256
|
+
enumeratedFiles += known.enumerated;
|
|
257
|
+
if (enumeratedFiles > maxFiles) {
|
|
258
|
+
throw new ServiceError('SCAN_FILE_LIMIT', 'Scan exceeds the configured file limit', {
|
|
259
|
+
files: enumeratedFiles,
|
|
260
|
+
limit: maxFiles,
|
|
261
|
+
});
|
|
262
|
+
}
|
|
263
|
+
if (totalBytes + known.bytes > maxBytes) {
|
|
264
|
+
throw new ServiceError('SCAN_BYTE_LIMIT', 'Scan exceeds the configured byte limit', {
|
|
265
|
+
bytes: totalBytes + known.bytes,
|
|
266
|
+
limit: maxBytes,
|
|
267
|
+
});
|
|
268
|
+
}
|
|
269
|
+
totalBytes += known.bytes;
|
|
270
|
+
for (const file of known.files) {
|
|
271
|
+
const { shadowedBy: _shadowedBy, ...fresh } = file;
|
|
272
|
+
result.push(fresh);
|
|
273
|
+
}
|
|
274
|
+
continue;
|
|
275
|
+
}
|
|
276
|
+
const resultBefore = result.length;
|
|
277
|
+
const enumeratedBefore = enumeratedFiles;
|
|
278
|
+
// Re-enumerate every other root: installing content or changing load order can
|
|
279
|
+
// invalidate a mod inventory.
|
|
165
280
|
const matches = iterateFiles(options.patterns, {
|
|
166
281
|
cwd: root.path,
|
|
167
282
|
ignore: options.ignore ?? ['**/.hoi4-agent/**'],
|
|
@@ -219,6 +334,20 @@ export class WorkspaceScanner {
|
|
|
219
334
|
readOffset++;
|
|
220
335
|
}
|
|
221
336
|
const reads = await Promise.allSettled(group.map(async (source) => {
|
|
337
|
+
// The installed game changes only when the game updates, and a file's identity
|
|
338
|
+
// moves with every write, so an unchanged game file keeps its bytes and hash
|
|
339
|
+
// instead of being read from disk again on every call. Mod files are always read.
|
|
340
|
+
// The retained buffer is shared with earlier results, so it must still match its
|
|
341
|
+
// hash: a caller that wrote into one must not change what a later scan returns.
|
|
342
|
+
const retained = installedRoot(root.kind)
|
|
343
|
+
? this.#sourceCache.get(this.cacheKey(source.absolutePath))
|
|
344
|
+
: undefined;
|
|
345
|
+
if (retained?.identity === fileIdentity(source.metadata) &&
|
|
346
|
+
sha256Bytes(retained.bytes) === retained.sha256) {
|
|
347
|
+
await verifySource(root, source);
|
|
348
|
+
options.signal?.throwIfAborted();
|
|
349
|
+
return { bytes: retained.bytes, sha256: retained.sha256 };
|
|
350
|
+
}
|
|
222
351
|
let bytes;
|
|
223
352
|
try {
|
|
224
353
|
bytes = await readBoundedFile(source.handle, source.metadata.size, options.signal);
|
|
@@ -232,7 +361,7 @@ export class WorkspaceScanner {
|
|
|
232
361
|
throw new ServiceError('SCAN_SOURCE_CHANGED', 'Source changed while it was being scanned; retry a focused query', { file: source.relativePath });
|
|
233
362
|
await verifySource(root, source);
|
|
234
363
|
options.signal?.throwIfAborted();
|
|
235
|
-
return bytes;
|
|
364
|
+
return { bytes, sha256: undefined };
|
|
236
365
|
}));
|
|
237
366
|
const readFailure = reads.find((entry) => entry.status === 'rejected');
|
|
238
367
|
if (readFailure?.status === 'rejected')
|
|
@@ -242,13 +371,17 @@ export class WorkspaceScanner {
|
|
|
242
371
|
continue;
|
|
243
372
|
const source = group[index];
|
|
244
373
|
const cacheKey = this.cacheKey(source.absolutePath);
|
|
245
|
-
const observed = read.value;
|
|
246
|
-
const sha256 = sha256Bytes(observed);
|
|
374
|
+
const observed = read.value.bytes;
|
|
375
|
+
const sha256 = read.value.sha256 ?? sha256Bytes(observed);
|
|
247
376
|
const cached = this.#sourceCache.get(cacheKey);
|
|
248
377
|
const bytes = cached?.sha256 === sha256 && cached.bytes.equals(observed)
|
|
249
378
|
? cached.bytes
|
|
250
379
|
: observed;
|
|
251
|
-
this.retainSource(cacheKey, {
|
|
380
|
+
this.retainSource(cacheKey, {
|
|
381
|
+
sha256,
|
|
382
|
+
bytes,
|
|
383
|
+
...(installedRoot(root.kind) ? { identity: fileIdentity(source.metadata) } : {}),
|
|
384
|
+
});
|
|
252
385
|
totalBytes += bytes.length;
|
|
253
386
|
result.push({
|
|
254
387
|
absolutePath: source.absolutePath,
|
|
@@ -268,6 +401,14 @@ export class WorkspaceScanner {
|
|
|
268
401
|
await Promise.all(opened.map(({ handle }) => handle.close()));
|
|
269
402
|
}
|
|
270
403
|
}
|
|
404
|
+
if (inventoryKey !== undefined && fingerprint !== undefined) {
|
|
405
|
+
this.rememberGameInventory(inventoryKey, {
|
|
406
|
+
fingerprint,
|
|
407
|
+
enumerated: enumeratedFiles - enumeratedBefore,
|
|
408
|
+
files: result.slice(resultBefore).map((file) => ({ ...file })),
|
|
409
|
+
bytes: result.slice(resultBefore).reduce((sum, file) => sum + file.bytes.length, 0),
|
|
410
|
+
});
|
|
411
|
+
}
|
|
271
412
|
}
|
|
272
413
|
options.signal?.throwIfAborted();
|
|
273
414
|
result.sort((left, right) => left.loadOrder - right.loadOrder || compareCodeUnits(left.relativePath, right.relativePath));
|
|
@@ -47,6 +47,53 @@ async function assertNoLinkComponents(absolutePath) {
|
|
|
47
47
|
}
|
|
48
48
|
}
|
|
49
49
|
}
|
|
50
|
+
/**
|
|
51
|
+
* A link only the superuser can create or change: owned by root, in a root-owned directory that
|
|
52
|
+
* neither group nor others can write. macOS ships `/var`, `/tmp` and `/etc` as such links into
|
|
53
|
+
* `/private`, so `$TMPDIR` (`/var/folders/...`) always has one. Windows has no such rule.
|
|
54
|
+
*/
|
|
55
|
+
export function isTrustedSystemLink(facts, platform = process.platform) {
|
|
56
|
+
return (platform !== 'win32' &&
|
|
57
|
+
facts.linkUid === 0 &&
|
|
58
|
+
facts.parentUid === 0 &&
|
|
59
|
+
(facts.parentMode & 0o022) === 0);
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Replace the leading components that pass through trusted system links with their real paths,
|
|
63
|
+
* so a state root such as `/var/folders/.../state` becomes `/private/var/folders/.../state`. A
|
|
64
|
+
* link anyone else could change stays in the path and is refused by `assertNoLinkComponents`.
|
|
65
|
+
*/
|
|
66
|
+
async function resolveTrustedSystemLinks(absolutePath) {
|
|
67
|
+
const parsed = path.parse(absolutePath);
|
|
68
|
+
const segments = absolutePath.slice(parsed.root.length).split(path.sep).filter(Boolean);
|
|
69
|
+
let cursor = parsed.root;
|
|
70
|
+
for (let index = 0; index < segments.length; index += 1) {
|
|
71
|
+
const candidate = path.join(cursor, segments[index]);
|
|
72
|
+
let metadata;
|
|
73
|
+
try {
|
|
74
|
+
metadata = await lstat(candidate);
|
|
75
|
+
}
|
|
76
|
+
catch (error) {
|
|
77
|
+
if (isNotFound(error))
|
|
78
|
+
return path.join(candidate, ...segments.slice(index + 1));
|
|
79
|
+
throw error;
|
|
80
|
+
}
|
|
81
|
+
if (!metadata.isSymbolicLink()) {
|
|
82
|
+
cursor = candidate;
|
|
83
|
+
continue;
|
|
84
|
+
}
|
|
85
|
+
const parent = await lstat(cursor);
|
|
86
|
+
if (!isTrustedSystemLink({
|
|
87
|
+
linkUid: metadata.uid,
|
|
88
|
+
parentUid: parent.uid,
|
|
89
|
+
parentMode: parent.mode,
|
|
90
|
+
})) {
|
|
91
|
+
return absolutePath;
|
|
92
|
+
}
|
|
93
|
+
cursor = path.normalize(await realpath(candidate));
|
|
94
|
+
}
|
|
95
|
+
return cursor;
|
|
96
|
+
}
|
|
50
97
|
async function assertPrivateFile(filePath, expectedBytes) {
|
|
51
98
|
let metadata;
|
|
52
99
|
try {
|
|
@@ -100,10 +147,11 @@ export class ServerState {
|
|
|
100
147
|
this.journalKey = journalKey;
|
|
101
148
|
}
|
|
102
149
|
static async create(requestedRoot) {
|
|
103
|
-
const
|
|
104
|
-
if (!path.isAbsolute(
|
|
150
|
+
const normalizedRoot = path.normalize(requestedRoot);
|
|
151
|
+
if (!path.isAbsolute(normalizedRoot)) {
|
|
105
152
|
throw stateError('SERVER_STATE_ROOT_INVALID', 'Server state root must be absolute');
|
|
106
153
|
}
|
|
154
|
+
const absoluteRoot = await resolveTrustedSystemLinks(normalizedRoot);
|
|
107
155
|
await assertNoLinkComponents(absoluteRoot);
|
|
108
156
|
await mkdir(absoluteRoot, { recursive: true, mode: 0o700 });
|
|
109
157
|
await assertNoLinkComponents(absoluteRoot);
|
|
@@ -4,6 +4,12 @@ import { SourceDiagnosticCollector } from './limits.js';
|
|
|
4
4
|
import { SOURCE_ENTRY_LIMIT, SOURCE_LINE_LIMIT, SOURCE_MAX_BYTES } from './limits.js';
|
|
5
5
|
const languagePattern = /^\s*(l_[a-z_]+):\s*(?:#.*)?$/u;
|
|
6
6
|
const entryPattern = /^\s*([A-Za-z0-9_.-]+):(?:(\d+)\s+|\s*)"((?:\\.|[^"\\])*)"\s*(?:#.*)?$/u;
|
|
7
|
+
/**
|
|
8
|
+
* A value with quotes inside it, as in `k:0 "He said "hi" now"`. The game reads from the first quote
|
|
9
|
+
* to the last one on the line: the installed game's own localisation has 400 such lines, and mods
|
|
10
|
+
* use them freely. Tried only when `entryPattern` does not match.
|
|
11
|
+
*/
|
|
12
|
+
const innerQuotePattern = /^\s*([A-Za-z0-9_.-]+):(?:(\d+)\s+|\s*)"(.*)"\s*$/u;
|
|
7
13
|
function decodeLocalisationValue(value) {
|
|
8
14
|
let result = '';
|
|
9
15
|
for (let index = 0; index < value.length; index += 1) {
|
|
@@ -114,7 +120,7 @@ export function parseLocalisation(bytes, sourcePath) {
|
|
|
114
120
|
lineNumber += 1;
|
|
115
121
|
continue;
|
|
116
122
|
}
|
|
117
|
-
const match = entryPattern.exec(line);
|
|
123
|
+
const match = entryPattern.exec(line) ?? innerQuotePattern.exec(line);
|
|
118
124
|
if (match === null) {
|
|
119
125
|
diagnosticCollector.add(() => ({
|
|
120
126
|
code: 'LOCALISATION_MALFORMED_LINE',
|
|
@@ -33,6 +33,42 @@ function semanticStateAccess(access) {
|
|
|
33
33
|
conditions: access.conditions.map(semanticCondition),
|
|
34
34
|
};
|
|
35
35
|
}
|
|
36
|
+
/**
|
|
37
|
+
* Edges and state accesses share their condition objects: every effect inside an option
|
|
38
|
+
* carries the option's guards. Hashing each condition once and naming it by its digest keeps
|
|
39
|
+
* the hash a function of the same semantic content while the bytes hashed stay proportional
|
|
40
|
+
* to the distinct conditions. On a large mod the inline form hashed about 3 GB per graph.
|
|
41
|
+
*/
|
|
42
|
+
const conditionDigests = new WeakMap();
|
|
43
|
+
function conditionDigest(condition) {
|
|
44
|
+
let digest = conditionDigests.get(condition);
|
|
45
|
+
if (digest === undefined) {
|
|
46
|
+
digest = hashCanonical(semanticCondition(condition));
|
|
47
|
+
conditionDigests.set(condition, digest);
|
|
48
|
+
}
|
|
49
|
+
return digest;
|
|
50
|
+
}
|
|
51
|
+
function edgeHash(edge) {
|
|
52
|
+
return hashCanonical({
|
|
53
|
+
...edge,
|
|
54
|
+
location: { path: edge.location.path },
|
|
55
|
+
conditions: edge.conditions.map(conditionDigest),
|
|
56
|
+
provenance: edge.provenance.map(({ role, location }) => ({
|
|
57
|
+
role,
|
|
58
|
+
location: { path: location.path },
|
|
59
|
+
})),
|
|
60
|
+
weight: edge.weight === undefined
|
|
61
|
+
? undefined
|
|
62
|
+
: { ...edge.weight, modifiers: edge.weight.modifiers.map(conditionDigest) },
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
function stateAccessHash(access) {
|
|
66
|
+
return hashCanonical({
|
|
67
|
+
...access,
|
|
68
|
+
location: { path: access.location.path },
|
|
69
|
+
conditions: access.conditions.map(conditionDigest),
|
|
70
|
+
});
|
|
71
|
+
}
|
|
36
72
|
function semanticIssue(issue) {
|
|
37
73
|
return {
|
|
38
74
|
...issue,
|
|
@@ -57,11 +93,11 @@ function semanticUnresolved(item) {
|
|
|
57
93
|
})),
|
|
58
94
|
};
|
|
59
95
|
}
|
|
60
|
-
function semanticCollectionHash(domain, values, identity,
|
|
96
|
+
function semanticCollectionHash(domain, values, identity, hash, signal) {
|
|
61
97
|
const records = values.map((value, index) => {
|
|
62
98
|
if ((index & 255) === 0)
|
|
63
99
|
signal?.throwIfAborted();
|
|
64
|
-
return { id: identity(value), hash:
|
|
100
|
+
return { id: identity(value), hash: hash(value) };
|
|
65
101
|
});
|
|
66
102
|
records.sort((left, right) => compareCodeUnits(left.id, right.id) || compareCodeUnits(left.hash, right.hash));
|
|
67
103
|
const digest = createHash('sha256');
|
|
@@ -83,13 +119,13 @@ function semanticCollectionHash(domain, values, identity, semantic, signal) {
|
|
|
83
119
|
function graphHash(graph, signal) {
|
|
84
120
|
signal?.throwIfAborted();
|
|
85
121
|
return hashCanonical({
|
|
86
|
-
schema: 'event-semantic-graph-hash.
|
|
87
|
-
nodes: semanticCollectionHash('nodes', graph.nodes, ({ id }) => id, semanticNode, signal),
|
|
88
|
-
edges: semanticCollectionHash('edges', graph.edges, ({ id }) => id,
|
|
89
|
-
stateAccesses: semanticCollectionHash('state-accesses', graph.stateAccesses, ({ id }) => id,
|
|
90
|
-
stateLinks: semanticCollectionHash('state-links', graph.stateLinks, ({ id }) => id, (value) => value, signal),
|
|
91
|
-
issues: semanticCollectionHash('issues', graph.issues, issueId, semanticIssue, signal),
|
|
92
|
-
unresolved: semanticCollectionHash('unresolved', graph.unresolved, ({ id }) => id, semanticUnresolved, signal),
|
|
122
|
+
schema: 'event-semantic-graph-hash.v3',
|
|
123
|
+
nodes: semanticCollectionHash('nodes', graph.nodes, ({ id }) => id, (node) => hashCanonical(semanticNode(node)), signal),
|
|
124
|
+
edges: semanticCollectionHash('edges', graph.edges, ({ id }) => id, edgeHash, signal),
|
|
125
|
+
stateAccesses: semanticCollectionHash('state-accesses', graph.stateAccesses, ({ id }) => id, stateAccessHash, signal),
|
|
126
|
+
stateLinks: semanticCollectionHash('state-links', graph.stateLinks, ({ id }) => id, (value) => hashCanonical(value), signal),
|
|
127
|
+
issues: semanticCollectionHash('issues', graph.issues, issueId, (issue) => hashCanonical(semanticIssue(issue)), signal),
|
|
128
|
+
unresolved: semanticCollectionHash('unresolved', graph.unresolved, ({ id }) => id, (item) => hashCanonical(semanticUnresolved(item)), signal),
|
|
93
129
|
});
|
|
94
130
|
}
|
|
95
131
|
function mapById(values, signal) {
|
|
@@ -198,8 +234,7 @@ export function compareEventGraphs(before, after, signal) {
|
|
|
198
234
|
.filter((id) => {
|
|
199
235
|
check();
|
|
200
236
|
const current = afterEdges.get(id);
|
|
201
|
-
return
|
|
202
|
-
hashCanonical(semanticEdge(beforeEdges.get(id))) !== hashCanonical(semanticEdge(current)));
|
|
237
|
+
return current !== undefined && edgeHash(beforeEdges.get(id)) !== edgeHash(current);
|
|
203
238
|
})
|
|
204
239
|
.sort(compareCodeUnits);
|
|
205
240
|
const addedStateAccessIds = [...afterStateAccesses.keys()]
|
|
@@ -219,8 +254,7 @@ export function compareEventGraphs(before, after, signal) {
|
|
|
219
254
|
check();
|
|
220
255
|
const current = afterStateAccesses.get(id);
|
|
221
256
|
return (current !== undefined &&
|
|
222
|
-
|
|
223
|
-
hashCanonical(semanticStateAccess(current)));
|
|
257
|
+
stateAccessHash(beforeStateAccesses.get(id)) !== stateAccessHash(current));
|
|
224
258
|
})
|
|
225
259
|
.sort(compareCodeUnits);
|
|
226
260
|
const addedStateLinkIds = [...afterStateLinks.keys()]
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { compareCodeUnits, sha256Bytes } from '../core/canonical.js';
|
|
2
2
|
import { assignments, firstScalar, nodeLocation, } from '../core/source/index.js';
|
|
3
|
-
import { FOCUS_PLAN_SCHEMA_VERSION, FOCUS_COST_CONSTANT_PATTERN, focusPlanHash, } from './model.js';
|
|
3
|
+
import { FOCUS_PLAN_SCHEMA_VERSION, FOCUS_COST_CONSTANT_PATTERN, focusPlanHash, referenceCatalogSet, } from './model.js';
|
|
4
4
|
import { nativeFocusEffectKeys } from './native-effects.js';
|
|
5
5
|
const knownTreeKeys = new Set([
|
|
6
6
|
'id',
|
|
@@ -123,10 +123,7 @@ const scopeKeys = new Set([
|
|
|
123
123
|
'target',
|
|
124
124
|
]);
|
|
125
125
|
function catalogValues(options, kind) {
|
|
126
|
-
|
|
127
|
-
if (values === undefined)
|
|
128
|
-
return new Set();
|
|
129
|
-
return values instanceof Set ? values : new Set(values);
|
|
126
|
+
return referenceCatalogSet(options.references?.[kind]) ?? new Set();
|
|
130
127
|
}
|
|
131
128
|
function isFormableDecision(target, options) {
|
|
132
129
|
if (catalogValues(options, 'formable').has(target))
|
|
@@ -5,7 +5,7 @@ import { ServiceError } from '../core/result.js';
|
|
|
5
5
|
import { flattenFocusConnectorCurve, focusConnectorCurve, focusConnectorPolylinesIntersect, focusNodesVisiblyOverlap, } from './geometry.js';
|
|
6
6
|
import { layoutFocusTree } from './layout.js';
|
|
7
7
|
import { FOCUS_CYCLE_SAMPLE_MAX, FOCUS_DIAGNOSTIC_MAX, FOCUS_GRAPH_MAX_DEPTH, FOCUS_GRAPH_MAX_EDGES, FOCUS_GRAPH_MAX_NODES, FOCUS_LINT_WORK_MAX, FOCUS_PAIR_COMPARISON_MAX, } from './limits.js';
|
|
8
|
-
import { layoutNodeMap, } from './model.js';
|
|
8
|
+
import { layoutNodeMap, referenceCatalogSet, } from './model.js';
|
|
9
9
|
export function lintContinuousFocusPalette(plan) {
|
|
10
10
|
if (plan.focuses.length > FOCUS_GRAPH_MAX_NODES) {
|
|
11
11
|
return [
|
|
@@ -69,10 +69,7 @@ function prerequisiteIds(focus) {
|
|
|
69
69
|
return focus.prerequisites.groups.flatMap(({ focusIds }) => focusIds);
|
|
70
70
|
}
|
|
71
71
|
function referenceSet(catalog, kind) {
|
|
72
|
-
|
|
73
|
-
if (values === undefined)
|
|
74
|
-
return undefined;
|
|
75
|
-
return values instanceof Set ? values : new Set(values);
|
|
72
|
+
return referenceCatalogSet(catalog?.[kind]);
|
|
76
73
|
}
|
|
77
74
|
function referenceSymbolKind(kind) {
|
|
78
75
|
switch (kind) {
|
|
@@ -2,6 +2,25 @@ import { hashCanonical } from '../core/canonical.js';
|
|
|
2
2
|
export const FOCUS_PLAN_SCHEMA_VERSION = 1;
|
|
3
3
|
/** A source-safe Clausewitz file constant such as `@focus_cost_standard`. */
|
|
4
4
|
export const FOCUS_COST_CONSTANT_PATTERN = /^@[A-Za-z_][A-Za-z0-9_]*$/u;
|
|
5
|
+
const referenceSets = new WeakMap();
|
|
6
|
+
/**
|
|
7
|
+
* One catalog kind as a set. A catalog arrives as arrays of every identifier in the game and
|
|
8
|
+
* the mod, and the importer and the lint ask for it once per focus or per assignment, so the
|
|
9
|
+
* conversion is cached per array instead of repeated tens of thousands of times per call.
|
|
10
|
+
*/
|
|
11
|
+
export function referenceCatalogSet(values) {
|
|
12
|
+
if (values === undefined)
|
|
13
|
+
return undefined;
|
|
14
|
+
if (values instanceof Set)
|
|
15
|
+
return values;
|
|
16
|
+
const array = values;
|
|
17
|
+
let cached = referenceSets.get(array);
|
|
18
|
+
if (cached === undefined) {
|
|
19
|
+
cached = new Set(array);
|
|
20
|
+
referenceSets.set(array, cached);
|
|
21
|
+
}
|
|
22
|
+
return cached;
|
|
23
|
+
}
|
|
5
24
|
function withoutTransientFields(value) {
|
|
6
25
|
if (Array.isArray(value))
|
|
7
26
|
return value.map(withoutTransientFields);
|
|
@@ -29,6 +29,21 @@ const focusRewriteRecipeSchema = z
|
|
|
29
29
|
filesScanned: z.array(z.string().min(1).max(4096)),
|
|
30
30
|
})
|
|
31
31
|
.strict();
|
|
32
|
+
/**
|
|
33
|
+
* The focus files an inspect call reads. A call that names a tree but no file reads only the files
|
|
34
|
+
* that define that tree: importing every focus file of the game to keep one tree took tens of
|
|
35
|
+
* seconds. A tree the index does not know falls back to every file, so the not-found answer is
|
|
36
|
+
* unchanged.
|
|
37
|
+
*/
|
|
38
|
+
function filesForInspect(snapshot, active, relativePath, treeId) {
|
|
39
|
+
if (relativePath !== undefined)
|
|
40
|
+
return active.filter((file) => file.relativePath === relativePath);
|
|
41
|
+
if (treeId === undefined)
|
|
42
|
+
return active;
|
|
43
|
+
const definingPaths = new Set(snapshot.index.findAll('focus_tree', treeId).map(({ path }) => path));
|
|
44
|
+
const defining = active.filter((file) => definingPaths.has(file.displayPath));
|
|
45
|
+
return defining.length === 0 ? active : defining;
|
|
46
|
+
}
|
|
32
47
|
export async function computeFocusVisualRevisions(engine, context, workspaceId, snapshot, selectors) {
|
|
33
48
|
const workspace = engine.resolver.get(workspaceId, context.principal);
|
|
34
49
|
const paletteImport = continuousPalettes(snapshot);
|
|
@@ -576,7 +591,7 @@ export async function inspectFocus(engine, workbench, input, context) {
|
|
|
576
591
|
await context.progress(3, 3, 'Continuous focus inspection complete');
|
|
577
592
|
return { result, sourceRevision: snapshot.revision };
|
|
578
593
|
}
|
|
579
|
-
const selectedFiles = activeFocusFiles(snapshot, workspace.registration.roots.focus)
|
|
594
|
+
const selectedFiles = filesForInspect(snapshot, activeFocusFiles(snapshot, workspace.registration.roots.focus), input.relativePath, input.treeId);
|
|
580
595
|
if (selectedFiles.length === 0)
|
|
581
596
|
throw new ServiceError('FOCUS_SOURCE_NOT_FOUND', 'No active focus source matched the request');
|
|
582
597
|
const selectedSidecarFiles = selectedFiles.flatMap((file) => {
|
|
@@ -98,7 +98,21 @@ export function focusImportOptions(snapshot) {
|
|
|
98
98
|
: { nativeEffects: snapshot.documentedEffects.names }),
|
|
99
99
|
};
|
|
100
100
|
}
|
|
101
|
+
const referenceCatalogs = new WeakMap();
|
|
102
|
+
/**
|
|
103
|
+
* The identifiers of every decision, event, idea and helper in the game and the mod. A scan lists
|
|
104
|
+
* tens of thousands, and one call asks for the catalog once per imported file, so it is built once
|
|
105
|
+
* per scan.
|
|
106
|
+
*/
|
|
101
107
|
export function referenceCatalog(snapshot) {
|
|
108
|
+
const cached = referenceCatalogs.get(snapshot);
|
|
109
|
+
if (cached !== undefined)
|
|
110
|
+
return cached;
|
|
111
|
+
const built = buildReferenceCatalog(snapshot);
|
|
112
|
+
referenceCatalogs.set(snapshot, built);
|
|
113
|
+
return built;
|
|
114
|
+
}
|
|
115
|
+
function buildReferenceCatalog(snapshot) {
|
|
102
116
|
const identifiers = (kind) => [
|
|
103
117
|
...new Set(snapshot.index
|
|
104
118
|
.findAll(kind)
|
|
@@ -161,7 +161,12 @@ function* validateHeightmap(index, raster, report, options) {
|
|
|
161
161
|
}
|
|
162
162
|
const { width, height, kind } = raster;
|
|
163
163
|
const hasLake = kind.includes(LAKE);
|
|
164
|
-
|
|
164
|
+
// Only "farther than the bank allowance" is asked, so the search stops one step past it: a
|
|
165
|
+
// pixel it does not reach holds the limit, which is past the allowance as before. The full
|
|
166
|
+
// field (limit 255) flooded every sea pixel of the map.
|
|
167
|
+
const distance = hasLake
|
|
168
|
+
? landDistanceField(kind, width, height, LAKE_BANK_ALLOWANCE_PX + 1)
|
|
169
|
+
: undefined;
|
|
165
170
|
let lakePixels = 0;
|
|
166
171
|
let landBelow = 0;
|
|
167
172
|
let seaAbove = 0;
|