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.
Files changed (93) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/dist/hoi4_agent_tools/characters/write-operations.js +2 -2
  3. package/dist/hoi4_agent_tools/characters/write-plan.js +21 -205
  4. package/dist/hoi4_agent_tools/core/artifacts-engine.js +272 -0
  5. package/dist/hoi4_agent_tools/core/configuration.js +6 -0
  6. package/dist/hoi4_agent_tools/core/engine.js +67 -21
  7. package/dist/hoi4_agent_tools/core/idle-cache-lifetime.js +7 -0
  8. package/dist/hoi4_agent_tools/core/operation-tasks.js +3 -1
  9. package/dist/hoi4_agent_tools/core/transactions.js +6 -0
  10. package/dist/hoi4_agent_tools/core/workspace.js +14 -1
  11. package/dist/hoi4_agent_tools/decision/write-operations.js +7 -8
  12. package/dist/hoi4_agent_tools/decision/write-plan.js +25 -245
  13. package/dist/hoi4_agent_tools/doctrine/write-operations.js +2 -2
  14. package/dist/hoi4_agent_tools/doctrine/write-plan.js +21 -180
  15. package/dist/hoi4_agent_tools/event/graph.js +3 -3
  16. package/dist/hoi4_agent_tools/event/job-operations.js +2 -2
  17. package/dist/hoi4_agent_tools/event/write-job-operations.js +2 -2
  18. package/dist/hoi4_agent_tools/event/write-operations.js +9 -10
  19. package/dist/hoi4_agent_tools/event/write-plan.js +28 -278
  20. package/dist/hoi4_agent_tools/focus/job-operations.js +2 -2
  21. package/dist/hoi4_agent_tools/gui/assets.js +3 -13
  22. package/dist/hoi4_agent_tools/gui/job-operations.js +2 -2
  23. package/dist/hoi4_agent_tools/gui/layout.js +2 -4
  24. package/dist/hoi4_agent_tools/gui/renderer.js +2 -1
  25. package/dist/hoi4_agent_tools/gui/source-graph.js +16 -0
  26. package/dist/hoi4_agent_tools/gui/studio.js +31 -0
  27. package/dist/hoi4_agent_tools/ideas/write-operations.js +7 -8
  28. package/dist/hoi4_agent_tools/ideas/write-plan.js +24 -304
  29. package/dist/hoi4_agent_tools/map/engine-validation.js +230 -0
  30. package/dist/hoi4_agent_tools/map/job-operations.js +2 -2
  31. package/dist/hoi4_agent_tools/map/model.js +17 -3
  32. package/dist/hoi4_agent_tools/map/validation.js +12 -18
  33. package/dist/hoi4_agent_tools/mcp/transports/negotiated-stdio.js +24 -16
  34. package/dist/hoi4_agent_tools/probability/job-operations.js +2 -2
  35. package/dist/hoi4_agent_tools/runtime.js +4 -2
  36. package/dist/hoi4_agent_tools/script-write/engine-plan.js +45 -0
  37. package/dist/hoi4_agent_tools/technology/engine-graph.js +156 -0
  38. package/dist/hoi4_agent_tools/technology/job-operations.js +2 -2
  39. package/dist/hoi4_agent_tools/technology/operations.js +1 -2
  40. package/dist/hoi4_agent_tools/technology/service.js +30 -59
  41. package/dist/hoi4_agent_tools/technology/write-job-operations.js +2 -2
  42. package/dist/hoi4_agent_tools/technology/write-operations.js +2 -2
  43. package/dist/hoi4_agent_tools/technology/write-plan.js +21 -207
  44. package/dist/hoi4_agent_tools/version.js +1 -1
  45. package/docs/configuration.md +11 -10
  46. package/docs/troubleshooting.md +11 -11
  47. package/engine/bin/darwin-arm64/hoi4-engine +0 -0
  48. package/engine/bin/linux-arm64/hoi4-engine +0 -0
  49. package/engine/bin/linux-x64/hoi4-engine +0 -0
  50. package/engine/bin/manifest.json +8 -8
  51. package/engine/bin/win32-x64/hoi4-engine.exe +0 -0
  52. package/npm-shrinkwrap.json +2 -2
  53. package/package.json +2 -2
  54. package/schemas/configuration.schema.json +143 -134
  55. package/schemas/continuous-focus-palette.schema.json +1 -1
  56. package/schemas/custom-weighted-pool.schema.json +1 -1
  57. package/schemas/decision-inspect-input.schema.json +1 -1
  58. package/schemas/error-log-input.schema.json +1 -1
  59. package/schemas/event-feature-manifest.schema.json +1 -1
  60. package/schemas/focus-plan.schema.json +1 -1
  61. package/schemas/focus-planning-sidecar.schema.json +1 -1
  62. package/schemas/geography-model.schema.json +1 -1
  63. package/schemas/gui-animation-source.schema.json +1 -1
  64. package/schemas/gui-helper.schema.json +1 -1
  65. package/schemas/gui-scenario.schema.json +1 -1
  66. package/schemas/helper-expansion-request.schema.json +1 -1
  67. package/schemas/helper-expansion-summary.schema.json +1 -1
  68. package/schemas/impact-inspect-input.schema.json +1 -1
  69. package/schemas/map-operation.schema.json +1 -1
  70. package/schemas/mechanic-test-input.schema.json +1 -1
  71. package/schemas/mod-index-input.schema.json +1 -1
  72. package/schemas/operation-result.schema.json +1 -1
  73. package/schemas/package-check-input.schema.json +1 -1
  74. package/schemas/package-manifest.schema.json +1 -1
  75. package/schemas/probability-analysis-result.schema.json +1 -1
  76. package/schemas/probability-compare-input.schema.json +1 -1
  77. package/schemas/probability-evaluate-input.schema.json +1 -1
  78. package/schemas/probability-inspect-input.schema.json +1 -1
  79. package/schemas/probability-render-input.schema.json +1 -1
  80. package/schemas/probability-scenario-set.schema.json +1 -1
  81. package/schemas/probability-sequence-input.schema.json +1 -1
  82. package/schemas/probability-simulate-input.schema.json +1 -1
  83. package/schemas/probability-sweep-input.schema.json +1 -1
  84. package/schemas/reference-context-input.schema.json +1 -1
  85. package/schemas/reference-read-input.schema.json +1 -1
  86. package/schemas/reference-search-input.schema.json +1 -1
  87. package/schemas/reference-sheets.schema.json +1 -1
  88. package/schemas/scenario-suite.schema.json +1 -1
  89. package/schemas/scenario-test-input.schema.json +1 -1
  90. package/schemas/script-validate-input.schema.json +1 -1
  91. package/schemas/shared-scenario.schema.json +1 -1
  92. package/schemas/source-lookup-input.schema.json +1 -1
  93. package/server.json +2 -2
