hoi4-agent-tools 4.6.5 → 4.8.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 (122) hide show
  1. package/CHANGELOG.md +40 -5
  2. package/README.md +32 -13
  3. package/dist/hoi4_agent_tools/core/engine-client.js +342 -0
  4. package/dist/hoi4_agent_tools/core/operation-result.js +33 -5
  5. package/dist/hoi4_agent_tools/core/resident-engine.js +273 -0
  6. package/dist/hoi4_agent_tools/core/temporary-directories.js +3 -2
  7. package/dist/hoi4_agent_tools/decision/service.js +7 -0
  8. package/dist/hoi4_agent_tools/event/service.js +18 -6
  9. package/dist/hoi4_agent_tools/event/summary.js +9 -0
  10. package/dist/hoi4_agent_tools/focus/compact.js +197 -18
  11. package/dist/hoi4_agent_tools/focus/engine-layout.js +201 -0
  12. package/dist/hoi4_agent_tools/focus/game-render.js +72 -0
  13. package/dist/hoi4_agent_tools/focus/game-view-output.js +160 -0
  14. package/dist/hoi4_agent_tools/focus/job-operations.js +3 -1
  15. package/dist/hoi4_agent_tools/focus/layout.js +3 -2
  16. package/dist/hoi4_agent_tools/focus/native-effects.js +4 -4
  17. package/dist/hoi4_agent_tools/focus/quality/branches.js +32 -0
  18. package/dist/hoi4_agent_tools/focus/quality/calibration.js +364 -0
  19. package/dist/hoi4_agent_tools/focus/quality/delta.js +85 -0
  20. package/dist/hoi4_agent_tools/focus/quality/focus-quality-calibration.json +2265 -0
  21. package/dist/hoi4_agent_tools/focus/quality/graph.js +170 -0
  22. package/dist/hoi4_agent_tools/focus/quality/index.js +24 -0
  23. package/dist/hoi4_agent_tools/focus/quality/inline-images.js +132 -0
  24. package/dist/hoi4_agent_tools/focus/quality/metrics.js +424 -0
  25. package/dist/hoi4_agent_tools/focus/quality/orthogonal.js +213 -0
  26. package/dist/hoi4_agent_tools/focus/quality/positions.js +41 -0
  27. package/dist/hoi4_agent_tools/focus/quality/schematic.js +243 -0
  28. package/dist/hoi4_agent_tools/focus/quality/scorecard.js +549 -0
  29. package/dist/hoi4_agent_tools/focus/quality/stored-calibration.js +7 -0
  30. package/dist/hoi4_agent_tools/focus/quality/tool-output.js +113 -0
  31. package/dist/hoi4_agent_tools/focus/quality/types.js +5 -0
  32. package/dist/hoi4_agent_tools/focus/render.js +21 -9
  33. package/dist/hoi4_agent_tools/focus/tool-operations.js +364 -25
  34. package/dist/hoi4_agent_tools/focus/tool-support.js +1 -1
  35. package/dist/hoi4_agent_tools/gui/assets.js +18 -0
  36. package/dist/hoi4_agent_tools/gui/dds.js +38 -5
  37. package/dist/hoi4_agent_tools/gui/engine-textures.js +48 -0
  38. package/dist/hoi4_agent_tools/gui/source-graph.js +7 -0
  39. package/dist/hoi4_agent_tools/gui/tool-operations.js +23 -4
  40. package/dist/hoi4_agent_tools/gui/validators.js +31 -2
  41. package/dist/hoi4_agent_tools/ideas/inspect.js +43 -0
  42. package/dist/hoi4_agent_tools/localisation/inspect.js +34 -0
  43. package/dist/hoi4_agent_tools/mcp/server/argument-errors.js +2 -0
  44. package/dist/hoi4_agent_tools/mcp/server/instructions.js +1 -1
  45. package/dist/hoi4_agent_tools/mcp/tools/event.js +2 -0
  46. package/dist/hoi4_agent_tools/mcp/tools/focus.js +76 -4
  47. package/dist/hoi4_agent_tools/mcp/tools/reference.js +18 -0
  48. package/dist/hoi4_agent_tools/probability/operations.js +27 -1
  49. package/dist/hoi4_agent_tools/probability/service.js +91 -11
  50. package/dist/hoi4_agent_tools/probability/source-analysis.js +2 -2
  51. package/dist/hoi4_agent_tools/probability/sweep.js +20 -6
  52. package/dist/hoi4_agent_tools/reference/command-phrases.json +11065 -0
  53. package/dist/hoi4_agent_tools/reference/error-log.js +24 -0
  54. package/dist/hoi4_agent_tools/reference/game-text.js +109 -0
  55. package/dist/hoi4_agent_tools/reference/known-mistakes.js +8 -5
  56. package/dist/hoi4_agent_tools/reference/known-mistakes.json +4 -4
  57. package/dist/hoi4_agent_tools/reference/operations.js +68 -2
  58. package/dist/hoi4_agent_tools/reference/ranking.js +92 -2
  59. package/dist/hoi4_agent_tools/reference/script-validation.js +46 -6
  60. package/dist/hoi4_agent_tools/reference/service.js +125 -21
  61. package/dist/hoi4_agent_tools/reference/source-lookup.js +8 -0
  62. package/dist/hoi4_agent_tools/schemas/focus-requests.js +68 -7
  63. package/dist/hoi4_agent_tools/schemas/focus.js +121 -6
  64. package/dist/hoi4_agent_tools/schemas/ideas.js +142 -0
  65. package/dist/hoi4_agent_tools/schemas/localisation.js +94 -0
  66. package/dist/hoi4_agent_tools/schemas/mod-tools.js +11 -0
  67. package/dist/hoi4_agent_tools/version.js +1 -1
  68. package/docs/configuration.md +17 -17
  69. package/docs/focus.md +104 -4
  70. package/docs/reference.md +1 -1
  71. package/docs/research/reference-benchmark.md +152 -1
  72. package/docs/setup.md +1 -1
  73. package/docs/tools.md +48 -44
  74. package/docs/troubleshooting.md +13 -12
  75. package/engine/README.md +284 -0
  76. package/engine/bin/darwin-arm64/hoi4-engine +0 -0
  77. package/engine/bin/linux-arm64/hoi4-engine +0 -0
  78. package/engine/bin/linux-x64/hoi4-engine +0 -0
  79. package/engine/bin/manifest.json +26 -0
  80. package/engine/bin/win32-x64/hoi4-engine.exe +0 -0
  81. package/npm-shrinkwrap.json +2 -2
  82. package/package.json +5 -1
  83. package/schemas/configuration.schema.json +1 -1
  84. package/schemas/continuous-focus-palette.schema.json +1 -1
  85. package/schemas/custom-weighted-pool.schema.json +1 -1
  86. package/schemas/decision-inspect-input.schema.json +1 -1
  87. package/schemas/error-log-input.schema.json +1 -1
  88. package/schemas/event-feature-manifest.schema.json +1 -1
  89. package/schemas/focus-plan.schema.json +146 -120
  90. package/schemas/focus-planning-sidecar.schema.json +15 -7
  91. package/schemas/geography-model.schema.json +1 -1
  92. package/schemas/gui-animation-source.schema.json +1 -1
  93. package/schemas/gui-helper.schema.json +1 -1
  94. package/schemas/gui-scenario.schema.json +1 -1
  95. package/schemas/helper-expansion-request.schema.json +1 -1
  96. package/schemas/helper-expansion-summary.schema.json +1 -1
  97. package/schemas/impact-inspect-input.schema.json +1 -1
  98. package/schemas/map-operation.schema.json +1 -1
  99. package/schemas/mechanic-test-input.schema.json +1 -1
  100. package/schemas/mod-index-input.schema.json +1 -1
  101. package/schemas/operation-result.schema.json +1 -1
  102. package/schemas/package-check-input.schema.json +1 -1
  103. package/schemas/package-manifest.schema.json +1 -1
  104. package/schemas/probability-analysis-result.schema.json +1 -1
  105. package/schemas/probability-compare-input.schema.json +1 -1
  106. package/schemas/probability-evaluate-input.schema.json +1 -1
  107. package/schemas/probability-inspect-input.schema.json +1 -1
  108. package/schemas/probability-render-input.schema.json +1 -1
  109. package/schemas/probability-scenario-set.schema.json +1 -1
  110. package/schemas/probability-sequence-input.schema.json +1 -1
  111. package/schemas/probability-simulate-input.schema.json +1 -1
  112. package/schemas/probability-sweep-input.schema.json +1 -1
  113. package/schemas/reference-context-input.schema.json +1 -1
  114. package/schemas/reference-read-input.schema.json +1 -1
  115. package/schemas/reference-search-input.schema.json +1 -1
  116. package/schemas/reference-sheets.schema.json +1 -1
  117. package/schemas/scenario-suite.schema.json +1 -1
  118. package/schemas/scenario-test-input.schema.json +1 -1
  119. package/schemas/script-validate-input.schema.json +1 -1
  120. package/schemas/shared-scenario.schema.json +1 -1
  121. package/schemas/source-lookup-input.schema.json +1 -1
  122. package/server.json +2 -2
