hoi4-agent-tools 4.6.4 → 4.7.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 (89) hide show
  1. package/CHANGELOG.md +22 -5
  2. package/dist/hoi4_agent_tools/core/artifacts.js +9 -2
  3. package/dist/hoi4_agent_tools/core/changed-summary.js +41 -0
  4. package/dist/hoi4_agent_tools/core/engine-client.js +273 -0
  5. package/dist/hoi4_agent_tools/core/job-worker-host.js +5 -1
  6. package/dist/hoi4_agent_tools/core/operation-result.js +24 -5
  7. package/dist/hoi4_agent_tools/focus/compact.js +197 -18
  8. package/dist/hoi4_agent_tools/focus/engine-layout.js +201 -0
  9. package/dist/hoi4_agent_tools/focus/job-operations.js +3 -1
  10. package/dist/hoi4_agent_tools/focus/layout.js +3 -2
  11. package/dist/hoi4_agent_tools/focus/quality/branches.js +32 -0
  12. package/dist/hoi4_agent_tools/focus/quality/calibration.js +364 -0
  13. package/dist/hoi4_agent_tools/focus/quality/delta.js +85 -0
  14. package/dist/hoi4_agent_tools/focus/quality/focus-quality-calibration.json +2265 -0
  15. package/dist/hoi4_agent_tools/focus/quality/graph.js +170 -0
  16. package/dist/hoi4_agent_tools/focus/quality/index.js +24 -0
  17. package/dist/hoi4_agent_tools/focus/quality/inline-images.js +132 -0
  18. package/dist/hoi4_agent_tools/focus/quality/metrics.js +424 -0
  19. package/dist/hoi4_agent_tools/focus/quality/orthogonal.js +202 -0
  20. package/dist/hoi4_agent_tools/focus/quality/positions.js +41 -0
  21. package/dist/hoi4_agent_tools/focus/quality/schematic.js +241 -0
  22. package/dist/hoi4_agent_tools/focus/quality/scorecard.js +549 -0
  23. package/dist/hoi4_agent_tools/focus/quality/stored-calibration.js +7 -0
  24. package/dist/hoi4_agent_tools/focus/quality/tool-output.js +113 -0
  25. package/dist/hoi4_agent_tools/focus/quality/types.js +5 -0
  26. package/dist/hoi4_agent_tools/focus/tool-operations.js +206 -22
  27. package/dist/hoi4_agent_tools/focus/tool-support.js +1 -1
  28. package/dist/hoi4_agent_tools/map/references.js +26 -1
  29. package/dist/hoi4_agent_tools/map/render.js +29 -3
  30. package/dist/hoi4_agent_tools/map/service.js +3 -0
  31. package/dist/hoi4_agent_tools/map/tool-operations.js +5 -0
  32. package/dist/hoi4_agent_tools/mcp/server/instructions.js +1 -1
  33. package/dist/hoi4_agent_tools/mcp/tools/focus.js +76 -4
  34. package/dist/hoi4_agent_tools/reference/game-text.js +109 -0
  35. package/dist/hoi4_agent_tools/reference/ranking.js +60 -2
  36. package/dist/hoi4_agent_tools/reference/service.js +92 -21
  37. package/dist/hoi4_agent_tools/schemas/focus-requests.js +64 -7
  38. package/dist/hoi4_agent_tools/schemas/focus.js +121 -6
  39. package/dist/hoi4_agent_tools/version.js +1 -1
  40. package/docs/configuration.md +17 -17
  41. package/docs/focus.md +100 -4
  42. package/docs/map.md +5 -2
  43. package/docs/reference.md +1 -1
  44. package/docs/research/reference-benchmark.md +111 -1
  45. package/docs/setup.md +1 -1
  46. package/docs/tools.md +5 -5
  47. package/docs/troubleshooting.md +12 -11
  48. package/npm-shrinkwrap.json +2 -2
  49. package/package.json +2 -1
  50. package/schemas/configuration.schema.json +1 -1
  51. package/schemas/continuous-focus-palette.schema.json +1 -1
  52. package/schemas/custom-weighted-pool.schema.json +1 -1
  53. package/schemas/decision-inspect-input.schema.json +1 -1
  54. package/schemas/error-log-input.schema.json +1 -1
  55. package/schemas/event-feature-manifest.schema.json +1 -1
  56. package/schemas/focus-plan.schema.json +146 -120
  57. package/schemas/focus-planning-sidecar.schema.json +15 -7
  58. package/schemas/geography-model.schema.json +1 -1
  59. package/schemas/gui-animation-source.schema.json +1 -1
  60. package/schemas/gui-helper.schema.json +1 -1
  61. package/schemas/gui-scenario.schema.json +1 -1
  62. package/schemas/helper-expansion-request.schema.json +1 -1
  63. package/schemas/helper-expansion-summary.schema.json +1 -1
  64. package/schemas/impact-inspect-input.schema.json +1 -1
  65. package/schemas/map-operation.schema.json +1 -1
  66. package/schemas/mechanic-test-input.schema.json +1 -1
  67. package/schemas/mod-index-input.schema.json +1 -1
  68. package/schemas/operation-result.schema.json +1 -1
  69. package/schemas/package-check-input.schema.json +1 -1
  70. package/schemas/package-manifest.schema.json +1 -1
  71. package/schemas/probability-analysis-result.schema.json +1 -1
  72. package/schemas/probability-compare-input.schema.json +1 -1
  73. package/schemas/probability-evaluate-input.schema.json +1 -1
  74. package/schemas/probability-inspect-input.schema.json +1 -1
  75. package/schemas/probability-render-input.schema.json +1 -1
  76. package/schemas/probability-scenario-set.schema.json +1 -1
  77. package/schemas/probability-sequence-input.schema.json +1 -1
  78. package/schemas/probability-simulate-input.schema.json +1 -1
  79. package/schemas/probability-sweep-input.schema.json +1 -1
  80. package/schemas/reference-context-input.schema.json +1 -1
  81. package/schemas/reference-read-input.schema.json +1 -1
  82. package/schemas/reference-search-input.schema.json +1 -1
  83. package/schemas/reference-sheets.schema.json +1 -1
  84. package/schemas/scenario-suite.schema.json +1 -1
  85. package/schemas/scenario-test-input.schema.json +1 -1
  86. package/schemas/script-validate-input.schema.json +1 -1
  87. package/schemas/shared-scenario.schema.json +1 -1
  88. package/schemas/source-lookup-input.schema.json +1 -1
  89. package/server.json +2 -2
