hoi4-agent-tools 4.16.0 → 4.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (109) hide show
  1. package/CHANGELOG.md +41 -0
  2. package/README.md +1 -0
  3. package/dist/hoi4_agent_tools/core/analysis-checkpoints.js +11 -4
  4. package/dist/hoi4_agent_tools/core/engine-client.js +30 -1
  5. package/dist/hoi4_agent_tools/core/engine.js +56 -27
  6. package/dist/hoi4_agent_tools/core/managed-outputs.js +54 -3
  7. package/dist/hoi4_agent_tools/core/operation-result.js +37 -6
  8. package/dist/hoi4_agent_tools/core/scanner.js +148 -7
  9. package/dist/hoi4_agent_tools/core/server-state.js +50 -2
  10. package/dist/hoi4_agent_tools/core/source/localisation.js +7 -1
  11. package/dist/hoi4_agent_tools/event/compare.js +47 -13
  12. package/dist/hoi4_agent_tools/event/operations.js +111 -20
  13. package/dist/hoi4_agent_tools/focus/importer.js +2 -5
  14. package/dist/hoi4_agent_tools/focus/lint.js +2 -5
  15. package/dist/hoi4_agent_tools/focus/model.js +19 -0
  16. package/dist/hoi4_agent_tools/focus/tool-operations.js +16 -1
  17. package/dist/hoi4_agent_tools/focus/tool-support.js +14 -0
  18. package/dist/hoi4_agent_tools/map/appearance-validation.js +6 -1
  19. package/dist/hoi4_agent_tools/map/border-quality-input.js +57 -8
  20. package/dist/hoi4_agent_tools/map/border-quality.js +15 -6
  21. package/dist/hoi4_agent_tools/map/engine-raster.js +160 -0
  22. package/dist/hoi4_agent_tools/map/limits.js +13 -0
  23. package/dist/hoi4_agent_tools/map/model.js +9 -8
  24. package/dist/hoi4_agent_tools/map/natural-lands.js +902 -0
  25. package/dist/hoi4_agent_tools/map/operations.js +266 -23
  26. package/dist/hoi4_agent_tools/map/partition-provinces.js +6 -2
  27. package/dist/hoi4_agent_tools/map/partition-tuning.js +37 -0
  28. package/dist/hoi4_agent_tools/map/service.js +25 -12
  29. package/dist/hoi4_agent_tools/map/territory-operations.js +180 -3
  30. package/dist/hoi4_agent_tools/map/territory-quality.js +72 -5
  31. package/dist/hoi4_agent_tools/map/territory.js +63 -2
  32. package/dist/hoi4_agent_tools/map/tool-operations.js +79 -3
  33. package/dist/hoi4_agent_tools/map/validation.js +23 -3
  34. package/dist/hoi4_agent_tools/map/water.js +13 -10
  35. package/dist/hoi4_agent_tools/map/world-outputs.js +41 -26
  36. package/dist/hoi4_agent_tools/map/world.js +51 -1
  37. package/dist/hoi4_agent_tools/mcp/tools/map.js +52 -0
  38. package/dist/hoi4_agent_tools/mcp/tools/reference.js +3 -3
  39. package/dist/hoi4_agent_tools/mcp/tools/technology.js +25 -1
  40. package/dist/hoi4_agent_tools/reference/closure.js +65 -0
  41. package/dist/hoi4_agent_tools/reference/command-phrases.json +7899 -1127
  42. package/dist/hoi4_agent_tools/reference/mod-index.js +14 -5
  43. package/dist/hoi4_agent_tools/reference/operations.js +38 -21
  44. package/dist/hoi4_agent_tools/reference/ranking.js +77 -2
  45. package/dist/hoi4_agent_tools/reference/script-validation.js +4 -2
  46. package/dist/hoi4_agent_tools/reference/service.js +45 -2
  47. package/dist/hoi4_agent_tools/reference/source-lookup.js +43 -121
  48. package/dist/hoi4_agent_tools/runtime.js +27 -11
  49. package/dist/hoi4_agent_tools/schemas/lenient-arguments.js +7 -1
  50. package/dist/hoi4_agent_tools/schemas/map-requests.js +29 -1
  51. package/dist/hoi4_agent_tools/schemas/map.js +103 -2
  52. package/dist/hoi4_agent_tools/schemas/mod-tools.js +49 -0
  53. package/dist/hoi4_agent_tools/schemas/reference.js +1 -1
  54. package/dist/hoi4_agent_tools/schemas/script-validation.js +57 -3
  55. package/dist/hoi4_agent_tools/technology/operations.js +5 -0
  56. package/dist/hoi4_agent_tools/technology/queries.js +54 -0
  57. package/dist/hoi4_agent_tools/version.js +1 -1
  58. package/docs/configuration.md +1 -1
  59. package/docs/map.md +67 -23
  60. package/docs/research/reference-benchmark.md +64 -0
  61. package/docs/tools.md +20 -20
  62. package/docs/troubleshooting.md +4 -0
  63. package/engine/bin/darwin-arm64/hoi4-engine +0 -0
  64. package/engine/bin/linux-arm64/hoi4-engine +0 -0
  65. package/engine/bin/linux-x64/hoi4-engine +0 -0
  66. package/engine/bin/manifest.json +8 -8
  67. package/engine/bin/win32-x64/hoi4-engine.exe +0 -0
  68. package/npm-shrinkwrap.json +2 -2
  69. package/package.json +5 -3
  70. package/schemas/configuration.schema.json +1 -1
  71. package/schemas/continuous-focus-palette.schema.json +1 -1
  72. package/schemas/custom-weighted-pool.schema.json +1 -1
  73. package/schemas/decision-inspect-input.schema.json +1 -1
  74. package/schemas/error-log-input.schema.json +1 -1
  75. package/schemas/event-feature-manifest.schema.json +1 -1
  76. package/schemas/focus-plan.schema.json +1 -1
  77. package/schemas/focus-planning-sidecar.schema.json +1 -1
  78. package/schemas/geography-model.schema.json +1 -1
  79. package/schemas/gui-animation-source.schema.json +1 -1
  80. package/schemas/gui-helper.schema.json +1 -1
  81. package/schemas/gui-scenario.schema.json +1 -1
  82. package/schemas/helper-expansion-request.schema.json +1 -1
  83. package/schemas/helper-expansion-summary.schema.json +1 -1
  84. package/schemas/impact-inspect-input.schema.json +1 -1
  85. package/schemas/map-operation.schema.json +1087 -815
  86. package/schemas/mechanic-test-input.schema.json +1 -1
  87. package/schemas/mod-index-input.schema.json +1 -1
  88. package/schemas/operation-result.schema.json +1 -1
  89. package/schemas/package-check-input.schema.json +1 -1
  90. package/schemas/package-manifest.schema.json +1 -1
  91. package/schemas/probability-analysis-result.schema.json +1 -1
  92. package/schemas/probability-compare-input.schema.json +1 -1
  93. package/schemas/probability-evaluate-input.schema.json +1 -1
  94. package/schemas/probability-inspect-input.schema.json +1 -1
  95. package/schemas/probability-render-input.schema.json +1 -1
  96. package/schemas/probability-scenario-set.schema.json +1 -1
  97. package/schemas/probability-sequence-input.schema.json +1 -1
  98. package/schemas/probability-simulate-input.schema.json +1 -1
  99. package/schemas/probability-sweep-input.schema.json +1 -1
  100. package/schemas/reference-context-input.schema.json +1 -1
  101. package/schemas/reference-read-input.schema.json +1 -1
  102. package/schemas/reference-search-input.schema.json +2 -2
  103. package/schemas/reference-sheets.schema.json +1 -1
  104. package/schemas/scenario-suite.schema.json +1 -1
  105. package/schemas/scenario-test-input.schema.json +1 -1
  106. package/schemas/script-validate-input.schema.json +7 -1
  107. package/schemas/shared-scenario.schema.json +1 -1
  108. package/schemas/source-lookup-input.schema.json +1 -1
  109. package/server.json +2 -2
