hoi4-agent-tools 3.0.7 → 3.0.9

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 (48) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/dist/hoi4_agent_tools/core/artifacts.js +21 -1
  3. package/dist/hoi4_agent_tools/core/condition-evaluator.js +399 -0
  4. package/dist/hoi4_agent_tools/core/condition-model.js +1 -0
  5. package/dist/hoi4_agent_tools/core/condition-schema.js +42 -0
  6. package/dist/hoi4_agent_tools/core/configuration.js +14 -28
  7. package/dist/hoi4_agent_tools/core/engine.js +7 -1
  8. package/dist/hoi4_agent_tools/core/index.js +25 -0
  9. package/dist/hoi4_agent_tools/core/request-scheduler.js +79 -0
  10. package/dist/hoi4_agent_tools/core/scenario-state.js +97 -0
  11. package/dist/hoi4_agent_tools/core/shared-request-capacity.js +125 -0
  12. package/dist/hoi4_agent_tools/gui/scenario-conditions.js +119 -0
  13. package/dist/hoi4_agent_tools/gui/scenario-generator.js +59 -73
  14. package/dist/hoi4_agent_tools/gui/scenario.js +3 -0
  15. package/dist/hoi4_agent_tools/gui/studio.js +9 -3
  16. package/dist/hoi4_agent_tools/mcp/server/create.js +3 -1
  17. package/dist/hoi4_agent_tools/mcp/server/progress.js +29 -8
  18. package/dist/hoi4_agent_tools/mcp/server/request-lifecycle.js +14 -0
  19. package/dist/hoi4_agent_tools/mcp/transports/bounded-stdio.js +44 -14
  20. package/dist/hoi4_agent_tools/mcp/transports/http.js +75 -7
  21. package/dist/hoi4_agent_tools/probability/scenario-state.js +2 -95
  22. package/dist/hoi4_agent_tools/probability/trigger-evaluator.js +1 -287
  23. package/dist/hoi4_agent_tools/version.js +1 -1
  24. package/docs/development.md +2 -0
  25. package/docs/gui.md +3 -1
  26. package/docs/http.md +5 -1
  27. package/package.json +3 -2
  28. package/schemas/configuration.schema.json +151 -133
  29. package/schemas/continuous-focus-palette.schema.json +1 -1
  30. package/schemas/custom-weighted-pool.schema.json +1 -1
  31. package/schemas/event-feature-manifest.schema.json +1 -1
  32. package/schemas/focus-plan.schema.json +1 -1
  33. package/schemas/focus-planning-sidecar.schema.json +1 -1
  34. package/schemas/gui-animation-source.schema.json +1 -1
  35. package/schemas/gui-helper.schema.json +1 -1
  36. package/schemas/gui-scenario.schema.json +189 -33
  37. package/schemas/map-operation.schema.json +1 -1
  38. package/schemas/operation-result.schema.json +1 -1
  39. package/schemas/probability-analysis-result.schema.json +1 -1
  40. package/schemas/probability-compare-input.schema.json +1 -1
  41. package/schemas/probability-evaluate-input.schema.json +1 -1
  42. package/schemas/probability-inspect-input.schema.json +1 -1
  43. package/schemas/probability-render-input.schema.json +1 -1
  44. package/schemas/probability-scenario-set.schema.json +1 -1
  45. package/schemas/probability-sequence-input.schema.json +1 -1
  46. package/schemas/probability-simulate-input.schema.json +1 -1
  47. package/schemas/probability-sweep-input.schema.json +1 -1
  48. package/server.json +2 -2
@@ -284,6 +284,31 @@ export class SymbolIndex {
284
284
  index.finalize();
285
285
  return index;
286
286
  }
287
+ /** Yield between source files so protocol cancellation and progress remain responsive. */
288
+ static async buildAsync(files, signal) {
289
+ signal?.throwIfAborted();
290
+ const index = new SymbolIndex();
291
+ const definitionSelection = selectedDefinitionFiles(files);
292
+ for (const displayPath of definitionSelection.selected)
293
+ index.#definitionFiles.add(displayPath);
294
+ for (const skipped of definitionSelection.skipped) {
295
+ index.recordSkippedSource(skipped.file, skipped.diagnostics);
296
+ }
297
+ let yieldedAt = performance.now();
298
+ for (const file of [...files].sort((a, b) => a.loadOrder - b.loadOrder || compareCodeUnits(a.displayPath, b.displayPath))) {
299
+ signal?.throwIfAborted();
300
+ index.files.set(file.displayPath, file);
301
+ index.indexFile(file);
302
+ if (performance.now() - yieldedAt >= 20) {
303
+ await new Promise((resolve) => setImmediate(resolve));
304
+ signal?.throwIfAborted();
305
+ yieldedAt = performance.now();
306
+ }
307
+ }
308
+ index.finalize();
309
+ signal?.throwIfAborted();
310
+ return index;
311
+ }
287
312
  get complete() {
288
313
  return this.#complete;
289
314
  }