@@ -1,3 +1,4 @@
1
+ import { statSync } from 'node:fs';
1
2
  import { realpath } from 'node:fs/promises';
2
3
  import path from 'node:path';
3
4
  import { globFiles } from '../core/file-glob.js';
@@ -6,9 +7,11 @@ import { ServiceError } from '../core/result.js';
6
7
  import { isWithin } from '../core/workspace.js';
7
8
  import { prepareSource, verifySource, readBoundedFile, } from '../core/scanner.js';
8
9
  import { decodeSource } from '../core/source/encoding.js';
10
+ import commandPhrases from './command-phrases.json' with { type: 'json' };
9
11
  import { activeKnownMistakes } from './known-mistakes.js';
10
12
  import { readBoundedJsonLines } from './lines.js';
11
- import { RankingIndex, sectionTerms } from './ranking.js';
13
+ import { commandTexts, readGameText } from './game-text.js';
14
+ import { RankingIndex, sectionTerms, textTerms } from './ranking.js';
12
15
  const MAX_FILES = 512;
13
16
  const MAX_FILE_BYTES = 2_000_000;
14
17
  const MAX_TOTAL_BYTES = 32_000_000;
@@ -34,6 +37,10 @@ export function publicReferenceSection(section) {
34
37
  const { lines: _lines, terms: _terms, ...citation } = section;
35
38
  return citation;
36
39
  }
