hoi4-agent-tools 4.16.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.
Files changed (101) hide show
  1. package/CHANGELOG.md +29 -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/scanner.js +148 -7
  8. package/dist/hoi4_agent_tools/core/server-state.js +50 -2
  9. package/dist/hoi4_agent_tools/core/source/localisation.js +7 -1
  10. package/dist/hoi4_agent_tools/event/compare.js +47 -13
  11. package/dist/hoi4_agent_tools/focus/importer.js +2 -5
  12. package/dist/hoi4_agent_tools/focus/lint.js +2 -5
  13. package/dist/hoi4_agent_tools/focus/model.js +19 -0
  14. package/dist/hoi4_agent_tools/focus/tool-operations.js +16 -1
  15. package/dist/hoi4_agent_tools/focus/tool-support.js +14 -0
  16. package/dist/hoi4_agent_tools/map/appearance-validation.js +6 -1
  17. package/dist/hoi4_agent_tools/map/engine-raster.js +160 -0
  18. package/dist/hoi4_agent_tools/map/model.js +9 -8
  19. package/dist/hoi4_agent_tools/map/operations.js +20 -5
  20. package/dist/hoi4_agent_tools/map/partition-provinces.js +6 -2
  21. package/dist/hoi4_agent_tools/map/partition-tuning.js +37 -0
  22. package/dist/hoi4_agent_tools/map/service.js +25 -12
  23. package/dist/hoi4_agent_tools/map/territory-operations.js +114 -3
  24. package/dist/hoi4_agent_tools/map/territory-quality.js +39 -0
  25. package/dist/hoi4_agent_tools/map/territory.js +63 -2
  26. package/dist/hoi4_agent_tools/map/tool-operations.js +27 -1
  27. package/dist/hoi4_agent_tools/map/validation.js +23 -3
  28. package/dist/hoi4_agent_tools/map/water.js +13 -10
  29. package/dist/hoi4_agent_tools/map/world-outputs.js +41 -26
  30. package/dist/hoi4_agent_tools/map/world.js +51 -1
  31. package/dist/hoi4_agent_tools/mcp/tools/map.js +23 -0
  32. package/dist/hoi4_agent_tools/mcp/tools/reference.js +2 -2
  33. package/dist/hoi4_agent_tools/mcp/tools/technology.js +25 -1
  34. package/dist/hoi4_agent_tools/reference/closure.js +65 -0
  35. package/dist/hoi4_agent_tools/reference/command-phrases.json +7899 -1127
  36. package/dist/hoi4_agent_tools/reference/operations.js +38 -21
  37. package/dist/hoi4_agent_tools/reference/ranking.js +77 -2
  38. package/dist/hoi4_agent_tools/reference/script-validation.js +4 -2
  39. package/dist/hoi4_agent_tools/reference/service.js +45 -2
  40. package/dist/hoi4_agent_tools/reference/source-lookup.js +43 -121
  41. package/dist/hoi4_agent_tools/runtime.js +27 -11
  42. package/dist/hoi4_agent_tools/schemas/lenient-arguments.js +7 -1
  43. package/dist/hoi4_agent_tools/schemas/map.js +33 -0
  44. package/dist/hoi4_agent_tools/schemas/mod-tools.js +49 -0
  45. package/dist/hoi4_agent_tools/schemas/reference.js +1 -1
  46. package/dist/hoi4_agent_tools/schemas/script-validation.js +57 -3
  47. package/dist/hoi4_agent_tools/technology/operations.js +5 -0
  48. package/dist/hoi4_agent_tools/technology/queries.js +54 -0
  49. package/dist/hoi4_agent_tools/version.js +1 -1
  50. package/docs/configuration.md +1 -1
  51. package/docs/map.md +13 -11
  52. package/docs/research/reference-benchmark.md +64 -0
  53. package/docs/tools.md +20 -20
  54. package/docs/troubleshooting.md +4 -0
  55. package/engine/bin/darwin-arm64/hoi4-engine +0 -0
  56. package/engine/bin/linux-arm64/hoi4-engine +0 -0
  57. package/engine/bin/linux-x64/hoi4-engine +0 -0
  58. package/engine/bin/manifest.json +8 -8
  59. package/engine/bin/win32-x64/hoi4-engine.exe +0 -0
  60. package/npm-shrinkwrap.json +2 -2
  61. package/package.json +5 -3
  62. package/schemas/configuration.schema.json +1 -1
  63. package/schemas/continuous-focus-palette.schema.json +1 -1
  64. package/schemas/custom-weighted-pool.schema.json +1 -1
  65. package/schemas/decision-inspect-input.schema.json +1 -1
  66. package/schemas/error-log-input.schema.json +1 -1
  67. package/schemas/event-feature-manifest.schema.json +1 -1
  68. package/schemas/focus-plan.schema.json +1 -1
  69. package/schemas/focus-planning-sidecar.schema.json +1 -1
  70. package/schemas/geography-model.schema.json +1 -1
  71. package/schemas/gui-animation-source.schema.json +1 -1
  72. package/schemas/gui-helper.schema.json +1 -1
  73. package/schemas/gui-scenario.schema.json +1 -1
  74. package/schemas/helper-expansion-request.schema.json +1 -1
  75. package/schemas/helper-expansion-summary.schema.json +1 -1
  76. package/schemas/impact-inspect-input.schema.json +1 -1
  77. package/schemas/map-operation.schema.json +817 -728
  78. package/schemas/mechanic-test-input.schema.json +1 -1
  79. package/schemas/mod-index-input.schema.json +1 -1
  80. package/schemas/operation-result.schema.json +1 -1
  81. package/schemas/package-check-input.schema.json +1 -1
  82. package/schemas/package-manifest.schema.json +1 -1
  83. package/schemas/probability-analysis-result.schema.json +1 -1
  84. package/schemas/probability-compare-input.schema.json +1 -1
  85. package/schemas/probability-evaluate-input.schema.json +1 -1
  86. package/schemas/probability-inspect-input.schema.json +1 -1
  87. package/schemas/probability-render-input.schema.json +1 -1
  88. package/schemas/probability-scenario-set.schema.json +1 -1
  89. package/schemas/probability-sequence-input.schema.json +1 -1
  90. package/schemas/probability-simulate-input.schema.json +1 -1
  91. package/schemas/probability-sweep-input.schema.json +1 -1
  92. package/schemas/reference-context-input.schema.json +1 -1
  93. package/schemas/reference-read-input.schema.json +1 -1
  94. package/schemas/reference-search-input.schema.json +2 -2
  95. package/schemas/reference-sheets.schema.json +1 -1
  96. package/schemas/scenario-suite.schema.json +1 -1
  97. package/schemas/scenario-test-input.schema.json +1 -1
  98. package/schemas/script-validate-input.schema.json +7 -1
  99. package/schemas/shared-scenario.schema.json +1 -1
  100. package/schemas/source-lookup-input.schema.json +1 -1
  101. package/server.json +2 -2