@@ -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
- // Re-enumerate every root: installing content or changing load order can
164
- // invalidate a vanilla inventory just as it can a mod inventory.
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, { sha256, bytes });
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 absoluteRoot = path.normalize(requestedRoot);
104
- if (!path.isAbsolute(absoluteRoot)) {
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, semantic, signal) {
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: hashCanonical(semantic(value)) };
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.v2',
87
- nodes: semanticCollectionHash('nodes', graph.nodes, ({ id }) => id, semanticNode, signal),
88
- edges: semanticCollectionHash('edges', graph.edges, ({ id }) => id, semanticEdge, signal),
89
- stateAccesses: semanticCollectionHash('state-accesses', graph.stateAccesses, ({ id }) => id, semanticStateAccess, signal),
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 (current !== undefined &&
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
- hashCanonical(semanticStateAccess(beforeStateAccesses.get(id))) !==
223
- hashCanonical(semanticStateAccess(current)));
257
+ stateAccessHash(beforeStateAccesses.get(id)) !== stateAccessHash(current));
224
258
  })
225
259
  .sort(compareCodeUnits);
226
260
  const addedStateLinkIds = [...afterStateLinks.keys()]
@@ -49,33 +49,125 @@ export function eventGraphCounts(graph, artifacts) {
49
49
  artifacts,
50
50
  };