40
+ /** An unchanged stamp lets a repeated query reuse the hashed revision without rereading. */
41
+ function fileStamp(metadata) {
42
+ return `${metadata.size}:${metadata.mtimeMs}:${metadata.ctimeMs}:${metadata.ino}:${metadata.dev}`;
43
+ }
37
44
  /** Up to three non-empty lines from `first`, trimmed to the 300-character excerpt bound. */
38
45
  function snippet(lines, first = 0) {
39
46
  return lines
@@ -120,6 +127,21 @@ function sectionize(root, filePath, content, revision) {
120
127
  ...rows.map((row) => section(row.heading, row.start, row.start + 1)),
121
128
  ];
122
129
  }
130
+ /** The kit's HOI4 wiki folder, and the name it had before the kit renamed it. */
131
+ const WIKI_FOLDER = 'hoi4_wiki';
132
+ const LEGACY_WIKI_FOLDER = 'paradox_wiki';
133
+ /** `hoi4_wiki/` when the mod has it, otherwise the older `paradox_wiki/` of a mod the kit has not updated. */
134
+ function defaultWikiRoot(modRoot) {
135
+ const current = path.join(modRoot, WIKI_FOLDER);
136
+ try {
137
+ if (statSync(current).isDirectory())
138
+ return current;
139
+ }
140
+ catch {
141
+ // Not there: fall back to the legacy name, which is reported unavailable when absent too.
142
+ }
143
+ return path.join(modRoot, LEGACY_WIKI_FOLDER);
144
+ }
123
145
  function sourceRoots(workspace) {
124
146
  const gameRoot = workspace.gameRoot ?? (workspace.registration.kind === 'game' ? workspace.modRoot : undefined);
125
147
  return [
@@ -135,9 +157,9 @@ function sourceRoots(workspace) {
135
157
  ]),
136
158
  {
137
159
  kind: 'wiki',
138
- root: workspace.wikiRoot ?? path.join(workspace.modRoot, 'paradox_wiki'),
160
+ root: workspace.wikiRoot ?? defaultWikiRoot(workspace.modRoot),
139
161
  patterns: ['**/*.md'],
140
- authority: 'Offline Paradox Wiki snapshot',
162
+ authority: 'HOI4 wiki (kit)',
141
163
  },
142
164
  {
143
165
  kind: 'script_doc',
@@ -202,6 +224,66 @@ const gameDocNames = {
202
224
  ],
203
225
  ai: ['common/ai_strategy/_documentation', 'documentation/triggers_documentation'],
204
226
  };
227
+ const commandHeading = /^[a-z][a-z0-9_]*$/u;
228
+ /**
229
+ * Plain-word phrasings count this many times a game text word, because they name the
230
+ * command the way a question does rather than the way a tooltip labels it.
231
+ */
232
+ const PHRASE_WEIGHT = 4;
233
+ let phraseTerms;
234
+ /**
235
+ * The terms of `command-phrases.json`: four plain-word phrasings of each documented effect,
236
+ * trigger and modifier, such as "state on the coast" for `is_coastal`, written once from
237
+ * the command's documentation and in-game text (ADR 0078). A command the file does not
238
+ * name, such as one a later game version adds, keeps only its documentation and game text.
239
+ */
240
+ function phraseCards() {
241
+ if (phraseTerms !== undefined)
242
+ return phraseTerms;
243
+ phraseTerms = new Map();
244
+ for (const [name, phrases] of Object.entries(commandPhrases)) {
245
+ const card = new Map();
246
+ for (const term of phrases.flatMap((text) => textTerms(text)))
247
+ card.set(term, Math.min((card.get(term) ?? 0) + PHRASE_WEIGHT, 3 * PHRASE_WEIGHT));
248
+ phraseTerms.set(name, card);
249
+ }
250
+ return phraseTerms;
251
+ }
252
+ /**
253
+ * For each entry about one command, the words the game shows players for it: the installed
254
+ * documentation says "check if state is coastal" and the tooltip "Is coastal"; a modifier
255
+ * entry gains its in-game name, such as "Supply Consumption". Console commands and defines
256
+ * gain nothing.
257
+ */
258
+ function commandCards(sections, gameText) {
259
+ const commands = new Set(sections
260
+ .filter(({ source, heading }) => source === 'game_doc' && commandHeading.test(heading.trim()))
261
+ .map(({ heading }) => heading.trim()));
262
+ const spoken = new Map();
263
+ for (const [name, texts] of commandTexts(commands, gameText)) {
264
+ const card = new Map();
265
+ for (const term of texts.flatMap((text) => textTerms(text)))
266
+ card.set(term, Math.min((card.get(term) ?? 0) + 1, 3));
267
+ spoken.set(name, card);
268
+ }
269
+ for (const [name, card] of phraseCards()) {
270
+ if (!commands.has(name))
271
+ continue;
272
+ const merged = new Map(spoken.get(name));
273
+ for (const [term, weight] of card)
274
+ merged.set(term, (merged.get(term) ?? 0) + weight);
275
+ spoken.set(name, merged);
276
+ }
277
+ const cards = new Map();
278
+ for (const section of sections) {
279
+ if (section.terms.specialty !== undefined || section.terms.navigation)
280
+ continue;
281
+ const card = spoken.get(section.heading.trim());
282
+ if (card !== undefined)
283
+ cards.set(section.terms, card);
284
+ }
285
+ return cards;
286
+ }
205
287
  /** A workspace-private, read-only reference index over explicitly known local roots. */
206
288
  export class ReferenceService {
207
289
  #cache = new Map();
@@ -304,7 +386,13 @@ export class ReferenceService {
304
386
  coverage[root.kind].files++;
305
387
  admittedSources.push(source);
306
388
  }
389
+ const keyOf = (source) => `${root.kind}:${canonicalRoot}:${source.canonicalPath}`;
307
390
  const reads = await Promise.allSettled(admittedSources.map(async (source) => {
391
+ const known = this.#cache.get(keyOf(source));
392
+ if (known?.stamp === fileStamp(source.metadata)) {
393
+ await verifySource(readRoot, source);
394
+ return known;
395
+ }
308
396
  const content = await readBoundedFile(source.handle, source.metadata.size, signal);
309
397
  await verifySource(readRoot, source);
310
398
  if (content.length !== source.metadata.size)
@@ -318,17 +406,26 @@ export class ReferenceService {
318
406
  for (const [index, read] of reads.entries()) {
319
407
  if (read.status !== 'fulfilled')
320
408
  continue;
321
- const canonical = admittedSources[index].canonicalPath;
322
- const content = read.value;
323
- const key = `${root.kind}:${canonicalRoot}:${canonical}`;
324
- const revision = sha256Bytes(content);
325
- let cached = this.#cache.get(key);
326
- if (cached?.revision !== revision)
327
- cached = {
328
- revision,
329
- bytes: content.length,
330
- sections: sectionize(root, canonical, referenceText(content), revision),
331
- };
409
+ const source = admittedSources[index];
410
+ const canonical = source.canonicalPath;
411
+ const key = keyOf(source);
412
+ let cached;
413
+ if (Buffer.isBuffer(read.value)) {
414
+ const content = read.value;
415
+ const revision = sha256Bytes(content);
416
+ const previous = this.#cache.get(key);
417
+ cached =
418
+ previous?.revision === revision
419
+ ? { ...previous, stamp: fileStamp(source.metadata) }
420
+ : {
421
+ revision,
422
+ bytes: content.length,
423
+ stamp: fileStamp(source.metadata),
424
+ sections: sectionize(root, canonical, referenceText(content), revision),
425
+ };
426
+ }
427
+ else
428
+ cached = read.value;
332
429
  this.retain(key, cached);
333
430
  const admitted = cached.sections.slice(0, MAX_SECTIONS - sections.length);
334
431
  if (admitted.length < cached.sections.length)
@@ -346,7 +443,7 @@ export class ReferenceService {
346
443
  }
347
444
  async search(workspace, input, signal) {
348
445
  const inventory = await this.inventory(workspace, signal, input.sources);
349
- const { ranked: matches, describe } = this.rank(inventory.sections, input.query);
446
+ const { ranked: matches, describe } = this.rank(inventory.sections, input.query, await this.gameText(workspace));
350
447
  const results = matches.slice(0, input.limit).map((match) => {
351
448
  const { section, score, excerpt, matchLine } = describe(match);
352
449
  return { ...this.publicSection(section), score, excerpt, matchLine };
@@ -367,8 +464,8 @@ export class ReferenceService {
367
464
  };
368
465
  }
369
466
  /** One index per distinct set of section revisions; IDF depends on the whole inventory. */
370
- rankingIndex(sections) {
371
- const parts = [];
467
+ rankingIndex(sections, gameText) {
468
+ const parts = [`game-text\0${gameText.revision}`];
372
469
  let previous;
373
470
  for (const section of sections) {
374
471
  if (previous?.path !== section.path || previous.revision !== section.revision)
@@ -382,7 +479,7 @@ export class ReferenceService {
382
479
  this.#indexes.set(key, cached);
383
480
  return cached;
384
481
  }
385
- const index = new RankingIndex(sections.map(({ terms }) => terms));
482
+ const index = new RankingIndex(sections.map(({ terms }) => terms), commandCards(sections, gameText));
386
483
  this.#indexes.set(key, index);
387
484
  while (this.#indexes.size > 4) {
388
485
  const oldest = this.#indexes.keys().next().value;
@@ -392,8 +489,8 @@ export class ReferenceService {
392
489
  }
393
490
  return index;
394
491
  }
395
- rank(sections, question) {
396
- const index = this.rankingIndex(sections);
492
+ rank(sections, question, gameText) {
493
+ const index = this.rankingIndex(sections, gameText);
397
494
  const plan = index.plan(question);
398
495
  const scored = [];
399
496
  for (const section of sections) {
@@ -485,7 +582,9 @@ export class ReferenceService {
485
582
  async context(workspace, input, signal) {
486
583
  const inventory = await this.inventory(workspace, signal);
487
584
  const wanted = surfaceNames[input.surface];
488
- const ranking = input.question === undefined ? undefined : this.rank(inventory.sections, input.question);
585
+ const ranking = input.question === undefined
586
+ ? undefined
587
+ : this.rank(inventory.sections, input.question, await this.gameText(workspace));
489
588
  const ranked = ranking?.ranked ?? [];
490
589
  const required = [];
491
590
  const missing = [];
@@ -552,6 +651,11 @@ export class ReferenceService {
552
651
  })),
553
652
  };
554
653
  }
654
+ async gameText(workspace) {
655
+ const gameRoot = workspace.gameRoot ??
656
+ (workspace.registration.kind === 'game' ? workspace.modRoot : undefined);
657
+ return readGameText(gameRoot);
658
+ }
555
659
  publicSection(section) {
556
660
  return publicReferenceSection(section);
557
661
  }
@@ -150,6 +150,14 @@ export async function sourceLookup(engine, workspaceId, input, principal, signal
150
150
  path: entry.path,
151
151
  line: entry.location?.start.line ?? null,
152
152
  }));
153
+ // A complete index that neither defines nor uses the symbol answers not-found, never an
154
+ // empty success.
155
+ if (matchedDefinitions.length === 0 && matchedReferences.length === 0 && snapshot.complete) {
156
+ const suggestions = nearestNames(symbol, new Set(snapshot.index.symbols
157
+ .filter((entry) => input.kind === undefined || entry.kind === input.kind)
158
+ .map(({ id }) => id)));
159
+ throw new ServiceError('SYMBOL_NOT_FOUND', `No indexed file defines${input.includeReferences ? ' or uses' : ''} ${symbol.slice(0, 256)}${input.kind === undefined ? '' : ` as a ${input.kind}`}${suggestions.length === 0 ? '' : `; did you mean ${suggestions.join(', ')}?`}`, { symbol: symbol.slice(0, 256), suggestions });
160
+ }
153
161
  const result = {
154
162
  sourceScope: input.kind === 'event'
155
163
  ? input.includeReferences
@@ -74,13 +74,30 @@ export const focusRenderRequestSchema = z
74
74
  .min(FOCUS_RENDER_MIN_OUTPUT_SCALE)
75
75
  .max(FOCUS_RENDER_MAX_OUTPUT_SCALE)
76
76
  .optional(),
77
- cropFocusIds: z.array(z.string().min(1).max(256)).max(16).optional(),
77
+ cropFocusIds: z
78
+ .array(z.string().min(1).max(256))
79
+ .max(16)
80
+ .optional()
81
+ .describe('Close-ups around these focuses: PNG artifacts of the icon render, and inline schematic crops.'),
82
+ cropBranchIds: z
83
+ .array(z.string().min(1).max(256))
84
+ .max(8)
85
+ .optional()
86
+ .describe('Inline close-ups of whole branches. Use a declared branch id or the first focus of a derived branch; the scorecard lists them.'),
87
+ inline: z
88
+ .boolean()
89
+ .optional()
90
+ .describe('Default true: return an in-game-style schematic overview and crops of the worst places as inline images, so no second call is needed. False returns only linked artifacts.'),
78
91
  columns: z.number().int().min(1).max(12).optional(),
79
92
  padding: z.number().int().min(0).max(1000).optional(),
80
93
  png: z
81
94
  .boolean()
82
95
  .optional()
83
96
  .describe('Default true: add a PNG with decoded source icons. False returns only the faster HTML, SVG and JSON.'),
97
+ view: z
98
+ .enum(['full', 'game'])
99
+ .optional()
100
+ .describe('Default full. game: only the tree as the game draws it (PNG, hover map, zoomable HTML, inline overview), without the schematic; fast enough to call after every edit. Needs hoi4-engine.'),
84
101
  })
85
102
  .strict()
86
103
  .superRefine((value, context) => {
@@ -102,6 +119,8 @@ export const focusRenderRequestSchema = z
102
119
  ['verticalSpacing', value.verticalSpacing],
103
120
  ['reviewScale', value.reviewScale],
104
121
  ['cropFocusIds', value.cropFocusIds],
122
+ ['cropBranchIds', value.cropBranchIds],
123
+ ['inline', value.inline],
105
124
  ];
106
125
  for (const [field, fieldValue] of invalid) {
107
126
  if (fieldValue !== undefined)
@@ -124,7 +143,7 @@ export const focusRewriteRequestSchema = z
124
143
  workspaceId: workspaceIdSchema,
125
144
  relativePath: workspaceRelativePathSchema,
126
145
  treeId: z.string().min(1).max(256).optional(),
127
- layoutMode: z.enum(['authored', 'compact']).default('authored'),
146
+ layoutMode: z.enum(['authored', 'compact', 'engine']).default('authored'),
128
147
  compactFocusIds: z.array(z.string().min(1).max(256)).min(1).max(10_000).optional(),
129
148
  pinnedFocusIds: z.array(z.string().min(1).max(256)).max(10_000).optional(),
130
149
  symmetryGroups: z
@@ -144,6 +163,15 @@ export const focusRewriteRequestSchema = z
144
163
  .strict())
145
164
  .max(64)
146
165
  .optional(),
166
+ placement: z
167
+ .object({
168
+ focusIds: z.array(z.string().min(1).max(256)).min(1).max(10_000),
169
+ anchorId: z.string().min(1).max(256).optional(),
170
+ preferSide: z.enum(['left', 'right', 'either']).optional(),
171
+ allowShift: z.boolean().optional(),
172
+ })
173
+ .strict()
174
+ .optional(),
147
175
  plan: compactFocusPlanSchema.optional(),
148
176
  createIfMissing: z.boolean().default(false),
149
177
  horizontalSpacing: z.number().int().min(80).max(1000).optional(),
@@ -166,6 +194,33 @@ export const focusRewriteRequestSchema = z
166
194
  path: [field],
167
195
  message: `${field} requires compact layout mode`,
168
196
  });
197
+ if (value.placement !== undefined) {
198
+ if (value.layoutMode === 'compact')
199
+ context.addIssue({
200
+ code: 'custom',
201
+ path: ['placement'],
202
+ message: 'placement requires authored or engine layout mode',
203
+ });
204
+ if (value.layoutMode === 'authored' && value.plan === undefined)
205
+ context.addIssue({
206
+ code: 'custom',
207
+ path: ['placement'],
208
+ message: 'placement in authored layout mode requires a plan that adds the focuses',
209
+ });
210
+ if (value.placement.anchorId !== undefined &&
211
+ !value.placement.focusIds.includes(value.placement.anchorId))
212
+ context.addIssue({
213
+ code: 'custom',
214
+ path: ['placement', 'anchorId'],
215
+ message: 'placement.anchorId must be one of placement.focusIds',
216
+ });
217
+ if (new Set(value.placement.focusIds).size !== value.placement.focusIds.length)
218
+ context.addIssue({
219
+ code: 'custom',
220
+ path: ['placement', 'focusIds'],
221
+ message: 'placement.focusIds must not repeat a focus',
222
+ });
223
+ }
169
224
  const mode = value.mode ?? 'national';
170
225
  const schema = mode === 'continuous' ? continuousFocusPaletteSchema : focusTreePlanSchema;
171
226
  if (value.plan !== undefined && !schema.safeParse(value.plan).success)
@@ -191,7 +246,13 @@ export const focusRewriteRequestSchema = z
191
246
  context.addIssue({
192
247
  code: 'custom',
193
248
  path: ['layoutMode'],
194
- message: 'compact layout mode is only valid in national mode',
249
+ message: `${value.layoutMode} layout mode is only valid in national mode`,
250
+ });
251
+ if (value.placement !== undefined)
252
+ context.addIssue({
253
+ code: 'custom',
254
+ path: ['placement'],
255
+ message: 'placement is only valid in national mode',
195
256
  });
196
257
  for (const [field, fieldValue] of [
197
258
  ['horizontalSpacing', value.horizontalSpacing],
@@ -207,23 +268,23 @@ export const focusRewriteRequestSchema = z
207
268
  });
208
269
  }
209
270
  else {
210
- if (value.plan === undefined && value.layoutMode !== 'compact')
271
+ if (value.plan === undefined && value.layoutMode === 'authored')
211
272
  context.addIssue({
212
273
  code: 'custom',
213
274
  path: ['plan'],
214
- message: 'plan is required unless layoutMode is compact',
275
+ message: 'plan is required unless layoutMode is compact or engine',
215
276
  });
216
277
  if (value.plan === undefined && value.treeId === undefined)
217
278
  context.addIssue({
218
279
  code: 'custom',
219
280
  path: ['treeId'],
220
- message: 'treeId is required for plan-free compact reflow',
281
+ message: 'treeId is required for plan-free compact or engine layout',
221
282
  });
222
283
  if (value.plan === undefined && value.createIfMissing)
223
284
  context.addIssue({
224
285
  code: 'custom',
225
286
  path: ['createIfMissing'],
226
- message: 'plan-free compact reflow requires an existing focus source',
287
+ message: 'plan-free compact or engine layout requires an existing focus source',
227
288
  });
228
289
  if (value.plan !== undefined &&
229
290
  value.treeId !== undefined &&
@@ -36,11 +36,24 @@ const automaticPositionSchema = z
36
36
  .object({
37
37
  mode: z.literal('auto'),
38
38
  pinned: z.literal(false),
39
- preferredX: z.number().int().min(-100_000).max(100_000).optional(),
40
- preferredY: z.number().int().min(-100_000).max(100_000).optional(),
39
+ preferredX: z
40
+ .number()
41
+ .int()
42
+ .min(-100_000)
43
+ .max(100_000)
44
+ .optional()
45
+ .describe('Column the solver aims for; it still spaces and balances the branch.'),
46
+ preferredY: z
47
+ .number()
48
+ .int()
49
+ .min(-100_000)
50
+ .max(100_000)
51
+ .optional()
52
+ .describe('Row the solver aims for; a focus always sits below its lowest prerequisite.'),
41
53
  })
42
54
  .strict();
43
- const positionSchema = z.discriminatedUnion('mode', [
55
+ const positionSchema = z
56
+ .discriminatedUnion('mode', [
44
57
  z
45
58
  .object({
46
59
  mode: z.literal('fixed'),
@@ -59,7 +72,8 @@ const positionSchema = z.discriminatedUnion('mode', [
59
72
  })
60
73
  .strict(),
61
74
  automaticPositionSchema,
62
- ]);
75
+ ])
76
+ .describe('fixed = an exact grid coordinate; relative = an offset from another focus, so the branch moves with it; auto = the solver places the focus (prefer it for new trees). One x unit is half a plaque: neighbouring plaques are 2 apart on a row, and a focus directly below its parent has the same x.');
63
77
  const routeLockSchema = z
64
78
  .object({
65
79
  id: z.string().min(1),
@@ -92,8 +106,14 @@ const focusNodeSchema = z
92
106
  .object({
93
107
  id: z.string().min(1).max(256),
94
108
  label: z.string().max(1024),
95
- branchId: z.string().optional(),
96
- laneId: z.string().optional(),
109
+ branchId: z
110
+ .string()
111
+ .optional()
112
+ .describe('Branch family of this focus; per-branch crops and the layout scorecard use it.'),
113
+ laneId: z
114
+ .string()
115
+ .optional()
116
+ .describe('Lane the solver keeps this focus in: one column band per lane.'),
97
117
  prerequisites: prerequisitesSchema,
98
118
  mutuallyExclusive: z.array(z.string()).max(10_000),
99
119
  routeLocks: z.array(routeLockSchema).max(10_000),
@@ -397,3 +417,98 @@ export const focusLayoutSchema = z
397
417
  layoutHash: z.string().regex(/^[a-f0-9]{64}$/u),
398
418
  })
399
419
  .strict();
420
+ const qualityMetricIdSchema = z.enum([
421
+ 'H1',
422
+ 'H2',
423
+ 'H3',
424
+ 'H4',
425
+ 'H5',
426
+ 'S1',
427
+ 'S2',
428
+ 'S3',
429
+ 'S4',
430
+ 'S5',
431
+ 'S6',
432
+ 'S7',
433
+ 'S8',
434
+ 'S9',
435
+ 'S10',
436
+ 'S11',
437
+ 'D1',
438
+ 'D2',
439
+ 'D3',
440
+ 'D4',
441
+ ]);
442
+ const qualityVerdictSchema = z.enum(['blocked', 'revise', 'review', 'pass']);
443
+ export const focusScorecardRowSchema = z
444
+ .object({
445
+ id: qualityMetricIdSchema,
446
+ name: z.string().max(128),
447
+ group: z.enum(['H', 'S', 'D']),
448
+ value: z.number(),
449
+ unit: z.string().max(64),
450
+ reviewLimit: z.number().nullable(),
451
+ reviseLimit: z.number().nullable(),
452
+ vanillaMedian: z.number().nullable(),
453
+ status: z.enum(['ok', 'review', 'revise', 'blocked', 'flag', 'not_evaluated']),
454
+ inVerdict: z.boolean(),
455
+ where: z.array(z.string().max(256)).max(8),
456
+ message: z.string().max(600),
457
+ fix: z
458
+ .object({
459
+ action: z.string().max(64),
460
+ targetFocusIds: z.array(z.string().max(256)).max(16),
461
+ suggested: z.string().max(500),
462
+ expectedMetricChange: z.string().max(300),
463
+ preservesGameplay: z.boolean(),
464
+ })
465
+ .strict()
466
+ .optional(),
467
+ })
468
+ .strict();
469
+ /** Verdict, scorecard and fix hints for one layout of a national focus tree. */
470
+ export const focusLayoutQualitySchema = z
471
+ .object({
472
+ verdict: qualityVerdictSchema,
473
+ score: z.number().int().min(0).max(100),
474
+ summary: z.string().max(500),
475
+ focusCount: z.number().int().nonnegative(),
476
+ bucket: z.enum(['small', 'medium', 'large']),
477
+ softMetricsEvaluated: z.boolean(),
478
+ scorecard: z.array(focusScorecardRowSchema).max(20),
479
+ failingRowCount: z.number().int().nonnegative(),
480
+ nextActions: z.array(z.string().max(500)).max(6),
481
+ notEvaluated: z.array(z.string().max(400)).max(8),
482
+ branches: z
483
+ .array(z
484
+ .object({
485
+ id: z.string().max(256),
486
+ focusCount: z.number().int().nonnegative(),
487
+ minimumX: z.number().int(),
488
+ maximumX: z.number().int(),
489
+ minimumY: z.number().int(),
490
+ maximumY: z.number().int(),
491
+ })
492
+ .strict())
493
+ .max(12),
494
+ })
495
+ .strict();
496
+ /** What a layout change did: verdicts, moved focuses and proof that gameplay relations are intact. */
497
+ export const focusLayoutDeltaSchema = z
498
+ .object({
499
+ verdictBefore: qualityVerdictSchema.nullable(),
500
+ verdictAfter: qualityVerdictSchema,
501
+ scoreBefore: z.number().int().min(0).max(100).nullable(),
502
+ scoreAfter: z.number().int().min(0).max(100),
503
+ improved: z.array(qualityMetricIdSchema).max(20),
504
+ regressed: z.array(qualityMetricIdSchema).max(20),
505
+ movedFocusCount: z.number().int().nonnegative(),
506
+ movedFocusIds: z.array(z.string().max(256)).max(100),
507
+ unmovedFocusCount: z.number().int().nonnegative(),
508
+ unmovedHash: z.string().max(64),
509
+ prerequisiteHash: z.string().max(64),
510
+ prerequisitesUnchanged: z.boolean().nullable(),
511
+ mutualExclusionHash: z.string().max(64),
512
+ mutualExclusionsUnchanged: z.boolean().nullable(),
513
+ })
514
+ .strict();