@@ -0,0 +1,79 @@
1
+ import { ServiceError } from './result.js';
2
+ /** Shares execution capacity across all sessions using an engine, with fair, cancellable waits. */
3
+ export class RequestScheduler {
4
+ capacity;
5
+ maxPending;
6
+ maxPendingBytes;
7
+ active = 0;
8
+ pendingBytes = 0;
9
+ pending = [];
10
+ lastOwner;
11
+ constructor(capacity = 2, maxPending = 1024, maxPendingBytes = 134_217_728) {
12
+ this.capacity = capacity;
13
+ this.maxPending = maxPending;
14
+ this.maxPendingBytes = maxPendingBytes;
15
+ if (!Number.isSafeInteger(capacity) || capacity < 1) {
16
+ throw new RangeError('Execution capacity must be a positive integer');
17
+ }
18
+ }
19
+ async run(owner, bytes, signal, action) {
20
+ signal.throwIfAborted();
21
+ await new Promise((resolve, reject) => {
22
+ if (this.pending.length >= this.maxPending ||
23
+ bytes > this.maxPendingBytes - this.pendingBytes) {
24
+ reject(new ServiceError('REQUEST_QUEUE_FULL', 'The server request queue is full; retry after current work completes'));
25
+ return;
26
+ }
27
+ const entry = {
28
+ owner,
29
+ bytes,
30
+ start: () => {
31
+ signal.removeEventListener('abort', entry.cancel);
32
+ this.active += 1;
33
+ this.lastOwner = owner;
34
+ resolve();
35
+ },
36
+ cancel: () => {
37
+ const index = this.pending.indexOf(entry);
38
+ if (index < 0)
39
+ return;
40
+ this.pending.splice(index, 1);
41
+ this.pendingBytes -= bytes;
42
+ signal.removeEventListener('abort', entry.cancel);
43
+ reject(signal.reason instanceof Error
44
+ ? signal.reason
45
+ : new DOMException('Request cancelled', 'AbortError'));
46
+ this.drain();
47
+ },
48
+ };
49
+ signal.addEventListener('abort', entry.cancel, { once: true });
50
+ this.pending.push(entry);
51
+ this.pendingBytes += bytes;
52
+ this.drain();
53
+ });
54
+ try {
55
+ signal.throwIfAborted();
56
+ return await action();
57
+ }
58
+ finally {
59
+ this.active -= 1;
60
+ this.drain();
61
+ }
62
+ }
63
+ drain() {
64
+ while (this.active < this.capacity && this.pending.length > 0) {
65
+ const other = this.pending.findIndex(({ owner }) => owner !== this.lastOwner);
66
+ const entry = this.pending.splice(Math.max(0, other), 1)[0];
67
+ // Move this session's remaining work behind every other waiting session.
68
+ // Merely avoiding the last owner can alternate two busy sessions forever.
69
+ const sameOwner = [];
70
+ const otherOwners = [];
71
+ for (const pending of this.pending) {
72
+ (pending.owner === entry.owner ? sameOwner : otherOwners).push(pending);
73
+ }
74
+ this.pending.splice(0, this.pending.length, ...otherOwners, ...sameOwner);
75
+ this.pendingBytes -= entry.bytes;
76
+ entry.start();
77
+ }
78
+ }
79
+ }
@@ -0,0 +1,97 @@
1
+ function caseInsensitiveEntry(record, key) {
2
+ if (record === undefined)
3
+ return undefined;
4
+ if (Object.hasOwn(record, key))
5
+ return record[key];
6
+ const normalized = key.toLowerCase();
7
+ const found = Object.entries(record).find(([candidate]) => candidate.toLowerCase() === normalized);
8
+ return found?.[1];
9
+ }
10
+ export function rootScopeContext(scenario) {
11
+ return {
12
+ expression: 'ROOT',
13
+ binding: {
14
+ id: scenario.actor ?? 'ROOT',
15
+ ...(scenario.actor === undefined ? {} : { actor: scenario.actor }),
16
+ state: scenario.state,
17
+ ...(scenario.flags === undefined ? {} : { flags: scenario.flags }),
18
+ ...(scenario.eventTargets === undefined ? {} : { eventTargets: scenario.eventTargets }),
19
+ },
20
+ };
21
+ }
22
+ function explicitScope(scenario, expression, parent) {
23
+ const binding = caseInsensitiveEntry(scenario.scopes, expression);
24
+ return binding === undefined ? undefined : { expression, binding, parent };
25
+ }
26
+ export function resolveScopeContext(scenario, expression, current) {
27
+ const upper = expression.toUpperCase();
28
+ if (upper === 'ROOT')
29
+ return current.expression === 'ROOT'
30
+ ? current
31
+ : { ...rootScopeContext(scenario), parent: current };
32
+ if (upper === 'THIS')
33
+ return current;
34
+ if (upper === 'PREV')
35
+ return current.parent ?? explicitScope(scenario, expression, current);
36
+ const chained = current.expression === 'ROOT' || current.expression === 'THIS'
37
+ ? expression
38
+ : `${current.expression}.${expression}`;
39
+ const chainedBinding = explicitScope(scenario, chained, current);
40
+ if (chainedBinding !== undefined)
41
+ return chainedBinding;
42
+ const direct = explicitScope(scenario, expression, current);
43
+ if (direct !== undefined)
44
+ return direct;
45
+ const targetMatch = /^(?:event_target|scope):(.+)$/iu.exec(expression);
46
+ const targetId = targetMatch === null
47
+ ? undefined
48
+ : (caseInsensitiveEntry(current.binding.eventTargets, targetMatch[1]) ??
49
+ caseInsensitiveEntry(scenario.eventTargets, targetMatch[1]));
50
+ if (targetId !== undefined) {
51
+ const declaredBinding = Object.values(scenario.scopes ?? {}).find((binding) => binding.id === targetId || binding.actor === targetId);
52
+ return {
53
+ expression,
54
+ binding: declaredBinding ?? { id: targetId, actor: targetId, state: {} },
55
+ parent: current,
56
+ };
57
+ }
58
+ return undefined;
59
+ }
60
+ export function scopeStateValue(scenario, key, current) {
61
+ if (Object.hasOwn(current.binding.state, key))
62
+ return current.binding.state[key];
63
+ if (Object.hasOwn(current.binding.state, `trigger.${key}`))
64
+ return current.binding.state[`trigger.${key}`];
65
+ if (current.expression !== 'ROOT')
66
+ return undefined;
67
+ if (Object.hasOwn(scenario.state, key))
68
+ return scenario.state[key];
69
+ if (Object.hasOwn(scenario.state, `trigger.${key}`))
70
+ return scenario.state[`trigger.${key}`];
71
+ return undefined;
72
+ }
73
+ export function rootStateValue(scenario, key) {
74
+ if (Object.hasOwn(scenario.state, key))
75
+ return scenario.state[key];
76
+ if (Object.hasOwn(scenario.state, `trigger.${key}`))
77
+ return scenario.state[`trigger.${key}`];
78
+ return undefined;
79
+ }
80
+ export function scopeIdentity(current) {
81
+ return current.binding.actor ?? current.binding.id;
82
+ }
83
+ export function scopedExpressionValue(scenario, expression) {
84
+ const scopes = Object.entries(scenario.scopes ?? {}).sort(([left], [right]) => right.length - left.length);
85
+ for (const [scope, binding] of scopes) {
86
+ for (const prefix of [`${scope}.`, `scope.${scope}.`, `scopes.${scope}.`]) {
87
+ if (!expression.toLowerCase().startsWith(prefix.toLowerCase()))
88
+ continue;
89
+ const key = expression.slice(prefix.length).replace(/^state\./u, '');
90
+ if (Object.hasOwn(binding.state, key))
91
+ return binding.state[key];
92
+ if (Object.hasOwn(binding.state, `variable.${key}`))
93
+ return binding.state[`variable.${key}`];
94
+ }
95
+ }
96
+ return undefined;
97
+ }
@@ -0,0 +1,125 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { lstat, mkdir, readdir, rmdir, unlink, writeFile } from 'node:fs/promises';
3
+ import { hostname } from 'node:os';
4
+ import path from 'node:path';
5
+ import { setTimeout as delay } from 'node:timers/promises';
6
+ import { sha256Bytes } from './canonical.js';
7
+ import { canonicalPath, containedGeneratedPath } from './workspace.js';
8
+ import { ServiceError } from './result.js';
9
+ function processAlive(pid) {
10
+ try {
11
+ process.kill(pid, 0);
12
+ return true;
13
+ }
14
+ catch (error) {
15
+ return error.code !== 'ESRCH';
16
+ }
17
+ }
18
+ /** Bounds heavy work across task processes sharing the same private server state. */
19
+ export class SharedRequestCapacity {
20
+ stateRoot;
21
+ capacity;
22
+ constructor(stateRoot, capacity = 4) {
23
+ this.stateRoot = stateRoot;
24
+ this.capacity = capacity;
25
+ }
26
+ async run(signal, action) {
27
+ signal.throwIfAborted();
28
+ if (this.stateRoot === undefined)
29
+ return action();
30
+ const root = await containedGeneratedPath(await canonicalPath(this.stateRoot, signal), 'request-capacity', sha256Bytes(hostname().toLowerCase()).slice(0, 16));
31
+ await mkdir(root, { recursive: true });
32
+ const lease = `${process.pid}-${randomUUID()}.lease`;
33
+ const pendingDeletionFailures = new Map();
34
+ for (;;) {
35
+ signal.throwIfAborted();
36
+ for (let index = 0; index < this.capacity; index += 1) {
37
+ // Only the stable private parent is canonicalized. A slot can disappear during
38
+ // another owner's release; realpath on that ephemeral directory races on Windows.
39
+ // The numeric component cannot escape, and mkdir atomically proves new ownership.
40
+ const slot = path.join(root, String(index));
41
+ try {
42
+ await mkdir(slot);
43
+ pendingDeletionFailures.delete(index);
44
+ }
45
+ catch (error) {
46
+ const code = error.code;
47
+ // Windows can retain a delete-pending directory handle after rmdir
48
+ // returns. Recreating that slot reports EPERM/EBUSY, not EEXIST.
49
+ // No work is admitted until a later mkdir actually succeeds.
50
+ if (process.platform === 'win32' && ['EPERM', 'EBUSY'].includes(code ?? '')) {
51
+ const failures = (pendingDeletionFailures.get(index) ?? 0) + 1;
52
+ pendingDeletionFailures.set(index, failures);
53
+ if (failures >= 50)
54
+ throw error;
55
+ await this.reap(slot);
56
+ continue;
57
+ }
58
+ if (code !== 'EEXIST')
59
+ throw error;
60
+ pendingDeletionFailures.delete(index);
61
+ await this.reap(slot);
62
+ continue;
63
+ }
64
+ let owner;
65
+ try {
66
+ owner = path.join(slot, lease);
67
+ await writeFile(owner, '', { flag: 'wx', mode: 0o600 });
68
+ }
69
+ catch (error) {
70
+ // A competing stale-owner cleanup can remove an empty slot before our
71
+ // owner file is published. No work starts until the owner exists.
72
+ if (error.code === 'ENOENT')
73
+ continue;
74
+ await rmdir(slot).catch(() => undefined);
75
+ throw error;
76
+ }
77
+ try {
78
+ signal.throwIfAborted();
79
+ return await action();
80
+ }
81
+ finally {
82
+ await unlink(owner);
83
+ await rmdir(slot).catch((error) => {
84
+ const code = error.code;
85
+ if (!['ENOENT', 'ENOTEMPTY'].includes(code ?? '') &&
86
+ !(process.platform === 'win32' && ['EPERM', 'EBUSY'].includes(code ?? '')))
87
+ throw error;
88
+ });
89
+ }
90
+ }
91
+ await delay(100, undefined, { signal });
92
+ }
93
+ }
94
+ async reap(slot) {
95
+ try {
96
+ const metadata = await lstat(slot);
97
+ if (metadata.isSymbolicLink() || !metadata.isDirectory())
98
+ throw new ServiceError('PATH_GENERATED_ROOT_ESCAPE', 'Execution capacity slot must be a real directory beneath its private root');
99
+ const owners = await readdir(slot);
100
+ if (owners.length === 0) {
101
+ if (Date.now() - metadata.mtimeMs < 30_000)
102
+ return;
103
+ }
104
+ else {
105
+ for (const name of owners) {
106
+ const match = /^([1-9][0-9]*)-[0-9a-f-]{36}\.lease$/u.exec(name);
107
+ if (match === null || processAlive(Number(match[1])))
108
+ return;
109
+ // Unique owner names prevent a concurrent reaper from deleting a new lease.
110
+ await unlink(path.join(slot, name)).catch((error) => {
111
+ if (error.code !== 'ENOENT')
112
+ throw error;
113
+ });
114
+ }
115
+ }
116
+ await rmdir(slot);
117
+ }
118
+ catch (error) {
119
+ const code = error.code ?? '';
120
+ if (!['ENOENT', 'ENOTEMPTY', 'EEXIST'].includes(code) &&
121
+ !(process.platform === 'win32' && ['EPERM', 'EBUSY'].includes(code)))
122
+ throw error;
123
+ }
124
+ }
125
+ }
@@ -0,0 +1,119 @@
1
+ import { ClausewitzEvaluationDefinitions } from '../core/clausewitz-evaluation.js';
2
+ import { hasBlockingDiagnostics } from '../core/diagnostics.js';
3
+ import { evaluateTriggerBlock } from '../core/condition-evaluator.js';
4
+ import { resolveScopeContext, rootScopeContext } from '../core/scenario-state.js';
5
+ import { assignments, firstScalar, parseClausewitz } from '../core/source/index.js';
6
+ /** Keep declared scoped scalars out of exploratory value generation. */
7
+ export function guiExplicitConditionValues(base) {
8
+ const values = { ...base.stateValues, ...base.variables, ...base.values };
9
+ for (const [key, value] of Object.entries(values)) {
10
+ if (key.includes('.'))
11
+ continue;
12
+ values[`ROOT.${key}`] ??= value;
13
+ values[`THIS.${key}`] ??= value;
14
+ }
15
+ for (const [scope, binding] of Object.entries(base.scopes ?? {})) {
16
+ for (const [key, value] of Object.entries(binding.state)) {
17
+ if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean')
18
+ values[`${scope}.${key}`] ??= value;
19
+ }
20
+ }
21
+ return values;
22
+ }
23
+ function parsedCondition(expression) {
24
+ const text = expression.trim();
25
+ const document = parseClausewitz(Buffer.from(`condition = ${text.startsWith('{') ? text : `{ ${text} }`}`), 'scenario:condition');
26
+ const assignment = assignments(document.root, 'condition')[0];
27
+ return {
28
+ ...(assignment?.value.type === 'block' ? { block: assignment.value } : {}),
29
+ invalid: hasBlockingDiagnostics(document.diagnostics) || assignment?.value.type !== 'block',
30
+ };
31
+ }
32
+ export function guiConditionScenario(base, values = base.values) {
33
+ const state = { ...base.stateValues, ...base.variables, ...values };
34
+ for (const [key, value] of Object.entries(base.flags))
35
+ state[`flag.${key}`] = value;
36
+ const scopes = structuredClone(base.scopes ?? {});
37
+ for (const [key, value] of Object.entries(state)) {
38
+ const match = /^(ROOT|THIS|FROM(?:\.FROM)*|PREV)\.(.+)$/u.exec(key);
39
+ if (match === null)
40
+ continue;
41
+ if (match[1] === 'ROOT' || match[1] === 'THIS')
42
+ state[match[2]] ??= value;
43
+ else {
44
+ const scope = (scopes[match[1]] ??= { id: match[1], state: {} });
45
+ scope.state[match[2]] ??= value;
46
+ }
47
+ }
48
+ const actor = base.country?.tag ?? base.country?.countryTag ?? base.country?.GetTag;
49
+ return {
50
+ id: base.id,
51
+ state,
52
+ scopes,
53
+ closedFlags: false,
54
+ ...(typeof actor === 'string' ? { actor } : {}),
55
+ };
56
+ }
57
+ export function evaluateGuiCondition(expression, scenario, subject, definitions = new ClausewitzEvaluationDefinitions(), scope = 'ROOT') {
58
+ const context = resolveScopeContext(scenario, scope, rootScopeContext(scenario));
59
+ const parsed = expression === undefined ? { invalid: false } : parsedCondition(expression);
60
+ if (parsed.invalid || context === undefined)
61
+ return {
62
+ state: 'unresolved',
63
+ unresolved: [
64
+ {
65
+ code: 'GUI_CONDITION_UNRESOLVED',
66
+ message: parsed.invalid
67
+ ? 'Condition could not be parsed'
68
+ : `Scenario does not declare scope ${scope}`,
69
+ candidateId: subject.id,
70
+ },
71
+ ],
72
+ };
73
+ return evaluateTriggerBlock(parsed.block, scenario, subject, definitions, [], context);
74
+ }
75
+ /** Find operands structurally for exploratory previews, without asserting branch eligibility. */
76
+ export function guiConditionVariables(expression, definitions) {
77
+ if (expression === undefined)
78
+ return [];
79
+ const parsed = parsedCondition(expression);
80
+ if (parsed.invalid || parsed.block === undefined)
81
+ return [];
82
+ const output = new Set();
83
+ const visit = (block, scope, stack) => {
84
+ const add = (key) => {
85
+ // Scoped operands need actual bindings; fabricated flat values can shadow ROOT/PREV.
86
+ if (scope === '' &&
87
+ key !== undefined &&
88
+ !key.includes('.') &&
89
+ !key.startsWith('@') &&
90
+ !key.startsWith('constant:') &&
91
+ !Number.isFinite(Number(key)))
92
+ output.add(key);
93
+ };
94
+ for (const assignment of assignments(block)) {
95
+ const key = assignment.key.value;
96
+ if (key === 'check_variable' && assignment.value.type === 'block') {
97
+ const short = assignments(assignment.value).find(({ key }) => !['var', 'value', 'compare', 'tooltip'].includes(key.value));
98
+ add(firstScalar(assignment.value, 'var')?.value ?? short?.key.value);
99
+ add(firstScalar(assignment.value, 'value')?.value ??
100
+ (short?.value.type === 'scalar' ? short.value.value : undefined));
101
+ }
102
+ else if (assignment.value.type === 'block') {
103
+ const prefix = ['ROOT', 'THIS', 'FROM', 'PREV'].includes(key) ? `${key}.` : scope;
104
+ visit(assignment.value, prefix, stack);
105
+ }
106
+ else if (assignment.operator.text === '>' || assignment.operator.text === '<') {
107
+ add(key);
108
+ add(assignment.value.value);
109
+ }
110
+ else {
111
+ const helper = definitions.scriptedTriggers.get(key);
112
+ if (helper !== undefined && !stack.has(key))
113
+ visit(helper.value, scope, new Set([...stack, key]));
114
+ }
115
+ }
116
+ };
117
+ visit(parsed.block, '', new Set());
118
+ return [...output].sort();
119
+ }
@@ -1,4 +1,6 @@
1
1
  import { sha256Bytes } from '../core/canonical.js';
