hoi4-agent-tools 4.21.0 → 4.22.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +34 -0
- package/README.md +3 -1
- package/dist/bin/setup.js +1 -0
- package/dist/bin/stdio.js +1 -0
- package/dist/hoi4_agent_tools/common-write/documented-lists.js +62 -0
- package/dist/hoi4_agent_tools/common-write/limits.js +35 -0
- package/dist/hoi4_agent_tools/common-write/paths.js +17 -0
- package/dist/hoi4_agent_tools/common-write/write-job-operations.js +42 -0
- package/dist/hoi4_agent_tools/common-write/write-operations.js +360 -0
- package/dist/hoi4_agent_tools/common-write/write-plan.js +34 -0
- package/dist/hoi4_agent_tools/core/bounded-source.js +1 -1
- package/dist/hoi4_agent_tools/core/domain-tools.js +8 -0
- package/dist/hoi4_agent_tools/core/engine-client.js +3 -1
- package/dist/hoi4_agent_tools/core/image-diff.js +1 -1
- package/dist/hoi4_agent_tools/core/job-controls.js +12 -2
- package/dist/hoi4_agent_tools/core/job-executor.js +8 -7
- package/dist/hoi4_agent_tools/core/job-operation-registration.js +4 -0
- package/dist/hoi4_agent_tools/core/job-store.js +97 -5
- package/dist/hoi4_agent_tools/core/job-worker-host.js +2 -2
- package/dist/hoi4_agent_tools/core/lazy-native.js +26 -0
- package/dist/hoi4_agent_tools/core/operation-result.js +118 -33
- package/dist/hoi4_agent_tools/core/operation-tasks.js +1 -1
- package/dist/hoi4_agent_tools/core/svg-text.js +1 -1
- package/dist/hoi4_agent_tools/core/workspace.js +11 -1
- package/dist/hoi4_agent_tools/country/job-operations.js +42 -0
- package/dist/hoi4_agent_tools/country/write-operations.js +646 -0
- package/dist/hoi4_agent_tools/country/write-plan.js +28 -0
- package/dist/hoi4_agent_tools/event/render.js +1 -1
- package/dist/hoi4_agent_tools/focus/continuous-render.js +1 -1
- package/dist/hoi4_agent_tools/focus/game-view-output.js +1 -1
- package/dist/hoi4_agent_tools/focus/limits.js +3 -0
- package/dist/hoi4_agent_tools/focus/quality/schematic.js +1 -1
- package/dist/hoi4_agent_tools/focus/render.js +3 -3
- package/dist/hoi4_agent_tools/gui/assets.js +2 -2
- package/dist/hoi4_agent_tools/gui/limits.js +2 -0
- package/dist/hoi4_agent_tools/gui/renderer.js +1 -1
- package/dist/hoi4_agent_tools/gui/studio.js +2 -4
- package/dist/hoi4_agent_tools/map/engine-validation.js +1 -1
- package/dist/hoi4_agent_tools/map/geography/preview.js +1 -1
- package/dist/hoi4_agent_tools/map/landmass-source.js +42 -0
- package/dist/hoi4_agent_tools/map/landmass.js +190 -0
- package/dist/hoi4_agent_tools/map/operations.js +20 -6
- package/dist/hoi4_agent_tools/map/reference-import.js +1 -1
- package/dist/hoi4_agent_tools/map/reference-labels.js +1 -1
- package/dist/hoi4_agent_tools/map/reference-preparation.js +1 -1
- package/dist/hoi4_agent_tools/map/reference-world.js +1 -1
- package/dist/hoi4_agent_tools/map/references.js +6 -3
- package/dist/hoi4_agent_tools/map/render.js +1 -1
- package/dist/hoi4_agent_tools/map/service.js +88 -8
- package/dist/hoi4_agent_tools/map/world-preview.js +1 -1
- package/dist/hoi4_agent_tools/mcp/server/argument-errors.js +2 -0
- package/dist/hoi4_agent_tools/mcp/server/create-modern-operations.js +1 -1
- package/dist/hoi4_agent_tools/mcp/server/create.js +4 -0
- package/dist/hoi4_agent_tools/mcp/server/task-tool-catalog.js +4 -0
- package/dist/hoi4_agent_tools/mcp/tools/common-write.js +21 -0
- package/dist/hoi4_agent_tools/mcp/tools/country-write.js +21 -0
- package/dist/hoi4_agent_tools/mcp/tools/focus.js +3 -2
- package/dist/hoi4_agent_tools/mcp/tools/map.js +1 -1
- package/dist/hoi4_agent_tools/mcp/transports/http.js +2 -0
- package/dist/hoi4_agent_tools/probability/render.js +1 -1
- package/dist/hoi4_agent_tools/reference/known-mistakes.js +65 -0
- package/dist/hoi4_agent_tools/reference/known-mistakes.json +19 -0
- package/dist/hoi4_agent_tools/reference/operations.js +15 -2
- package/dist/hoi4_agent_tools/runtime.js +79 -1
- package/dist/hoi4_agent_tools/schemas/character-write.js +5 -1
- package/dist/hoi4_agent_tools/schemas/common-write.js +74 -0
- package/dist/hoi4_agent_tools/schemas/country-write.js +206 -0
- package/dist/hoi4_agent_tools/schemas/decision-write.js +5 -1
- package/dist/hoi4_agent_tools/schemas/doctrine-write.js +5 -1
- package/dist/hoi4_agent_tools/schemas/event-write.js +5 -1
- package/dist/hoi4_agent_tools/schemas/focus-requests.js +1 -1
- package/dist/hoi4_agent_tools/schemas/gui-requests.js +2 -1
- package/dist/hoi4_agent_tools/schemas/idea-write.js +5 -1
- package/dist/hoi4_agent_tools/schemas/landmass.js +129 -0
- package/dist/hoi4_agent_tools/schemas/localisation-write.js +10 -1
- package/dist/hoi4_agent_tools/schemas/map-requests.js +1 -1
- package/dist/hoi4_agent_tools/schemas/map.js +2 -0
- package/dist/hoi4_agent_tools/schemas/tech-write.js +5 -1
- package/dist/hoi4_agent_tools/technology/render.js +1 -1
- package/dist/hoi4_agent_tools/version.js +1 -1
- package/docs/focus.md +1 -1
- package/docs/jobs.md +2 -2
- package/docs/reference.md +10 -9
- package/docs/setup.md +13 -1
- package/docs/tools.md +16 -2
- package/engine/bin/darwin-arm64/hoi4-engine +0 -0
- package/engine/bin/darwin-x64/hoi4-engine +0 -0
- package/engine/bin/linux-arm64/hoi4-engine +0 -0
- package/engine/bin/linux-x64/hoi4-engine +0 -0
- package/engine/bin/manifest.json +13 -8
- package/engine/bin/win32-x64/hoi4-engine.exe +0 -0
- package/npm-shrinkwrap.json +43 -19
- package/package.json +1 -1
- package/schemas/configuration.schema.json +1 -1
- package/schemas/continuous-focus-palette.schema.json +1 -1
- package/schemas/custom-weighted-pool.schema.json +1 -1
- package/schemas/decision-inspect-input.schema.json +1 -1
- package/schemas/error-log-input.schema.json +1 -1
- package/schemas/event-feature-manifest.schema.json +1 -1
- package/schemas/focus-plan.schema.json +1 -1
- package/schemas/focus-planning-sidecar.schema.json +1 -1
- package/schemas/geography-model.schema.json +1 -1
- package/schemas/gui-animation-source.schema.json +1 -1
- package/schemas/gui-helper.schema.json +1 -1
- package/schemas/gui-scenario.schema.json +1 -1
- package/schemas/helper-expansion-request.schema.json +1 -1
- package/schemas/helper-expansion-summary.schema.json +1 -1
- package/schemas/impact-inspect-input.schema.json +1 -1
- package/schemas/map-operation.schema.json +354 -1
- package/schemas/mechanic-test-input.schema.json +1 -1
- package/schemas/mod-index-input.schema.json +1 -1
- package/schemas/operation-result.schema.json +1 -1
- package/schemas/package-check-input.schema.json +1 -1
- package/schemas/package-manifest.schema.json +1 -1
- package/schemas/probability-analysis-result.schema.json +1 -1
- package/schemas/probability-compare-input.schema.json +1 -1
- package/schemas/probability-evaluate-input.schema.json +1 -1
- package/schemas/probability-inspect-input.schema.json +1 -1
- package/schemas/probability-render-input.schema.json +1 -1
- package/schemas/probability-scenario-set.schema.json +1 -1
- package/schemas/probability-sequence-input.schema.json +1 -1
- package/schemas/probability-simulate-input.schema.json +1 -1
- package/schemas/probability-sweep-input.schema.json +1 -1
- package/schemas/reference-context-input.schema.json +1 -1
- package/schemas/reference-read-input.schema.json +1 -1
- package/schemas/reference-search-input.schema.json +1 -1
- package/schemas/reference-sheets.schema.json +1 -1
- package/schemas/scenario-suite.schema.json +1 -1
- package/schemas/scenario-test-input.schema.json +1 -1
- package/schemas/script-validate-input.schema.json +1 -1
- package/schemas/shared-scenario.schema.json +1 -1
- package/schemas/source-lookup-input.schema.json +1 -1
- package/server.json +2 -2
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,40 @@
|
|
|
2
2
|
|
|
3
3
|
## Unreleased
|
|
4
4
|
|
|
5
|
+
## 4.22.1 - 2026-12-05
|
|
6
|
+
|
|
7
|
+
- Releasing guide: removed the one-off 4.0.0 cut-over steps, which named an old version, a script that does not exist and a local folder.
|
|
8
|
+
- Fix the stdio server taking 4 to 14 s to answer `initialize` on a loaded Windows machine, which made Claude Code show it as failed. The image library (`sharp`, with its native code), the font library (`fontkit`) and the focus tool implementations were loaded before the first message was read. They load on the first call that needs them now, and the request schemas no longer import the renderers for their limits. The startup loads 242 module files instead of 340. Measured on the same Windows machine at 100% CPU, 4.22.0 answered in 6.8 to 9.4 s and this release in 1.2 to 4.5 s.
|
|
9
|
+
- Fix `hoi4.focus_render`'s game view drawing no line between mutually exclusive focuses (#355). It drew only the middle mark. Pairs more than two columns apart on one row now get the game's grey line (`GFX_focus_exclusive_line1`), an arrow at each end and the mark in the middle. They are placed by the `national_focus_exclusive_item` container of the loaded `nationalfocusview.gui`, and a mod's own sprites come before the game's. The report counts `exclusiveLines` and `exclusivePairsWithoutLine`. Limits: the game sets the line's width in code, so the render mirrors the line's left end at its right end. No in-game capture of a pair has confirmed this yet. The red line (`link2`) is not drawn, because the game's code picks it in a state a static render cannot know. Pairs on different rows are counted in the report and not drawn.
|
|
10
|
+
- Docs: the README no longer sends every user to the `all` profile. It names the profile for each kind of work (`core,map` for the world map, `core,advanced` for the editors), and the setup guide lists the measured size of each tool list, from 24 KB for `core` to 112 KB for `all`.
|
|
11
|
+
- `hoi4.script_validate` now flags scripted effects and triggers that take arguments (issue 338): a `$NAME$` placeholder in a definition, and a call of a helper the mod defines written with a block, such as `kb_add = { AMOUNT = 12 }`. The game rejects both at load with `Unknown effect-type`. The finding is `KNOWN_MISTAKE_SCRIPTED_ARGUMENTS` and says to set a variable before the call and read it in the body.
|
|
12
|
+
- The package now ships the `hoi4-engine` binary for Intel Macs (`darwin-x64`), built natively on an Intel macOS runner and checked there by the same `--version` run as the other platforms. The full test suite does not run on an Intel Mac; the evidence is that run and the bundle check. Before, the tools that need the engine answered `ENGINE_UNAVAILABLE` on an Intel Mac.
|
|
13
|
+
|
|
14
|
+
## 4.22.0 - 2026-12-04
|
|
15
|
+
|
|
16
|
+
- Updated `cross-spawn`, `@hono/node-server`, `glob` and other locked dependencies to fixed versions, so the `npm audit --omit=dev --audit-level=high` gate passes again (critical cross-spawn advisories GHSA-ghv9-86vm-4v8m and GHSA-m6qr-m48x-3xhh).
|
|
17
|
+
- Added `hoi4.country_write` (advanced profile): add, update or remove one country of the mod in one journaled write. It covers the tag line in the mod's `common/country_tags` file, the `common/countries` file (both graphical cultures and the map colour), the `colors.txt` entry, the `history/countries` file (capital, politics, popularities, research slots, stability, war support, technology, `oob` and `recruit_character`), the names in localisation (`<TAG>`, `<TAG>_ADJ`, `<TAG>_DEF` and per ideology) and, when asked, an entry in a named bookmark or a new bookmark. `apply: false` returns the diffs. A new tag must be an upper-case letter and two upper-case letters or digits; it is refused when it exists, is a dynamic name (`D00` to `D99`), a Windows device name or a three-letter effect or trigger name from the game documentation, and the refusal lists them. An unknown capital state, graphical culture or ideology is refused, and so is a removal while other mod files still name the tag (with the lines). When the mod has no `colors.txt` or edits a bookmark of the game, it gets a copy of the active file with the change, so the other entries stay. Missing flags, characters, order of battle files and text are warnings and the write still happens; the tool never draws flags. The edits are planned in the Rust engine (`country_write.plan`), whose new-file text is `create_world`'s, byte for byte, and whose shared history edit (`set_top_level_scalar`) matches keys in any ASCII case.
|
|
18
|
+
- Fixed tools that run as jobs (every `*_write` tool and the other background operations) dropping a refusal's `details`: a failed job now keeps the refusal's public details, bounded to 64 KiB of canonical JSON (larger details become `{ truncated: true, originalBytes, maximumBytes, omittedKeyCount, omittedKeys, details }`), and returns them unchanged in the tool answer, the task result and `hoi4.job_inspect`, whose output gains an optional `failure.details` (#327).
|
|
19
|
+
- Fixed `hoi4.map_rewrite` on a map that already has more validation errors than the review limit (a new mod on the vanilla map): the `REWRITE_STRUCTURE_LIMIT` refusal now carries a `remedy` detail naming a full `hoi4.map_inspect` and its `baselineFingerprint`, passed back as `baselineFingerprint`, and the field's description says when to use it. The detail is added only when the diagnostics limit was hit and the call stated no fingerprint (and no `create_world`); the code is unchanged, and failed jobs keep the detail.
|
|
20
|
+
- `hoi4.map_rewrite` has a new operation, `add_landmass`: it adds one island with relief to an existing map, in open sea. The island comes from a geography model on the map's frame (one land plus its ranges, passes, volcanoes, plateaus, rivers and lakes) or from a drawn mask image. One operation writes:
|
|
21
|
+
- its land and lake provinces, in `provinces.bmp` and `definition.csv`;
|
|
22
|
+
- the heightmap, rivers, terrain, trees and normal map;
|
|
23
|
+
- the land and water colour maps;
|
|
24
|
+
- its states (optionally owned by an existing country);
|
|
25
|
+
- its own new strategic region, with weather;
|
|
26
|
+
- building, unit and weather positions, and supply nodes and railways when asked;
|
|
27
|
+
- sea crossings when asked.
|
|
28
|
+
|
|
29
|
+
By default the island never changes an existing strategic region (issue 223). With the opt-in `absorbCoveredSeaProvinces`, a sea province the island covers whole becomes its land: it keeps its id and colour, and leaves its old region, which must stay non-empty and connected. The opt-in is refused, with each reference listed, when anything uses that province as sea: adjacencies, supply nodes, railways, naval building positions, states, the `sea_starts` and `lakes` of `default.map`, fleets, or any event, focus, decision or other `common/` script. A province name written for the sea gives a warning. Every sea province it takes pixels from keeps its id, its region and one connected piece, and becomes coastal where it now touches land. The write is refused with a named reason when the mask lies over or beside land, reaches the map edge, is not one piece, would empty or split a sea province, has a lake on its coast, exceeds the province id limit, or names an unknown owner, continent, state category or region. The map rewrite then validates the whole map against its baseline and blocks any new error-level finding, as for every map operation. The island is planned on the shared Rust engine (`map.add_landmass`); the relief, river, terrain and province synthesis of `create_world` is ported there for it and reused unchanged. Public schema addition: a new `add_landmass` member of the map operation schema.
|
|
30
|
+
|
|
31
|
+
- Fixed refusal details stored in job records and shown in tool answers being filtered by a top-level deny-list only: the filter now works at any depth (nested denied keys removed, absolute host paths in text reduced to their last segment, cyclic or too deep details replaced by a marker) (#332).
|
|
32
|
+
- The stdio server now also serves its working folder as an extra workspace when that folder is itself a mod (`descriptor.mod` and the usual mod detection) outside the configured `modRoots` and workspaces; configured ones are unchanged, the configuration file is never written, and a working folder inside a configured root adds nothing (#333, D-176).
|
|
33
|
+
- New `hoi4.common_write` (advanced profile): add, replace or remove one balance of power, AI strategy, AI strategy plan or on_action in the mod's own `common/` files, touching only that block, from raw script bodies that must parse and are written as given. It is one descriptor-driven engine operation (`common.block_write`), so a further kind is a descriptor, not new code. A balance of power whose ranges do not cover -1 to 1 once, or whose sides do not match, is refused; an unknown strategy type, a missing abort, or a missing localisation key, sprite, category or focus is a warning; an on_action name the documentation does not list (and that is not `on_daily_TAG`, `on_weekly_TAG` or `on_monthly_TAG`) is refused with the documented names. on_action blocks merge by key: add appends to the key's block, and `blockIndex` replaces or removes one child block.
|
|
34
|
+
|
|
35
|
+
- Fixed `hoi4.event_write` writing a broken event, reported as applied and passing validation, when `body` was a whole `country_event = { ... }` block (or another event kind): the file got an event nested inside the event. The call is now refused with `EVENT_WRITE_BODY_INVALID`, which says to pass only the text between the braces. `hoi4.decision_write`, `hoi4.idea_write`, `hoi4.character_write`, `hoi4.tech_write`, `hoi4.doctrine_write` and `hoi4.common_write` refuse a body that is the whole definition (`id = { ... }`, with or without the block it sits in) the same way, `hoi4.localisation_write` refuses a `text` that is a whole `key: "..."` line, and the `body` and `text` inputs are now described in the tool schemas.
|
|
36
|
+
|
|
37
|
+
- Clarified that the entries printed by `hoi4-agent-tools-setup --print-client-config` list only the core tools: the output now has a `toolProfiles` line, and the README quick start and the setup guide say how to list every tool with `HOI4_AGENT_TOOLS_PROFILES=all`.
|
|
38
|
+
|
|
5
39
|
## 4.21.0 - 2026-11-28
|
|
6
40
|
|
|
7
41
|
- Fixed `hoi4.gui_inspect` and `hoi4.gui_render` reporting false unresolved references: a sprite or font of another window in the inspected window's `.gui` file, or one a kept script names, now resolves from its `.gfx` file in the game or the mod instead of being reported as missing because that file was left out of the window graph, and a static GUI text that is not in the form of a localisation key (such as `Title text here!` or `--`) is drawn as written, as the game does, instead of being reported as a missing key. A missing sprite and a missing key in key form are still reported.
|
package/README.md
CHANGED
|
@@ -42,7 +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
|
|
45
|
+
The package ships its analysis engine for Windows x64, Linux x64 and arm64, and macOS on Apple silicon and Intel. On another platform, such as Windows on Arm, the tools that need the engine say so and how to build it; set `HOI4_ENGINE` to that build.
|
|
46
46
|
2. Install the server:
|
|
47
47
|
|
|
48
48
|
```bash
|
|
@@ -57,6 +57,8 @@ You describe what you want; the agent picks the right tools.
|
|
|
57
57
|
|
|
58
58
|
Paste the `globalInstall` block into a JSON client such as Claude Code, Claude Desktop or Cursor, or the `codexTomlGlobal` block into Codex's `config.toml`.
|
|
59
59
|
|
|
60
|
+
As printed, the entry lists the 13 core tools (documentation, script checks, localisation and skills). Add only the profile your work needs, because every listed tool costs context on every turn. For the world map, add `"env": { "HOI4_AGENT_TOOLS_PROFILES": "core,map" }` to the JSON server entry, or `HOI4_AGENT_TOOLS_PROFILES = "core,map"` inside the Codex `env` table. For the focus, event, GUI, technology and decision editors, use `core,advanced`. Use `all` only in a client that loads tool definitions on demand, such as Claude Code with tool search, because the full list is about 112 KB of tool definitions against 24 KB for `core` ([tool profiles](docs/setup.md#choose-tool-profiles)).
|
|
61
|
+
|
|
60
62
|
4. Open your mod folder as the agent's workspace and tell it what you want to build or fix.
|
|
61
63
|
|
|
62
64
|
The [setup guide](docs/setup.md) covers several mods, explicit game paths, local wiki snapshots and troubleshooting with `--discover` and `--diagnose`.
|
package/dist/bin/setup.js
CHANGED
|
@@ -266,6 +266,7 @@ function printClientConfig(configPath) {
|
|
|
266
266
|
const globalToml = `[mcp_servers.hoi4_agent_tools]\ncommand = "${installedCommand}"${codexEnv}`;
|
|
267
267
|
process.stdout.write(`${JSON.stringify({
|
|
268
268
|
note: 'Review and paste one example into your MCP client; this utility does not edit client settings.',
|
|
269
|
+
toolProfiles: 'As printed, an entry lists only the core tools. To list every tool, add HOI4_AGENT_TOOLS_PROFILES=all to the env of the server entry; see docs/setup.md, Choose tool profiles.',
|
|
269
270
|
generic: { mcpServers: { hoi4_agent_tools: common } },
|
|
270
271
|
globalInstall: { mcpServers: { hoi4_agent_tools: installed } },
|
|
271
272
|
codexToml: npxToml,
|
package/dist/bin/stdio.js
CHANGED
|
@@ -31,6 +31,7 @@ async function main() {
|
|
|
31
31
|
const engine = await createEngine(undefined, {
|
|
32
32
|
workspaces: 'background',
|
|
33
33
|
defaultProfiles: DEFAULT_PROFILES,
|
|
34
|
+
workingFolderMod: true,
|
|
34
35
|
});
|
|
35
36
|
// Plugins load only from the paths the server configuration lists (M-14).
|
|
36
37
|
const plugins = await loadPlugins(engine.resolver.config().plugins, PACKAGE_VERSION, (file, reason) => process.stderr.write(`${canonicalJson({ level: 'warn', event: 'plugin_skipped', plugin: path.basename(file), reason })}\n`));
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
import { ReferenceService } from '../reference/service.js';
|
|
3
|
+
const services = new WeakMap();
|
|
4
|
+
const BULLET = /^\s*[-*]\s+`([a-z][a-z0-9_]*)`/u;
|
|
5
|
+
const TOKEN_HEADING = /^##\s+List of available strategy tokens\s*$/iu;
|
|
6
|
+
const STRATEGY_DOC = 'common/ai_strategy/_documentation.md';
|
|
7
|
+
const ON_ACTION_DOC = 'common/on_actions/_documentation.md';
|
|
8
|
+
function referencesOf(engine) {
|
|
9
|
+
const known = services.get(engine);
|
|
10
|
+
if (known !== undefined)
|
|
11
|
+
return known;
|
|
12
|
+
const created = new ReferenceService({ docsRoot: engine.resolver.config().docsRoot });
|
|
13
|
+
services.set(engine, created);
|
|
14
|
+
return created;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* The lists from the lines of the two documentation files, by path under the game root. The
|
|
18
|
+
* strategy tokens are the bullets between the heading "List of available strategy tokens" and the
|
|
19
|
+
* next heading of its level or above: the later sections of that file (unit ratios, examples) have
|
|
20
|
+
* bullets of their own that are not tokens. The on_action names are every bullet of its file; the
|
|
21
|
+
* `on_daily_TAG` style entries have an upper-case tag and are not names.
|
|
22
|
+
*/
|
|
23
|
+
export function parseDocumentedLists(files) {
|
|
24
|
+
const tokens = new Set();
|
|
25
|
+
const names = new Set();
|
|
26
|
+
let inTokenList = false;
|
|
27
|
+
for (const line of files.get(STRATEGY_DOC) ?? []) {
|
|
28
|
+
if (TOKEN_HEADING.test(line))
|
|
29
|
+
inTokenList = true;
|
|
30
|
+
else if (/^#{1,2}\s/u.test(line))
|
|
31
|
+
inTokenList = false;
|
|
32
|
+
else if (inTokenList) {
|
|
33
|
+
const match = BULLET.exec(line);
|
|
34
|
+
if (match?.[1] !== undefined)
|
|
35
|
+
tokens.add(match[1]);
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
for (const line of files.get(ON_ACTION_DOC) ?? []) {
|
|
39
|
+
const match = BULLET.exec(line);
|
|
40
|
+
if (match?.[1] !== undefined)
|
|
41
|
+
names.add(match[1]);
|
|
42
|
+
}
|
|
43
|
+
return {
|
|
44
|
+
tokens: tokens.size === 0 ? undefined : [...tokens].sort(),
|
|
45
|
+
names: names.size === 0 ? undefined : [...names].sort(),
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
export async function documentedLists(engine, workspaceId, principal, signal) {
|
|
49
|
+
const workspace = engine.resolver.get(workspaceId, principal);
|
|
50
|
+
const inventory = await referencesOf(engine).inventory(workspace, signal, ['game_doc']);
|
|
51
|
+
const files = new Map();
|
|
52
|
+
const sections = [...inventory.sections].sort((a, b) => a.startLine - b.startLine);
|
|
53
|
+
for (const section of sections) {
|
|
54
|
+
const file = section.relativePath.replaceAll('\\', '/').toLowerCase();
|
|
55
|
+
if (path.posix.basename(file) !== '_documentation.md')
|
|
56
|
+
continue;
|
|
57
|
+
const lines = files.get(file) ?? [];
|
|
58
|
+
lines.push(...section.lines);
|
|
59
|
+
files.set(file, lines);
|
|
60
|
+
}
|
|
61
|
+
return parseDocumentedLists(files);
|
|
62
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The caps of `hoi4.common_write` output, applied before the output schema parses, so a large
|
|
3
|
+
* definition (a balance of power with many ranges, a plan with hundreds of focuses) is reported
|
|
4
|
+
* short, with a count of what was left out, and never makes the schema throw.
|
|
5
|
+
*/
|
|
6
|
+
export const MAX_DIFF_UNITS = 8_000;
|
|
7
|
+
export const MAX_FINDINGS = 50;
|
|
8
|
+
/** The diagnostics of the envelope; the count left out is in `omitted.diagnostics`. */
|
|
9
|
+
export const MAX_DIAGNOSTICS = 20;
|
|
10
|
+
export const MAX_NAMES = { localisation: 50, sprites: 20, categories: 5, focuses: 100 };
|
|
11
|
+
const MAX_NAME_LENGTH = 256;
|
|
12
|
+
const MAX_MESSAGE_LENGTH = 1_024;
|
|
13
|
+
/** `text` cut to at most `limit` UTF-16 units without splitting a surrogate pair. */
|
|
14
|
+
export function cutText(text, limit) {
|
|
15
|
+
if (text.length <= limit)
|
|
16
|
+
return text;
|
|
17
|
+
const high = text.charCodeAt(limit - 1);
|
|
18
|
+
return text.slice(0, high >= 0xd800 && high <= 0xdbff ? limit - 1 : limit);
|
|
19
|
+
}
|
|
20
|
+
export function capList(items, limit, length = MAX_NAME_LENGTH) {
|
|
21
|
+
return {
|
|
22
|
+
kept: items.slice(0, limit).map((item) => cutText(item, length)),
|
|
23
|
+
omitted: Math.max(0, items.length - limit),
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
export function capFindings(findings) {
|
|
27
|
+
return {
|
|
28
|
+
kept: findings.slice(0, MAX_FINDINGS).map((finding) => ({
|
|
29
|
+
...finding,
|
|
30
|
+
code: cutText(finding.code, 128),
|
|
31
|
+
message: cutText(finding.message, MAX_MESSAGE_LENGTH),
|
|
32
|
+
})),
|
|
33
|
+
omitted: Math.max(0, findings.length - MAX_FINDINGS),
|
|
34
|
+
};
|
|
35
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A new file's path, checked before the engine is asked (the engine refuses the same paths): a
|
|
3
|
+
* path segment the mod may hold on every platform has no NTFS stream or drive (`:`), wildcard or
|
|
4
|
+
* control character, no trailing dot or space, and is not a reserved device name.
|
|
5
|
+
*/
|
|
6
|
+
const RESERVED = /^(?:con|prn|aux|nul|conin\$|conout\$|(?:com|lpt)\d)$/iu;
|
|
7
|
+
export function isPlainSegment(part) {
|
|
8
|
+
if (part === '' || part === '.' || part === '..' || /[. ]$/u.test(part))
|
|
9
|
+
return false;
|
|
10
|
+
// eslint-disable-next-line no-control-regex -- control characters are the point
|
|
11
|
+
if (/[\u0000-\u001f\u007f:*?"<>|\\]/u.test(part))
|
|
12
|
+
return false;
|
|
13
|
+
return !RESERVED.test(part.split('.')[0] ?? '');
|
|
14
|
+
}
|
|
15
|
+
export function isPlainRelativePath(path) {
|
|
16
|
+
return path.split('/').every(isPlainSegment);
|
|
17
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { z } from 'zod/v4';
|
|
2
|
+
import { toolResult } from '../core/operation-result.js';
|
|
3
|
+
import { ServiceError } from '../core/result.js';
|
|
4
|
+
import { commonWriteRequestSchema } from '../schemas/common-write.js';
|
|
5
|
+
import { completeCommonWrite, prepareCommonWrite, previewCommonWrite, } from './write-operations.js';
|
|
6
|
+
const wireResult = z.record(z.string(), z.json());
|
|
7
|
+
function wire(result) {
|
|
8
|
+
return wireResult.parse(JSON.parse(JSON.stringify(toolResult(result))));
|
|
9
|
+
}
|
|
10
|
+
/** Registers `hoi4.common_write`: a read-only preview, or one journaled transaction. */
|
|
11
|
+
export function registerCommonWriteJobs(operations, engine) {
|
|
12
|
+
operations.registerWrite('hoi4.common_write', commonWriteRequestSchema, async (input, context) => {
|
|
13
|
+
if (input.workspaceId !== 'current' && input.workspaceId !== context.workspaceId)
|
|
14
|
+
throw new ServiceError('JOB_ARGUMENT_SCOPE_MISMATCH', 'The request workspace does not match the authorized job workspace');
|
|
15
|
+
const operationContext = {
|
|
16
|
+
workspaceId: context.workspaceId,
|
|
17
|
+
...(context.principal === undefined ? {} : { principal: context.principal }),
|
|
18
|
+
signal: context.signal,
|
|
19
|
+
progress: (completed, total, message) => context.progress({ completed, total, message }),
|
|
20
|
+
};
|
|
21
|
+
if (!input.apply)
|
|
22
|
+
return {
|
|
23
|
+
readOnlyPreview: wire(await previewCommonWrite(engine, input, operationContext)),
|
|
24
|
+
};
|
|
25
|
+
const prepared = await prepareCommonWrite(engine, input, operationContext);
|
|
26
|
+
if ('readOnlyPreview' in prepared)
|
|
27
|
+
return { readOnlyPreview: wire(prepared.readOnlyPreview) };
|
|
28
|
+
return { transaction: prepared.transaction, recipe: { ...prepared.recipe } };
|
|
29
|
+
}, async (_input, execution, _reconciled, recipe, context) => {
|
|
30
|
+
const result = completeCommonWrite(context.workspaceId, execution, recipe);
|
|
31
|
+
await context.progress({
|
|
32
|
+
completed: 3,
|
|
33
|
+
total: 3,
|
|
34
|
+
message: execution.outcome === 'applied'
|
|
35
|
+
? 'Definition change complete'
|
|
36
|
+
: execution.outcome === 'unchanged'
|
|
37
|
+
? 'The definition already matched the request'
|
|
38
|
+
: 'Definition change blocked',
|
|
39
|
+
});
|
|
40
|
+
return wire(result);
|
|
41
|
+
});
|
|
42
|
+
}
|
|
@@ -0,0 +1,360 @@
|
|
|
1
|
+
import { emptyServiceResult, ServiceError } from '../core/result.js';
|
|
2
|
+
import { autonomousResultArtifacts, } from '../core/transaction-execution.js';
|
|
3
|
+
import { commonWriteDataSchema, } from '../schemas/common-write.js';
|
|
4
|
+
import { documentedLists } from './documented-lists.js';
|
|
5
|
+
import { capFindings, capList, cutText, MAX_DIAGNOSTICS, MAX_DIFF_UNITS, MAX_NAMES, } from './limits.js';
|
|
6
|
+
import { isPlainRelativePath } from './paths.js';
|
|
7
|
+
import { planCommonWrite, planNewCommonFile, } from './write-plan.js';
|
|
8
|
+
const MAX_INLINE_PATHS = 8;
|
|
9
|
+
const MAX_INLINE_ARTIFACTS = 2;
|
|
10
|
+
/**
|
|
11
|
+
* Where each kind lives, for choosing the file. The engine's descriptor owns the folder rule and
|
|
12
|
+
* refuses a path outside it; this table only narrows the scan to the kind's files.
|
|
13
|
+
*/
|
|
14
|
+
const FOLDERS = {
|
|
15
|
+
bop: 'common/bop/',
|
|
16
|
+
ai_strategy: 'common/ai_strategy/',
|
|
17
|
+
ai_strategy_plan: 'common/ai_strategy_plans/',
|
|
18
|
+
on_action: 'common/on_actions/',
|
|
19
|
+
};
|
|
20
|
+
function fail(code, message, details) {
|
|
21
|
+
throw new ServiceError(code, message, details);
|
|
22
|
+
}
|
|
23
|
+
function normalized(path) {
|
|
24
|
+
return path.replaceAll('\\', '/').replace(/^\.\//u, '').toLowerCase();
|
|
25
|
+
}
|
|
26
|
+
/** The mod files of the kind, the ones this tool may write. */
|
|
27
|
+
function modFiles(snapshot, kind) {
|
|
28
|
+
return snapshot.files.filter(({ rootKind, shadowedBy, relativePath }) => rootKind === 'mod' &&
|
|
29
|
+
shadowedBy === undefined &&
|
|
30
|
+
normalized(relativePath).startsWith(FOLDERS[kind]) &&
|
|
31
|
+
relativePath.toLowerCase().endsWith('.txt'));
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* The mod files that define the id, found by asking the engine to plan a removal of it from each:
|
|
35
|
+
* a file without the id answers "not found", a file that cannot be read answers nothing about it.
|
|
36
|
+
*/
|
|
37
|
+
async function holders(files, input) {
|
|
38
|
+
const holding = [];
|
|
39
|
+
const unreadable = [];
|
|
40
|
+
for (const file of files) {
|
|
41
|
+
try {
|
|
42
|
+
await planCommonWrite({ bytes: file.bytes, path: file.relativePath }, { kind: input.kind, operation: 'remove', id: input.id });
|
|
43
|
+
holding.push(file);
|
|
44
|
+
}
|
|
45
|
+
catch (error) {
|
|
46
|
+
if (!(error instanceof ServiceError))
|
|
47
|
+
throw error;
|
|
48
|
+
if (error.code === 'COMMON_WRITE_NOT_FOUND')
|
|
49
|
+
continue;
|
|
50
|
+
// Only a file that really has the id holds it; one the engine cannot read or place an edit
|
|
51
|
+
// in is reported apart, so a refusal can name what it could not search.
|
|
52
|
+
if (error.code === 'COMMON_WRITE_DUPLICATE_ID')
|
|
53
|
+
holding.push(file);
|
|
54
|
+
else
|
|
55
|
+
unreadable.push(file.relativePath);
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
return { holding, unreadable };
|
|
59
|
+
}
|
|
60
|
+
async function targetFile(snapshot, input) {
|
|
61
|
+
const files = modFiles(snapshot, input.kind);
|
|
62
|
+
const folder = FOLDERS[input.kind];
|
|
63
|
+
const listed = files.map(({ relativePath }) => relativePath).slice(0, 20);
|
|
64
|
+
if (input.createFile === true && input.operation !== 'add')
|
|
65
|
+
fail('COMMON_WRITE_FILE_UNEXPECTED', 'createFile applies to add only', {});
|
|
66
|
+
// An add of a one-block-per-id kind must see every file of the kind: a file the engine cannot
|
|
67
|
+
// read might hold the id, so the add is refused, and a file that does hold it is a duplicate
|
|
68
|
+
// whichever file the add names.
|
|
69
|
+
const searched = input.operation === 'add' && input.kind !== 'on_action'
|
|
70
|
+
? await holders(files, input)
|
|
71
|
+
: undefined;
|
|
72
|
+
if (searched !== undefined) {
|
|
73
|
+
if (searched.unreadable.length > 0)
|
|
74
|
+
fail('COMMON_WRITE_FILES_UNREADABLE', `${searched.unreadable.length} ${folder} file(s) of the mod could not be read, so the add cannot tell whether ${input.id} is already defined; fix them first`, { id: input.id, unreadable: searched.unreadable.slice(0, 20) });
|
|
75
|
+
if (searched.holding.length > 0)
|
|
76
|
+
fail('COMMON_WRITE_DUPLICATE_ID', `${input.id} is already defined in the mod`, {
|
|
77
|
+
id: input.id,
|
|
78
|
+
path: searched.holding[0]?.relativePath,
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
if (input.file !== undefined) {
|
|
82
|
+
const named = files.find(({ relativePath }) => normalized(relativePath) === normalized(input.file));
|
|
83
|
+
if (named !== undefined) {
|
|
84
|
+
if (input.createFile === true)
|
|
85
|
+
// The file exists, so the flag has nothing to create; refusing keeps a wrong guess visible.
|
|
86
|
+
fail('COMMON_WRITE_FILE_EXISTS', `${named.relativePath} already exists; drop createFile to add to it`, { file: named.relativePath });
|
|
87
|
+
return { file: named };
|
|
88
|
+
}
|
|
89
|
+
if (input.operation !== 'add' || input.createFile !== true)
|
|
90
|
+
fail('COMMON_WRITE_FILE_NOT_FOUND', `${input.file} is not a ${folder} file of the mod${input.operation === 'add' ? '; pass createFile: true to create it' : ''}`, { file: input.file, files: listed });
|
|
91
|
+
const newPath = input.file.replaceAll('\\', '/').replace(/^\.\//u, '');
|
|
92
|
+
if (!normalized(newPath).startsWith(folder) ||
|
|
93
|
+
!newPath.toLowerCase().endsWith('.txt') ||
|
|
94
|
+
!isPlainRelativePath(newPath))
|
|
95
|
+
fail('COMMON_WRITE_FILE_INVALID', `${input.file} is not a plain .txt path under ${folder}, so a new file cannot go there`, { file: input.file });
|
|
96
|
+
return { newPath };
|
|
97
|
+
}
|
|
98
|
+
const { holding, unreadable } = searched ?? (await holders(files, input));
|
|
99
|
+
if (input.operation === 'add') {
|
|
100
|
+
if (input.createFile === true)
|
|
101
|
+
fail('COMMON_WRITE_FILE_REQUIRED', 'createFile needs file, the path of the new file', {
|
|
102
|
+
files: listed,
|
|
103
|
+
});
|
|
104
|
+
if (holding.length > 0 && input.kind !== 'on_action')
|
|
105
|
+
fail('COMMON_WRITE_DUPLICATE_ID', `${input.id} is already defined in the mod`, {
|
|
106
|
+
id: input.id,
|
|
107
|
+
path: holding[0]?.relativePath,
|
|
108
|
+
});
|
|
109
|
+
const choices = holding.length > 0 ? holding : files;
|
|
110
|
+
if (choices.length === 1)
|
|
111
|
+
return { file: choices[0] };
|
|
112
|
+
fail('COMMON_WRITE_FILE_REQUIRED', choices.length === 0
|
|
113
|
+
? `The mod has no ${folder} file; name a new one with file and createFile: true`
|
|
114
|
+
: `${choices.length} files of the mod could hold ${input.id}; name one with file`, { files: choices.map(({ relativePath }) => relativePath).slice(0, 20) });
|
|
115
|
+
}
|
|
116
|
+
if (holding.length === 0)
|
|
117
|
+
fail('COMMON_WRITE_NOT_FOUND', `${input.id} is not defined in a ${folder} file of the mod${unreadable.length === 0 ? '' : `; ${unreadable.length} file(s) could not be searched`}`, { id: input.id, files: listed, ...(unreadable.length === 0 ? {} : { unreadable }) });
|
|
118
|
+
if (holding.length > 1)
|
|
119
|
+
fail('COMMON_WRITE_FILE_REQUIRED', `${input.id} is defined in ${holding.length} files; name one with file`, { files: holding.map(({ relativePath }) => relativePath) });
|
|
120
|
+
return { file: holding[0] };
|
|
121
|
+
}
|
|
122
|
+
export async function computeCommonWrite(engine, input, context, applied) {
|
|
123
|
+
const snapshot = await engine.scan(context.workspaceId, {
|
|
124
|
+
patterns: [
|
|
125
|
+
`${FOLDERS[input.kind]}**/*.txt`,
|
|
126
|
+
'common/decisions/**/*.txt',
|
|
127
|
+
'common/national_focus/**/*.txt',
|
|
128
|
+
'interface/**/*.gfx',
|
|
129
|
+
'localisation/english/**/*.{yml,yaml}',
|
|
130
|
+
'localisation/*.{yml,yaml}',
|
|
131
|
+
],
|
|
132
|
+
}, context.principal, context.signal);
|
|
133
|
+
const lists = input.operation === 'remove'
|
|
134
|
+
? { tokens: undefined, names: undefined }
|
|
135
|
+
: await documentedLists(engine, context.workspaceId, context.principal, context.signal);
|
|
136
|
+
const planInput = {
|
|
137
|
+
kind: input.kind,
|
|
138
|
+
operation: input.operation,
|
|
139
|
+
id: input.id,
|
|
140
|
+
...(input.body === undefined ? {} : { body: input.body }),
|
|
141
|
+
...(input.blockIndex === undefined ? {} : { blockIndex: input.blockIndex }),
|
|
142
|
+
...(input.kind === 'ai_strategy' && lists.tokens !== undefined
|
|
143
|
+
? { knownTokens: lists.tokens }
|
|
144
|
+
: {}),
|
|
145
|
+
...(input.kind === 'on_action' && lists.names !== undefined ? { knownNames: lists.names } : {}),
|
|
146
|
+
};
|
|
147
|
+
const target = await targetFile(snapshot, input);
|
|
148
|
+
let file;
|
|
149
|
+
let plan;
|
|
150
|
+
if ('file' in target) {
|
|
151
|
+
file = target.file;
|
|
152
|
+
plan = await planCommonWrite({ bytes: file.bytes, path: file.relativePath }, planInput);
|
|
153
|
+
}
|
|
154
|
+
else {
|
|
155
|
+
plan = await planNewCommonFile(target.newPath, planInput);
|
|
156
|
+
}
|
|
157
|
+
const missing = {
|
|
158
|
+
localisation: [],
|
|
159
|
+
sprites: [],
|
|
160
|
+
categories: [],
|
|
161
|
+
focuses: [],
|
|
162
|
+
};
|
|
163
|
+
const diagnostics = plan.findings.map(({ code, severity, message }) => ({
|
|
164
|
+
code: `COMMON_WRITE_${code}`,
|
|
165
|
+
severity,
|
|
166
|
+
category: 'reference',
|
|
167
|
+
message,
|
|
168
|
+
details: { id: plan.id },
|
|
169
|
+
}));
|
|
170
|
+
if (input.operation !== 'remove') {
|
|
171
|
+
for (const key of plan.references.localisation)
|
|
172
|
+
if (snapshot.index.find('localisation', `l_english:${key}`) === undefined)
|
|
173
|
+
missing.localisation.push(key);
|
|
174
|
+
for (const sprite of plan.references.sprites)
|
|
175
|
+
if (snapshot.index.find('sprite', sprite) === undefined)
|
|
176
|
+
missing.sprites.push(sprite);
|
|
177
|
+
for (const category of plan.references.categories)
|
|
178
|
+
if (snapshot.index.find('decision_category', category) === undefined)
|
|
179
|
+
missing.categories.push(category);
|
|
180
|
+
for (const focus of plan.references.focuses)
|
|
181
|
+
if (snapshot.index.find('focus', focus) === undefined)
|
|
182
|
+
missing.focuses.push(focus);
|
|
183
|
+
const lines = [
|
|
184
|
+
[
|
|
185
|
+
'localisation',
|
|
186
|
+
'LOCALISATION_MISSING',
|
|
187
|
+
'No English text is defined for the localisation key',
|
|
188
|
+
],
|
|
189
|
+
['sprites', 'SPRITE_UNDEFINED', 'The sprite is not defined:'],
|
|
190
|
+
['categories', 'CATEGORY_UNDEFINED', 'No decision category is defined with the name'],
|
|
191
|
+
['focuses', 'FOCUS_UNDEFINED', 'No focus is defined with the id'],
|
|
192
|
+
];
|
|
193
|
+
for (const [field, code, text] of lines)
|
|
194
|
+
for (const name of missing[field])
|
|
195
|
+
diagnostics.push({
|
|
196
|
+
code: `COMMON_WRITE_${code}`,
|
|
197
|
+
severity: 'warning',
|
|
198
|
+
category: 'reference',
|
|
199
|
+
message: `${text} ${name}`,
|
|
200
|
+
details: { name },
|
|
201
|
+
});
|
|
202
|
+
}
|
|
203
|
+
const omittedDiagnostics = Math.max(0, diagnostics.length - MAX_DIAGNOSTICS);
|
|
204
|
+
const budget = plan.diff.length > MAX_DIFF_UNITS;
|
|
205
|
+
const findings = capFindings(plan.findings);
|
|
206
|
+
const capped = {
|
|
207
|
+
localisation: capList(missing.localisation, MAX_NAMES.localisation),
|
|
208
|
+
sprites: capList(missing.sprites, MAX_NAMES.sprites),
|
|
209
|
+
categories: capList(missing.categories, MAX_NAMES.categories),
|
|
210
|
+
focuses: capList(missing.focuses, MAX_NAMES.focuses),
|
|
211
|
+
};
|
|
212
|
+
const data = commonWriteDataSchema.parse({
|
|
213
|
+
operation: plan.operation,
|
|
214
|
+
kind: plan.kind,
|
|
215
|
+
id: plan.id,
|
|
216
|
+
path: cutText(plan.path, 1024),
|
|
217
|
+
applied,
|
|
218
|
+
diff: budget ? `${cutText(plan.diff, MAX_DIFF_UNITS)}\n` : plan.diff,
|
|
219
|
+
diffTruncated: budget,
|
|
220
|
+
untouchedDefinitions: plan.untouchedDefinitions,
|
|
221
|
+
findings: findings.kept.map(({ severity, code, message }) => ({ severity, code, message })),
|
|
222
|
+
missing: {
|
|
223
|
+
localisation: capped.localisation.kept,
|
|
224
|
+
sprites: capped.sprites.kept,
|
|
225
|
+
categories: capped.categories.kept,
|
|
226
|
+
focuses: capped.focuses.kept,
|
|
227
|
+
},
|
|
228
|
+
omitted: {
|
|
229
|
+
findings: findings.omitted,
|
|
230
|
+
diagnostics: omittedDiagnostics,
|
|
231
|
+
localisation: capped.localisation.omitted,
|
|
232
|
+
sprites: capped.sprites.omitted,
|
|
233
|
+
categories: capped.categories.omitted,
|
|
234
|
+
focuses: capped.focuses.omitted,
|
|
235
|
+
},
|
|
236
|
+
});
|
|
237
|
+
diagnostics.splice(MAX_DIAGNOSTICS);
|
|
238
|
+
return { plan, file, data, diagnostics };
|
|
239
|
+
}
|
|
240
|
+
function resultFor(workspaceId, data, outcome) {
|
|
241
|
+
const result = emptyServiceResult(workspaceId, data);
|
|
242
|
+
result.code =
|
|
243
|
+
outcome === 'preview'
|
|
244
|
+
? 'COMMON_WRITE_PREVIEW'
|
|
245
|
+
: outcome === 'applied'
|
|
246
|
+
? 'COMMON_WRITE_APPLIED'
|
|
247
|
+
: outcome === 'unchanged'
|
|
248
|
+
? 'COMMON_WRITE_UNCHANGED'
|
|
249
|
+
: 'COMMON_WRITE_BLOCKED';
|
|
250
|
+
result.status = outcome === 'blocked' ? 'blocked' : 'ok';
|
|
251
|
+
result.proposedFiles = [data.path].slice(0, MAX_INLINE_PATHS);
|
|
252
|
+
return result;
|
|
253
|
+
}
|
|
254
|
+
/** `apply: false`: the diff of the one file the call would change, and nothing written. */
|
|
255
|
+
export async function previewCommonWrite(engine, input, context) {
|
|
256
|
+
await context.progress?.(0, 2, 'Reading the definitions of the mod');
|
|
257
|
+
const computed = await computeCommonWrite(engine, input, context, false);
|
|
258
|
+
const result = resultFor(context.workspaceId, computed.data, computed.file !== undefined && computed.plan.bytes.equals(computed.file.bytes)
|
|
259
|
+
? 'unchanged'
|
|
260
|
+
: 'preview');
|
|
261
|
+
result.diagnostics = computed.diagnostics;
|
|
262
|
+
await context.progress?.(2, 2, 'Definition preview ready');
|
|
263
|
+
return result;
|
|
264
|
+
}
|
|
265
|
+
/** `apply: true`: the same plan, as one validated transaction for atomic replacement. */
|
|
266
|
+
export async function prepareCommonWrite(engine, input, context) {
|
|
267
|
+
await context.progress?.(0, 3, 'Reading the definitions of the mod');
|
|
268
|
+
const computed = await computeCommonWrite(engine, input, context, true);
|
|
269
|
+
const { plan, file, data, diagnostics } = computed;
|
|
270
|
+
if (file !== undefined && plan.bytes.equals(file.bytes)) {
|
|
271
|
+
const result = resultFor(context.workspaceId, { ...data, applied: false }, 'unchanged');
|
|
272
|
+
result.diagnostics = diagnostics;
|
|
273
|
+
return { readOnlyPreview: result };
|
|
274
|
+
}
|
|
275
|
+
const workspace = engine.resolver.get(context.workspaceId, context.principal);
|
|
276
|
+
const modRoot = workspace.roots.find((root) => root.kind === 'mod');
|
|
277
|
+
const operationId = `common-${plan.kind}-${plan.operation}`;
|
|
278
|
+
await context.progress?.(1, 3, 'Preparing the definition transaction');
|
|
279
|
+
const transaction = await engine.transactions.plan({
|
|
280
|
+
workspaceId: context.workspaceId,
|
|
281
|
+
...(context.principal === undefined ? {} : { principal: context.principal }),
|
|
282
|
+
operationKind: 'common-changes',
|
|
283
|
+
operations: [
|
|
284
|
+
{
|
|
285
|
+
id: operationId,
|
|
286
|
+
kind: operationId,
|
|
287
|
+
summary: `${plan.operation} ${plan.id} (${plan.kind})`,
|
|
288
|
+
data: { id: plan.id, kind: plan.kind },
|
|
289
|
+
},
|
|
290
|
+
],
|
|
291
|
+
changes: [
|
|
292
|
+
{
|
|
293
|
+
relativePath: plan.path,
|
|
294
|
+
content: plan.bytes,
|
|
295
|
+
operationIds: [operationId],
|
|
296
|
+
mediaType: 'text/plain',
|
|
297
|
+
},
|
|
298
|
+
],
|
|
299
|
+
readDependencies: file === undefined
|
|
300
|
+
? []
|
|
301
|
+
: [
|
|
302
|
+
{
|
|
303
|
+
rootKind: 'mod',
|
|
304
|
+
loadOrder: modRoot?.loadOrder ?? 0,
|
|
305
|
+
relativePath: file.relativePath,
|
|
306
|
+
sha256: file.sha256,
|
|
307
|
+
},
|
|
308
|
+
],
|
|
309
|
+
validate: (proposed, signal) => {
|
|
310
|
+
signal?.throwIfAborted();
|
|
311
|
+
const bytes = proposed.get(plan.path);
|
|
312
|
+
const matches = bytes !== undefined && bytes !== null && Buffer.from(bytes).equals(plan.bytes);
|
|
313
|
+
return Promise.resolve({
|
|
314
|
+
diagnostics: matches
|
|
315
|
+
? []
|
|
316
|
+
: [
|
|
317
|
+
{
|
|
318
|
+
code: 'COMMON_WRITE_TRANSACTION_BYTES_MISMATCH',
|
|
319
|
+
severity: 'blocker',
|
|
320
|
+
category: 'validation',
|
|
321
|
+
message: 'Transaction dry-run bytes differ from the planned file',
|
|
322
|
+
},
|
|
323
|
+
],
|
|
324
|
+
checks: [
|
|
325
|
+
{
|
|
326
|
+
id: 'common-proposed-bytes-match',
|
|
327
|
+
passed: matches,
|
|
328
|
+
message: matches
|
|
329
|
+
? 'Transaction bytes exactly match the planned file'
|
|
330
|
+
: 'Transaction bytes differ from the planned file',
|
|
331
|
+
},
|
|
332
|
+
],
|
|
333
|
+
});
|
|
334
|
+
},
|
|
335
|
+
...(context.signal === undefined ? {} : { signal: context.signal }),
|
|
336
|
+
});
|
|
337
|
+
await context.progress?.(2, 3, 'Definition change prepared for journaled application');
|
|
338
|
+
return { transaction, recipe: { data, diagnostics } };
|
|
339
|
+
}
|
|
340
|
+
export function completeCommonWrite(workspaceId, execution, recipe) {
|
|
341
|
+
const parsed = recipe;
|
|
342
|
+
const data = commonWriteDataSchema.parse({
|
|
343
|
+
...parsed.data,
|
|
344
|
+
applied: execution.outcome === 'applied',
|
|
345
|
+
});
|
|
346
|
+
const transaction = execution.transaction;
|
|
347
|
+
const result = resultFor(workspaceId, data, execution.outcome);
|
|
348
|
+
result.status = transaction.validation.passed ? 'ok' : 'blocked';
|
|
349
|
+
result.changedFiles = transaction.appliedFiles.slice(0, MAX_INLINE_PATHS);
|
|
350
|
+
const hard = transaction.diagnostics.filter(({ severity }) => severity === 'error' || severity === 'blocker');
|
|
351
|
+
result.diagnostics = [...hard, ...parsed.diagnostics].slice(0, 20);
|
|
352
|
+
result.artifacts = autonomousResultArtifacts(execution).slice(0, MAX_INLINE_ARTIFACTS);
|
|
353
|
+
result.validation = transaction.validation;
|
|
354
|
+
result.blockers = hard.slice(0, 20).map(({ code, message, details }) => ({
|
|
355
|
+
code,
|
|
356
|
+
message,
|
|
357
|
+
...(details === undefined ? {} : { details }),
|
|
358
|
+
}));
|
|
359
|
+
return result;
|
|
360
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { z } from 'zod/v4';
|
|
2
|
+
import { callWritePlan, replacementSchema } from '../script-write/engine-plan.js';
|
|
3
|
+
const planSchema = z.object({
|
|
4
|
+
operation: z.enum(['add', 'replace', 'remove']),
|
|
5
|
+
kind: z.enum(['bop', 'ai_strategy', 'ai_strategy_plan', 'on_action']),
|
|
6
|
+
id: z.string(),
|
|
7
|
+
path: z.string(),
|
|
8
|
+
edit: replacementSchema,
|
|
9
|
+
untouchedDefinitions: z.number().int().nonnegative(),
|
|
10
|
+
findings: z.array(z.object({ severity: z.enum(['warning']), code: z.string(), message: z.string() })),
|
|
11
|
+
references: z.object({
|
|
12
|
+
localisation: z.array(z.string()),
|
|
13
|
+
sprites: z.array(z.string()),
|
|
14
|
+
categories: z.array(z.string()),
|
|
15
|
+
focuses: z.array(z.string()),
|
|
16
|
+
}),
|
|
17
|
+
});
|
|
18
|
+
async function plan(path, input, source) {
|
|
19
|
+
const answer = await callWritePlan({
|
|
20
|
+
op: 'common.block_write.plan',
|
|
21
|
+
path,
|
|
22
|
+
input: { ...input },
|
|
23
|
+
...(source === undefined ? {} : { source }),
|
|
24
|
+
result: planSchema,
|
|
25
|
+
});
|
|
26
|
+
return { ...answer.result, text: answer.text, bytes: answer.bytes, diff: answer.diff };
|
|
27
|
+
}
|
|
28
|
+
/** The plan that creates a new file holding one new definition, for `createFile: true`. */
|
|
29
|
+
export function planNewCommonFile(path, input) {
|
|
30
|
+
return plan(path, input, undefined);
|
|
31
|
+
}
|
|
32
|
+
export function planCommonWrite(source, input) {
|
|
33
|
+
return plan(source.path, input, source.bytes);
|
|
34
|
+
}
|
|
@@ -5,7 +5,7 @@ import { createHash } from 'node:crypto';
|
|
|
5
5
|
import { lstat, mkdtemp, open, realpath, rmdir, unlink } from 'node:fs/promises';
|
|
6
6
|
import { tmpdir } from 'node:os';
|
|
7
7
|
import path from 'node:path';
|
|
8
|
-
import sharp from '
|
|
8
|
+
import sharp from './lazy-native.js';
|
|
9
9
|
import { TemporaryDirectoryLifetime, sweepTemporaryDirectories } from './temporary-directories.js';
|
|
10
10
|
export const REFERENCE_SOURCE_MAX_BYTES = 1_073_741_824;
|
|
11
11
|
export const REFERENCE_WORKING_MAX_SIDE = 3_072;
|