@@ -0,0 +1,424 @@
1
+ import { compareCodeUnits } from '../../core/canonical.js';
2
+ import { measureOrthogonalConnectors, ORTHOGONAL_PLAQUE_WIDTH } from './orthogonal.js';
3
+ /** Below this many focuses a tree is too small for the vanilla-calibrated soft metrics. */
4
+ export const MINIMUM_FOCUSES_FOR_SOFT_METRICS = 8;
5
+ /** A tree this large skips the quadratic sibling-subtree comparison (S7). */
6
+ const INTERLEAVING_NODE_MAX = 3_000;
7
+ /** Rows below an exclusive choice within which reconvergence counts as "no lasting consequence". */
8
+ export const CONVERGENCE_ROW_WINDOW = 12;
9
+ /** Choices that rejoin sooner than this are an ordinary fork-and-merge, not a hollow choice. */
10
+ export const CONVERGENCE_MINIMUM_ROWS = 6;
11
+ const LOCATOR_LIMIT = 24;
12
+ function sum(values) {
13
+ return values.reduce((total, value) => total + value, 0);
14
+ }
15
+ function limited(values) {
16
+ return values.slice(0, LOCATOR_LIMIT);
17
+ }
18
+ /**
19
+ * Largest empty axis-aligned rectangle inside the bounding box, as a fraction of the box. A plaque
20
+ * occupies its own column and the next, because neighbouring plaques are two columns apart.
21
+ */
22
+ function largestEmptyRectangle(graph, minimumX, minimumY, width, rows) {
23
+ const columns = width + 2;
24
+ const occupied = Array.from({ length: rows }, () => new Uint8Array(columns));
25
+ for (const node of graph.nodes) {
26
+ const row = occupied[node.y - minimumY];
27
+ row[node.x - minimumX] = 1;
28
+ row[node.x - minimumX + 1] = 1;
29
+ }
30
+ let bestArea = 0;
31
+ let best;
32
+ const heights = new Array(columns).fill(0);
33
+ for (let row = 0; row < rows; row += 1) {
34
+ const cells = occupied[row];
35
+ for (let column = 0; column < columns; column += 1)
36
+ heights[column] = cells[column] === 1 ? 0 : heights[column] + 1;
37
+ const stack = [];
38
+ for (let column = 0; column <= columns; column += 1) {
39
+ const height = column === columns ? 0 : heights[column];
40
+ let start = column;
41
+ while (stack.length > 0 && stack[stack.length - 1].height >= height) {
42
+ const top = stack.pop();
43
+ const area = top.height * (column - top.start);
44
+ if (area > bestArea) {
45
+ bestArea = area;
46
+ best = {
47
+ row,
48
+ column: top.start,
49
+ width: column - top.start,
50
+ height: top.height,
51
+ };
52
+ }
53
+ start = top.start;
54
+ }
55
+ stack.push({ start, height });
56
+ }
57
+ }
58
+ return {
59
+ fraction: bestArea / (columns * rows),
60
+ region: best === undefined
61
+ ? null
62
+ : {
63
+ minimumX: minimumX + best.column,
64
+ maximumX: minimumX + best.column + best.width - 1,
65
+ minimumY: minimumY + best.row - best.height + 1,
66
+ maximumY: minimumY + best.row,
67
+ },
68
+ };
69
+ }
70
+ function descendants(graph, start, blocked = new Set(), maximumRow = Number.POSITIVE_INFINITY) {
71
+ const seen = new Set();
72
+ const stack = [...(graph.children.get(start) ?? [])];
73
+ while (stack.length > 0) {
74
+ const id = stack.pop();
75
+ if (seen.has(id) || blocked.has(id))
76
+ continue;
77
+ if ((graph.position.get(id)?.y ?? 0) > maximumRow)
78
+ continue;
79
+ seen.add(id);
80
+ for (const child of graph.children.get(id) ?? [])
81
+ stack.push(child);
82
+ }
83
+ return seen;
84
+ }
85
+ /** Children that have this parent as their only prerequisite. */
86
+ function ownedChildren(graph, parentId) {
87
+ return (graph.children.get(parentId) ?? []).filter((child) => (graph.parents.get(child)?.length ?? 0) === 1);
88
+ }
89
+ function longestSingleSuccessorChain(graph) {
90
+ const linear = (id) => (graph.parents.get(id)?.length ?? 0) === 1 && (graph.children.get(id)?.length ?? 0) === 1;
91
+ const seen = new Set();
92
+ let longest = [];
93
+ for (const { id } of graph.nodes) {
94
+ if (!linear(id))
95
+ continue;
96
+ const parent = graph.parents.get(id)[0];
97
+ if (linear(parent) && (graph.children.get(parent)?.length ?? 0) === 1)
98
+ continue;
99
+ const chain = [];
100
+ let current = id;
101
+ while (current !== undefined && linear(current) && !seen.has(current)) {
102
+ seen.add(current);
103
+ chain.push(current);
104
+ current = graph.children.get(current)[0];
105
+ }
106
+ if (chain.length > longest.length)
107
+ longest = chain;
108
+ }
109
+ return longest;
110
+ }
111
+ function exclusiveSets(graph) {
112
+ const parent = new Map();
113
+ const find = (id) => {
114
+ let root = id;
115
+ while ((parent.get(root) ?? root) !== root)
116
+ root = parent.get(root);
117
+ parent.set(id, root);
118
+ return root;
119
+ };
120
+ for (const [left, right] of graph.exclusions) {
121
+ parent.set(find(left), find(right));
122
+ }
123
+ const sets = new Map();
124
+ for (const [left, right] of graph.exclusions)
125
+ for (const id of [left, right]) {
126
+ const root = find(id);
127
+ const members = sets.get(root) ?? [];
128
+ if (!members.includes(id))
129
+ members.push(id);
130
+ sets.set(root, members);
131
+ }
132
+ return [...sets.values()]
133
+ .map((members) => members.sort(compareCodeUnits))
134
+ .sort((left, right) => compareCodeUnits(left.join('\0'), right.join('\0')));
135
+ }
136
+ /** Focuses whose coordinates cannot be judged: an unevaluated offset or a conditional branch. */
137
+ function unjudged(graph, id) {
138
+ return graph.offsetDependent.has(id) || graph.conditional.has(id);
139
+ }
140
+ /** Measures every metric of the layout rubric on resolved grid coordinates. */
141
+ export function measureLayoutQuality(graph) {
142
+ const nodeCount = graph.nodes.length;
143
+ const edgeCount = graph.edges.length;
144
+ const values = {};
145
+ const notEvaluated = [];
146
+ const locators = {
147
+ duplicateCoordinates: [],
148
+ parentNotAbove: [],
149
+ overlaps: [],
150
+ stemsThroughPlaques: [],
151
+ crossings: [],
152
+ mergedBars: [],
153
+ detours: [],
154
+ offCenterCohorts: [],
155
+ mixedRowCohorts: [],
156
+ interleavedPairs: [],
157
+ slackChildren: [],
158
+ emptyRectangle: null,
159
+ longestChain: [],
160
+ convergingChoices: [],
161
+ rowCentroids: null,
162
+ sides: { left: 0, right: 0, centre: 0 },
163
+ bundles: [],
164
+ };
165
+ const counts = {
166
+ duplicateCoordinates: 0,
167
+ parentNotAbove: 0,
168
+ overlaps: 0,
169
+ stemsThroughPlaques: 0,
170
+ crossings: 0,
171
+ mergedBars: 0,
172
+ detours: 0,
173
+ leaves: 0,
174
+ cohorts: 0,
175
+ bundleEdges: 0,
176
+ exclusiveSets: 0,
177
+ };
178
+ if (nodeCount === 0) {
179
+ return { nodeCount, edgeCount, width: 0, rows: 0, values, counts, locators, notEvaluated };
180
+ }
181
+ const xs = graph.nodes.map(({ x }) => x);
182
+ const ys = graph.nodes.map(({ y }) => y);
183
+ const minimumX = Math.min(...xs);
184
+ const maximumX = Math.max(...xs);
185
+ const minimumY = Math.min(...ys);
186
+ const maximumY = Math.max(...ys);
187
+ const width = maximumX - minimumX;
188
+ const rows = maximumY - minimumY + 1;
189
+ const per100 = (count) => (edgeCount === 0 ? 0 : (100 * count) / edgeCount);
190
+ // H1 duplicate coordinates and H3 overlapping plaques (focuses with an unresolved offset are skipped).
191
+ const byCoordinate = new Map();
192
+ const byRow = new Map();
193
+ for (const node of graph.nodes) {
194
+ const key = `${node.x},${node.y}`;
195
+ const group = byCoordinate.get(key) ?? [];
196
+ group.push(node.id);
197
+ byCoordinate.set(key, group);
198
+ const row = byRow.get(node.y) ?? [];
199
+ row.push({ id: node.id, x: node.x });
200
+ byRow.set(node.y, row);
201
+ }
202
+ for (const [key, ids] of [...byCoordinate].sort(([left], [right]) => compareCodeUnits(left, right))) {
203
+ const certain = ids.filter((id) => !unjudged(graph, id));
204
+ if (ids.length < 2 || certain.length < 2)
205
+ continue;
206
+ const [x, y] = key.split(',').map(Number);
207
+ counts.duplicateCoordinates += certain.length - 1;
208
+ locators.duplicateCoordinates.push({ x, y, focusIds: certain });
209
+ }
210
+ for (const [y, row] of [...byRow].sort(([left], [right]) => left - right)) {
211
+ row.sort((left, right) => left.x - right.x || compareCodeUnits(left.id, right.id));
212
+ for (const [index, left] of row.entries()) {
213
+ for (const right of row.slice(index + 1)) {
214
+ const distance = right.x - left.x;
215
+ if (distance >= ORTHOGONAL_PLAQUE_WIDTH)
216
+ break;
217
+ if (distance <= 0)
218
+ continue;
219
+ if (unjudged(graph, left.id) || unjudged(graph, right.id))
220
+ continue;
221
+ counts.overlaps += 1;
222
+ locators.overlaps.push({ leftId: left.id, rightId: right.id, y, distance });
223
+ }
224
+ }
225
+ }
226
+ // H2 a prerequisite that is not above its dependant.
227
+ for (const edge of graph.edges) {
228
+ const parent = graph.position.get(edge.parent);
229
+ const child = graph.position.get(edge.child);
230
+ if (parent.y < child.y)
231
+ continue;
232
+ if (unjudged(graph, edge.parent) || unjudged(graph, edge.child))
233
+ continue;
234
+ counts.parentNotAbove += 1;
235
+ locators.parentNotAbove.push({ parentId: edge.parent, childId: edge.child });
236
+ }
237
+ values.H1 = counts.duplicateCoordinates;
238
+ values.H2 = counts.parentNotAbove;
239
+ values.H3 = counts.overlaps;
240
+ // H4, H5 and S9 under the orthogonal connector model.
241
+ const orthogonal = measureOrthogonalConnectors(graph);
242
+ if (orthogonal.notEvaluated !== undefined)
243
+ notEvaluated.push(orthogonal.notEvaluated);
244
+ counts.crossings = orthogonal.crossings.length;
245
+ counts.stemsThroughPlaques = orthogonal.stemsThroughPlaques.length;
246
+ counts.mergedBars = orthogonal.mergedBars.length;
247
+ counts.bundleEdges = orthogonal.bundleEdgeCount;
248
+ locators.bundles = orthogonal.bundles;
249
+ const connectorIds = (index) => ({
250
+ parentId: orthogonal.connectors[index].parent,
251
+ childId: orthogonal.connectors[index].child,
252
+ });
253
+ locators.stemsThroughPlaques = limited(orthogonal.stemsThroughPlaques.map(({ edgeIndex, focusId }) => ({
254
+ ...connectorIds(edgeIndex),
255
+ focusId,
256
+ })));
257
+ const pairLocator = (pair) => ({
258
+ firstParentId: connectorIds(pair.firstIndex).parentId,
259
+ firstChildId: connectorIds(pair.firstIndex).childId,
260
+ secondParentId: connectorIds(pair.secondIndex).parentId,
261
+ secondChildId: connectorIds(pair.secondIndex).childId,
262
+ });
263
+ locators.crossings = limited(orthogonal.crossings.map(pairLocator));
264
+ locators.mergedBars = limited(orthogonal.mergedBars.map(pairLocator));
265
+ values.H4 = per100(counts.stemsThroughPlaques);
266
+ values.H5 = per100(counts.crossings);
267
+ values.S9 = per100(counts.mergedBars);
268
+ // S1 empty space, S2 side balance, S3 mass skew, S4 fill, S5 row-centroid wander.
269
+ const empty = largestEmptyRectangle(graph, minimumX, minimumY, width, rows);
270
+ values.S1 = empty.fraction;
271
+ locators.emptyRectangle = empty.region;
272
+ const centre = (minimumX + maximumX) / 2;
273
+ const left = xs.filter((x) => x < centre - 0.5).length;
274
+ const right = xs.filter((x) => x > centre + 0.5).length;
275
+ locators.sides = { left, right, centre };
276
+ values.S2 = Math.abs(left - right) / Math.max(1, left + right);
277
+ values.S3 = width === 0 ? 0 : Math.abs(sum(xs) / nodeCount - centre) / (width / 2);
278
+ values.S4 = nodeCount / ((Math.floor(width / 2) + 1) * rows);
279
+ const rowMeans = [...byRow].map(([y, row]) => ({
280
+ y,
281
+ mean: sum(row.map(({ x }) => x)) / row.length,
282
+ }));
283
+ const lowestRow = rowMeans.reduce((best, row) => (row.mean < best.mean ? row : best));
284
+ const highestRow = rowMeans.reduce((best, row) => (row.mean > best.mean ? row : best));
285
+ values.S5 = width === 0 ? 0 : (highestRow.mean - lowestRow.mean) / width;
286
+ locators.rowCentroids = {
287
+ minimumRow: lowestRow.y,
288
+ maximumRow: highestRow.y,
289
+ minimumMean: lowestRow.mean,
290
+ maximumMean: highestRow.mean,
291
+ };
292
+ // S6 single-parent single-child links that jog sideways.
293
+ for (const edge of graph.edges) {
294
+ if ((graph.children.get(edge.parent)?.length ?? 0) !== 1)
295
+ continue;
296
+ if ((graph.parents.get(edge.child)?.length ?? 0) !== 1)
297
+ continue;
298
+ const dx = graph.position.get(edge.child).x - graph.position.get(edge.parent).x;
299
+ if (dx === 0)
300
+ continue;
301
+ counts.detours += 1;
302
+ locators.detours.push({ parentId: edge.parent, childId: edge.child, dx });
303
+ }
304
+ locators.detours = limited(locators.detours);
305
+ values.S6 = per100(counts.detours);
306
+ // S8 fan-out cohorts off the parent's column, S11 cohorts spread over several rows, S7 interleaving.
307
+ const cohorts = [];
308
+ for (const { id } of graph.nodes) {
309
+ const owned = ownedChildren(graph, id);
310
+ if (owned.length >= 2)
311
+ cohorts.push({ parentId: id, childIds: owned });
312
+ }
313
+ counts.cohorts = cohorts.length;
314
+ let largestOffset = 0;
315
+ let mixedRows = 0;
316
+ const offCentre = [];
317
+ for (const cohort of cohorts) {
318
+ const childX = cohort.childIds.map((id) => graph.position.get(id).x);
319
+ const cohortCentre = (Math.min(...childX) + Math.max(...childX)) / 2;
320
+ const offset = Math.abs(cohortCentre - graph.position.get(cohort.parentId).x);
321
+ largestOffset = Math.max(largestOffset, offset);
322
+ if (offset >= 2)
323
+ offCentre.push({ ...cohort, offset, centre: cohortCentre });
324
+ if (new Set(cohort.childIds.map((id) => graph.position.get(id).y)).size > 1) {
325
+ mixedRows += 1;
326
+ locators.mixedRowCohorts.push(cohort);
327
+ }
328
+ }
329
+ locators.offCenterCohorts = limited(offCentre.sort((a, b) => b.offset - a.offset || compareCodeUnits(a.parentId, b.parentId)));
330
+ locators.mixedRowCohorts = limited(locators.mixedRowCohorts);
331
+ values.S8 = largestOffset;
332
+ values.S11 = cohorts.length === 0 ? 0 : mixedRows / cohorts.length;
333
+ if (nodeCount > INTERLEAVING_NODE_MAX) {
334
+ notEvaluated.push('Sibling-subtree interleaving (S7) is skipped for trees above 3000 focuses');
335
+ }
336
+ else {
337
+ let pairs = 0;
338
+ let interleaved = 0;
339
+ for (const cohort of cohorts) {
340
+ const reach = cohort.childIds.map((id) => new Set([id, ...descendants(graph, id)]));
341
+ const reachCount = new Map();
342
+ for (const set of reach)
343
+ for (const id of set)
344
+ reachCount.set(id, (reachCount.get(id) ?? 0) + 1);
345
+ const rowRanges = reach.map((set) => {
346
+ const ranges = new Map();
347
+ for (const id of set) {
348
+ if (reachCount.get(id) !== 1)
349
+ continue;
350
+ const { x, y } = graph.position.get(id);
351
+ const range = ranges.get(y) ?? [Infinity, -Infinity];
352
+ range[0] = Math.min(range[0], x);
353
+ range[1] = Math.max(range[1], x);
354
+ ranges.set(y, range);
355
+ }
356
+ return ranges;
357
+ });
358
+ for (let first = 0; first < rowRanges.length; first += 1) {
359
+ for (let second = first + 1; second < rowRanges.length; second += 1) {
360
+ pairs += 1;
361
+ let overlap = false;
362
+ for (const [y, a] of rowRanges[first]) {
363
+ const b = rowRanges[second].get(y);
364
+ if (b !== undefined && Math.min(a[1], b[1]) - Math.max(a[0], b[0]) >= 0) {
365
+ overlap = true;
366
+ break;
367
+ }
368
+ }
369
+ if (overlap) {
370
+ interleaved += 1;
371
+ locators.interleavedPairs.push({
372
+ parentId: cohort.parentId,
373
+ firstChildId: cohort.childIds[first],
374
+ secondChildId: cohort.childIds[second],
375
+ });
376
+ }
377
+ }
378
+ }
379
+ }
380
+ locators.interleavedPairs = limited(locators.interleavedPairs);
381
+ values.S7 = pairs === 0 ? 0 : interleaved / pairs;
382
+ }
383
+ // S10 largest vertical gap between a focus and its lowest prerequisite.
384
+ let slackMaximum = 0;
385
+ const slackChildren = [];
386
+ for (const { id, y } of graph.nodes) {
387
+ const parents = graph.parents.get(id) ?? [];
388
+ if (parents.length === 0)
389
+ continue;
390
+ const slack = y - Math.max(...parents.map((parent) => graph.position.get(parent).y)) - 1;
391
+ slackMaximum = Math.max(slackMaximum, slack);
392
+ if (slack > 0)
393
+ slackChildren.push({ childId: id, slack });
394
+ }
395
+ locators.slackChildren = limited(slackChildren.sort((a, b) => b.slack - a.slack || compareCodeUnits(a.childId, b.childId)));
396
+ values.S10 = slackMaximum;
397
+ // D1 to D4 design proxies; they route a tree to review but never fail it.
398
+ locators.longestChain = longestSingleSuccessorChain(graph);
399
+ values.D1 = locators.longestChain.length;
400
+ counts.leaves = graph.nodes.filter(({ id }) => (graph.children.get(id)?.length ?? 0) === 0).length;
401
+ values.D2 = counts.leaves / nodeCount;
402
+ const sets = exclusiveSets(graph);
403
+ counts.exclusiveSets = sets.length;
404
+ for (const members of sets) {
405
+ const memberSet = new Set(members);
406
+ const lastRow = Math.max(...members.map((id) => graph.position.get(id).y));
407
+ const reaches = members.map((id) => descendants(graph, id, memberSet, lastRow + CONVERGENCE_ROW_WINDOW));
408
+ const shared = [...reaches[0]].filter((id) => reaches.every((set) => set.has(id)));
409
+ if (shared.length === 0)
410
+ continue;
411
+ const first = shared.sort((a, b) => graph.position.get(a).y - graph.position.get(b).y || compareCodeUnits(a, b))[0];
412
+ if (graph.position.get(first).y - lastRow < CONVERGENCE_MINIMUM_ROWS)
413
+ continue;
414
+ locators.convergingChoices.push({
415
+ choiceIds: members,
416
+ convergenceId: first,
417
+ rows: graph.position.get(first).y - lastRow,
418
+ });
419
+ }
420
+ locators.convergingChoices = limited(locators.convergingChoices);
421
+ values.D3 = locators.convergingChoices.length;
422
+ values.D4 = rows / Math.max(1, width / 2);
423
+ return { nodeCount, edgeCount, width, rows, values, counts, locators, notEvaluated };
424
+ }
@@ -0,0 +1,202 @@
1
+ import { compareCodeUnits } from '../../core/canonical.js';
2
+ import { FOCUS_PAIR_COMPARISON_MAX } from '../limits.js';
3
+ /**
4
+ * Orthogonal connector model "O1". The game draws right-angle connectors: a stem leaves the bottom
5
+ * of the parent, a horizontal bar runs in the gap just above the child's row, and a short stem
6
+ * enters the child. A plaque is about 1.6 grid columns wide and half a row high. This model was
7
+ * read from one in-game screenshot for adjacent rows; multi-row bar placement is unverified, so
8
+ * every number derived from it is advisory until it is confirmed in the game.
9
+ */
10
+ export const ORTHOGONAL_PLAQUE_WIDTH = 1.6;
11
+ export const ORTHOGONAL_PLAQUE_HEIGHT = 0.5;
12
+ /** A stem closer than this many columns to another plaque's centre runs through that plaque. */
13
+ export const ORTHOGONAL_STEM_CLEARANCE = ORTHOGONAL_PLAQUE_WIDTH / 2;
14
+ /** Distance of the horizontal bar above the child's row. */
15
+ export const ORTHOGONAL_BAR_OFFSET = 0.25;
16
+ export const ORTHOGONAL_MINIMUM_SHARED_BAR = 0.5;
17
+ export const ORTHOGONAL_MINIMUM_SHARED_STEM = 0.3;
18
+ const BUNDLE_CANDIDATE_PARENT_MAX = 800;
19
+ export function orthogonalConnector(parent, child) {
20
+ return {
21
+ parent: parent.id,
22
+ child: child.id,
23
+ parentX: parent.x,
24
+ childX: child.x,
25
+ parentY: parent.y,
26
+ childY: child.y,
27
+ barY: child.y - ORTHOGONAL_BAR_OFFSET,
28
+ barFrom: Math.min(parent.x, child.x),
29
+ barTo: Math.max(parent.x, child.x),
30
+ };
31
+ }
32
+ function intersection(left, right) {
33
+ return left.filter((value) => right.has(value));
34
+ }
35
+ /**
36
+ * Bundles are sets of at least two parents and two children with every parent a prerequisite of
37
+ * every child. The game draws such a set as one bar, so the connectors inside one bundle are never
38
+ * counted against each other.
39
+ */
40
+ export function detectBundles(graph) {
41
+ const candidates = graph.nodes
42
+ .map(({ id }) => id)
43
+ .filter((id) => (graph.children.get(id)?.length ?? 0) >= 2)
44
+ .slice(0, BUNDLE_CANDIDATE_PARENT_MAX);
45
+ const childSets = new Map(candidates.map((id) => [id, new Set(graph.children.get(id) ?? [])]));
46
+ const found = new Map();
47
+ for (const [index, first] of candidates.entries()) {
48
+ const firstChildren = graph.children.get(first) ?? [];
49
+ for (const second of candidates.slice(index + 1)) {
50
+ const common = intersection(firstChildren, childSets.get(second));
51
+ if (common.length < 2)
52
+ continue;
53
+ const bundleParents = candidates.filter((candidate) => {
54
+ const set = childSets.get(candidate);
55
+ return common.every((child) => set.has(child));
56
+ });
57
+ let bundleChildren = common;
58
+ for (const parent of bundleParents)
59
+ bundleChildren = intersection(bundleChildren, childSets.get(parent));
60
+ if (bundleParents.length < 2 || bundleChildren.length < 2)
61
+ continue;
62
+ const key = `${bundleParents.join('\0')}|${bundleChildren.join('\0')}`;
63
+ if (!found.has(key))
64
+ found.set(key, {
65
+ parents: [...bundleParents].sort(compareCodeUnits),
66
+ children: [...bundleChildren].sort(compareCodeUnits),
67
+ });
68
+ }
69
+ }
70
+ return [...found.values()].sort((left, right) => compareCodeUnits(left.parents.join('\0'), right.parents.join('\0')) ||
71
+ compareCodeUnits(left.children.join('\0'), right.children.join('\0')));
72
+ }
73
+ function pairKey(first, second) {
74
+ return first < second ? `${first}:${second}` : `${second}:${first}`;
75
+ }
76
+ /** Counts the defects of the orthogonal model; connectors inside one bundle are exempt. */
77
+ export function measureOrthogonalConnectors(graph) {
78
+ const bundles = detectBundles(graph);
79
+ const connectors = graph.edges.map((edge) => orthogonalConnector({ id: edge.parent, ...graph.position.get(edge.parent) }, { id: edge.child, ...graph.position.get(edge.child) }));
80
+ const bundleIdsOfEdge = connectors.map((connector) => {
81
+ const ids = [];
82
+ for (const [bundleIndex, bundle] of bundles.entries())
83
+ if (bundle.parents.includes(connector.parent) && bundle.children.includes(connector.child))
84
+ ids.push(bundleIndex);
85
+ return ids;
86
+ });
87
+ const bundleMembers = bundles.map((bundle) => new Set([...bundle.parents, ...bundle.children]));
88
+ const exempt = (first, second) => {
89
+ const a = connectors[first];
90
+ const b = connectors[second];
91
+ if (a.parent === b.parent || a.child === b.child)
92
+ return true;
93
+ const firstBundles = bundleIdsOfEdge[first];
94
+ const secondBundles = bundleIdsOfEdge[second];
95
+ return firstBundles.some((id) => secondBundles.includes(id));
96
+ };
97
+ let work = 0;
98
+ let notEvaluated;
99
+ const spend = (amount = 1) => {
100
+ work += amount;
101
+ if (work <= FOCUS_PAIR_COMPARISON_MAX)
102
+ return true;
103
+ notEvaluated ??=
104
+ 'The tree is too large for an exact connector comparison; crossing and merged-bar counts are partial';
105
+ return false;
106
+ };
107
+ const barsByRow = new Map();
108
+ for (const [index, connector] of connectors.entries()) {
109
+ const row = barsByRow.get(connector.childY) ?? [];
110
+ row.push(index);
111
+ barsByRow.set(connector.childY, row);
112
+ }
113
+ const nodesByRow = new Map();
114
+ for (const node of graph.nodes) {
115
+ const row = nodesByRow.get(node.y) ?? [];
116
+ row.push({ id: node.id, x: node.x });
117
+ nodesByRow.set(node.y, row);
118
+ }
119
+ const crossings = [];
120
+ const stems = [];
121
+ for (const [index, connector] of connectors.entries()) {
122
+ // The parent stem passes every row strictly between the parent and the child.
123
+ for (let row = connector.parentY + 1; row <= connector.childY - 1; row += 1) {
124
+ for (const otherIndex of barsByRow.get(row) ?? []) {
125
+ if (!spend())
126
+ break;
127
+ if (otherIndex === index)
128
+ continue;
129
+ const other = connectors[otherIndex];
130
+ if (other.barFrom < connector.parentX &&
131
+ connector.parentX < other.barTo &&
132
+ !exempt(index, otherIndex))
133
+ crossings.push({ firstIndex: index, secondIndex: otherIndex });
134
+ }
135
+ for (const node of nodesByRow.get(row) ?? []) {
136
+ if (!spend())
137
+ break;
138
+ if (node.id === connector.parent || node.id === connector.child)
139
+ continue;
140
+ if (Math.abs(node.x - connector.parentX) >= ORTHOGONAL_STEM_CLEARANCE)
141
+ continue;
142
+ const inOwnBundle = (bundleIdsOfEdge[index] ?? []).some((bundleIndex) => bundleMembers[bundleIndex].has(node.id));
143
+ if (!inOwnBundle)
144
+ stems.push({ edgeIndex: index, focusId: node.id });
145
+ }
146
+ }
147
+ }
148
+ const merged = new Map();
149
+ for (const indexes of barsByRow.values()) {
150
+ for (const [position, first] of indexes.entries()) {
151
+ for (const second of indexes.slice(position + 1)) {
152
+ if (!spend())
153
+ break;
154
+ const a = connectors[first];
155
+ const b = connectors[second];
156
+ if (exempt(first, second))
157
+ continue;
158
+ const overlap = Math.min(a.barTo, b.barTo) - Math.max(a.barFrom, b.barFrom);
159
+ if (overlap >= ORTHOGONAL_MINIMUM_SHARED_BAR)
160
+ merged.set(pairKey(first, second), { firstIndex: first, secondIndex: second });
161
+ }
162
+ }
163
+ }
164
+ const verticals = new Map();
165
+ const addVertical = (x, index, from, to) => {
166
+ if (to <= from)
167
+ return;
168
+ const group = verticals.get(x) ?? [];
169
+ group.push({ index, from, to });
170
+ verticals.set(x, group);
171
+ };
172
+ for (const [index, connector] of connectors.entries()) {
173
+ addVertical(connector.parentX, index, connector.parentY + ORTHOGONAL_PLAQUE_HEIGHT, connector.barY);
174
+ addVertical(connector.childX, index, connector.barY, connector.childY);
175
+ }
176
+ for (const group of verticals.values()) {
177
+ for (const [position, first] of group.entries()) {
178
+ for (const second of group.slice(position + 1)) {
179
+ if (!spend())
180
+ break;
181
+ if (first.index === second.index || exempt(first.index, second.index))
182
+ continue;
183
+ const overlap = Math.min(first.to, second.to) - Math.max(first.from, second.from);
184
+ if (overlap > ORTHOGONAL_MINIMUM_SHARED_STEM)
185
+ merged.set(pairKey(first.index, second.index), {
186
+ firstIndex: Math.min(first.index, second.index),
187
+ secondIndex: Math.max(first.index, second.index),
188
+ });
189
+ }
190
+ }
191
+ }
192
+ const bundleEdgeCount = bundleIdsOfEdge.filter((ids) => ids.length > 0).length;
193
+ return {
194
+ bundles,
195
+ bundleEdgeCount,
196
+ crossings,
197
+ stemsThroughPlaques: stems,
198
+ mergedBars: [...merged.values()],
199
+ connectors,
200
+ notEvaluated,
201
+ };
202
+ }
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Resolves the grid coordinates of a plan whose focuses all carry a fixed or relative position,
3
+ * the way the game reads them: a relative offset is added to the anchor's own resolved position.
4
+ * Returns `undefined` when a focus is placed by the solver or an anchor is missing or circular, so
5
+ * the caller falls back to the layout engine.
6
+ */
7
+ export function resolveStaticPositions(plan) {
8
+ const byId = new Map(plan.focuses.map((focus) => [focus.id, focus]));
9
+ const resolved = new Map();
10
+ const resolving = new Set();
11
+ const resolve = (id) => {
12
+ const known = resolved.get(id);
13
+ if (known !== undefined)
14
+ return known;
15
+ const focus = byId.get(id);
16
+ if (focus === undefined || resolving.has(id))
17
+ return undefined;
18
+ resolving.add(id);
19
+ let node;
20
+ if (focus.position.mode === 'fixed') {
21
+ node = { id, x: focus.position.x, y: focus.position.y };
22
+ }
23
+ else if (focus.position.mode === 'relative') {
24
+ const anchor = resolve(focus.position.relativeTo);
25
+ if (anchor !== undefined)
26
+ node = { id, x: anchor.x + focus.position.x, y: anchor.y + focus.position.y };
27
+ }
28
+ resolving.delete(id);
29
+ if (node !== undefined)
30
+ resolved.set(id, node);
31
+ return node;
32
+ };
33
+ const nodes = [];
34
+ for (const focus of plan.focuses) {
35
+ const node = resolve(focus.id);
36
+ if (node === undefined)
37
+ return undefined;
38
+ nodes.push(node);
39
+ }
40
+ return nodes;
41
+ }