hoi4-agent-tools 4.20.3 → 4.21.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.
- package/CHANGELOG.md +15 -0
- package/dist/hoi4_agent_tools/characters/write-operations.js +2 -2
- package/dist/hoi4_agent_tools/characters/write-plan.js +21 -205
- package/dist/hoi4_agent_tools/core/artifacts-engine.js +272 -0
- package/dist/hoi4_agent_tools/core/configuration.js +6 -0
- package/dist/hoi4_agent_tools/core/engine.js +67 -21
- package/dist/hoi4_agent_tools/core/idle-cache-lifetime.js +7 -0
- package/dist/hoi4_agent_tools/core/operation-tasks.js +3 -1
- package/dist/hoi4_agent_tools/core/transactions.js +6 -0
- package/dist/hoi4_agent_tools/core/workspace.js +14 -1
- package/dist/hoi4_agent_tools/decision/write-operations.js +7 -8
- package/dist/hoi4_agent_tools/decision/write-plan.js +25 -245
- package/dist/hoi4_agent_tools/doctrine/write-operations.js +2 -2
- package/dist/hoi4_agent_tools/doctrine/write-plan.js +21 -180
- package/dist/hoi4_agent_tools/event/graph.js +3 -3
- package/dist/hoi4_agent_tools/event/job-operations.js +2 -2
- package/dist/hoi4_agent_tools/event/write-job-operations.js +2 -2
- package/dist/hoi4_agent_tools/event/write-operations.js +9 -10
- package/dist/hoi4_agent_tools/event/write-plan.js +28 -278
- package/dist/hoi4_agent_tools/focus/job-operations.js +2 -2
- package/dist/hoi4_agent_tools/gui/assets.js +3 -13
- package/dist/hoi4_agent_tools/gui/job-operations.js +2 -2
- package/dist/hoi4_agent_tools/gui/layout.js +2 -4
- package/dist/hoi4_agent_tools/gui/renderer.js +2 -1
- package/dist/hoi4_agent_tools/gui/source-graph.js +16 -0
- package/dist/hoi4_agent_tools/gui/studio.js +31 -0
- package/dist/hoi4_agent_tools/ideas/write-operations.js +7 -8
- package/dist/hoi4_agent_tools/ideas/write-plan.js +24 -304
- package/dist/hoi4_agent_tools/map/engine-validation.js +230 -0
- package/dist/hoi4_agent_tools/map/job-operations.js +2 -2
- package/dist/hoi4_agent_tools/map/model.js +17 -3
- package/dist/hoi4_agent_tools/map/validation.js +12 -18
- package/dist/hoi4_agent_tools/mcp/transports/negotiated-stdio.js +24 -16
- package/dist/hoi4_agent_tools/probability/job-operations.js +2 -2
- package/dist/hoi4_agent_tools/runtime.js +4 -2
- package/dist/hoi4_agent_tools/script-write/engine-plan.js +45 -0
- package/dist/hoi4_agent_tools/technology/engine-graph.js +156 -0
- package/dist/hoi4_agent_tools/technology/job-operations.js +2 -2
- package/dist/hoi4_agent_tools/technology/operations.js +1 -2
- package/dist/hoi4_agent_tools/technology/service.js +30 -59
- package/dist/hoi4_agent_tools/technology/write-job-operations.js +2 -2
- package/dist/hoi4_agent_tools/technology/write-operations.js +2 -2
- package/dist/hoi4_agent_tools/technology/write-plan.js +21 -207
- package/dist/hoi4_agent_tools/version.js +1 -1
- package/docs/configuration.md +11 -10
- package/docs/troubleshooting.md +11 -11
- package/engine/bin/darwin-arm64/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 +8 -8
- package/engine/bin/win32-x64/hoi4-engine.exe +0 -0
- package/npm-shrinkwrap.json +2 -2
- package/package.json +2 -2
- package/schemas/configuration.schema.json +143 -134
- 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 +1 -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
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { z } from 'zod/v4';
|
|
2
|
-
import {
|
|
2
|
+
import { idleCacheLifetime } from '../core/idle-cache-lifetime.js';
|
|
3
3
|
import { errorResult, toolResult } from '../core/operation-result.js';
|
|
4
4
|
import { ServiceError } from '../core/result.js';
|
|
5
5
|
import { focusInspectRequestSchema, focusRenderRequestSchema, focusRewriteRequestSchema, } from '../schemas/focus-requests.js';
|
|
@@ -9,7 +9,7 @@ const wireResult = z.record(z.string(), z.json());
|
|
|
9
9
|
/** Registers read-only focus operations without invoking transport handlers. */
|
|
10
10
|
export function registerFocusJobs(operations, engine) {
|
|
11
11
|
const workbench = new FocusWorkbench(engine.resolver, engine.transactions, engine.artifacts);
|
|
12
|
-
const lifetime =
|
|
12
|
+
const lifetime = idleCacheLifetime(engine, () => engine.releaseScanCaches());
|
|
13
13
|
function register(name, schema, normalize, execute) {
|
|
14
14
|
operations.registerRead(name, schema, async (input, context) => {
|
|
15
15
|
const release = lifetime.begin();
|
|
@@ -496,24 +496,14 @@ export class GuiAssetCatalog {
|
|
|
496
496
|
.resize(width, height, { fit: 'fill', kernel: 'nearest' })
|
|
497
497
|
.raw()
|
|
498
498
|
.toBuffer();
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
for (let offset = 7; offset < maskPixels.length; offset += 4) {
|
|
502
|
-
if (maskPixels[offset] !== firstAlpha) {
|
|
503
|
-
alphaVaries = true;
|
|
504
|
-
break;
|
|
505
|
-
}
|
|
506
|
-
}
|
|
499
|
+
// The game's masked flag shader takes only the mask's alpha (`OutColor.a = MaskColor.a`);
|
|
500
|
+
// its colour is ignored, so a black mask with full alpha shows the whole flag.
|
|
507
501
|
const alphaMask = Buffer.alloc(maskPixels.length);
|
|
508
502
|
for (let offset = 0; offset < maskPixels.length; offset += 4) {
|
|
509
503
|
alphaMask[offset] = 255;
|
|
510
504
|
alphaMask[offset + 1] = 255;
|
|
511
505
|
alphaMask[offset + 2] = 255;
|
|
512
|
-
alphaMask[offset + 3] =
|
|
513
|
-
? maskPixels[offset + 3]
|
|
514
|
-
: Math.round(maskPixels[offset] * 0.2126 +
|
|
515
|
-
maskPixels[offset + 1] * 0.7152 +
|
|
516
|
-
maskPixels[offset + 2] * 0.0722);
|
|
506
|
+
alphaMask[offset + 3] = maskPixels[offset + 3];
|
|
517
507
|
}
|
|
518
508
|
composites.push({
|
|
519
509
|
input: await sharp(alphaMask, {
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { z } from 'zod/v4';
|
|
2
|
-
import {
|
|
2
|
+
import { idleCacheLifetime } from '../core/idle-cache-lifetime.js';
|
|
3
3
|
import { errorResult, toolResult } from '../core/operation-result.js';
|
|
4
4
|
import { ServiceError } from '../core/result.js';
|
|
5
5
|
import { guiInspectRequestSchema, guiRenderRequestSchema, guiRewriteRequestSchema, } from '../schemas/gui-requests.js';
|
|
@@ -9,7 +9,7 @@ const wireResult = z.record(z.string(), z.json());
|
|
|
9
9
|
/** Registers read-only GUI operations without invoking transport handlers. */
|
|
10
10
|
export function registerGuiJobs(operations, engine) {
|
|
11
11
|
const studio = new ScriptedGuiStudio(engine);
|
|
12
|
-
const lifetime =
|
|
12
|
+
const lifetime = idleCacheLifetime(engine, () => studio.clearCaches());
|
|
13
13
|
function register(name, schema, normalize, execute) {
|
|
14
14
|
operations.registerRead(name, schema, async (input, context) => {
|
|
15
15
|
const release = lifetime.begin();
|
|
@@ -5,7 +5,7 @@ import { ServiceError } from '../core/result.js';
|
|
|
5
5
|
import { nativeWindowState } from './native-state.js';
|
|
6
6
|
import { GuiAssetCatalog } from './assets.js';
|
|
7
7
|
import { GUI_GRAPH_MAX_EDGES, GUI_GRAPH_MAX_ELEMENTS, GUI_GRAPH_MAX_NODES, GUI_SCENE_MAX_DEPTH, GUI_SCENE_MAX_ELEMENTS, GUI_SCENE_MAX_TEXT_CHARACTERS, GUI_SCENE_MAX_TEXT_LAYOUT_OPERATIONS, GUI_SCENE_MAX_WORK, GUI_TEXT_MAX_CHARACTERS, GUI_TEXT_MAX_MISSING_GLYPH_SAMPLES, } from './limits.js';
|
|
8
|
-
import { guiElementAttributeFidelity } from './source-graph.js';
|
|
8
|
+
import { guiElementAttributeFidelity, guiTextLooksLikeLocalisationKey } from './source-graph.js';
|
|
9
9
|
import { emptyFidelityReport, fidelityCategories } from './types.js';
|
|
10
10
|
import { ClausewitzEvaluationDefinitions } from '../core/clausewitz-evaluation.js';
|
|
11
11
|
import { evaluateGuiCondition, guiConditionScenario } from './scenario-conditions.js';
|
|
@@ -215,9 +215,7 @@ function resolveTokenText(value, scenario, localisation, rowValues) {
|
|
|
215
215
|
const localised = scenario.localisation[value] ?? localisation.get(value);
|
|
216
216
|
let text = localised ?? value;
|
|
217
217
|
assertTextLength(text, 'GUI resolved localisation');
|
|
218
|
-
if (localised === undefined &&
|
|
219
|
-
/^[A-Za-z0-9_.-]+$/u.test(value) &&
|
|
220
|
-
(value.includes('_') || value === value.toUpperCase()))
|
|
218
|
+
if (localised === undefined && guiTextLooksLikeLocalisationKey(value))
|
|
221
219
|
missingLocalisation = true;
|
|
222
220
|
const expandTokens = (input, stack, depth) => replaceTextBounded(input, /\$([A-Za-z0-9_.-]+)\$/gu, (match) => {
|
|
223
221
|
const key = match[1] ?? '';
|
|
@@ -389,7 +389,8 @@ function renderMaskedShield(element, textures) {
|
|
|
389
389
|
if (mask?.supported !== true || mask.dataUri === undefined)
|
|
390
390
|
return renderSpriteImage(sprite, rect, textures);
|
|
391
391
|
const id = `gui-mask-${sha256Bytes(element.id).slice(0, 20)}`;
|
|
392
|
-
|
|
392
|
+
// Alpha, not luminance: the game's masked shader keeps only the mask's alpha.
|
|
393
|
+
return `<defs><mask id="${id}" maskUnits="userSpaceOnUse" style="mask-type:alpha" ${rectAttributes(rect)}>${textures.use(mask.dataUri, rect)}</mask></defs>${textures.use(sprite.dataUri, rect, ` mask="url(#${id})"`)}`;
|
|
393
394
|
}
|
|
394
395
|
function renderElementSprite(element, textures) {
|
|
395
396
|
if (element.sprite?.supported !== true || element.sprite.dataUri === undefined)
|
|
@@ -1149,6 +1149,10 @@ function linkGraph(nodes, edges, elements, sprites, fonts, scriptedGuis, scripte
|
|
|
1149
1149
|
!isStaticGuiLocalisationReference(value))
|
|
1150
1150
|
continue;
|
|
1151
1151
|
const entry = localisationByKey.get(value);
|
|
1152
|
+
// The game shows a text that matches no key as it is written, so a text that is not in key
|
|
1153
|
+
// form ("Title text here!", "--") is plain text, not a missing localisation key.
|
|
1154
|
+
if (entry === undefined && !guiTextLooksLikeLocalisationKey(value))
|
|
1155
|
+
continue;
|
|
1152
1156
|
addEdge(edges, 'uses_localisation', element.id, entry === undefined ? `localisation:${value}` : deterministicId('gui_loc', entry), entry !== undefined, { field: key, key: value }, element.location);
|
|
1153
1157
|
}
|
|
1154
1158
|
}
|
|
@@ -1231,6 +1235,18 @@ function localisationAttributeValue(attributes, name) {
|
|
|
1231
1235
|
return value;
|
|
1232
1236
|
return undefined;
|
|
1233
1237
|
}
|
|
1238
|
+
/**
|
|
1239
|
+
* Whether a GUI text that matches no localisation entry still reads as a key. The game looks a
|
|
1240
|
+
* static text up as a key and draws the text itself when nothing matches, without an error.
|
|
1241
|
+
* Only a text in the form of a key (the characters a localisation file allows in a key, at least
|
|
1242
|
+
* one letter, and an underscore or all capitals, as `MY_WINDOW_TITLE` or `OK`) is reported as a
|
|
1243
|
+
* missing key; anything else (`Title text here!`, `--`, `close`) is drawn literally.
|
|
1244
|
+
*/
|
|
1245
|
+
export function guiTextLooksLikeLocalisationKey(value) {
|
|
1246
|
+
return (/^[A-Za-z0-9_.-]+$/u.test(value) &&
|
|
1247
|
+
/[A-Za-z]/u.test(value) &&
|
|
1248
|
+
(value.includes('_') || value === value.toUpperCase()));
|
|
1249
|
+
}
|
|
1234
1250
|
function isStaticGuiLocalisationReference(value) {
|
|
1235
1251
|
const trimmed = value.trim();
|
|
1236
1252
|
return !(trimmed.startsWith('[') && trimmed.endsWith(']'));
|
|
@@ -331,6 +331,36 @@ function selectedElements(graph, windowName, additionalTemplateNames = []) {
|
|
|
331
331
|
}
|
|
332
332
|
return [...selected.values()];
|
|
333
333
|
}
|
|
334
|
+
const definitionReferenceKinds = new Set(['uses_sprite', 'uses_font', 'static_fallback']);
|
|
335
|
+
/**
|
|
336
|
+
* A window graph keeps whole .gui files, so it also holds the other windows of the selected
|
|
337
|
+
* window's file, and it keeps every script file. The graph checks the references of all of them.
|
|
338
|
+
* Adds the .gfx file of every sprite and font that a kept source names and the full inventory
|
|
339
|
+
* resolves, so a sprite of a sibling window, a sprite a defined_text returns or a static
|
|
340
|
+
* fallback is not reported as missing because its .gfx file was left out of the window graph.
|
|
341
|
+
*/
|
|
342
|
+
function keepReferencedDefinitionSources(graph, selectedPaths) {
|
|
343
|
+
const definitionPaths = new Map();
|
|
344
|
+
for (const { id, sourcePath } of [...graph.sprites, ...graph.fonts])
|
|
345
|
+
definitionPaths.set(id, sourcePath);
|
|
346
|
+
const nodePaths = new Map(graph.nodes.map(({ id, path: nodePath }) => [id, nodePath]));
|
|
347
|
+
const kept = (id) => {
|
|
348
|
+
const nodePath = nodePaths.get(id);
|
|
349
|
+
return (nodePath !== undefined && (!/\.(?:gui|gfx)$/iu.test(nodePath) || selectedPaths.has(nodePath)));
|
|
350
|
+
};
|
|
351
|
+
const references = graph.edges.filter(({ kind, resolved, to }) => resolved && definitionReferenceKinds.has(kind) && definitionPaths.has(to));
|
|
352
|
+
let added = true;
|
|
353
|
+
while (added) {
|
|
354
|
+
added = false;
|
|
355
|
+
for (const edge of references) {
|
|
356
|
+
const target = definitionPaths.get(edge.to);
|
|
357
|
+
if (selectedPaths.has(target) || !kept(edge.from))
|
|
358
|
+
continue;
|
|
359
|
+
selectedPaths.add(target);
|
|
360
|
+
added = true;
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
}
|
|
334
364
|
function assertTargetWindowAvailable(graph, windowName) {
|
|
335
365
|
if (graph.elements.some(({ name }) => name === windowName))
|
|
336
366
|
return;
|
|
@@ -1177,6 +1207,7 @@ export class ScriptedGuiStudio {
|
|
|
1177
1207
|
if (namedFonts.has(font.name) ||
|
|
1178
1208
|
font.assetPaths.some((value) => referenceVariants(value).some((variant) => assetPaths.has(variant.toLowerCase()))))
|
|
1179
1209
|
selectedPaths.add(font.sourcePath);
|
|
1210
|
+
keepReferencedDefinitionSources(definitions.graph, selectedPaths);
|
|
1180
1211
|
const files = mergeScannedFiles(definitions.files.filter((file) => !/\.(?:gui|gfx)$/iu.test(file.relativePath) || selectedPaths.has(file.displayPath)), referenced, fontPages);
|
|
1181
1212
|
await stage('Resolving selected GUI assets');
|
|
1182
1213
|
const scanned = this.graphForFiles(files, `window:${workspaceId}:${windowName}`, additionalLocalisationKeys);
|
|
@@ -36,7 +36,7 @@ function newIdeaFilePath(file) {
|
|
|
36
36
|
return path;
|
|
37
37
|
}
|
|
38
38
|
/** The file the operation writes: the one named, the one that defines the idea, or the one with the category. */
|
|
39
|
-
function targetFile(snapshot, input) {
|
|
39
|
+
async function targetFile(snapshot, input) {
|
|
40
40
|
const files = modIdeaFiles(snapshot);
|
|
41
41
|
if (input.file !== undefined) {
|
|
42
42
|
const named = files.find(({ relativePath }) => normalized(relativePath) === normalized(input.file));
|
|
@@ -61,7 +61,8 @@ function targetFile(snapshot, input) {
|
|
|
61
61
|
if (input.category === undefined)
|
|
62
62
|
fail('IDEA_WRITE_CATEGORY_REQUIRED', 'add needs the category block the idea goes in');
|
|
63
63
|
const category = input.category;
|
|
64
|
-
const
|
|
64
|
+
const categoriesByFile = await Promise.all(files.map(({ bytes, relativePath }) => ideaCategories({ bytes, path: relativePath })));
|
|
65
|
+
const holding = files.filter((_, index) => categoriesByFile[index].includes(category));
|
|
65
66
|
if (holding.length === 0) {
|
|
66
67
|
if (input.createCategory === true) {
|
|
67
68
|
if (files.length === 1)
|
|
@@ -72,9 +73,7 @@ function targetFile(snapshot, input) {
|
|
|
72
73
|
}
|
|
73
74
|
fail('IDEA_WRITE_CATEGORY_NOT_FOUND', `No common/ideas file of the mod has a ${category} category; pass createCategory: true to create it`, {
|
|
74
75
|
category,
|
|
75
|
-
categories: [
|
|
76
|
-
...new Set(files.flatMap(({ bytes, relativePath }) => ideaCategories({ bytes, path: relativePath }))),
|
|
77
|
-
],
|
|
76
|
+
categories: [...new Set(categoriesByFile.flat())],
|
|
78
77
|
});
|
|
79
78
|
}
|
|
80
79
|
if (holding.length > 1)
|
|
@@ -110,7 +109,7 @@ function referencesOf(id, body) {
|
|
|
110
109
|
}
|
|
111
110
|
export async function computeIdeaWrite(engine, input, context, applied) {
|
|
112
111
|
const snapshot = await engine.scan(context.workspaceId, { patterns: WRITE_PATTERNS }, context.principal, context.signal);
|
|
113
|
-
const target = targetFile(snapshot, input);
|
|
112
|
+
const target = await targetFile(snapshot, input);
|
|
114
113
|
const planInput = {
|
|
115
114
|
operation: input.operation,
|
|
116
115
|
id: input.id,
|
|
@@ -122,7 +121,7 @@ export async function computeIdeaWrite(engine, input, context, applied) {
|
|
|
122
121
|
let plan;
|
|
123
122
|
if ('file' in target) {
|
|
124
123
|
file = target.file;
|
|
125
|
-
plan = planIdeaWrite({ bytes: file.bytes, path: file.relativePath }, planInput);
|
|
124
|
+
plan = await planIdeaWrite({ bytes: file.bytes, path: file.relativePath }, planInput);
|
|
126
125
|
}
|
|
127
126
|
else {
|
|
128
127
|
const inMod = snapshot.index
|
|
@@ -133,7 +132,7 @@ export async function computeIdeaWrite(engine, input, context, applied) {
|
|
|
133
132
|
id: input.id,
|
|
134
133
|
path: inMod.path,
|
|
135
134
|
});
|
|
136
|
-
plan = planNewIdeaFile(target.newPath, planInput);
|
|
135
|
+
plan = await planNewIdeaFile(target.newPath, planInput);
|
|
137
136
|
}
|
|
138
137
|
const missing = { localisation: [], picture: [] };
|
|
139
138
|
const diagnostics = [];
|
|
@@ -1,103 +1,22 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
function
|
|
12
|
-
const
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
if (idea.value.type !== 'block')
|
|
21
|
-
continue;
|
|
22
|
-
found.push({
|
|
23
|
-
idea,
|
|
24
|
-
category,
|
|
25
|
-
categoryBlock: category.value,
|
|
26
|
-
});
|
|
27
|
-
}
|
|
28
|
-
}
|
|
29
|
-
}
|
|
30
|
-
return found;
|
|
31
|
-
}
|
|
32
|
-
function categoryBlocks(document) {
|
|
33
|
-
return assignments(document.root, 'ideas').flatMap((ideas) => ideas.value.type === 'block'
|
|
34
|
-
? assignments(ideas.value).filter(({ value }) => value.type === 'block')
|
|
35
|
-
: []);
|
|
36
|
-
}
|
|
37
|
-
/** One level of indentation, read from the file's own ideas, tabs when it has none. */
|
|
38
|
-
function indentUnit(document, located) {
|
|
39
|
-
for (const { idea, category } of located) {
|
|
40
|
-
const outer = lineIndent(document.text, category.start);
|
|
41
|
-
const inner = lineIndent(document.text, idea.start);
|
|
42
|
-
if (inner.length > outer.length && inner.startsWith(outer))
|
|
43
|
-
return inner.slice(outer.length);
|
|
44
|
-
}
|
|
45
|
-
return '\t';
|
|
46
|
-
}
|
|
47
|
-
/** The body, checked on its own as the block it will become. */
|
|
48
|
-
function assertBodyIsOneBlock(id, body) {
|
|
49
|
-
const probe = parseClausewitz(Buffer.from(`${id} = {\n${body}\n}\n`, 'utf8'), 'idea-body');
|
|
50
|
-
const only = probe.root.entries;
|
|
51
|
-
const single = only.length === 1 && only[0]?.type === 'assignment' && only[0].key.value === id;
|
|
52
|
-
if (hasBlockingDiagnostics(probe.diagnostics) || !single || only[0]?.type !== 'assignment')
|
|
53
|
-
fail('IDEA_WRITE_BODY_INVALID', 'The body must be the text between the braces of one idea: balanced braces and no definition of its own', { diagnosticCodes: probe.diagnostics.map(({ code }) => code) });
|
|
54
|
-
if (only[0].value.type !== 'block' || only[0].value.entries.length === 0)
|
|
55
|
-
fail('IDEA_WRITE_BODY_INVALID', 'The body of an idea cannot be empty');
|
|
56
|
-
}
|
|
57
|
-
function definitionTexts(document, skip) {
|
|
58
|
-
const byKey = new Map();
|
|
59
|
-
for (const { idea, category } of definitions(document)) {
|
|
60
|
-
if (idea.start === skip?.start)
|
|
61
|
-
continue;
|
|
62
|
-
const key = `${category.key.value}:${idea.key.value}`;
|
|
63
|
-
byKey.set(key, [...(byKey.get(key) ?? []), document.text.slice(idea.start, idea.end)]);
|
|
64
|
-
}
|
|
65
|
-
return byKey;
|
|
66
|
-
}
|
|
67
|
-
/**
|
|
68
|
-
* The edit that adds a category block holding the new idea to the file's single `ideas` block, for
|
|
69
|
-
* `createCategory: true`.
|
|
70
|
-
*/
|
|
71
|
-
function categoryCreation(document, input, unit) {
|
|
72
|
-
const wanted = input.category;
|
|
73
|
-
if (!ID_PATTERN.test(wanted))
|
|
74
|
-
fail('IDEA_WRITE_CATEGORY_INVALID', `${JSON.stringify(wanted)} is not a valid category name`, {
|
|
75
|
-
category: wanted,
|
|
76
|
-
});
|
|
77
|
-
const text = document.text;
|
|
78
|
-
const newline = document.newline;
|
|
79
|
-
const ideasBlocks = assignments(document.root, 'ideas').filter(({ value }) => value.type === 'block');
|
|
80
|
-
if (ideasBlocks.length !== 1)
|
|
81
|
-
fail('IDEA_WRITE_LAYOUT_UNSUPPORTED', ideasBlocks.length === 0
|
|
82
|
-
? 'The file has no ideas block to put a new category in'
|
|
83
|
-
: `The file has ${ideasBlocks.length} ideas blocks, so the new category has no single place`, { blocks: ideasBlocks.length });
|
|
84
|
-
const ideas = ideasBlocks[0];
|
|
85
|
-
const block = ideas.value;
|
|
86
|
-
const close = block.close;
|
|
87
|
-
if (close === undefined)
|
|
88
|
-
fail('IDEA_WRITE_LAYOUT_UNSUPPORTED', 'The ideas block has no closing brace');
|
|
89
|
-
const closeLineStart = text.lastIndexOf('\n', close.start - 1) + 1;
|
|
90
|
-
if (!/^[ \t]*$/u.test(text.slice(closeLineStart, close.start)))
|
|
91
|
-
fail('IDEA_WRITE_LAYOUT_UNSUPPORTED', 'The closing brace of the ideas block shares its line with other text', { line: close.line });
|
|
92
|
-
const categoryIndent = lineIndent(text, ideas.start) + unit;
|
|
93
|
-
const ideaIndent = categoryIndent + unit;
|
|
94
|
-
const ideaText = `${ideaIndent}${input.id} = {${newline}${indentedBody(input.body, ideaIndent + unit, newline)}${newline}${ideaIndent}}${newline}`;
|
|
95
|
-
return {
|
|
96
|
-
start: closeLineStart,
|
|
97
|
-
end: closeLineStart,
|
|
98
|
-
text: `${block.entries.length > 0 ? newline : ''}${categoryIndent}${wanted} = {${newline}${ideaText}${categoryIndent}}${newline}`,
|
|
99
|
-
description: `add ${input.id} in the new category ${wanted}`,
|
|
100
|
-
};
|
|
1
|
+
import { z } from 'zod/v4';
|
|
2
|
+
import { callSourceQuery, callWritePlan, replacementSchema, } from '../script-write/engine-plan.js';
|
|
3
|
+
const planSchema = z.object({
|
|
4
|
+
operation: z.enum(['add', 'replace', 'remove']),
|
|
5
|
+
id: z.string(),
|
|
6
|
+
category: z.string(),
|
|
7
|
+
path: z.string(),
|
|
8
|
+
edit: replacementSchema,
|
|
9
|
+
untouchedDefinitions: z.number().int().nonnegative(),
|
|
10
|
+
});
|
|
11
|
+
async function plan(path, input, source) {
|
|
12
|
+
const answer = await callWritePlan({
|
|
13
|
+
op: 'idea_write.plan',
|
|
14
|
+
path,
|
|
15
|
+
input: { ...input },
|
|
16
|
+
...(source === undefined ? {} : { source }),
|
|
17
|
+
result: planSchema,
|
|
18
|
+
});
|
|
19
|
+
return { ...answer.result, text: answer.text, bytes: answer.bytes, diff: answer.diff };
|
|
101
20
|
}
|
|
102
21
|
/**
|
|
103
22
|
* The plan that creates a new `common/ideas` file holding one new idea in one category, for
|
|
@@ -105,212 +24,13 @@ function categoryCreation(document, input, unit) {
|
|
|
105
24
|
* game's own ideas files do.
|
|
106
25
|
*/
|
|
107
26
|
export function planNewIdeaFile(path, input) {
|
|
108
|
-
|
|
109
|
-
fail('IDEA_WRITE_ID_INVALID', `${JSON.stringify(input.id)} is not a valid idea id`, {
|
|
110
|
-
id: input.id,
|
|
111
|
-
});
|
|
112
|
-
if (input.operation !== 'add')
|
|
113
|
-
fail('IDEA_WRITE_FILE_NOT_FOUND', `${path} does not exist, and only add can create a file`);
|
|
114
|
-
if (input.category === undefined || !ID_PATTERN.test(input.category))
|
|
115
|
-
fail('IDEA_WRITE_CATEGORY_REQUIRED', 'a new file needs the category block the idea goes in');
|
|
116
|
-
if (input.body === undefined || input.body.trim() === '')
|
|
117
|
-
fail('IDEA_WRITE_BODY_REQUIRED', 'add needs the body of the idea');
|
|
118
|
-
assertBodyIsOneBlock(input.id, input.body);
|
|
119
|
-
const text = [
|
|
120
|
-
'ideas = {',
|
|
121
|
-
`\t${input.category} = {`,
|
|
122
|
-
`\t\t${input.id} = {`,
|
|
123
|
-
indentedBody(input.body, '\t\t\t', '\n'),
|
|
124
|
-
'\t\t}',
|
|
125
|
-
'\t}',
|
|
126
|
-
'}',
|
|
127
|
-
'',
|
|
128
|
-
].join('\n');
|
|
129
|
-
const written = parseClausewitz(Buffer.from(text, 'utf8'), path);
|
|
130
|
-
if (hasBlockingDiagnostics(written.diagnostics))
|
|
131
|
-
fail('IDEA_WRITE_RESULT_INVALID', 'The new file would have syntax errors', {
|
|
132
|
-
diagnosticCodes: written.diagnostics.map(({ code }) => code),
|
|
133
|
-
});
|
|
134
|
-
return {
|
|
135
|
-
operation: 'add',
|
|
136
|
-
id: input.id,
|
|
137
|
-
category: input.category,
|
|
138
|
-
path,
|
|
139
|
-
text,
|
|
140
|
-
bytes: Buffer.from(text, 'utf8'),
|
|
141
|
-
edit: {
|
|
142
|
-
start: 0,
|
|
143
|
-
end: 0,
|
|
144
|
-
text,
|
|
145
|
-
description: `create ${path} with ${input.id}`,
|
|
146
|
-
},
|
|
147
|
-
diff: unifiedTextDiff('', text, `a/${path}`, `b/${path}`, { context: DIFF_CONTEXT_LINES }),
|
|
148
|
-
untouchedDefinitions: 0,
|
|
149
|
-
};
|
|
27
|
+
return plan(path, input, undefined);
|
|
150
28
|
}
|
|
151
29
|
export function planIdeaWrite(source, input) {
|
|
152
|
-
|
|
153
|
-
fail('IDEA_WRITE_ID_INVALID', `${JSON.stringify(input.id)} is not a valid idea id`, {
|
|
154
|
-
id: input.id,
|
|
155
|
-
});
|
|
156
|
-
if (input.operation === 'remove' && input.body !== undefined)
|
|
157
|
-
fail('IDEA_WRITE_BODY_UNEXPECTED', 'remove takes no body');
|
|
158
|
-
if (input.operation !== 'remove' && (input.body === undefined || input.body.trim() === ''))
|
|
159
|
-
fail('IDEA_WRITE_BODY_REQUIRED', `${input.operation} needs the body of the idea`);
|
|
160
|
-
const document = parseClausewitz(source.bytes, source.path);
|
|
161
|
-
if (hasBlockingDiagnostics(document.diagnostics))
|
|
162
|
-
fail('IDEA_WRITE_SOURCE_INVALID', 'The source has syntax errors and cannot be edited safely', {
|
|
163
|
-
path: source.path,
|
|
164
|
-
diagnosticCodes: document.diagnostics.map(({ code }) => code),
|
|
165
|
-
});
|
|
166
|
-
const text = document.text;
|
|
167
|
-
const newline = document.newline;
|
|
168
|
-
const located = definitions(document);
|
|
169
|
-
if (input.body !== undefined)
|
|
170
|
-
assertBodyIsOneBlock(input.id, input.body);
|
|
171
|
-
const unit = indentUnit(document, located);
|
|
172
|
-
const existing = located.filter(({ idea }) => idea.key.value === input.id);
|
|
173
|
-
let edit;
|
|
174
|
-
let category;
|
|
175
|
-
let skip;
|
|
176
|
-
if (input.operation === 'add') {
|
|
177
|
-
if (existing.length > 0)
|
|
178
|
-
fail('IDEA_WRITE_DUPLICATE_ID', `${input.id} is already defined in this file`, {
|
|
179
|
-
id: input.id,
|
|
180
|
-
category: existing[0]?.category.key.value,
|
|
181
|
-
line: existing[0]?.idea.key.token.line,
|
|
182
|
-
});
|
|
183
|
-
if (input.category === undefined)
|
|
184
|
-
fail('IDEA_WRITE_CATEGORY_REQUIRED', 'add needs the category block the idea goes in');
|
|
185
|
-
const wanted = input.category;
|
|
186
|
-
const matching = categoryBlocks(document).filter(({ key }) => key.value === wanted);
|
|
187
|
-
if (matching.length === 0 && input.createCategory !== true)
|
|
188
|
-
fail('IDEA_WRITE_CATEGORY_NOT_FOUND', `The file has no ${wanted} category; pass createCategory: true to create it`, {
|
|
189
|
-
category: wanted,
|
|
190
|
-
categories: [...new Set(categoryBlocks(document).map(({ key }) => key.value))],
|
|
191
|
-
});
|
|
192
|
-
if (matching.length > 1)
|
|
193
|
-
fail('IDEA_WRITE_CATEGORY_AMBIGUOUS', `The file has ${matching.length} ${wanted} categories`, {
|
|
194
|
-
category: wanted,
|
|
195
|
-
lines: matching.map(({ key }) => key.token.line),
|
|
196
|
-
});
|
|
197
|
-
if (matching.length === 0) {
|
|
198
|
-
edit = categoryCreation(document, input, unit);
|
|
199
|
-
}
|
|
200
|
-
else {
|
|
201
|
-
const target = matching[0];
|
|
202
|
-
const block = target.value;
|
|
203
|
-
const close = block.close;
|
|
204
|
-
if (close === undefined)
|
|
205
|
-
fail('IDEA_WRITE_LAYOUT_UNSUPPORTED', `The ${wanted} category has no closing brace`);
|
|
206
|
-
const closeLineStart = text.lastIndexOf('\n', close.start - 1) + 1;
|
|
207
|
-
if (!/^[ \t]*$/u.test(text.slice(closeLineStart, close.start)))
|
|
208
|
-
fail('IDEA_WRITE_LAYOUT_UNSUPPORTED', `The closing brace of ${wanted} shares its line with other text, so the new idea has no line to go on`, { category: wanted, line: close.line });
|
|
209
|
-
const categoryIndent = lineIndent(text, target.start);
|
|
210
|
-
const ideaIndent = categoryIndent + unit;
|
|
211
|
-
const hasSiblings = block.entries.length > 0;
|
|
212
|
-
const ideaText = `${ideaIndent}${input.id} = {${newline}${indentedBody(input.body, ideaIndent + unit, newline)}${newline}${ideaIndent}}${newline}`;
|
|
213
|
-
edit = {
|
|
214
|
-
start: closeLineStart,
|
|
215
|
-
end: closeLineStart,
|
|
216
|
-
text: `${hasSiblings ? newline : ''}${ideaText}`,
|
|
217
|
-
description: `add ${input.id} to ${wanted}`,
|
|
218
|
-
};
|
|
219
|
-
}
|
|
220
|
-
category = wanted;
|
|
221
|
-
}
|
|
222
|
-
else {
|
|
223
|
-
if (existing.length === 0)
|
|
224
|
-
fail('IDEA_WRITE_NOT_FOUND', `${input.id} is not defined in this file`, { id: input.id });
|
|
225
|
-
if (existing.length > 1)
|
|
226
|
-
fail('IDEA_WRITE_DUPLICATE_ID', `${input.id} is defined ${existing.length} times in this file`, {
|
|
227
|
-
id: input.id,
|
|
228
|
-
lines: existing.map(({ idea }) => idea.key.token.line),
|
|
229
|
-
});
|
|
230
|
-
const found = existing[0];
|
|
231
|
-
category = found.category.key.value;
|
|
232
|
-
if (input.category !== undefined && input.category !== category)
|
|
233
|
-
fail('IDEA_WRITE_CATEGORY_MISMATCH', `${input.id} is in ${category}, and moving an idea to another category is not supported`, { id: input.id, category });
|
|
234
|
-
skip = found.idea;
|
|
235
|
-
const ideaIndent = lineIndent(text, found.idea.start);
|
|
236
|
-
if (input.operation === 'replace') {
|
|
237
|
-
edit = {
|
|
238
|
-
start: found.idea.start,
|
|
239
|
-
end: found.idea.end,
|
|
240
|
-
text: `${input.id} = {${newline}${indentedBody(input.body, ideaIndent + unit, newline)}${newline}${ideaIndent}}`,
|
|
241
|
-
description: `replace ${input.id}`,
|
|
242
|
-
};
|
|
243
|
-
}
|
|
244
|
-
else {
|
|
245
|
-
const lineStart = text.lastIndexOf('\n', found.idea.start - 1) + 1;
|
|
246
|
-
const lineEndAt = text.indexOf('\n', found.idea.end);
|
|
247
|
-
const lineEnd = lineEndAt === -1 ? text.length : lineEndAt + 1;
|
|
248
|
-
const alone = /^[ \t]*$/u.test(text.slice(lineStart, found.idea.start)) &&
|
|
249
|
-
/^[ \t]*\r?$/u.test(text.slice(found.idea.end, lineEndAt === -1 ? text.length : lineEndAt));
|
|
250
|
-
if (!alone) {
|
|
251
|
-
edit = {
|
|
252
|
-
start: found.idea.start,
|
|
253
|
-
end: found.idea.end,
|
|
254
|
-
text: '',
|
|
255
|
-
description: `remove ${input.id}`,
|
|
256
|
-
};
|
|
257
|
-
}
|
|
258
|
-
else {
|
|
259
|
-
// A blank line that only separated this idea from the one before it goes with it.
|
|
260
|
-
const before = text.slice(0, lineStart);
|
|
261
|
-
const blankBefore = /(?:^|\n)[ \t]*\r?\n$/u.test(before) && before.length > 0;
|
|
262
|
-
const after = text.slice(lineEnd);
|
|
263
|
-
const nextIsBlankOrClose = /^[ \t]*(?:\r?\n|\})/u.test(after) || after === '';
|
|
264
|
-
let start = lineStart;
|
|
265
|
-
if (blankBefore && nextIsBlankOrClose) {
|
|
266
|
-
const previousLineStart = before.lastIndexOf('\n', before.length - 2) + 1;
|
|
267
|
-
start = previousLineStart;
|
|
268
|
-
}
|
|
269
|
-
edit = { start, end: lineEnd, text: '', description: `remove ${input.id}` };
|
|
270
|
-
}
|
|
271
|
-
}
|
|
272
|
-
}
|
|
273
|
-
const bytes = applyReplacements(document, [edit]);
|
|
274
|
-
const after = text.slice(0, edit.start) + edit.text + text.slice(edit.end);
|
|
275
|
-
const written = parseClausewitz(bytes, source.path);
|
|
276
|
-
if (hasBlockingDiagnostics(written.diagnostics))
|
|
277
|
-
fail('IDEA_WRITE_RESULT_INVALID', 'The edit would leave the file with syntax errors', {
|
|
278
|
-
diagnosticCodes: written.diagnostics.map(({ code }) => code),
|
|
279
|
-
});
|
|
280
|
-
const before = definitionTexts(document, skip);
|
|
281
|
-
const afterTexts = definitionTexts(written, undefined);
|
|
282
|
-
let untouched = 0;
|
|
283
|
-
for (const [key, texts] of before) {
|
|
284
|
-
const now = afterTexts.get(key) ?? [];
|
|
285
|
-
for (const textOfIdea of texts)
|
|
286
|
-
if (now.includes(textOfIdea))
|
|
287
|
-
untouched += 1;
|
|
288
|
-
else
|
|
289
|
-
fail('IDEA_WRITE_RESULT_INVALID', `The edit would change ${key}, which it must not touch`, {
|
|
290
|
-
key,
|
|
291
|
-
});
|
|
292
|
-
}
|
|
293
|
-
const now = written.text;
|
|
294
|
-
if (now !== after)
|
|
295
|
-
fail('IDEA_WRITE_RESULT_INVALID', 'The written file does not match the planned edit');
|
|
296
|
-
return {
|
|
297
|
-
operation: input.operation,
|
|
298
|
-
id: input.id,
|
|
299
|
-
category,
|
|
300
|
-
path: source.path,
|
|
301
|
-
text: after,
|
|
302
|
-
bytes,
|
|
303
|
-
edit,
|
|
304
|
-
diff: unifiedTextDiff(text, after, `a/${source.path}`, `b/${source.path}`, {
|
|
305
|
-
context: DIFF_CONTEXT_LINES,
|
|
306
|
-
}),
|
|
307
|
-
untouchedDefinitions: untouched,
|
|
308
|
-
};
|
|
30
|
+
return plan(source.path, input, source.bytes);
|
|
309
31
|
}
|
|
310
32
|
/** The category blocks of a `common/ideas` file, or none when the file cannot be parsed. */
|
|
311
|
-
export function ideaCategories(source) {
|
|
312
|
-
const
|
|
313
|
-
|
|
314
|
-
return [];
|
|
315
|
-
return [...new Set(categoryBlocks(document).map(({ key }) => key.value))];
|
|
33
|
+
export async function ideaCategories(source) {
|
|
34
|
+
const answer = await callSourceQuery('idea_write.categories', source.path, source.bytes, z.object({ categories: z.array(z.string()) }));
|
|
35
|
+
return answer.categories;
|
|
316
36
|
}
|