@@ -1,185 +1,26 @@
1
- import { indentedBody, lineIndent } from '../core/block-edit.js';
2
- import { hasBlockingDiagnostics } from '../core/diagnostics.js';
3
- import { DIFF_CONTEXT_LINES, unifiedTextDiff } from '../core/diff.js';
4
- import { ServiceError } from '../core/result.js';
5
- import { applyReplacements, assignments, parseClausewitz, } from '../core/source/index.js';
6
- const ID_PATTERN = /^[A-Za-z_][A-Za-z0-9_.-]*$/u;
7
- function fail(code, message, details) {
8
- throw new ServiceError(code, message, details);
9
- }
10
- /** Every top-level block of the document: one doctrine definition each. */
11
- function definitions(document) {
12
- return assignments(document.root).filter(({ value }) => value.type === 'block');
13
- }
14
- /** One level of indentation, read from the file's own doctrines, tabs when it has none. */
15
- function indentUnit(definitionsOfFile, text) {
16
- for (const doctrine of definitionsOfFile) {
17
- if (doctrine.value.type !== 'block')
18
- continue;
19
- const first = doctrine.value.entries[0];
20
- if (first === undefined)
21
- continue;
22
- const inner = lineIndent(text, first.start);
23
- const outer = lineIndent(text, doctrine.start);
24
- if (inner.length > outer.length && inner.startsWith(outer))
25
- return inner.slice(outer.length);
26
- }
27
- return '\t';
28
- }
29
- /** The body, checked on its own as the block it will become. */
30
- function assertBodyIsOneBlock(id, body) {
31
- const probe = parseClausewitz(Buffer.from(`${id} = {\n${body}\n}\n`, 'utf8'), 'doctrine-body');
32
- const only = probe.root.entries;
33
- const single = only.length === 1 && only[0]?.type === 'assignment' && only[0].key.value === id;
34
- if (hasBlockingDiagnostics(probe.diagnostics) || !single || only[0]?.type !== 'assignment')
35
- fail('DOCTRINE_WRITE_BODY_INVALID', 'The body must be the text between the braces of one doctrine: balanced braces and no definition of its own', { diagnosticCodes: probe.diagnostics.map(({ code }) => code) });
36
- if (only[0].value.type !== 'block' || only[0].value.entries.length === 0)
37
- fail('DOCTRINE_WRITE_BODY_INVALID', 'The body of a doctrine cannot be empty');
38
- }
39
- function definitionTexts(document, skip) {
40
- const byKey = new Map();
41
- for (const doctrine of definitions(document)) {
42
- if (doctrine.start === skip?.start)
43
- continue;
44
- const key = doctrine.key.value;
45
- byKey.set(key, [...(byKey.get(key) ?? []), document.text.slice(doctrine.start, doctrine.end)]);
46
- }
47
- return byKey;
48
- }
49
- function checkRequest(input) {
50
- if (!ID_PATTERN.test(input.id))
51
- fail('DOCTRINE_WRITE_ID_INVALID', `${JSON.stringify(input.id)} is not a valid doctrine id`, {
52
- id: input.id,
53
- });
54
- if (input.operation === 'remove' && input.body !== undefined)
55
- fail('DOCTRINE_WRITE_BODY_UNEXPECTED', 'remove takes no body');
56
- if (input.operation !== 'remove' && (input.body === undefined || input.body.trim() === ''))
57
- fail('DOCTRINE_WRITE_BODY_REQUIRED', `${input.operation} needs the body of the doctrine`);
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
+ id: z.string(),
6
+ path: z.string(),
7
+ edit: replacementSchema,
8
+ untouchedDefinitions: z.number().int().nonnegative(),
9
+ });
10
+ async function plan(path, input, source) {
11
+ const answer = await callWritePlan({
12
+ op: 'doctrine_write.plan',
13
+ path,
14
+ input: { ...input },
15
+ ...(source === undefined ? {} : { source }),
16
+ result: planSchema,
17
+ });
18
+ return { ...answer.result, text: answer.text, bytes: answer.bytes, diff: answer.diff };
58
19
  }