package/CHANGELOG.md CHANGED
@@ -2,6 +2,35 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ ## 4.17.0 - 2026-11-14
6
+
7
+ - `hoi4.map_inspect` names its matches inline: `data.matches` lists the first 20 query matches (kind, id, key and name, best first) and `data.coordinateMatches` what each requested coordinate falls in (province, states, regions). It only counted them, so `{"query":"Brandenburg","lookupOnly":true}` answered `queryMatchCount: 2` without saying the state is 64; the full lists stay in the linked artifact.
8
+ - `hoi4.tech_inspect` with `mode: "explain"` names the technology inline: its file and line, start year, research cost, folders and categories, its direct prerequisites, what it leads to, its exclusive choices and its unlocks (20 names each at most, `truncated` when there are more), and the totals of all prerequisites, descendants, unlocks, grants and issues. The answer gave only the whole tree's counts, so an agent had to read the linked report (280 KB for the game) to learn what `infantry_weapons` leads to.
9
+ - Accept localisation values with quotes inside them. A line such as `k:0 "He said "hi" now"` was reported as `LOCALISATION_MALFORMED_LINE`, and a file with more than 100 of them was skipped whole, which made `hoi4.mod_index` answer `MOD_INDEXED_PARTIAL` for Old World Blues (five files, over 100 such lines each) and left their keys out of every lookup. The game reads from the first quote to the last one on the line, and its own localisation has 444 such lines, so they are valid. The TypeScript parser and the engine's symbol index now take them; a line that never closes its value is still malformed.
10
+ - Answer every `hoi4.source_lookup` call that names a symbol from the shared Rust engine, references included (ADR 0083, maintainer decision M-8, issue 107). The engine ports the definition walk's technology, focus, GUI and state references and the semantic scan's typed script edges, keeps those to the requested symbol, and counts the rest, so `referenceCount`, `referencesComplete` and `unresolvedReferenceCount` stay the whole scan's. The answer is the TypeScript route's, checked by `scripts/source-lookup-parity.ts` on the installed game and the benchmark mods. Only a request for a source position (`path` and `line`) still scans in TypeScript. A missing engine is `ENGINE_UNAVAILABLE` for every lookup that names a symbol, `includeReferences` included.
11
+ - Add `closure: true` to `hoi4.script_validate`, on the shared engine (ADR 0083, issue 107). It counts the references of the mod's own sources that resolve, do not resolve, or cannot be decided, per target kind, and returns a verdict: `incomplete` whenever anything is unknown or the scan is partial, `unresolved` when only unresolved references remain, `closed` otherwise. Dynamic targets, kinds a skipped source could define, and variables, flags and event targets that are read but never written in the scanned sources count as unknown. The option excludes `source` and `path`; the result has `checksPerformed: ["closure"]`, a `closure` object, and no `documentation`, which is now optional in the output schema.
12
+ - Add `create_world.partitionTuning.areaByRow` (feature-aware partition). The owner asked on 9 November (ZIN decision K116) for larger provinces and states toward the north, and the partition sized provinces by ground alone. `areaByRow` takes `[row, factor]` points (row 0 at the top edge, 1 at the bottom; factors 0.25 to 8), linear between points and held beyond the ends, and multiplies the planned land province area after it is scaled to `landProvincePixels`, so rows with factor 1 keep their sizes. States keep their province counts, so they grow by the same factor. `MAP_PARTITION_AREA_BY_ROW` reports the land provinces and mean area per band. On a 512 by 256 test world `[[0, 3], [0.3, 1.6], [0.45, 1], [1, 1]]` gave 246 pixels on average in rows 0 to 0.3, 153 in rows 0.3 to 0.45 and 116 in the south (117 without the option), and 138 states instead of 171. Requests without `areaByRow` write the same files as before.
13
+ - Accept a server state root under the macOS temporary folder. macOS ships `/var`, `/tmp` and `/etc` as links into `/private`, so a state root such as `$TMPDIR/state` (`/var/folders/...`) always passed through a link and startup stopped with `SERVER_STATE_UNSAFE`. A link that only the superuser can change (owned by root, in a root-owned directory that group and others cannot write) is now resolved to its real path first. Any other link in the path is still refused, and Windows is unchanged. The test helper resolves `TMPDIR` before the suite runs, which is why macOS CI never saw this.
14
+ - Make `hoi4.focus_inspect` and `hoi4.focus_rewrite` far cheaper per call (issue 137). On a four-focus mod with the game installed a warm inspect took 20 to 30 s; it now takes about 2 s on a loaded machine. The importer rebuilt a set of every game identifier for each assignment of every focus, the reference catalog was rebuilt for each imported file, a call that named a tree but no file imported every focus file of the game, and every rewrite and the next inspect indexed the whole game again. Each is fixed (the catalog sets and the catalog are cached, a tree id reads only the files that define it, and the workspace's last index supplies the records of unchanged files after an edit). A call with a tree id and no file now lists only that tree's source files in its source hashes.
15
+ - Start the server outside a mod when no configuration file exists (issue 150). It stopped with `AUTO_MOD_ROOT_NOT_FOUND`, so a modder who installed it globally and fetched the docs pack could not search the documentation from their home folder without running `--init`. It now starts with no workspace: documentation search answers, and mod tools answer `WORKSPACE_CONTEXT_NOT_FOUND`.
16
+ - Answer more plain-word documentation questions first (issue 64). A little word of a command name that the question also says ("at war with" for `has_war_with`) now counts, an exact name keeps a trigger or effect ahead of a console command, define or variable of the same name, and about twenty player words map to script words (sea, temporary, vassal, spirit, owner). On a new set of 22 blind questions the right answer moved from first on 12 to 13, and on the earlier sets from 9 to 11 of 24 (held-out) and 17 to 19 of 38 (fresh) with no answer lost. The target of issue 64 is not met yet.
17
+ - Report a localisation key that nothing defines as a warning, not an error, and text written directly in a scripted localisation (`localization_key = "Planes"`) as information. The game shows such a key as written, the localisation audit already said so, and `hoi4.mod_health` on Chaos Redux listed 2,663 "errors" of this kind ahead of the real problems. The engine check's code for the text case is `LOC_SCRIPTED_TEXT_LITERAL`, the audit's.
18
+ - Stop reading the installed game from disk on every call (issue 137). A scan read all 1,438 game files a focus call needs, about 1 s each time, and a focus rewrite scans three times. An installed game or DLC file whose device, file number, size, modification time and change time are unchanged now keeps its bytes and hash, checked against its stored hash before each reuse. Mod files are still read every time.
19
+ - Answer plain-word documentation questions better, and show ten candidates (issue 64). Every one of the 1,127 documented effects and triggers now has ten plain-word phrasings in `command-phrases.json` instead of four, written once at build time and shipped as data. `hoi4.reference_search` returns up to ten hits by default, and a command hit carries a one-line meaning with the scopes it works in, so an agent can pick the right one. On a new blind set of 43 questions the right answer is first on 31 (was 23) and among the first ten on 39 (91 percent, was 36). Counting a hit by command instead of by documentation file corrects the earlier figures of this issue upward.
20
+ - Skip the walk of the installed game while it is unchanged (issue 137). A scan opened, resolved and checked the 1,438 game files a focus call needs, about a second each time. The scanner now keeps the inventory of the game folder and reuses it while the game's version files (`hoi4_rev.txt` and its neighbours) and top-level folders look the same, and walks again as soon as they change. On a four-focus mod a warm `focus_inspect` takes about 0.5 s (was 1.0 to 1.3 s, and 20 to 30 s before the earlier fixes to this issue), a rewrite with nothing to change 0.8 s. A game file edited in place without an update is not seen until the server restarts; `HOI4_AGENT_FULL_GAME_SCAN` turns the shortcut off (see troubleshooting).
21
+ - Say "Did you mean ...?" in the message of a script command the game does not document (`SCRIPT_COMMAND_UNRESOLVED`). The close documented names were already in `suggestions`, but an agent that reads only the diagnostics saw "Not documented as a native command" and no hint, so `add_poltical_power` gave no pointer to `add_political_power`.
22
+ - `hoi4.script_validate` says what an unknown id does in game: `add_timed_idea names idea X, which no loaded file defines; the game loads the file, but this command does nothing`. It stays a warning, as the game loads such files and vanilla ships dangling ids, but now reads as the bug it is in the modder's own file. Benchmark: `vanilla.validation.timed-idea-wrong-id` expects that warning, and the undefined-description case moved from the ZIN corpus (which fixed its own file) to the synthetic regression mod, whose localisation now uses the double quotes the game reads.
23
+ - Say what is missing and how to get it when no `hoi4-engine` binary is found. The package ships the engine for Windows x64, Linux x64 and arm64, and macOS on Apple silicon; on another platform, such as an Intel Mac (`darwin-x64`), a tool that needs it answers `ENGINE_UNAVAILABLE` naming the shipped platforms and how to build the engine and point `HOI4_ENGINE` at it, and on a shipped platform whose binary is missing it says to reinstall. The README names the supported platforms.
24
+ - Map tools pass the province raster request and answer to `hoi4-engine map-provinces` through temporary files (`--input`, `--output`) instead of the engine's stdin and stdout. On macOS runners the synchronous call, which wrote hundreds of kilobytes to the pipe and read as much back, sometimes hung until its 120-second timeout and failed the map tests with `ENGINE_UNAVAILABLE` (`spawnSync ... ETIMEDOUT`). The engine still reads stdin and writes stdout when the options are absent.
25
+ - Event Chain Viewer analysis spends far less time hashing (maintainer decision M-8, issue 69). A CPU profile of `hoi4.event_inspect` `state_flow` on Chaos Redux (141 s) showed about 60 s of canonical JSON hashing and 22 s of garbage collection. Two causes are fixed. A dependency-walk checkpoint ran `z.json()` over the walk's whole frontier before every save (25 s) and canonicalised it twice. It now checks only the key and revision, and canonical JSON still refuses what JSON cannot hold. Loading a checkpoint still validates all of it. The semantic graph hash serialised each edge and state access with its option's conditions inline, about 3 GB on Chaos Redux (264,828 edges of 9.5 KB on average). Each shared condition is now hashed once and named by its digest (`event-semantic-graph-hash.v3`). `graphHash` values therefore differ from earlier versions, but within one version they still change exactly when the graph's meaning does. On the benchmark machine the Chaos Redux `state_flow` case took 79 and 70 s instead of 107 and 111 s.
26
+ - Build the province raster and run the province geometry checks on the shared Rust engine (ADR 0084, maintainer decision M-8, step 4). The province of every pixel, each province's extent, neighbours, seam-only pairs, undefined colours, coastal provinces, and the 4-connected parts, holes and thin runs that map validation reports now come from `hoi4-engine map-provinces`, in the same order the TypeScript code produced them. `scripts/map-raster-parity.ts` checks this on the installed game and the benchmark mods. Map tools that read `provinces.bmp` now answer `ENGINE_UNAVAILABLE` without an engine, as `hoi4.mod_index` does.
27
+ - `hoi4.map_inspect` and the other map tools no longer build the shared symbol index (maintainer decision M-8, step 4). The map model parses its own sources and never read it, yet every map call indexed every scanned file, its localisation included. Map scans now use `CoreEngine.scanFiles`, which shares the scan cache and admission limit and skips the index. On the benchmark machine (median of three cold runs), `{"query":"Brandenburg","lookupOnly":true}` on the game took 6.4 s instead of 11.4 s, an unknown-state lookup on Chaos Redux 3.0 s instead of 4.5 s, and a full inspection of the game map 22.5 s instead of 27.1 s. Answers are unchanged. The heightmap check of a full inspection also stops its land-distance search one step past the three-pixel lake-bank allowance instead of flooding every sea pixel, with the same answers; on the game a full inspection took 13.7 s instead of 26.8 s. The new benchmark case `vanilla.map.full-inspect` measures it.
28
+ - `hoi4.probability_inspect` and `hoi4.probability_analyze` accept a top-level `path` for the source file, as their description promises ("by path, ID or candidate IDs"). `{"path":"common/national_focus/germany.txt","candidatePool":[...]}` was refused with `INVALID_ARGUMENTS`; it now means `source: {"path": ...}`. A call that gives both `path` and `source` is still refused.
29
+ - Add the files map operations create to the world output record (`.hoi4-agent-world.json`). `assign_territory`, `split_state`, `create_state` and the other operations created state and strategic-region files that never entered the record, so a sync that copies the recorded files left them out. ZIN's first Linux run of a redrawn map lost 124 state files this way, and the game stopped at setup. Every map rewrite now also adds each file it creates where the world keeps its outputs (state files, strategic regions, map files and world localisation, not country files), in the same transaction. `MAP_WORLD_OUTPUTS_REFRESHED` gives `added` and `addedPaths`. For mods already in this state, `record_world_outputs` now also adds the mod's files at those paths that the record lacks; `adoptUnrecorded: false` keeps the old behaviour of re-hashing listed entries only.
30
+ - `record_world_outputs` no longer drops recorded files that are on disk. Its scan did not read the bitmaps, colour maps and world scripts that only `create_world` scanned, so it dropped them as gone: on ZIN, 12 entries, among them `map/rivers.bmp`, `map/terrain.bmp` and `common/on_actions/world.txt`. A Linux copy of the recorded files then ran with the base game's rivers. It now reads every world output, and drops only recorded state and strategic-region files that are gone. Any other recorded file it did not read keeps its entry and is listed in `unscannedPaths`.
31
+ - Territory controls for redrawing borders, from the ZIN map lane's rev3 findings. `assign_territory` takes culture or people `groups` (`{ provinceId: group }`): a growth step across a group line costs `1 + groupPenalty` times more (default 2), and with `groupHard: true` growth never crosses one. In rev3, peoples' pockets were shared across those lines. A country with `fixed: true` owns exactly its seeds and forced land and never grows. In rev3, Kingson still grew from 122 to 142 provinces into its neighbours' free bands. A preview and a write add `map-territory-assignment.json`, the provinces of each owner and of each new or changed state; before, the only source was the 22 MB proposed map. A seed in water is refused with the nearest land province named (`details.nearestLandProvince`).
32
+ - `assign_territory` warns when a country or overlord tag gets land although no active `common/country_tags` file declares it (`MAP_TERRITORY_TAG_UNDEFINED`). It took such tags silently, and the game then did not know the states' owner. The ZIN map lane assigns new realms before their country files exist. The assignment is still written, unless the new `strictTags: true` asks for a refusal. Nothing is reported when the workspace declares no tags at all.
33
+
5
34
  ## 4.16.0 - 2026-11-09
6
35
 
7
36
  - Keep the world output record (`.hoi4-agent-world.json`) current with the tool's own map edits. `update_states`, `move_state_provinces` and every other map operation rewrote recorded state, strategic-region and map files without recording their new hashes, so the next `create_world` refused them as hand edits (`MANAGED_OUTPUT_EDITED`). This happened in a later call and also later in the `create_world` call itself, because the record was planned at the end of `create_world`. ZIN had 191 such files on 9 November: 184 state files and 7 strategic regions. Every map rewrite now records the new hash of each recorded file it writes, and drops each one it deletes, in the same transaction (`MAP_WORLD_OUTPUTS_REFRESHED`). A recorded file edited by hand before the call keeps its old hash and is named in a warning, so it stays protected. The new `record_world_outputs` operation takes the current bytes of every recorded file as the world's own. It is for mods whose record is already stale: it writes only the record, drops files that are gone, and reports the counts (`MAP_WORLD_OUTPUTS_RECORDED`).
package/README.md CHANGED
@@ -42,6 +42,7 @@ You describe what you want; the agent picks the right tools.
42
42
  ## Quick start
43
43
 
44
44
  1. Install [Node.js](https://nodejs.org/) 22 (22.19 or later) or 24, and keep Hearts of Iron IV installed for vanilla files, artwork and fonts.
45
+ The package ships its analysis engine for Windows x64, Linux x64 and arm64, and macOS on Apple silicon. On another platform, such as an Intel Mac, the tools that need the engine say so and how to build it; set `HOI4_ENGINE` to that build.
45
46
  2. Install the server:
46
47
 
47
48
  ```bash
@@ -1,6 +1,6 @@
1
1
  import { AsyncLocalStorage } from 'node:async_hooks';
2
2
  import { z } from 'zod/v4';
3
- import { canonicalJson, hashCanonical } from './canonical.js';
3
+ import { canonicalJson, hashCanonical, sha256Bytes } from './canonical.js';
4
4
  import { ServiceError } from './result.js';
5
5
  import { PACKAGE_VERSION } from '../version.js';
6
6
  const digest = z.string().regex(/^[a-f0-9]{64}$/u);
@@ -12,6 +12,7 @@ const envelopeSchema = z
12
12
  state: z.json(),
13
13
  })
14
14
  .strict();
15
+ const saveIdentitySchema = z.object({ key: digest, sourceRevision: digest }).strict();
15
16
  const active = new AsyncLocalStorage();
16
17
  /** Internal typed execution context; no transport or caller-supplied executable hooks. */
17
18
  export function withAnalysisCheckpoints(checkpoints, run) {
@@ -44,12 +45,18 @@ export function jobAnalysisCheckpoints(context) {
44
45
  },
45
46
  async save(key, sourceRevision, state, completed, total) {
46
47
  context.signal.throwIfAborted();
47
- const envelope = envelopeSchema.parse({ version: 1, key, sourceRevision, state });
48
+ // The state is the analysis's own in-memory value. Canonical JSON already refuses what
49
+ // JSON cannot hold, so only the identity fields are checked here: a deep z.json() pass
50
+ // over a large frontier cost more than the analysis itself (25 s of a 141 s event query on a
51
+ // large mod). `load` still validates the whole envelope it reads back from disk.
52
+ saveIdentitySchema.parse({ key, sourceRevision });
53
+ const content = canonicalJson({ version: 1, key, sourceRevision, state });
54
+ const stateHash = sha256Bytes(content);
48
55
  await context.engine.artifacts.withAtomicChunkedWrites(workspace, [
49
56
  {
50
57
  name: 'analysis-checkpoint.json',
51
58
  mimeType: 'application/json',
52
- content: canonicalJson(envelope),
59
+ content,
53
60
  provenance: {
54
61
  kind: 'analysis-checkpoint',
55
62
  toolVersion: PACKAGE_VERSION,
@@ -64,7 +71,7 @@ export function jobAnalysisCheckpoints(context) {
64
71
  sourceRevision,
65
72
  resourceUri: resource.uri,
66
73
  cursor: `analysis:${key}`,
67
- stateHash: hashCanonical(envelope),
74
+ stateHash,
68
75
  resources: physical.map(({ uri }) => uri),
69
76
  };
70
77
  // Publish the authenticated pin before releasing artifact admission. A competing
@@ -27,6 +27,35 @@ function isFile(candidate) {
27
27
  return false;
28
28
  }
29
29
  }
30
+ /**
31
+ * Every platform a release ships `hoi4-engine` for (ADR 0074), as `<process.platform>-<process.arch>`.
32
+ * Other platforms, such as macOS on Intel (`darwin-x64`), get no bundled binary.
33
+ */
34
+ export const ENGINE_BUNDLE_PLATFORMS = [
35
+ 'darwin-arm64',
36
+ 'linux-arm64',
37
+ 'linux-x64',
38
+ 'win32-x64',
39
+ ];
40
+ const PLATFORM_NAMES = {
41
+ 'darwin-arm64': 'macOS on Apple silicon',
42
+ 'linux-arm64': 'Linux arm64',
43
+ 'linux-x64': 'Linux x64',
44
+ 'win32-x64': 'Windows x64',
45
+ };
46
+ /**
47
+ * What a tool answers when no engine binary is found: what is missing and how to get one. A
48
+ * platform the release does not ship for needs a local build; a shipped platform whose binary is
49
+ * missing needs a reinstall.
50
+ */
51
+ export function missingEngineMessage(platform, arch) {
52
+ const target = `${platform}-${arch}`;
53
+ const supported = ENGINE_BUNDLE_PLATFORMS.map((name) => PLATFORM_NAMES[name]).join(', ');
54
+ const build = `build it from the repository's engine/ folder (cargo build --release -p hoi4-engine-cli) and set ${ENGINE_BINARY_ENV} to the binary's absolute path`;
55
+ return ENGINE_BUNDLE_PLATFORMS.includes(target)
56
+ ? `The hoi4-engine binary for ${target} is missing from this installation. Reinstall hoi4-agent-tools (npm install --global hoi4-agent-tools), or ${build}.`
57
+ : `hoi4-agent-tools ships the hoi4-engine binary for ${supported}, not for ${target}. To use the tools that need it here, ${build}.`;
58
+ }
30
59
  export const ENGINE_BUNDLE_MANIFEST_SCHEMA = 'hoi4-engine-bundle/1';
31
60
  /** `engine/bin/manifest.json`: the SHA-256 and size of every bundled binary, keyed by `<platform>-<arch>`. */
32
61
  export const engineBundleManifestSchema = z.strictObject({
@@ -123,7 +152,7 @@ export function locateEngineBinary(options = {}) {
123
152
  }
124
153
  return {
125
154
  reason: 'binary_not_found',
126
- message: `No hoi4-engine binary for ${process.platform}-${process.arch} is installed with this package and ${ENGINE_BINARY_ENV} is not set`,
155
+ message: missingEngineMessage(process.platform, process.arch),
127
156
  };
128
157
  }
129
158
  function clip(text) {
@@ -100,6 +100,14 @@ export class CoreEngine {
100
100
  #scanCache = new Map();
101
101
  #scanFlights = new Map();
102
102
  #scanGenerations = new Map();
103
+ /**
104
+ * The newest completed index of each workspace. After an edit or with another file pattern no
105
+ * scan of the same request is left to start from, and the segment cache holds too few records
106
+ * to index the installed game again cheaply, so this index supplies every unchanged file's
107
+ * records. They are addressed by the file's content hash, so an older index can never supply
108
+ * a wrong one.
109
+ */
110
+ #latestIndexes = new Map();
103
111
  #scanAdmissionQueue = [];
104
112
  #activeScanAdmissions = new Set();
105
113
  #recovery;
@@ -191,6 +199,17 @@ export class CoreEngine {
191
199
  return this.resolver.list(principal).map(({ id }) => this.status(id, principal));
192
200
  }
193
201
  async scan(workspaceId, options = {}, principal, signal) {
202
+ return (await this.#scan(workspaceId, options, principal, signal, true));
203
+ }
204
+ /**
205
+ * The same scan without the symbol index, for callers that read only the files (the map
206
+ * model parses its own sources). It shares the admission limit and the cache with `scan`,
207
+ * under its own cache entries, and skips the index build and the persistent analysis cache.
208
+ */
209
+ async scanFiles(workspaceId, options = {}, principal, signal) {
210
+ return this.#scan(workspaceId, options, principal, signal, false);
211
+ }
212
+ async #scan(workspaceId, options, principal, signal, withIndex) {
194
213
  signal?.throwIfAborted();
195
214
  await this.resolver.refreshDescriptors(workspaceId, principal);
196
215
  const workspace = this.resolver.get(workspaceId, principal);
@@ -203,6 +222,7 @@ export class CoreEngine {
203
222
  rootKinds: [...(options.rootKinds ?? [])].sort(),
204
223
  maxFiles: options.maxFiles ?? this.resolver.config().scanMaxFiles,
205
224
  maxBytes: options.maxBytes ?? this.resolver.config().scanMaxBytes,
225
+ ...(withIndex ? {} : { index: false }),
206
226
  })}`;
207
227
  let flight = this.#scanFlights.get(requestKey);
208
228
  if (flight === undefined) {
@@ -234,6 +254,11 @@ export class CoreEngine {
234
254
  this.#scanCache.set(cacheKey, cached);
235
255
  return cached;
236
256
  }
257
+ if (!withIndex) {
258
+ const snapshot = { workspaceId, revision, files };
259
+ this.#retainScan(workspaceId, generation, requestKey, cacheKey, snapshot);
260
+ return snapshot;
261
+ }
237
262
  const persistentAnalysisCache = await this.persistentAnalysisCache;
238
263
  const analysisScope = {
239
264
  workspaceIdentity: workspace.workspaceIdentity,
@@ -245,9 +270,10 @@ export class CoreEngine {
245
270
  // records, so only edited files are parsed and indexed again.
246
271
  const previous = [...this.#scanCache]
247
272
  .filter(([key]) => key.startsWith(`${requestKey}:`))
248
- .at(-1)?.[1].index;
273
+ .at(-1)?.[1]?.index ?? this.#latestIndexes.get(workspaceId);
249
274
  const index = await SymbolIndex.buildAsync(files, controller.signal, this.indexSegments, previous);
250
275
  await persistentAnalysisCache?.persist(analysisScope, files, sourceDocuments, this.indexSegments, controller.signal);
276
+ this.#latestIndexes.set(workspaceId, index);
251
277
  const documentedEffects = await installedEffectCommands(workspace.gameRoot);
252
278
  const snapshot = {
253
279
  workspaceId,
@@ -260,32 +286,7 @@ export class CoreEngine {
260
286
  diagnostics: index.diagnostics,
261
287
  ...(documentedEffects === undefined ? {} : { documentedEffects }),
262
288
  };
263
- if ((this.#scanGenerations.get(workspaceId) ?? 0) === generation) {
264
- // Replace this request's earlier revision and drop earlier generations; keep the
265
- // most recent other requests of this workspace.
266
- for (const key of this.#scanCache.keys()) {
267
- if (key.startsWith(`${requestKey}:`) ||
268
- (key.startsWith(`${workspaceId}:`) &&
269
- !key.startsWith(`${workspaceId}:${generation}:`)))
270
- this.#scanCache.delete(key);
271
- }
272
- this.#scanCache.set(cacheKey, snapshot);
273
- const retained = [...this.#scanCache.keys()].filter((key) => key.startsWith(`${workspaceId}:`));
274
- for (const key of retained.slice(0, -SCAN_CACHE_ENTRIES_PER_WORKSPACE))
275
- this.#scanCache.delete(key);
276
- // Snapshots hold every file's bytes; keep all of them within twice one scan's limit.
277
- const limit = this.resolver.config().scanMaxBytes * 2;
278
- const bytes = (cached) => cached.files.reduce((sum, { size }) => sum + size, 0);
279
- let retainedBytes = [...this.#scanCache.values()].reduce((sum, cached) => sum + bytes(cached), 0);
280
- for (const [key, cached] of this.#scanCache) {
281
- if (retainedBytes <= limit)
282
- break;
283
- if (key === cacheKey)
284
- continue;
285
- this.#scanCache.delete(key);
286
- retainedBytes -= bytes(cached);
287
- }
288
- }
289
+ this.#retainScan(workspaceId, generation, requestKey, cacheKey, snapshot);
289
290
  return snapshot;
290
291
  });
291
292
  })();
@@ -306,6 +307,33 @@ export class CoreEngine {
306
307
  }
307
308
  return this.awaitScanFlight(requestKey, flight, signal);
308
309
  }
310
+ #retainScan(workspaceId, generation, requestKey, cacheKey, snapshot) {
311
+ if ((this.#scanGenerations.get(workspaceId) ?? 0) !== generation)
312
+ return;
313
+ // Replace this request's earlier revision and drop earlier generations; keep the most
314
+ // recent other requests of this workspace.
315
+ for (const key of this.#scanCache.keys()) {
316
+ if (key.startsWith(`${requestKey}:`) ||
317
+ (key.startsWith(`${workspaceId}:`) && !key.startsWith(`${workspaceId}:${generation}:`)))
318
+ this.#scanCache.delete(key);
319
+ }
320
+ this.#scanCache.set(cacheKey, snapshot);
321
+ const retained = [...this.#scanCache.keys()].filter((key) => key.startsWith(`${workspaceId}:`));
322
+ for (const key of retained.slice(0, -SCAN_CACHE_ENTRIES_PER_WORKSPACE))
323
+ this.#scanCache.delete(key);
324
+ // Snapshots hold every file's bytes; keep all of them within twice one scan's limit.
325
+ const limit = this.resolver.config().scanMaxBytes * 2;
326
+ const bytes = (cached) => cached.files.reduce((sum, { size }) => sum + size, 0);
327
+ let retainedBytes = [...this.#scanCache.values()].reduce((sum, cached) => sum + bytes(cached), 0);
328
+ for (const [key, cached] of this.#scanCache) {
329
+ if (retainedBytes <= limit)
330
+ break;
331
+ if (key === cacheKey)
332
+ continue;
333
+ this.#scanCache.delete(key);
334
+ retainedBytes -= bytes(cached);
335
+ }
336
+ }
309
337
  invalidate(workspaceId) {
310
338
  this.#scanGenerations.set(workspaceId, (this.#scanGenerations.get(workspaceId) ?? 0) + 1);
311
339
  for (const key of this.#scanCache.keys()) {
@@ -322,6 +350,7 @@ export class CoreEngine {
322
350
  /** Drop completed scan buffers without invalidating revisions or interrupting active scans. */
323
351
  releaseScanCaches() {
324
352
  this.#scanCache.clear();
353
+ this.#latestIndexes.clear();
325
354
  this.indexSegments.clear();
326
355
  sourceDocuments.clear();
327
356
  this.scanner.clearCaches();
@@ -127,6 +127,7 @@ export function refreshManagedOutputs(input) {
127
127
  const dropped = [];
128
128
  const keptEdited = [];
129
129
  const unchanged = [];
130
+ const unscanned = [];
130
131
  const operationIds = new Set();
131
132
  const next = [];
132
133
  for (const entry of parseManifest(bytes)) {
@@ -147,8 +148,19 @@ export function refreshManagedOutputs(input) {
147
148
  for (const id of change.operationIds)
148
149
  operationIds.add(id);
149
150
  }
150
- else if (input.adoptAll === true)
151
- current = source === undefined ? null : source.bytes;
151
+ else if (input.adoptAll === true) {
152
+ // A file the scan did not read is not a file that is gone: keep its entry.
153
+ if (source === undefined && input.alwaysScanned?.(entry.relativePath) === true) {
154
+ dropped.push(entry.relativePath);
155
+ continue;
156
+ }
157
+ if (source === undefined) {
158
+ unscanned.push(entry.relativePath);
159
+ next.push(entry);
160
+ continue;
161
+ }
162
+ current = source.bytes;
163
+ }
152
164
  else {
153
165
  next.push(entry);
154
166
  continue;
@@ -164,13 +176,52 @@ export function refreshManagedOutputs(input) {
164
176
  refreshed.push(entry.relativePath);
165
177
  next.push({ relativePath: entry.relativePath, sha256 });
166
178
  }
167
- const changed = refreshed.length > 0 || dropped.length > 0;
179
+ // Files the request creates at managed paths, and on request the ones already on disk.
180
+ const added = [];
181
+ const recorded = new Set(next.map(({ relativePath }) => key(relativePath)));
182
+ for (const entry of dropped)
183
+ recorded.add(key(entry));
184
+ const addable = input.addable;
185
+ if (addable !== undefined) {
186
+ const candidates = new Map();
187
+ if (input.adoptUnrecorded === true)
188
+ for (const [name, file] of sources)
189
+ candidates.set(name, {
190
+ relativePath: file.relativePath.replaceAll('\\', '/'),
191
+ bytes: file.bytes,
192
+ ids: [],
193
+ });
194
+ for (const [name, change] of proposed) {
195
+ if (change.content === null) {
196
+ candidates.delete(name);
197
+ continue;
198
+ }
199
+ // A change to an existing unrecorded file is not a creation unless adoption was asked for.
200
+ if (!sources.has(name) || input.adoptUnrecorded === true)
201
+ candidates.set(name, {
202
+ relativePath: change.relativePath.replaceAll('\\', '/'),
203
+ bytes: change.content,
204
+ ids: [...change.operationIds],
205
+ });
206
+ }
207
+ for (const [name, candidate] of [...candidates].sort(([a], [b]) => compareCodeUnits(a, b))) {
208
+ if (name === manifestKey || recorded.has(name) || !addable(candidate.relativePath))
209
+ continue;
210
+ next.push({ relativePath: candidate.relativePath, sha256: sha256Bytes(candidate.bytes) });
211
+ added.push(candidate.relativePath);
212
+ for (const id of candidate.ids)
213
+ operationIds.add(id);
214
+ }
215
+ }
216
+ const changed = refreshed.length > 0 || dropped.length > 0 || added.length > 0;
168
217
  return {
169
218
  content: changed ? manifestBytes(next) : undefined,
219
+ added: added.sort(compareCodeUnits),
170
220
  refreshed: refreshed.sort(compareCodeUnits),
171
221
  dropped: dropped.sort(compareCodeUnits),
172
222
  keptEdited: keptEdited.sort(compareCodeUnits),
173
223
  unchanged: unchanged.sort(compareCodeUnits),
224
+ unscanned: unscanned.sort(compareCodeUnits),
174
225
  operationIds: [...operationIds].sort(compareCodeUnits),
175
226
  };
176
227
  }
@@ -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));