51
51
  }
52
- export function eventGraphValidation(graph) {
52
+ /**
53
+ * `answerPaths` names the source files the answer stands on, for a focused trace or path. Blocking
54
+ * diagnostics in other files of the workspace do not make that answer fail; they are counted apart
55
+ * and stay in the linked evidence. Without it, every blocking diagnostic of the workspace counts.
56
+ */
57
+ export function eventGraphValidation(graph, answerPaths) {
53
58
  const counts = eventGraphCounts(graph, 0);
59
+ const blockingHere = answerPaths === undefined
60
+ ? counts.blockingDiagnostics
61
+ : eventDiagnostics(graph).filter(({ severity, location }) => (severity === 'error' || severity === 'blocker') &&
62
+ location !== undefined &&
63
+ answerPaths.has(location.path)).length;
64
+ const blockingElsewhere = counts.blockingDiagnostics - blockingHere;
54
65
  const analysisBoundaryPassed = graph.complete || (graph.analysisMode === 'focused' && graph.skippedSourceCount === 0);
55
- const passed = analysisBoundaryPassed && counts.blockingDiagnostics === 0;
66
+ const passed = analysisBoundaryPassed && blockingHere === 0;
56
67
  return {
57
68
  passed,
58
69
  checks: [
59
70
  {
60
71
  id: 'event-analysis',
61
72
  passed,
62
- message: counts.blockingDiagnostics > 0
63
- ? `${counts.blockingDiagnostics} blocking event-chain diagnostics; full evidence is linked`
64
- : graph.complete
65
- ? 'The event-chain analysis is complete and has no blocking diagnostics'
66
- : graph.analysisMode === 'focused' && graph.skippedSourceCount === 0
67
- ? 'Whole-workspace helper projections and lifecycle passes were deferred; the requested event analysis retains direct source evidence'
68
- : graph.analysisMode === 'focused'
69
- ? `${graph.skippedSourceCount} event-analysis source(s) were skipped; linked evidence records the partial boundary`
70
- : graph.issues.some(({ code }) => code === 'EVENT_HELPER_DEPTH_LIMIT' ||
71
- code === 'EVENT_HELPER_PROJECTION_LIMIT' ||
72
- code === 'EVENT_HELPER_STATE_PROJECTION_LIMIT')
73
- ? 'Helper expansion reached a depth or materialization boundary; helper_expansion mode provides bounded source-linked continuation'
74
- : `${graph.skippedSourceCount} event-analysis source(s) were skipped; full evidence is linked`,
73
+ message: blockingHere > 0
74
+ ? `${blockingHere} blocking event-chain diagnostics${answerPaths === undefined ? '' : ' in the files of this answer'}; full evidence is linked`
75
+ : answerPaths !== undefined && blockingElsewhere > 0
76
+ ? `No blocking diagnostics in the files of this answer; ${blockingElsewhere} elsewhere in the workspace are in the linked evidence`
77
+ : graph.complete
78
+ ? 'The event-chain analysis is complete and has no blocking diagnostics'
79
+ : graph.analysisMode === 'focused' && graph.skippedSourceCount === 0
80
+ ? 'Whole-workspace helper projections and lifecycle passes were deferred; the requested event analysis retains direct source evidence'
81
+ : graph.analysisMode === 'focused'
82
+ ? `${graph.skippedSourceCount} event-analysis source(s) were skipped; linked evidence records the partial boundary`
83
+ : graph.issues.some(({ code }) => code === 'EVENT_HELPER_DEPTH_LIMIT' ||
84
+ code === 'EVENT_HELPER_PROJECTION_LIMIT' ||
85
+ code === 'EVENT_HELPER_STATE_PROJECTION_LIMIT')
86
+ ? 'Helper expansion reached a depth or materialization boundary; helper_expansion mode provides bounded source-linked continuation'
87
+ : `${graph.skippedSourceCount} event-analysis source(s) were skipped; full evidence is linked`,
75
88
  },
76
89
  ],
77
90
  };
78
91
  }
92
+ /**
93
+ * Whether the answer to the question that was asked is complete. A result is partial only when
94
+ * something the answer needs is missing, and the narrower scope of a focused analysis (the
95
+ * whole-workspace passes it defers, named by \`analysisMode\`) is not a gap in an answer that
96
+ * stands on its own. A focused trace is complete when no source was skipped, no limit cut it
97
+ * short and no node sits on its boundary. A focused path is complete when it was found without an
98
+ * assumption.
99
+ */
100
+ function eventAnswerComplete(inspected) {
101
+ if (inspected.helperExpansion !== undefined)
102
+ return inspected.helperExpansion.complete;
103
+ const { graph, summary } = inspected;
104
+ if (graph.complete)
105
+ return true;
106
+ if (graph.analysisMode !== 'focused' || graph.skippedSourceCount !== 0 || summary === undefined)
107
+ return false;
108
+ const trace = summary.trace;
109
+ if (typeof trace === 'object' && trace !== null && !Array.isArray(trace))
110
+ return trace.truncated === false && trace.boundaryNodes === 0;
111
+ return summary.found === true && summary.unresolvedAssumptions === 0;
112
+ }
113
+ /** The source files of a focused trace or path, or undefined for any other answer. */
114
+ function answerPaths(inspected) {
115
+ if (inspected.graph.analysisMode !== 'focused')
116
+ return undefined;
117
+ const report = inspected.report;
118
+ const nodes = report?.trace?.nodes ?? report?.explanation?.steps?.map(({ node }) => node);
119
+ if (nodes === undefined)
120
+ return undefined;
121
+ return new Set(nodes.flatMap((node) => {
122
+ const path = node.location?.path ?? node.sourcePath;
123
+ return path === undefined ? [] : [path];
124
+ }));
125
+ }
126
+ /**
127
+ * What a partial event answer is missing, as inline information, so an agent knows whether to
128
+ * raise a limit, trace from the boundary, or accept that callers reached only through scripted
129
+ * effects may be absent (ADR 0086: a partial result says what is missing).
130
+ */
131
+ export function eventPartialReasons(inspected) {
132
+ const { graph, summary } = inspected;
133
+ const reasons = [];
134
+ if (inspected.helperExpansion?.complete === false)
135
+ reasons.push({
136
+ code: 'EVENT_HELPER_EXPANSION_INCOMPLETE',
137
+ message: 'Helper expansion stopped at its depth or size limit; continue it with mode helper_expansion from a helper on its boundary',
138
+ });
139
+ if (graph.skippedSourceCount > 0)
140
+ reasons.push({
141
+ code: 'EVENT_SOURCES_SKIPPED',
142
+ message: `${graph.skippedSourceCount} event source file(s) were skipped as over a size limit, so events they define are missing from this answer`,
143
+ details: { skippedSources: graph.skippedSourceCount },
144
+ });
145
+ const trace = summary?.trace;
146
+ const cut = typeof trace === 'object' &&
147
+ trace !== null &&
148
+ !Array.isArray(trace) &&
149
+ (trace.truncated === true ||
150
+ (typeof trace.boundaryNodes === 'number' && trace.boundaryNodes > 0));
151
+ if (cut)
152
+ reasons.push({
153
+ code: 'EVENT_TRACE_TRUNCATED',
154
+ message: 'The trace stopped at its limits and continues beyond its boundary nodes; raise maxDepth or maxNodes, or trace again from a node on the boundary',
155
+ });
156
+ else if (graph.analysisMode === 'focused' &&
157
+ graph.skippedSourceCount === 0 &&
158
+ inspected.helperExpansion === undefined)
159
+ reasons.push({
160
+ code: 'EVENT_FOCUSED_ANALYSIS_DEFERRED',
161
+ message: 'This large workspace defers the workspace-wide helper projections and state links, so callers and state links that exist only inside scripted effects may be missing from this answer',
162
+ });
163
+ return reasons.map(({ code, message, details }) => ({
164
+ category: 'configuration',
165
+ code,
166
+ severity: 'info',
167
+ message,
168
+ ...(details === undefined ? {} : { details }),
169
+ }));
170
+ }
79
171
  /** Transport-independent event inspection and its complete bounded result contract. */
80
172
  export async function inspectEvents(viewer, input) {
81
173
  const inspected = await viewer.inspect(input);
@@ -99,10 +191,9 @@ export async function inspectEvents(viewer, input) {
99
191
  refresh: input.refresh ?? input.mode === 'scan',
100
192
  },
101
193
  });