59
- /**
60
- * The plan that creates a new doctrine file holding one new doctrine, for `createFile: true`. The file
61
- * is UTF-8 without a byte order mark and uses tabs and LF, as the game's own doctrine files do.
62
- */
20
+ /** The plan that creates a new file holding one new doctrine, for `createFile: true`. */
63
21
  export function planNewDoctrineFile(path, input) {
64
- checkRequest(input);
65
- if (input.operation !== 'add')
66
- fail('DOCTRINE_WRITE_FILE_NOT_FOUND', `${path} does not exist, and only add can create a file`);
67
- assertBodyIsOneBlock(input.id, input.body);
68
- const text = [`${input.id} = {`, indentedBody(input.body, '\t', '\n'), '}', ''].join('\n');
69
- const written = parseClausewitz(Buffer.from(text, 'utf8'), path);
70
- if (hasBlockingDiagnostics(written.diagnostics))
71
- fail('DOCTRINE_WRITE_RESULT_INVALID', 'The new file would have syntax errors', {
72
- diagnosticCodes: written.diagnostics.map(({ code }) => code),
73
- });
74
- return {
75
- operation: 'add',
76
- id: input.id,
77
- path,
78
- text,
79
- bytes: Buffer.from(text, 'utf8'),
80
- edit: { start: 0, end: 0, text, description: `create ${path} with ${input.id}` },
81
- diff: unifiedTextDiff('', text, `a/${path}`, `b/${path}`, { context: DIFF_CONTEXT_LINES }),
82
- untouchedDefinitions: 0,
83
- };
22
+ return plan(path, input, undefined);
84
23
  }
85
24
  export function planDoctrineWrite(source, input) {
86
- checkRequest(input);
87
- const document = parseClausewitz(source.bytes, source.path);
88
- if (hasBlockingDiagnostics(document.diagnostics))
89
- fail('DOCTRINE_WRITE_SOURCE_INVALID', 'The source has syntax errors and cannot be edited safely', { path: source.path, diagnosticCodes: document.diagnostics.map(({ code }) => code) });
90
- const text = document.text;
91
- const newline = document.newline;
92
- if (input.body !== undefined)
93
- assertBodyIsOneBlock(input.id, input.body);
94
- const located = definitions(document);
95
- const unit = indentUnit(located, text);
96
- const existing = located.filter(({ key }) => key.value === input.id);
97
- let edit;
98
- let skip;
99
- if (input.operation === 'add') {
100
- if (existing.length > 0)
101
- fail('DOCTRINE_WRITE_DUPLICATE_ID', `${input.id} is already defined in this file`, {
102
- id: input.id,
103
- line: existing[0]?.key.token.line,
104
- });
105
- const lead = text === '' ? '' : `${text.endsWith('\n') ? '' : newline}${newline}`;
106
- edit = {
107
- start: text.length,
108
- end: text.length,
109
- text: `${lead}${input.id} = {${newline}${indentedBody(input.body, unit, newline)}${newline}}${newline}`,
110
- description: `add ${input.id}`,
111
- };
112
- }
113
- else {
114
- if (existing.length === 0)
115
- fail('DOCTRINE_WRITE_NOT_FOUND', `${input.id} is not defined in this file`, {
116
- id: input.id,
117
- });
118
- if (existing.length > 1)
119
- fail('DOCTRINE_WRITE_DUPLICATE_ID', `${input.id} is defined ${existing.length} times in this file`, { id: input.id, lines: existing.map(({ key }) => key.token.line) });
120
- const found = existing[0];
121
- skip = found;
122
- const indent = lineIndent(text, found.start);
123
- if (input.operation === 'replace') {
124
- edit = {
125
- start: found.start,
126
- end: found.end,
127
- text: `${input.id} = {${newline}${indentedBody(input.body, indent + unit, newline)}${newline}${indent}}`,
128
- description: `replace ${input.id}`,
129
- };
130
- }
131
- else {
132
- const lineStart = text.lastIndexOf('\n', found.start - 1) + 1;
133
- const lineEndAt = text.indexOf('\n', found.end);
134
- const lineEnd = lineEndAt === -1 ? text.length : lineEndAt + 1;
135
- const alone = /^[ \t]*$/u.test(text.slice(lineStart, found.start)) &&
136
- /^[ \t]*\r?$/u.test(text.slice(found.end, lineEndAt === -1 ? text.length : lineEndAt));
137
- if (!alone) {
138
- edit = { start: found.start, end: found.end, text: '', description: `remove ${input.id}` };
139
- }
140
- else {
141
- // A blank line that only separated this doctrine from the one before it goes with it.
142
- const before = text.slice(0, lineStart);
143
- const blankBefore = /(?:^|\n)[ \t]*\r?\n$/u.test(before) && before.length > 0;
144
- const after = text.slice(lineEnd);
145
- const nextIsBlankOrEnd = /^[ \t]*\r?(?:\n|$)/u.test(after);
146
- let start = lineStart;
147
- if (blankBefore && nextIsBlankOrEnd)
148
- start = before.lastIndexOf('\n', before.length - 2) + 1;
149
- edit = { start, end: lineEnd, text: '', description: `remove ${input.id}` };
150
- }
151
- }
152
- }
153
- const bytes = applyReplacements(document, [edit]);
154
- const after = text.slice(0, edit.start) + edit.text + text.slice(edit.end);
155
- const written = parseClausewitz(bytes, source.path);
156
- if (hasBlockingDiagnostics(written.diagnostics))
157
- fail('DOCTRINE_WRITE_RESULT_INVALID', 'The edit would leave the file with syntax errors', {
158
- diagnosticCodes: written.diagnostics.map(({ code }) => code),
159
- });
160
- const before = definitionTexts(document, skip);
161
- const afterTexts = definitionTexts(written, undefined);
162
- let untouched = 0;
163
- for (const [key, texts] of before) {
164
- const now = afterTexts.get(key) ?? [];
165
- for (const textOfDoctrine of texts)
166
- if (now.includes(textOfDoctrine))
167
- untouched += 1;
168
- else
169
- fail('DOCTRINE_WRITE_RESULT_INVALID', `The edit would change ${key}, which it must not touch`, { key });
170
- }
171
- if (written.text !== after)
172
- fail('DOCTRINE_WRITE_RESULT_INVALID', 'The written file does not match the planned edit');
173
- return {
174
- operation: input.operation,
175
- id: input.id,
176
- path: source.path,
177
- text: after,
178
- bytes,
179
- edit,
180
- diff: unifiedTextDiff(text, after, `a/${source.path}`, `b/${source.path}`, {
181
- context: DIFF_CONTEXT_LINES,
182
- }),
183
- untouchedDefinitions: untouched,
184
- };
25
+ return plan(source.path, input, source.bytes);
185
26
  }
