hoi4-agent-tools 4.8.0 → 4.9.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 (79) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/dist/hoi4_agent_tools/core/index.js +28 -0
  3. package/dist/hoi4_agent_tools/decision/service.js +39 -2
  4. package/dist/hoi4_agent_tools/event/queries.js +25 -2
  5. package/dist/hoi4_agent_tools/event/service.js +66 -11
  6. package/dist/hoi4_agent_tools/impact/service.js +15 -0
  7. package/dist/hoi4_agent_tools/map/appearance-validation.js +14 -2
  8. package/dist/hoi4_agent_tools/map/geography/resolve.js +3 -2
  9. package/dist/hoi4_agent_tools/map/tool-operations.js +41 -0
  10. package/dist/hoi4_agent_tools/map/world-edge.js +117 -15
  11. package/dist/hoi4_agent_tools/map/world.js +158 -34
  12. package/dist/hoi4_agent_tools/mcp/server/argument-errors.js +57 -9
  13. package/dist/hoi4_agent_tools/mcp/server/create-modern-operations.js +1 -1
  14. package/dist/hoi4_agent_tools/mcp/server/request-lifecycle.js +1 -1
  15. package/dist/hoi4_agent_tools/mcp/tools/analysis.js +4 -2
  16. package/dist/hoi4_agent_tools/mcp/tools/event.js +13 -0
  17. package/dist/hoi4_agent_tools/mcp/tools/gui.js +1 -1
  18. package/dist/hoi4_agent_tools/mcp/tools/reference.js +25 -0
  19. package/dist/hoi4_agent_tools/reference/error-log.js +35 -1
  20. package/dist/hoi4_agent_tools/reference/operations.js +141 -14
  21. package/dist/hoi4_agent_tools/reference/script-validation.js +113 -2
  22. package/dist/hoi4_agent_tools/schemas/ideas.js +4 -4
  23. package/dist/hoi4_agent_tools/schemas/map.js +32 -4
  24. package/dist/hoi4_agent_tools/schemas/script-validation.js +8 -1
  25. package/dist/hoi4_agent_tools/schemas/system.js +157 -0
  26. package/dist/hoi4_agent_tools/system/inspect.js +55 -0
  27. package/dist/hoi4_agent_tools/version.js +1 -1
  28. package/docs/analysis.md +2 -2
  29. package/docs/events.md +1 -1
  30. package/docs/map.md +19 -8
  31. package/docs/tools.md +49 -43
  32. package/engine/README.md +9 -0
  33. package/engine/bin/darwin-arm64/hoi4-engine +0 -0
  34. package/engine/bin/linux-arm64/hoi4-engine +0 -0
  35. package/engine/bin/linux-x64/hoi4-engine +0 -0
  36. package/engine/bin/manifest.json +8 -8
  37. package/engine/bin/win32-x64/hoi4-engine.exe +0 -0
  38. package/npm-shrinkwrap.json +2 -2
  39. package/package.json +1 -1
  40. package/schemas/configuration.schema.json +1 -1
  41. package/schemas/continuous-focus-palette.schema.json +1 -1
  42. package/schemas/custom-weighted-pool.schema.json +1 -1
  43. package/schemas/decision-inspect-input.schema.json +1 -1
  44. package/schemas/error-log-input.schema.json +1 -1
  45. package/schemas/event-feature-manifest.schema.json +1 -1
  46. package/schemas/focus-plan.schema.json +1 -1
  47. package/schemas/focus-planning-sidecar.schema.json +1 -1
  48. package/schemas/geography-model.schema.json +1 -1
  49. package/schemas/gui-animation-source.schema.json +1 -1
  50. package/schemas/gui-helper.schema.json +1 -1
  51. package/schemas/gui-scenario.schema.json +1 -1
  52. package/schemas/helper-expansion-request.schema.json +1 -1
  53. package/schemas/helper-expansion-summary.schema.json +1 -1
  54. package/schemas/impact-inspect-input.schema.json +1 -1
  55. package/schemas/map-operation.schema.json +165 -101
  56. package/schemas/mechanic-test-input.schema.json +1 -1
  57. package/schemas/mod-index-input.schema.json +1 -1
  58. package/schemas/operation-result.schema.json +1 -1
  59. package/schemas/package-check-input.schema.json +1 -1
  60. package/schemas/package-manifest.schema.json +1 -1
  61. package/schemas/probability-analysis-result.schema.json +1 -1
  62. package/schemas/probability-compare-input.schema.json +1 -1
  63. package/schemas/probability-evaluate-input.schema.json +1 -1
  64. package/schemas/probability-inspect-input.schema.json +1 -1
  65. package/schemas/probability-render-input.schema.json +1 -1
  66. package/schemas/probability-scenario-set.schema.json +1 -1
  67. package/schemas/probability-sequence-input.schema.json +1 -1
  68. package/schemas/probability-simulate-input.schema.json +1 -1
  69. package/schemas/probability-sweep-input.schema.json +1 -1
  70. package/schemas/reference-context-input.schema.json +1 -1
  71. package/schemas/reference-read-input.schema.json +1 -1
  72. package/schemas/reference-search-input.schema.json +1 -1
  73. package/schemas/reference-sheets.schema.json +1 -1
  74. package/schemas/scenario-suite.schema.json +1 -1
  75. package/schemas/scenario-test-input.schema.json +1 -1
  76. package/schemas/script-validate-input.schema.json +1 -1
  77. package/schemas/shared-scenario.schema.json +1 -1
  78. package/schemas/source-lookup-input.schema.json +1 -1
  79. package/server.json +2 -2