102
- result.code =
103
- (inspected.helperExpansion?.complete ?? inspected.graph.complete)
104
- ? 'EVENT_INSPECTED'
105
- : 'EVENT_INSPECTED_PARTIAL';
194
+ result.code = eventAnswerComplete(inspected) ? 'EVENT_INSPECTED' : 'EVENT_INSPECTED_PARTIAL';
195
+ if (result.code === 'EVENT_INSPECTED_PARTIAL')
196
+ result.diagnostics.push(...eventPartialReasons(inspected));
106
197
  setInlineFilesScanned(result, inspected.graph.filesScanned);
107
198
  result.artifacts = inspected.artifacts.map(publicArtifactLink);
108
199
  if (inspected.graphSnapshotOmitted === true)
@@ -113,7 +204,7 @@ export async function inspectEvents(viewer, input) {
113
204
  message: 'The workspace graph is too large to retain as a snapshot artifact; the scan report is linked, and comparisons use revisions held by this server',
114
205
  details: { maximumBytes: EVENT_GRAPH_SNAPSHOT_MAX_BYTES },
115
206
  });
116
- result.validation = eventGraphValidation(inspected.graph);
207
+ result.validation = eventGraphValidation(inspected.graph, answerPaths(inspected));
117
208
  if (inspected.helperExpansion !== undefined)
118
209
  result.validation = helperExpansionValidation(inspected.helperExpansion);
119
210
  return result;
@@ -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
- const values = options.references?.[kind];
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
- const values = catalog?.[kind];
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);