2
+ import { ClausewitzEvaluationDefinitions } from '../core/clausewitz-evaluation.js';
3
+ import { evaluateGuiCondition, guiConditionScenario, guiConditionVariables, guiExplicitConditionValues, } from './scenario-conditions.js';
2
4
  import { parsePreviewScenario } from './scenario.js';
3
5
  const countryNames = ['Germany', 'France', 'Poland', 'Italy', 'Brazil', 'India', 'Canada'];
4
6
  const countryTags = ['GER', 'FRA', 'POL', 'ITA', 'BRA', 'RAJ', 'CAN'];
@@ -257,70 +259,46 @@ function generatedNumberForKey(key, options, random, inferred = {}) {
257
259
  function setIfMissing(target, key, value) {
258
260
  target[key] ??= value;
259
261
  }
260
- function scriptedLocalisationValue(graph, token, language, random, kind, values) {
262
+ function scriptedLocalisationValue(graph, token, language, kind, values, base, definitions, results) {
261
263
  const shortToken = token.slice(token.lastIndexOf('.') + 1);
262
- const definitions = graph.scriptedLocalisation.filter(({ name }) => name === token || name === shortToken);
263
- if (definitions.length === 0)
264
+ const definition = graph.scriptedLocalisation
265
+ .filter(({ name }) => name === token || name === shortToken)
266
+ .at(-1);
267
+ if (definition === undefined)
264
268
  return undefined;
265
- const sprites = new Set(graph.sprites.map(({ name }) => name.toLocaleLowerCase('en-US')));
266
- const choices = definitions.flatMap(({ choices }) => choices);
267
- const eligible = choices.filter(({ localisationKey }) => kind === 'image'
268
- ? sprites.has(localisationKey.toLocaleLowerCase('en-US'))
269
- : localisationText(graph, language, localisationKey) !== undefined);
270
- if (eligible.length === 0)
271
- return undefined;
272
- const evaluated = eligible.map((choice) => ({
273
- choice,
274
- result: evaluateSimpleTrigger(choice.triggerExpression, values),
275
- }));
276
- const matched = evaluated.find(({ result }) => result === true)?.choice;
277
- const firstThreshold = evaluated
278
- .map(({ choice }) => simpleThreshold(choice.triggerExpression))
279
- .find((threshold) => threshold !== undefined && typeof values[threshold.variable] === 'number');
280
- const unknownExists = evaluated.some(({ result }) => result === undefined);
281
- const ranked = matched === undefined && unknownExists && firstThreshold !== undefined
282
- ? eligible[Math.min(eligible.length - 1, Math.max(0, Math.round((1 - Math.max(0, Math.min(100, Number(values[firstThreshold.variable]))) / 100) *
283
- (eligible.length - 1))))]
284
- : undefined;
285
- const fallback = evaluated.find(({ result }) => result === 'fallback')?.choice;
286
- const selected = matched ?? ranked ?? fallback ?? random.pick(eligible);
287
- if (kind === 'image')
288
- return selected.localisationKey;
289
- return localisationText(graph, language, selected.localisationKey);
290
- }
291
- function simpleThreshold(triggerExpression) {
292
- if (triggerExpression === undefined)
293
- return undefined;
294
- const direct = /([A-Za-z_][A-Za-z0-9_.:^]*)\s*([<>])\s*(-?(?:\d+\.?\d*|\.\d+))/u.exec(triggerExpression);
295
- if (direct !== null)
296
- return {
297
- variable: direct[1],
298
- operator: direct[2],
299
- threshold: Number(direct[3]),
300
- };
301
- const variable = /\bvar\s*=\s*([A-Za-z_][A-Za-z0-9_.:^]*)/u.exec(triggerExpression)?.[1];
302
- const threshold = /\bvalue\s*=\s*(-?(?:\d+\.?\d*|\.\d+))/u.exec(triggerExpression)?.[1];
303
- const compare = /\bcompare\s*=\s*(greater_than|less_than)/u.exec(triggerExpression)?.[1];
304
- if (variable === undefined || threshold === undefined || compare === undefined)
305
- return undefined;
306
- return {
307
- variable,
308
- operator: compare === 'greater_than' ? '>' : '<',
309
- threshold: Number(threshold),
269
+ const scenario = guiConditionScenario(base, values);
270
+ const subject = {
271
+ id: token,
272
+ provenance: [
273
+ {
274
+ path: definition.sourcePath,
275
+ rootKind: 'source',
276
+ loadOrder: 0,
277
+ sourceHash: graph.sourceHashes[definition.sourcePath] ?? '',
278
+ ...(definition.location === undefined ? {} : { location: definition.location }),
279
+ },
280
+ ],
310
281
  };
311
- }
312
- function evaluateSimpleTrigger(triggerExpression, values) {
313
- if (triggerExpression === undefined || /\balways\s*=\s*yes\b/u.test(triggerExpression))
314
- return 'fallback';
315
- if (/\balways\s*=\s*no\b/u.test(triggerExpression))
316
- return false;
317
- const threshold = simpleThreshold(triggerExpression);
318
- if (threshold === undefined)
319
- return undefined;
320
- const value = values[threshold.variable];
321
- if (typeof value !== 'number')
322
- return undefined;
323
- return threshold.operator === '>' ? value > threshold.threshold : value < threshold.threshold;
282
+ const prefix = token.includes('.') ? token.slice(0, token.lastIndexOf('.')) : 'ROOT';
283
+ for (const choice of definition.choices) {
284
+ const result = evaluateGuiCondition(choice.triggerExpression, scenario, subject, definitions, prefix);
285
+ results.push({
286
+ token,
287
+ sourcePath: definition.sourcePath,
288
+ state: result.state,
289
+ localisationKey: choice.localisationKey,
290
+ unresolved: result.unresolved.map(({ message }) => message),
291
+ });
292
+ // An earlier unknown branch may be selected by the game; a later fallback cannot prove it false.
293
+ if (result.state === 'unresolved')
294
+ return undefined;
295
+ if (result.state === 'false')
296
+ continue;
297
+ return kind === 'image'
298
+ ? choice.localisationKey
299
+ : localisationText(graph, language, choice.localisationKey);
300
+ }
301
+ return undefined;
324
302
  }
325
303
  function materializeDynamicText(template, values) {
326
304
  const valueFor = (key) => {
@@ -481,7 +459,7 @@ function generatedRows(count, random, options) {
481
459
  };
482
460
  });
483
461
  }
484
- export function generateGuiPreviewScenarios(graph, windowName, base, options) {
462
+ export function generateGuiPreviewScenarios(graph, windowName, base, options, definitions = new ClausewitzEvaluationDefinitions()) {
485
463
  if (!options.enabled)
486
464
  return [];
487
465
  const scripted = relatedScriptedGuis(graph, windowName);
@@ -519,9 +497,8 @@ export function generateGuiPreviewScenarios(graph, windowName, base, options) {
519
497
  if (![...relevantDynamicTokens].some((token) => token === definition.name || token.endsWith(`.${definition.name}`)))
520
498
  continue;
521
499
  for (const choice of definition.choices) {
522
- const threshold = simpleThreshold(choice.triggerExpression);
523
- if (threshold !== undefined)
524
- tokens.numeric.add(threshold.variable);
500
+ for (const variable of guiConditionVariables(choice.triggerExpression, definitions))
501
+ tokens.numeric.add(variable);
525
502
  }
526
503
  }
527
504
  const progressRanges = new Map();
@@ -545,7 +522,10 @@ export function generateGuiPreviewScenarios(graph, windowName, base, options) {
545
522
  const sourceSeed = options.seed === 'auto' ? `${windowName}:${base.id}:${hashSourceGraph(graph)}` : options.seed;
546
523
  return Array.from({ length: options.count }, (_unused, scenarioIndex) => {
547
524
  const random = new ScenarioRandom(`${sourceSeed}:${scenarioIndex}`);
548
- const values = { ...base.values };
525
+ const explicitValues = guiExplicitConditionValues(base);
526
+ const values = { ...explicitValues };
527
+ const conditionResults = [];
528
+ const scriptedTokens = new Set([...tokens.textual].filter((token) => graph.scriptedLocalisation.some(({ name }) => name === token || token.endsWith(`.${name}`))));
549
529
  const lists = Object.fromEntries(Object.entries(base.lists).map(([key, rows]) => [key, rows.map((row) => ({ ...row }))]));
550
530
  const visibility = generatedVisibility(graph, scripted, options, random, base.visibility);
551
531
  const elementStates = { ...base.elementStates };
@@ -571,7 +551,7 @@ export function generateGuiPreviewScenarios(graph, windowName, base, options) {
571
551
  setIfMissing(values, startValueToken, value);
572
552
  }
573
553
  for (const key of tokens.numeric) {
574
- if (!key.endsWith('_bar') || base.values[key] !== undefined)
554
+ if (!key.endsWith('_bar') || explicitValues[key] !== undefined)
575
555
  continue;
576
556
  const sourceKey = key.slice(0, -'_bar'.length);
577
557
  const sourceValue = values[sourceKey];
@@ -579,7 +559,7 @@ export function generateGuiPreviewScenarios(graph, windowName, base, options) {
579
559
  values[key] = sourceValue;
580
560
  }
581
561
  for (const { value: valueKey, limit: limitKey } of numericConstraints.relationships) {
582
- if (base.values[valueKey] !== undefined)
562
+ if (explicitValues[valueKey] !== undefined)
583
563
  continue;
584
564
  const value = values[valueKey];
585
565
  const limit = values[limitKey];
@@ -589,22 +569,27 @@ export function generateGuiPreviewScenarios(graph, windowName, base, options) {
589
569
  values[valueKey] = Math.max(minimum, Math.min(value, limit));
590
570
  }
591
571
  for (const key of tokens.textual)
592
- setIfMissing(values, key, plausibleText(key, random, options.textSamples, scopedCountries));
572
+ if (!scriptedTokens.has(key))
573
+ setIfMissing(values, key, plausibleText(key, random, options.textSamples, scopedCountries));
593
574
  const scriptedTextTemplates = new Map();
594
575
  for (const key of tokens.textual) {
595
- const scriptedValue = scriptedLocalisationValue(graph, key, base.language, random, 'text', values);
596
- if (scriptedValue !== undefined && base.values[key] === undefined)
576
+ if (explicitValues[key] !== undefined)
577
+ continue;
578
+ const scriptedValue = scriptedLocalisationValue(graph, key, base.language, 'text', values, base, definitions, conditionResults);
579
+ if (scriptedValue !== undefined)
597
580
  scriptedTextTemplates.set(key, scriptedValue);
598
581
  }
599
582
  for (let pass = 0; pass < 3; pass += 1)
600
583
  for (const [key, template] of scriptedTextTemplates)
601
584
  values[key] = materializeDynamicText(template, values);
602
585
  for (const key of imageTokens) {
586
+ if (explicitValues[key] !== undefined)
587
+ continue;
603
588
  if (/(?:^|\.)GetFlag$/u.test(key)) {
604
589
  setIfMissing(values, key, generatedCountryTag);
605
590
  continue;
606
591
  }
607
- const sprite = scriptedLocalisationValue(graph, key, base.language, random, 'image', values);
592
+ const sprite = scriptedLocalisationValue(graph, key, base.language, 'image', values, base, definitions, conditionResults);
608
593
  if (sprite !== undefined)
609
594
  setIfMissing(values, key, sprite);
610
595
  }
@@ -625,7 +610,8 @@ export function generateGuiPreviewScenarios(graph, windowName, base, options) {
625
610
  return parsePreviewScenario({
626
611
  ...base,
627
612
  id: `${base.id}-${options.idPrefix}-${scenarioIndex + 1}`,
628
- description: `Generated source-aware scenario ${scenarioIndex + 1} (seed ${sourceSeed})`,
613
+ description: `Generated exploratory preview ${scenarioIndex + 1} (seed ${sourceSeed}; not verified campaign state)`,
614
+ conditionResults,
629
615
  values,
630
616
  country: [...imageTokens].some((key) => /(?:^|\.)GetFlag$/u.test(key))
631
617
  ? {