package/CHANGELOG.md CHANGED
@@ -2,6 +2,16 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ ## 4.9.0 - 2026-11-05
6
+
7
+ - Results no longer suggest the wrong conclusion (#65, the parts #82 left open). `error_log` fails a new `error-log-age` check when the mod's script, localisation or interface files changed after the log was written, and names how many, the newest time and an example file, because such a log cannot vouch for the current source. `script_validate` names what made a result partial (`partialReasons`), for example the blocks of a scripted helper file whose scope depends on the caller, by line, so `SCRIPT_CHECK_PARTIAL` with `unresolvedCount: 0` no longer comes without a reason. Every example in a tool description or an argument error is now checked against the tool's own schema in a test. That found and fixed the `gui_rewrite` patch example, which lacked the required `description`, and the `gui_rewrite` and `mechanic_test` examples, which held `...` placeholders. An unknown field in the arguments now lists the fields that object accepts. The tools list budget in the discovery test moves from 80 to 84 KiB for the longer, runnable examples.
8
+ - Apply every selector, and answer unknown ids with an explicit not-found instead of `ok` with nothing (#59). `event_inspect` checks its selector in every mode: an event, namespace, node or source that nothing matches is `EVENT_NOT_FOUND`, `EVENT_NAMESPACE_NOT_FOUND`, `EVENT_NODE_NOT_FOUND` or `EVENT_SOURCE_NOT_FOUND` with close names. `roots` keeps only the selected events, the entry points that start them and the cycles through them. It now counts an event a scripted effect fires as called, so such events are no longer listed as callerless. `state_flow` narrows its issues and summary to the `stateSubject`, puts the subject's producers and readers inline, and answers `EVENT_STATE_NOT_FOUND` for a flag, variable or target nothing uses. A `decision_inspect` inventory with an `id` lists only that category's decisions, or that one decision, with their ids inline, and any other id is `DECISION_NOT_FOUND`. `impact_inspect` answers `IMPACT_SYMBOL_NOT_FOUND` for a symbol nothing defines or uses, instead of dropping it. `map_inspect` answers `MAP_ENTITY_ID_NOT_FOUND` when none of the requested state, province or region ids exists, before any validation or render. A selection with some known ids still reports the unknown ones.
9
+ - `script_validate` checks identifier arguments against the definitions of the mod, its dependencies and the game (#68): ideas (`add_ideas`, `remove_ideas`, `has_idea`, `add_timed_idea`, `modify_timed_idea`), decisions (`activate_decision`, `activate_targeted_decision`), focuses (`has_completed_focus`, `complete_national_focus`, `uncomplete_national_focus`), technologies (`has_tech`) and events (`country_event`, `news_event`, `state_event`, `unit_leader_event`, `operative_leader_event`). An id that nothing defines is `SCRIPT_ARGUMENT_UNKNOWN_ID` with up to three close names, and `parametersChecked` is true. It is a warning, because the game loads the file and the command does nothing, as five dangling ids in vanilla 1.19.4.1 show. Ids match without case, as the game finds them (vanilla fires `NSB_news.2` for `nsb_news.2`). Computed values are not read, and a partial index reports `unresolved` instead. The index now holds shared and joint focuses and the ideas that advisors' `idea_token`s make. The known-good sweeps of vanilla, Chaos Redux, ZIN, Ireland Total Overhaul, Kaiserreich and Old World Blues raise no new error.
10
+ - Add `hoi4.asset_inspect` on the shared Rust engine (`hoi4-engine assets`; coverage tools part 5, issue #71). One tool reads sprites, sounds and flags. A sprite comes back with every definition in load order, its texture with layer, container, pixel format, size and mipmaps, and its frames. A sound, sound effect, category or music track comes back with its audio file (relative to its `.asset` file's folder) and the sounds or sound effects it plays. A flag comes back with its three files (82x52, `medium/` 41x26 and `small/` 10x7). Each answer lists the files that mention the asset. `audit: true` checks every sprite, sound or flag the mod defines, and the flag audit also reports country tags of the mod with no flag at all (dynamic tags excepted). Missing and unreadable textures, BC7 textures (`ASSET_TEXTURE_FORMAT_RISKY`, after an in-game crash on 1.19.4.1), missing audio files, unknown sounds and wrong flag sizes are warnings. Uneven frames, sprites without a texture that the game fills itself, empty texture files that hide a picture and flags one pixel off are information. Texture headers are now read by content, so PNG files named `.dds` read as PNG, as the game reads them. On vanilla 1.19.4.1, Chaos Redux, ZIN, Ireland Total Overhaul, Kaiserreich and Old World Blues every warning was checked by hand. Vanilla's are real: six sound files saved under other names, three flags of the wrong size and a placeholder flag with one size.
11
+ - Add `hoi4.unit_inspect` on the shared Rust engine (`hoi4-engine units`; coverage tools part 4, issue #71). One tool reads orders of battle (`history/units` files), sub-units, equipment and equipment modules, and equipment variants. One id comes back with every definition in load order, its parts (templates, fleets, module slots), each name it uses with whether something defines it, its name and description in every language, and the files that mention it. `audit: true` checks every one the mod makes. An order of battle's templates must fit the division designer's grid, read from the `MAX_DIVISION_` defines so a mod that changes the grid is judged by its own, and no two sub-units may share a slot. Its divisions, fleets and air wings must name templates (from any order of battle or the `division_template` effect), sub-units, equipment, variants, provinces, states or carriers that load. Equipment must name known archetypes, parents, upgrades, resources, module categories and default modules, and a variant known equipment, modules and upgrades. Equipment that a `duplicate_archetypes` copy derives counts as defined. The audit of orders of battle also reports `oob`, `set_oob` and `load_oob` names that no `history/units` file has. A missing name is information. An unknown id is `UNIT_DEFINITION_NOT_FOUND` with close ids. On vanilla 1.19.4.1, Chaos Redux, ZIN, Ireland Total Overhaul, Kaiserreich and Old World Blues every finding was checked by hand. Vanilla still has real ones: two regiments in one slot in `CZE_1936`, `oob` names of countries without a file, and division name groups lost to unbalanced quotes in `FIN_names_divisions.txt`. An audit takes 5 to 40 s with a cold file cache.
12
+ - Add `hoi4.system_inspect` on the shared Rust engine (`hoi4-engine system`; coverage tools part 3, issue #71). One tool reads the newer systems: on_actions hooks, military-industrial organizations and their policies, balances of power, special projects with their prototype rewards, specializations and project tags, operations with their phases and tokens, and raids with their categories. One id comes back with every definition in load order, its fields as written, its parts (traits, ranges, sides, options, phases), each reference it makes with whether something defines the target, its name and description in every language, and the files that mention it. `audit: true` checks every definition of that system the mod makes. The checks follow the documentation in each game folder, corrected where the shipped files differ: an organization's include, removed and overridden traits and trait parents, duplicate trait tokens, pictures, and modifiers; a balance of power's sides and ranges; a project's specialization, tags, parents, rewards and the equipment, modules and sub-units it enables; an operation's phases, tokens and equipment; a raid's category, sub-units and target buildings; the events an on_actions hook fires; and the hooks a mod drops by replacing an on_actions file. A hook that neither the documentation, the game's own files nor its executable uses, and a missing name, are information. A balance of power's `decision_category` creates its category, so it is not checked. An unknown id is `SYSTEM_DEFINITION_NOT_FOUND` with close ids. On vanilla 1.19.4.1, Chaos Redux, ZIN, Ireland Total Overhaul, Kaiserreich and Old World Blues no warning remains and every finding was checked by hand. An audit takes 2 to 12 s with a warm file cache.
13
+ - Close the world seam for fleets as well as armies: `create_world.edge.mode: "wall"` (ADR 0061, amended). A `rim` blocks land provinces across the seam but leaves the sea there sailable, so ships crossed from the far west to the far east. A wall fills `rimPx` (default 48) at the east and west edges with land over the full height (`MAP_EDGE_WALL_FILLED`), with a ragged inner edge, the rim's heights and seam rows, and the look of the land it meets row by row (or caller `wallTerrain` segments), and puts its provinces in impassable `enclave` states linked by `force_link_ownership_to` to the nearest passable state, as the base game's impassable states are. Cities and workspace capitals in the wall are refused, and validation reports water on the seam columns of a wall world as `MAP_EDGE_WALL_OPEN`. `polarPx: 0` lets land run off the top and bottom edges.
14
+
5
15
  ## 4.8.0 - 2026-11-05
6
16
 
7
17
  - Ship `hoi4-engine` inside the npm package and the container image (ADR 0074, amended): the release builds it for Windows x64, macOS arm64 and Linux x64 and arm64 (glibc 2.35 or later) and bundles every platform under `engine/bin/` with a SHA-256 manifest, so `layoutMode: "engine"`, `placement` and the engine checks work after a plain install. The bundled binary runs only when its SHA-256 matches `engine/bin/manifest.json`; otherwise the call reports `binary_checksum_mismatch` and nothing runs. `HOI4_ENGINE` still wins, and other platforms report the engine unavailable as before. Each image holds the binary for its own architecture. The package grows by about 4 MB.
@@ -594,6 +594,20 @@ export class SymbolIndex {
594
594
  for (const assignment of assignments(block)) {
595
595
  const key = assignment.key.value;
596
596
  if (assignment.value.type !== 'block') {
597
+ // An advisor's `idea_token` is the idea that `add_ideas` and `has_idea` name.
598
+ if (key === 'idea_token' &&
599
+ sourcePath.startsWith('common/characters/') &&
600
+ ancestors.at(-1) === 'advisor') {
601
+ this.addSymbol({
602
+ kind: 'idea',
603
+ id: assignment.value.value,
604
+ path: file.displayPath,
605
+ rootKind: file.rootKind,
606
+ loadOrder: file.loadOrder,
607
+ location: nodeLocation(document, assignment, assignment.value.value),
608
+ metadata: { advisor: true },
609
+ });
610
+ }
597
611
  if (sourcePath.startsWith('common/script_constants/') &&
598
612
  key !== 'schema' &&
599
613
  !ancestors.includes('schema')) {
@@ -918,6 +932,20 @@ export class SymbolIndex {
918
932
  location: nodeLocation(document, icon, id),
919
933
  });
920
934
  }
935
+ else if ((key === 'shared_focus' || key === 'joint_focus') &&
936
+ id !== undefined &&
937
+ ancestors.length === 0) {
938
+ // Shared and joint focuses sit outside any tree; trees add them with `shared_focus = <id>`.
939
+ this.addSymbol({
940
+ kind: 'focus',
941
+ id,
942
+ path: file.displayPath,
943
+ rootKind: file.rootKind,
944
+ loadOrder: file.loadOrder,
945
+ location: nodeLocation(document, assignment, id),
946
+ metadata: { shared: key },
947
+ });
948
+ }
921
949
  else if (key === 'focus' && id !== undefined && ancestors.at(-1) === 'focus_tree') {
922
950
  this.addSymbol({
923
951
  kind: 'focus',
@@ -8,7 +8,34 @@ import { nearestNames } from '../reference/suggestions.js';
8
8
  import { PACKAGE_VERSION } from '../version.js';
9
9
  import { inspectDecisionAi } from './ai.js';
10
10
  import { compareDecisionScenarios, inspectDecisionScenario } from './comparison.js';
11
- import { decisionSourceInventory, decisionTargetCatalog } from './source-inventory.js';
11
+ import { decisionSourceInventory, decisionTargetCatalog, } from './source-inventory.js';
12
+ /**
13
+ * An inventory narrowed to one category (its decisions) or one decision (#59). Any other id is
14
+ * not-found with close names, never a whole-workspace inventory.
15
+ */
16
+ function scopedInventory(inventory, id, complete) {
17
+ const ids = new Set([id]);
18
+ const isCategory = inventory.categories.some((category) => category.id === id);
19
+ const decisions = inventory.decisions.filter((source) => isCategory ? source.category === id : source.id === id);
20
+ if (!isCategory && decisions.length === 0) {
21
+ const suggestions = nearestNames(id, new Set([
22
+ ...inventory.categories.map((category) => category.id),
23
+ ...inventory.decisions.map((source) => source.id),
24
+ ]));
25
+ throw new ServiceError('DECISION_NOT_FOUND', `No decision or decision category ${id.slice(0, 256)} is defined${complete ? '' : ' in the scanned files (the scan is incomplete)'}${suggestions.length === 0 ? '' : `; did you mean ${suggestions.join(', ')}?`}`, { id: id.slice(0, 256), suggestions, scanComplete: complete });
26
+ }
27
+ for (const source of decisions) {
28
+ ids.add(source.category);
29
+ ids.add(source.id);
30
+ }
31
+ return {
32
+ ...inventory,
33
+ decisions,
34
+ categories: inventory.categories.filter((category) => ids.has(category.id)),
35
+ overrides: inventory.overrides.filter((override) => ids.has(override.id)),
36
+ unresolvedDefinitions: inventory.unresolvedDefinitions.filter((entry) => ids.has(entry.id)),
37
+ };
38
+ }
12
39
  /** Authorized, read-only decision operation over the shared source scanner. */
13
40
  export class DecisionAnalyzer {
14
41
  engine;
@@ -33,7 +60,10 @@ export class DecisionAnalyzer {
33
60
  throw new ServiceError('DECISION_PROPOSAL_REQUIRED', 'Decision comparison requires proposed sources');
34
61
  if (input.mode !== 'compare' && input.proposedSources !== undefined)
35
62
  throw new ServiceError('DECISION_PROPOSAL_MODE', 'Proposed sources require compare mode');
36
- const inventory = decisionSourceInventory(before);
63
+ const fullInventory = decisionSourceInventory(before);
64
+ const inventory = input.mode === 'inventory' && input.id !== undefined
65
+ ? scopedInventory(fullInventory, input.id, before.complete)
66
+ : fullInventory;
37
67
  if (input.mode === 'inspect' &&
38
68
  input.id !== undefined &&
39
69
  !inventory.decisions.some((source) => source.id === input.id)) {
@@ -156,6 +186,13 @@ export class DecisionAnalyzer {
156
186
  categories: inventory.categories.length,
157
187
  overrides: inventory.overrides.length,
158
188
  scenarios: input.mode === 'inventory' ? 0 : input.scenarios.length,
189
+ // A scoped inventory answers inline: the decisions of that category or the one decision.
190
+ ...(input.mode === 'inventory' && input.id !== undefined
191
+ ? {
192
+ decisionIds: inventory.decisions.slice(0, 64).map(({ id }) => id),
193
+ decisionIdsTruncated: inventory.decisions.length > 64,
194
+ }
195
+ : {}),
159
196
  unresolvedDefinitions: inventory.unresolvedDefinitions.length,
160
197
  ...(inventory.unresolvedDefinitions.length === 0
161
198
  ? {}
@@ -103,11 +103,34 @@ export function selectEventNodes(graph, selector, signal) {
103
103
  signal?.throwIfAborted();
104
104
  return matched.sort((left, right) => compareCodeUnits(left.id, right.id));
105
105
  }
106
- export function discoverEventRoots(graph, signal) {
106
+ export function discoverEventRoots(graph, signal, selector) {
107
+ const roots = allEventRoots(graph, signal);
108
+ if (selector === undefined)
109
+ return roots;
110
+ // A selector keeps the roots among its nodes, the entry points that start them and the
111
+ // cycles through them (#59).
112
+ const selected = new Set(selectEventNodes(graph, selector, signal).map(({ id }) => id));
113
+ const startsSelected = new Set(eventFlowEdges(graph, false)
114
+ .filter(({ to }) => selected.has(to))
115
+ .map(({ from }) => from));
116
+ const ids = new Set(graph.nodes
117
+ .filter(({ id, kind }) => kind === 'event' && selected.has(id))
118
+ .flatMap(({ eventId }) => (eventId === undefined ? [] : [eventId])));
119
+ return {
120
+ entryPoints: roots.entryPoints.filter(({ id }) => selected.has(id) || startsSelected.has(id)),
121
+ automaticEvents: roots.automaticEvents.filter(({ id }) => selected.has(id)),
122
+ knownRootEventIds: roots.knownRootEventIds.filter((id) => ids.has(id)),
123
+ callerlessTriggeredEvents: roots.callerlessTriggeredEvents.filter(({ id }) => selected.has(id)),
124
+ stronglyConnectedComponents: roots.stronglyConnectedComponents.filter(({ nodeIds }) => nodeIds.some((id) => selected.has(id))),
125
+ };
126
+ }
127
+ function allEventRoots(graph, signal) {
107
128
  signal?.throwIfAborted();
108
129
  const edges = eventFlowEdges(graph, false);
109
130
  const incoming = new Map();
110
- for (const [index, edge] of edges.entries()) {
131
+ // An event a scripted effect fires has a caller. Roots do not project helpers, so count the
132
+ // direct edges too, helper edges included.
133
+ for (const [index, edge] of [...edges, ...eventFlowEdges(graph, true)].entries()) {
111
134
  if ((index & 255) === 0)
112
135
  signal?.throwIfAborted();
113
136
  incoming.set(edge.to, (incoming.get(edge.to) ?? 0) + 1);
@@ -271,6 +271,25 @@ function boundedEvidence(values, limit = EVENT_FOCUSED_EVIDENCE_LIMIT) {
271
271
  inventory: { count: values.length, retainedCount: limit, truncated: true },
272
272
  };
273
273
  }
274
+ /** The not-found for a selector no scanned node matches, with close names where there are any. */
275
+ function selectorNotFound(graph, selector) {
276
+ const close = (value, names) => nearestNames(value, new Set([...names].filter((name) => name !== undefined)));
277
+ const hint = (suggestions) => suggestions.length === 0 ? '' : `; did you mean ${suggestions.join(', ')}?`;
278
+ switch (selector.kind) {
279
+ case 'event': {
280
+ const suggestions = close(selector.eventId, graph.nodes.map(({ eventId }) => eventId));
281
+ return new ServiceError('EVENT_NOT_FOUND', `No scanned file defines or fires event ${selector.eventId.slice(0, 256)}${hint(suggestions)}`, { eventId: selector.eventId.slice(0, 256), suggestions });
282
+ }
283
+ case 'namespace': {
284
+ const suggestions = close(selector.namespace, graph.nodes.map(({ namespace }) => namespace));
285
+ return new ServiceError('EVENT_NAMESPACE_NOT_FOUND', `No scanned event belongs to the namespace ${selector.namespace.slice(0, 256)}${hint(suggestions)}`, { namespace: selector.namespace.slice(0, 256), suggestions });
286
+ }
287
+ case 'node':
288
+ return new ServiceError('EVENT_NODE_NOT_FOUND', `No node ${selector.nodeId.slice(0, 256)} is in the event graph`, { nodeId: selector.nodeId.slice(0, 256) });
289
+ default:
290
+ return new ServiceError('EVENT_SOURCE_NOT_FOUND', 'No event, option or entry point of the event graph is in the selected source', { selector: selector.kind });
291
+ }
292
+ }
274
293
  function boundedUnresolved(graph, selectedNodeIds) {
275
294
  const relevant = selectedNodeIds === undefined
276
295
  ? graph.unresolved
@@ -834,17 +853,32 @@ export class EventChainViewer {
834
853
  ...(input.impactSubject === undefined ? {} : { impactSubject: input.impactSubject }),
835
854
  refresh: input.refresh ?? input.mode === 'scan',
836
855
  };
856
+ // A selector or state subject that matches nothing is not-found, never an empty answer (#59).
857
+ if (input.selector !== undefined &&
858
+ input.mode !== 'impact' &&
859
+ selectEventNodes(graph, input.selector).length === 0)
860
+ throw selectorNotFound(graph, input.selector);
861
+ if (input.mode === 'state_flow' &&
862
+ input.stateSubject !== undefined &&
863
+ !graph.stateAccesses.some(({ kind, name }) => kind === input.stateSubject.kind && name === input.stateSubject.name)) {
864
+ const { kind, name } = input.stateSubject;
865
+ const suggestions = nearestNames(name, new Set(graph.stateAccesses.filter((access) => access.kind === kind).map((a) => a.name)));
866
+ throw new ServiceError('EVENT_STATE_NOT_FOUND', `No scanned file sets, checks or clears the ${kind.replaceAll('_', ' ')} ${name.slice(0, 256)}${suggestions.length === 0 ? '' : `; did you mean ${suggestions.join(', ')}?`}`, { kind, name: name.slice(0, 256), suggestions });
867
+ }
837
868
  let report;
838
869
  let summary;
839
870
  switch (input.mode) {
840
871
  case 'scan':
841
872
  report = eventScanReport(graph);
842
- summary = summarizeEventIssues(graph.issues);
873
+ // A selector narrows the findings to its events, as lint does (#59).
874
+ summary = summarizeEventIssues(input.selector === undefined
875
+ ? graph.issues
876
+ : lintEventGraph(graph, input.selector, input.signal));
843
877
  break;
844
878
  case 'roots':
845
879
  {
846
880
  const unresolved = boundedUnresolved(graph);
847
- const roots = discoverEventRoots(graph, input.signal);
881
+ const roots = discoverEventRoots(graph, input.signal, input.selector);
848
882
  summary = summarizeEventRoots(roots);
849
883
  report = {
850
884
  graphRevision: graph.revision,
@@ -860,12 +894,6 @@ export class EventChainViewer {
860
894
  case 'trace':
861
895
  if (input.selector === undefined)
862
896
  throw new ServiceError('EVENT_SELECTOR_REQUIRED', 'Trace requires a selector');
863
- if (input.selector.kind === 'event' &&
864
- selectEventNodes(graph, input.selector).length === 0) {
865
- // An event no file defines or fires is not-found, never an empty trace.
866
- const suggestions = nearestNames(input.selector.eventId, new Set(graph.nodes.flatMap(({ eventId }) => (eventId === undefined ? [] : [eventId]))));
867
- throw new ServiceError('EVENT_NOT_FOUND', `No scanned file defines or fires event ${input.selector.eventId.slice(0, 256)}${suggestions.length === 0 ? '' : `; did you mean ${suggestions.join(', ')}?`}`, { eventId: input.selector.eventId.slice(0, 256), suggestions });
868
- }
869
897
  {
870
898
  const trace = traceSelectedEvents(graph, input.selector, {
871
899
  maxDepth,
@@ -906,13 +934,40 @@ export class EventChainViewer {
906
934
  case 'state_flow':
907
935
  {
908
936
  const unresolved = boundedUnresolved(graph);
909
- const stateIssues = lintEventGraph(graph, input.selector, input.signal).filter(({ code }) => /(?:STATE|FLAG|VARIABLE|ARRAY|TARGET|SCOPE|WRITER)/u.test(code));
910
- summary = summarizeEventIssues(stateIssues);
937
+ const subject = input.stateSubject;
938
+ const stateIssues = lintEventGraph(graph, input.selector, input.signal).filter(({ code, details }) => /(?:STATE|FLAG|VARIABLE|ARRAY|TARGET|SCOPE|WRITER)/u.test(code) &&
939
+ // A subject narrows the issues as well as the flow. Analysis limits stay, because
940
+ // they make the flow partial.
941
+ (subject === undefined ||
942
+ (typeof details.name === 'string'
943
+ ? details.name === subject.name &&
944
+ (details.stateKind === undefined || details.stateKind === subject.kind)
945
+ : code.endsWith('_LIMIT'))));
946
+ const flow = inspectEventStateFlow(graph, input.selector, input.stateSubject, input.signal);
947
+ const where = (accesses) => accesses.slice(0, 8).map(({ location }) => `${location.path}:${location.start.line}`);
948
+ summary = {
949
+ ...summarizeEventIssues(stateIssues),
950
+ // The subject's own flow answers inline; the report holds every access.
951
+ ...(subject === undefined
952
+ ? {}
953
+ : {
954
+ flow: {
955
+ subject: `${subject.kind}:${subject.name}`,
956
+ producers: flow.producers.length,
957
+ consumers: flow.consumers.length,
958
+ clears: flow.clears.length,
959
+ links: flow.links.length,
960
+ unproducedReads: flow.unproducedReads.length,
961
+ producedAt: where(flow.producers),
962
+ readAt: where(flow.consumers),
963
+ },
964
+ }),
965
+ };
911
966
  const issues = boundedEvidence(stateIssues);
912
967
  report = {
913
968
  graphRevision: graph.revision,
914
969
  sourceHashes: graph.sourceHashes,
915
- flow: inspectEventStateFlow(graph, input.selector, input.stateSubject, input.signal),
970
+ flow,
916
971
  issues: issues.values,
917
972
  unresolved: unresolved.values,
918
973
  ...(issues.inventory === undefined ? {} : { issueInventory: issues.inventory }),
@@ -6,6 +6,7 @@ import { inspectImpactGraph } from '../core/impact-graph.js';
6
6
  import { setInlineFilesScanned } from '../core/operation-result.js';
7
7
  import { emptyServiceResult, ServiceError } from '../core/result.js';
8
8
  import { buildProposedSourceOverlay } from '../core/source-overlay.js';
9
+ import { nearestNames } from '../reference/suggestions.js';
9
10
  import { PACKAGE_VERSION } from '../version.js';
10
11
  import { inspectImpactScenarioSuites } from './scenario-suites.js';
11
12
  /** Authorized, read-only impact operation shared by ordinary calls and persistent jobs. */
@@ -35,6 +36,20 @@ export class ImpactAnalyzer {
35
36
  for (const file of input.changedFiles)
36
37
  if (!availablePaths.has(file))
37
38
  throw new ServiceError('IMPACT_SOURCE_UNKNOWN', 'Changed file is not in the authorized source inventory or proposed overlay', { file });
39
+ // A symbol that nothing defines or names would answer an empty graph; say so instead (#59).
40
+ const indexes = [before.index, ...(overlay === undefined ? [] : [overlay.snapshot.index])];
41
+ const unknown = input.symbols.filter(({ kind, id }) => !indexes.some((index) => index.find(kind, id) !== undefined ||
42
+ index.references.some((reference) => reference.toKind === kind && reference.to === id)));
43
+ if (unknown.length > 0) {
44
+ const symbols = unknown.map(({ kind, id }) => ({
45
+ kind,
46
+ id: id.slice(0, 256),
47
+ suggestions: nearestNames(id, new Set(before.index.findAll(kind).map((symbol) => symbol.id))),
48
+ }));
49
+ throw new ServiceError('IMPACT_SYMBOL_NOT_FOUND', `Nothing defines or uses ${symbols
50
+ .map(({ kind, id, suggestions }) => `${kind} ${id}${suggestions.length === 0 ? '' : ` (did you mean ${suggestions.join(', ')}?)`}`)
51
+ .join('; ')}${before.complete ? '' : ' in the scanned files (the scan is incomplete)'}`, { symbols, scanComplete: before.complete });
52
+ }
38
53
  const query = {
39
54
  symbols: input.symbols,
40
55
  changedFiles: input.changedFiles.length > 0
@@ -1046,11 +1046,23 @@ function* validateLakesAndEdge(index, raster, report, options) {
1046
1046
  pairs.add(`${Math.min(a, b)}:${Math.max(a, b)}`);
1047
1047
  }
1048
1048
  }
1049
- if (rows > 0)
1049
+ // A wall closes the seam with land on purpose; there, water at the seam is the defect.
1050
+ if (options.edgeMode === 'wall') {
1051
+ const open = height * 2 - left - right;
1052
+ if (open > 0)
1053
+ report({
1054
+ code: 'MAP_EDGE_WALL_OPEN',
1055
+ severity: 'error',
1056
+ message: `Water reaches the first or last column at ${open} pixels (${height - left} on the west edge, ${height - right} on the east); ships can cross the seam there`,
1057
+ location,
1058
+ details: { west: height - left, east: height - right },
1059
+ });
1060
+ }
1061
+ else if (rows > 0)
1050
1062
  report({
1051
1063
  code: 'MAP_EDGE_LAND_CUT',
1052
1064
  severity: options.edgeMode === 'sea-band' ? 'error' : 'warning',
1053
- message: `Land touches the first or last column on ${rows} rows (${left} on the west edge, ${right} on the east); where the world wraps, the coast is cut by a straight vertical line. Use edge.mode "sea-band" or "rim"`,
1065
+ message: `Land touches the first or last column on ${rows} rows (${left} on the west edge, ${right} on the east); where the world wraps, the coast is cut by a straight vertical line. Use edge.mode "sea-band", "rim" or "wall"`,
1054
1066
  location,
1055
1067
  details: { rows, west: left, east: right, firstRows: rowSamples },
1056
1068
  });
@@ -1421,8 +1421,9 @@ function coarseChecks(input) {
1421
1421
  }
1422
1422
  function edgeChecks(input) {
1423
1423
  const { frame, edgeBand, sink, grid } = input;
1424
- // A rim wall ends land inside the band by design, and `none` opts out of the check.
1425
- if (input.policy?.mode === 'none' || input.policy?.mode === 'rim')
1424
+ // A rim or wall ends land inside the band by design, and `none` opts out of the check.
1425
+ const mode = input.policy?.mode;
1426
+ if (mode === 'none' || mode === 'rim' || mode === 'wall')
1426
1427
  return;
1427
1428
  const severity = input.policy?.mode === 'sea-band' ? 'error' : 'warning';
1428
1429
  const fx = edgeBand.westEastPx / frame.width;
@@ -140,6 +140,43 @@ function mapArtifactSourceEvidence(files) {
140
140
  const complete = Object.fromEntries(files.map(({ displayPath, sha256 }) => [displayPath, sha256]));
141
141
  return { complete, bounded: boundedSourceHashEvidence(complete) };
142
142
  }
143
+ /**
144
+ * A selection whose ids the map defines none of is not-found before any work, never an ok result
145
+ * with empty records and a whole-map artifact (#59). A selection with some known ids goes on and
146
+ * reports the unknown ones (unknownProvinceIds, and a null state or region record).
147
+ */
148
+ function assertKnownMapEntities(snapshot, input) {
149
+ const index = snapshot.index;
150
+ const unknown = {
151
+ stateIds: [...new Set(input.stateIds)].filter((id) => !index.statesById.has(id)),
152
+ provinceIds: [...new Set(input.provinceIds)].filter((id) => !index.definitionsById.has(id)),
153
+ regionIds: [...new Set(input.regionIds)].filter((id) => !index.regionsById.has(id)),
154
+ };
155
+ const requested = new Set(input.stateIds).size + new Set(input.provinceIds).size + new Set(input.regionIds).size;
156
+ const unknownCount = unknown.stateIds.length + unknown.provinceIds.length + unknown.regionIds.length;
157
+ if (requested === 0 || unknownCount < requested)
158
+ return;
159
+ const highest = (ids) => {
160
+ let value = 0;
161
+ for (const id of ids)
162
+ if (id > value)
163
+ value = id;
164
+ return value;
165
+ };
166
+ const parts = [
167
+ ['state', unknown.stateIds, highest(index.statesById.keys())],
168
+ ['province', unknown.provinceIds, highest(index.definitionsById.keys())],
169
+ ['strategic region', unknown.regionIds, highest(index.regionsById.keys())],
170
+ ];
171
+ const missing = parts.filter(([, ids]) => ids.length > 0);
172
+ throw new ServiceError('MAP_ENTITY_ID_NOT_FOUND', `The map defines no ${missing
173
+ .map(([kind, ids, highest]) => `${kind} ${ids.slice(0, 16).join(', ')}${ids.length > 16 ? ' and more' : ''} (the highest ${kind} id is ${highest})`)
174
+ .join('; no ')}`, {
175
+ stateIds: unknown.stateIds.slice(0, 64),
176
+ provinceIds: unknown.provinceIds.slice(0, 64),
177
+ regionIds: unknown.regionIds.slice(0, 64),
178
+ });
179
+ }
143
180
  function selectedMapEntities(snapshot, provinceIds, stateIds, regionIds) {
144
181
  const provinces = [...new Set(provinceIds)]
145
182
  .sort((a, b) => a - b)
@@ -661,6 +698,7 @@ export async function inspectMap(engine, nudger, input, context) {
661
698
  if (input.allocationRequests.length > 0)
662
699
  throw new ServiceError('MAP_LOOKUP_ALLOCATION_UNSUPPORTED', 'Use full map inspection for identifier allocation previews');
663
700
  const snapshot = await nudger.scan(context.workspaceId, context.principal, context.signal);
701
+ assertKnownMapEntities(snapshot, input);
664
702
  const catalog = input.query === undefined ? undefined : buildMapCatalog(snapshot.index);
665
703
  const queryMatches = catalog === undefined ? [] : searchMapCatalog(catalog, input.query, input.queryLimit);
666
704
  const coordinateMatches = input.coordinates.map((coordinate) => lookupMapCoordinate(snapshot.index, coordinate));
@@ -720,6 +758,9 @@ export async function inspectMap(engine, nudger, input, context) {
720
758
  await context.progress(3, 3, 'Map lookup complete');
721
759
  return result;
722
760
  }
761
+ // Check the ids on the cached scan before the full validation.
762
+ if (input.stateIds.length + input.provinceIds.length + input.regionIds.length > 0)
763
+ assertKnownMapEntities(await nudger.scan(context.workspaceId, context.principal, context.signal), input);
723
764
  const { snapshot, validation, scriptReferences } = await nudger.validate(context.workspaceId, context.principal, context.signal, input.references, input.quality);
724
765
  const sharedRevision = snapshot.revision;
725
766
  let borderQuality;