@@ -25,7 +25,7 @@ function stableUnique(values) {
25
25
  function worstConfidence(...values) {
26
26
  return values.reduce((worst, value) => confidenceRank[value] > confidenceRank[worst] ? value : worst);
27
27
  }
28
- function activeFiles(snapshot) {
28
+ export function activeFiles(snapshot) {
29
29
  return snapshot.files
30
30
  .filter(({ relativePath, shadowedBy }) => shadowedBy === undefined &&
31
31
  /\.(?:txt|ya?ml)$/iu.test(relativePath) &&
@@ -33,14 +33,14 @@ function activeFiles(snapshot) {
33
33
  .sort((left, right) => compareCodeUnits(left.displayPath, right.displayPath));
34
34
  }
35
35
  const EVENT_SETUP_CALL_PATTERN = /\b(?:country_event|news_event|state_event|unit_leader_event|operative_leader_event|fire_event|event)\s*=/iu;
36
- function shouldAnalyzeEventFile(file) {
36
+ export function shouldAnalyzeEventFile(file) {
37
37
  const sourcePath = file.relativePath.replaceAll('\\', '/').toLowerCase();
38
38
  if (!sourcePath.startsWith('history/countries/') && !sourcePath.startsWith('history/states/')) {
39
39
  return true;
40
40
  }
41
41
  return EVENT_SETUP_CALL_PATTERN.test(file.bytes.toString('utf8'));
42
42
  }
43
- function catalogFor(snapshot) {
43
+ export function catalogFor(snapshot) {
44
44
  const unshadowedEventSymbols = snapshot.index
45
45
  .findAll('event')
46
46
  .filter(({ sourceShadowed }) => !sourceShadowed);
@@ -1,5 +1,5 @@
1
1
  import { z } from 'zod/v4';
2
- import { IdleCacheLifetime } from '../core/idle-cache-lifetime.js';
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 { eventInspectRequestSchema, eventRenderRequestSchema } from '../schemas/event.js';
@@ -9,7 +9,7 @@ const wireResult = z.record(z.string(), z.json());
9
9
  /** Registers typed event operations without invoking transport handlers. */
10
10
  export function registerEventJobs(operations, engine) {
11
11
  const viewer = new EventChainViewer(engine);
12
- const lifetime = new IdleCacheLifetime(() => viewer.clearCaches());
12
+ const lifetime = idleCacheLifetime(engine, () => viewer.clearCaches());
13
13
  function register(name, schema, normalize, execute, message) {
14
14
  operations.registerRead(name, schema, async (input, context) => {
15
15
  const release = lifetime.begin();
@@ -1,5 +1,5 @@
1
1
  import { z } from 'zod/v4';
2
- import { IdleCacheLifetime } from '../core/idle-cache-lifetime.js';
2
+ import { idleCacheLifetime } from '../core/idle-cache-lifetime.js';
3
3
  import { toolResult } from '../core/operation-result.js';
4
4
  import { ServiceError } from '../core/result.js';
5
5
  import { eventWriteRequestSchema } from '../schemas/event-write.js';
@@ -12,7 +12,7 @@ function wire(result) {
12
12
  /** Registers `hoi4.event_write`: a read-only preview, or one journaled transaction. */
13
13
  export function registerEventWriteJobs(operations, engine) {
14
14
  const viewer = new EventChainViewer(engine);
15
- const lifetime = new IdleCacheLifetime(() => viewer.clearCaches());
15
+ const lifetime = idleCacheLifetime(engine, () => viewer.clearCaches());
16
16
  operations.registerWrite('hoi4.event_write', eventWriteRequestSchema, async (input, context) => {
17
17
  if (input.workspaceId !== 'current' && input.workspaceId !== context.workspaceId)
18
18
  throw new ServiceError('JOB_ARGUMENT_SCOPE_MISMATCH', 'The request workspace does not match the authorized job workspace');
@@ -23,16 +23,15 @@ function normalized(path) {
23
23
  return path.replaceAll('\\', '/').replace(/^\.\//u, '').toLowerCase();
24
24
  }
25
25
  /** The mod's own `events` files, the ones this tool may write, with what each holds. */
26
- function modEventFiles(snapshot) {
27
- return snapshot.files
28
- .filter(({ rootKind, shadowedBy, relativePath }) => rootKind === 'mod' &&
26
+ async function modEventFiles(snapshot) {
27
+ const own = snapshot.files.filter(({ rootKind, shadowedBy, relativePath }) => rootKind === 'mod' &&
29
28
  shadowedBy === undefined &&
30
29
  normalized(relativePath).startsWith('events/') &&
31
- relativePath.toLowerCase().endsWith('.txt'))
32
- .map((file) => ({
30
+ relativePath.toLowerCase().endsWith('.txt'));
31
+ return Promise.all(own.map(async (file) => ({
33
32
  file,
34
- ...eventFileContents({ bytes: file.bytes, path: file.relativePath }),
35
- }));
33
+ ...(await eventFileContents({ bytes: file.bytes, path: file.relativePath })),
34
+ })));
36
35
  }
37
36
  /** A path createFile may make: a .txt file under events, inside the mod. */
38
37
  function newEventFilePath(file) {
@@ -134,7 +133,7 @@ function referencesOf(kind, body) {
134
133
  }
135
134
  export async function computeEventWrite(engine, input, context, applied) {
136
135
  const snapshot = await engine.scan(context.workspaceId, { patterns: WRITE_PATTERNS }, context.principal, context.signal);
137
- const files = modEventFiles(snapshot);
136
+ const files = await modEventFiles(snapshot);
138
137
  const target = targetFile(snapshot, files, input);
139
138
  const namespace = namespaceOf(input.id);
140
139
  const planInput = {
@@ -149,7 +148,7 @@ export async function computeEventWrite(engine, input, context, applied) {
149
148
  let plan;
150
149
  if ('file' in target) {
151
150
  file = target.file;
152
- plan = planEventWrite({ bytes: file.bytes, path: file.relativePath }, planInput);
151
+ plan = await planEventWrite({ bytes: file.bytes, path: file.relativePath }, planInput);
153
152
  }
154
153
  else {
155
154
  const inMod = snapshot.index
@@ -160,7 +159,7 @@ export async function computeEventWrite(engine, input, context, applied) {
160
159
  id: input.id,
161
160
  path: inMod.path,
162
161
  });
163
- plan = planNewEventFile(target.newPath, planInput);
162
+ plan = await planNewEventFile(target.newPath, planInput);
164
163
  }
165
164
  const missing = { localisation: [], picture: [] };
166
165
  const diagnostics = [];
@@ -1,13 +1,11 @@
1
- import { indentedBody, lineIndent } from '../core/block-edit.js';
2
- import { hasBlockingDiagnostics } from '../core/diagnostics.js';
3
- import { DIFF_CONTEXT_LINES, unifiedTextDiff } from '../core/diff.js';
4
- import { ServiceError } from '../core/result.js';
5
- import { applyReplacements, assignments, parseClausewitz, } from '../core/source/index.js';
1
+ import { z } from 'zod/v4';
2
+ import { callSourceQuery, callWritePlan, replacementSchema, } from '../script-write/engine-plan.js';
6
3
  /**
7
4
  * The edit behind `hoi4.event_write` (issue 159): add, replace or remove one event block of an
8
- * `events/*.txt` file and nothing else. Every byte outside the touched block, the other events,
9
- * unrelated top-level entries, comments, the newline style and the encoding, comes back exactly as it
10
- * was read, and a layout the edit cannot place safely is refused with the reason, not guessed.
5
+ * `events/*.txt` file and nothing else. The engine plans it (`hoi4-script-write`, ADR 0089): every
6
+ * byte outside the touched block, the other events, unrelated top-level entries, comments, the
7
+ * newline style and the encoding come back as they were read, and a layout the edit cannot place
8
+ * safely is refused with the reason, not guessed.
11
9
  */
12
10
  export const EVENT_KINDS = [
13
11
  'country_event',
@@ -20,108 +18,24 @@ export const EVENT_ID_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*\.[0-9]+$/u;
20
18
  export function namespaceOf(id) {
21
19
  return id.slice(0, id.indexOf('.'));
22
20
  }
23
- function fail(code, message, details) {
24
- throw new ServiceError(code, message, details);
25
- }
26
- function isKind(key) {
27
- return EVENT_KINDS.includes(key);
28
- }
29
- /** Every top-level event block of the document that has an `id`. */
30
- function definitions(document) {
31
- const found = [];
32
- for (const event of assignments(document.root)) {
33
- const kind = event.key.value;
34
- if (!isKind(kind) || event.value.type !== 'block')
35
- continue;
36
- const id = assignments(event.value, 'id')[0];
37
- if (id?.value.type === 'scalar')
38
- found.push({ event, kind, id: id.value.value });
39
- }
40
- return found;
41
- }
42
- function namespaces(document) {
43
- return assignments(document.root, 'add_namespace');
44
- }
45
- /** One level of indentation, read from the file's own events, tabs when it has none. */
46
- function indentUnit(located, text) {
47
- for (const { event } of located) {
48
- if (event.value.type !== 'block')
49
- continue;
50
- const first = event.value.entries[0];
51
- if (first === undefined)
52
- continue;
53
- const inner = lineIndent(text, first.start);
54
- const outer = lineIndent(text, event.start);
55
- if (inner.length > outer.length && inner.startsWith(outer))
56
- return inner.slice(outer.length);
57
- }
58
- return '\t';
59
- }
60
- /** The body, checked on its own as the block it will become, and its own `id` when it has one. */
61
- function checkedBody(kind, id, body) {
62
- const probe = parseClausewitz(Buffer.from(`${kind} = {\n${body}\n}\n`, 'utf8'), 'event-body');
63
- const only = probe.root.entries;
64
- const single = only.length === 1 && only[0]?.type === 'assignment' && only[0].key.value === kind;
65
- if (hasBlockingDiagnostics(probe.diagnostics) || !single || only[0]?.type !== 'assignment')
66
- fail('EVENT_WRITE_BODY_INVALID', 'The body must be the text between the braces of one event: balanced braces and no definition of its own', { diagnosticCodes: probe.diagnostics.map(({ code }) => code) });
67
- if (only[0].value.type !== 'block' || only[0].value.entries.length === 0)
68
- fail('EVENT_WRITE_BODY_INVALID', 'The body of an event cannot be empty');
69
- const own = assignments(only[0].value, 'id');
70
- if (own.length > 1)
71
- fail('EVENT_WRITE_BODY_INVALID', 'The body names an id more than once');
72
- if (own[0] !== undefined && (own[0].value.type !== 'scalar' || own[0].value.value !== id))
73
- fail('EVENT_WRITE_ID_MISMATCH', `The body has its own id, which is not ${id}; leave id out of the body, the tool writes it`, { id });
74
- return own.length === 1 ? [] : [`id = ${id}`];
75
- }
76
- function definitionTexts(document, skip) {
77
- const byId = new Map();
78
- for (const { event, id } of definitions(document)) {
79
- if (event.start === skip?.start)
80
- continue;
81
- byId.set(id, [...(byId.get(id) ?? []), document.text.slice(event.start, event.end)]);
82
- }
83
- return byId;
84
- }
85
- function checkRequest(input) {
86
- if (!EVENT_ID_PATTERN.test(input.id))
87
- fail('EVENT_WRITE_ID_INVALID', `${JSON.stringify(input.id)} is not a valid event id; it is a namespace, a dot and a number, as in my_events.1`, { id: input.id });
88
- if (input.operation === 'remove' && input.body !== undefined)
89
- fail('EVENT_WRITE_BODY_UNEXPECTED', 'remove takes no body');
90
- if (input.operation !== 'remove' && (input.body === undefined || input.body.trim() === ''))
91
- fail('EVENT_WRITE_BODY_REQUIRED', `${input.operation} needs the body of the event`);
92
- if (input.operation !== 'add' && input.createNamespace === true)
93
- fail('EVENT_WRITE_NAMESPACE_UNEXPECTED', 'createNamespace applies to add only');
94
- }
95
- /** The event block text at `indent`, with `id` first. */
96
- function blockText(kind, id, body, idLine, indent, unit, newline) {
97
- const inner = indent + unit;
98
- const lines = [
99
- ...idLine.map((line) => `${inner}${line}`),
100
- indentedBody(body, inner, newline),
101
- ].join(newline);
102
- return `${indent}${kind} = {${newline}${lines}${newline}${indent}}`;
103
- }
104
- function assertWritten(document, edits, path, skip) {
105
- const bytes = applyReplacements(document, edits);
106
- const written = parseClausewitz(bytes, path);
107
- if (hasBlockingDiagnostics(written.diagnostics))
108
- fail('EVENT_WRITE_RESULT_INVALID', 'The edit would leave the file with syntax errors', {
109
- diagnosticCodes: written.diagnostics.map(({ code }) => code),
110
- });
111
- const before = definitionTexts(document, skip);
112
- const afterTexts = definitionTexts(written, undefined);
113
- let untouched = 0;
114
- for (const [id, texts] of before) {
115
- const now = afterTexts.get(id) ?? [];
116
- for (const text of texts)
117
- if (now.includes(text))
118
- untouched += 1;
119
- else
120
- fail('EVENT_WRITE_RESULT_INVALID', `The edit would change ${id}, which it must not touch`, {
121
- id,
122
- });
123
- }
124
- return { bytes, after: written.text, untouched };
21
+ const planSchema = z.object({
22
+ operation: z.enum(['add', 'replace', 'remove']),
23
+ id: z.string(),
24
+ kind: z.enum(EVENT_KINDS),
25
+ path: z.string(),
26
+ edits: z.array(replacementSchema),
27
+ untouchedDefinitions: z.number().int().nonnegative(),
28
+ namespaceAdded: z.boolean(),
29
+ });
30
+ async function plan(path, input, source) {
31
+ const answer = await callWritePlan({
32
+ op: 'event_write.plan',
33
+ path,
34
+ input: { ...input },
35
+ ...(source === undefined ? {} : { source }),
36
+ result: planSchema,
37
+ });
38
+ return { ...answer.result, text: answer.text, bytes: answer.bytes, diff: answer.diff };
125
39
  }
126
40
  /**
127
41
  * The plan that creates a new `events` file holding the namespace line and one new event, for
@@ -129,176 +43,12 @@ function assertWritten(document, edits, path, skip) {
129
43
  * own event files do.
130
44
  */
131
45
  export function planNewEventFile(path, input) {
132
- checkRequest(input);
133
- if (input.operation !== 'add')
134
- fail('EVENT_WRITE_FILE_NOT_FOUND', `${path} does not exist, and only add can create a file`);
135
- const kind = input.kind ?? 'country_event';
136
- const idLine = checkedBody(kind, input.id, input.body);
137
- const namespaceAdded = input.namespaceDeclared !== true;
138
- if (namespaceAdded && input.createNamespace !== true)
139
- fail('EVENT_WRITE_NAMESPACE_MISSING', `No mod file declares the namespace ${namespaceOf(input.id)}; pass createNamespace: true to write add_namespace`, { namespace: namespaceOf(input.id) });
140
- const text = [
141
- ...(namespaceAdded ? [`add_namespace = ${namespaceOf(input.id)}`, ''] : []),
142
- blockText(kind, input.id, input.body, idLine, '', '\t', '\n'),
143
- '',
144
- ].join('\n');
145
- const written = parseClausewitz(Buffer.from(text, 'utf8'), path);
146
- if (hasBlockingDiagnostics(written.diagnostics))
147
- fail('EVENT_WRITE_RESULT_INVALID', 'The new file would have syntax errors', {
148
- diagnosticCodes: written.diagnostics.map(({ code }) => code),
149
- });
150
- return {
151
- operation: 'add',
152
- id: input.id,
153
- kind,
154
- path,
155
- text,
156
- bytes: Buffer.from(text, 'utf8'),
157
- edits: [{ start: 0, end: 0, text, description: `create ${path} with ${input.id}` }],
158
- diff: unifiedTextDiff('', text, `a/${path}`, `b/${path}`, { context: DIFF_CONTEXT_LINES }),
159
- untouchedDefinitions: 0,
160
- namespaceAdded,
161
- };
46
+ return plan(path, input, undefined);
162
47
  }
163
48
  export function planEventWrite(source, input) {
164
- checkRequest(input);
165
- const document = parseClausewitz(source.bytes, source.path);
166
- if (hasBlockingDiagnostics(document.diagnostics))
167
- fail('EVENT_WRITE_SOURCE_INVALID', 'The source has syntax errors and cannot be edited safely', {
168
- path: source.path,
169
- diagnosticCodes: document.diagnostics.map(({ code }) => code),
170
- });
171
- const text = document.text;
172
- const newline = document.newline;
173
- const located = definitions(document);
174
- const unit = indentUnit(located, text);
175
- const existing = located.filter(({ id }) => id === input.id);
176
- const edits = [];
177
- let skip;
178
- let kind;
179
- let namespaceAdded = false;
180
- if (input.operation === 'add') {
181
- kind = input.kind ?? 'country_event';
182
- if (existing.length > 0)
183
- fail('EVENT_WRITE_DUPLICATE_ID', `${input.id} is already defined in this file`, {
184
- id: input.id,
185
- line: existing[0]?.event.key.token.line,
186
- });
187
- const idLine = checkedBody(kind, input.id, input.body);
188
- const declaredHere = namespaces(document).some(({ value }) => value.type === 'scalar' && value.value === namespaceOf(input.id));
189
- if (!declaredHere && input.namespaceDeclared !== true) {
190
- if (input.createNamespace !== true)
191
- fail('EVENT_WRITE_NAMESPACE_MISSING', `No mod file declares the namespace ${namespaceOf(input.id)}; pass createNamespace: true to write add_namespace`, { namespace: namespaceOf(input.id) });
192
- namespaceAdded = true;
193
- const lines = namespaces(document);
194
- const last = lines.at(-1);
195
- const first = document.root.entries[0];
196
- if (last !== undefined) {
197
- const lineEndAt = text.indexOf('\n', last.end);
198
- const at = lineEndAt === -1 ? text.length : lineEndAt + 1;
199
- edits.push({
200
- start: at,
201
- end: at,
202
- text: `${lineEndAt === -1 ? newline : ''}add_namespace = ${namespaceOf(input.id)}${newline}`,
203
- description: `declare the namespace ${namespaceOf(input.id)}`,
204
- });
205
- }
206
- else if (first !== undefined) {
207
- const at = text.lastIndexOf('\n', first.start - 1) + 1;
208
- edits.push({
209
- start: at,
210
- end: at,
211
- text: `add_namespace = ${namespaceOf(input.id)}${newline}${newline}`,
212
- description: `declare the namespace ${namespaceOf(input.id)}`,
213
- });
214
- }
215
- }
216
- const block = blockText(kind, input.id, input.body, idLine, '', unit, newline);
217
- const lead = text === '' ? '' : `${text.endsWith('\n') ? '' : newline}${newline}`;
218
- edits.push({
219
- start: text.length,
220
- end: text.length,
221
- text: `${lead}${block}${newline}`,
222
- description: `add ${input.id}`,
223
- });
224
- if (namespaceAdded && document.root.entries.length === 0)
225
- edits.splice(0, edits.length, {
226
- start: text.length,
227
- end: text.length,
228
- text: `${text === '' ? '' : newline}add_namespace = ${namespaceOf(input.id)}${newline}${newline}${block}${newline}`,
229
- description: `add ${input.id} and declare its namespace`,
230
- });
231
- }
232
- else {
233
- if (existing.length === 0)
234
- fail('EVENT_WRITE_NOT_FOUND', `${input.id} is not defined in this file`, { id: input.id });
235
- if (existing.length > 1)
236
- fail('EVENT_WRITE_DUPLICATE_ID', `${input.id} is defined ${existing.length} times in this file`, { id: input.id, lines: existing.map(({ event }) => event.key.token.line) });
237
- const found = existing[0];
238
- kind = found.kind;
239
- if (input.kind !== undefined && input.kind !== kind)
240
- fail('EVENT_WRITE_KIND_MISMATCH', `${input.id} is a ${kind}, and changing the kind of an event is not supported`, { id: input.id, kind });
241
- skip = found.event;
242
- if (input.operation === 'replace') {
243
- const idLine = checkedBody(kind, input.id, input.body);
244
- const indent = lineIndent(text, found.event.start);
245
- edits.push({
246
- start: found.event.start,
247
- end: found.event.end,
248
- text: blockText(kind, input.id, input.body, idLine, indent, unit, newline).slice(indent.length),
249
- description: `replace ${input.id}`,
250
- });
251
- }
252
- else {
253
- const lineStart = text.lastIndexOf('\n', found.event.start - 1) + 1;
254
- const lineEndAt = text.indexOf('\n', found.event.end);
255
- const lineEnd = lineEndAt === -1 ? text.length : lineEndAt + 1;
256
- const alone = /^[ \t]*$/u.test(text.slice(lineStart, found.event.start)) &&
257
- /^[ \t]*\r?$/u.test(text.slice(found.event.end, lineEndAt === -1 ? text.length : lineEndAt));
258
- if (!alone) {
259
- edits.push({
260
- start: found.event.start,
261
- end: found.event.end,
262
- text: '',
263
- description: `remove ${input.id}`,
264
- });
265
- }
266
- else {
267
- // A blank line that only separated this event from the one before it goes with it.
268
- const before = text.slice(0, lineStart);
269
- const blankBefore = /(?:^|\n)[ \t]*\r?\n$/u.test(before) && before.length > 0;
270
- const after = text.slice(lineEnd);
271
- const nextIsBlank = /^[ \t]*\r?(?:\n|$)/u.test(after);
272
- let start = lineStart;
273
- if (blankBefore && (nextIsBlank || after === ''))
274
- start = before.lastIndexOf('\n', before.length - 2) + 1;
275
- edits.push({ start, end: lineEnd, text: '', description: `remove ${input.id}` });
276
- }
277
- }
278
- }
279
- const { bytes, after, untouched } = assertWritten(document, edits, source.path, skip);
280
- return {
281
- operation: input.operation,
282
- id: input.id,
283
- kind,
284
- path: source.path,
285
- text: after,
286
- bytes,
287
- edits,
288
- diff: unifiedTextDiff(text, after, `a/${source.path}`, `b/${source.path}`, {
289
- context: DIFF_CONTEXT_LINES,
290
- }),
291
- untouchedDefinitions: untouched,
292
- namespaceAdded,
293
- };
49
+ return plan(source.path, input, source.bytes);
294
50
  }
295
51
  /** The ids of the events in a source, and the namespaces it declares. */
296
- export function eventFileContents(source) {
297
- const document = parseClausewitz(source.bytes, source.path);
298
- if (hasBlockingDiagnostics(document.diagnostics))
299
- return { ids: [], namespaces: [] };
300
- return {
301
- ids: definitions(document).map(({ id }) => id),
302
- namespaces: namespaces(document).flatMap(({ value }) => value.type === 'scalar' ? [value.value] : []),
303
- };
52
+ export async function eventFileContents(source) {
53
+ return callSourceQuery('event_write.contents', source.path, source.bytes, z.object({ ids: z.array(z.string()), namespaces: z.array(z.string()) }));
304
54
  }