-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuml-diff.ts
More file actions
908 lines (822 loc) · 29.4 KB
/
Copy pathuml-diff.ts
File metadata and controls
908 lines (822 loc) · 29.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
import type {
ClassAttribute,
ClassDiagramEdge,
ClassDiagramNode,
ClassDiagramState,
ClassMethod,
RelationshipType,
UmlElementType,
} from '../client/components/uml/classDiagram.js';
import type {
LifelineKind,
SequenceDiagramState,
SequenceFragment,
SequenceFragmentKind,
SequenceLifeline,
SequenceMessage,
SequenceMessageType,
} from '../client/components/uml/sequenceDiagram.js';
export type DiffStatus = 'matched' | 'missing' | 'extra';
export type AttributeMatch = {
refName: string;
studentName: string;
visibilityMatches: boolean;
typeMatches: boolean;
staticMatches: boolean;
/** 0..1 — partial credit for aspect matches */
aspectScore: number;
};
export type MethodMatch = {
refName: string;
studentName: string;
visibilityMatches: boolean;
parametersMatch: boolean;
returnTypeMatches: boolean;
staticMatches: boolean;
abstractMatches: boolean;
/** 0..1 — partial credit for aspect matches */
aspectScore: number;
};
export type ClassMatch = {
refName: string;
studentName: string;
refElementType: UmlElementType;
studentElementType: UmlElementType;
elementTypeMatches: boolean;
attributes: {
matched: AttributeMatch[];
missing: string[];
extra: string[];
score: number; // 0..1
};
methods: {
matched: MethodMatch[];
missing: string[];
extra: string[];
score: number; // 0..1
};
};
export type EdgeRef = {
source: string;
target: string;
relationship: RelationshipType;
};
export type EdgeMatch = {
ref: EdgeRef;
student: EdgeRef;
relationshipMatches: boolean;
};
export type ClassDiagramDiffResult = {
/** Aggregate structural score, 0..1 */
score: number;
classes: {
matched: ClassMatch[];
missing: string[];
extra: string[];
score: number; // 0..1
};
edges: {
matched: EdgeMatch[];
missing: EdgeRef[];
extra: EdgeRef[];
score: number; // 0..1
};
summary: string;
};
const CLASS_WEIGHT = 0.3;
const EDGE_WEIGHT = 0.25;
const ATTRIBUTE_WEIGHT = 0.25;
const METHOD_WEIGHT = 0.2;
const normalizeName = (raw: string | undefined): string =>
(raw ?? '').trim().toLowerCase().replace(/\s+/g, '');
const normalizeType = (raw: string | undefined): string =>
(raw ?? '').trim().toLowerCase().replace(/\s+/g, '');
const normalizeParams = (raw: string | undefined): string => {
if (!raw) return '';
// "x: int, y: int" → "x:int,y:int" (case-preserving names but trimmed/joined)
return raw
.split(',')
.map((p) => p.trim().replace(/\s+/g, '').toLowerCase())
.join(',');
};
const safeRatio = (matched: number, total: number): number => {
if (total === 0) return 1;
return matched / total;
};
const compareAttribute = (refAttr: ClassAttribute, studentAttr: ClassAttribute): AttributeMatch => {
const visibilityMatches = refAttr.visibility === studentAttr.visibility;
const typeMatches = normalizeType(refAttr.type) === normalizeType(studentAttr.type);
const staticMatches = Boolean(refAttr.isStatic) === Boolean(studentAttr.isStatic);
// 4 aspects: presence (always 1 since matched), visibility, type, static
const aspectScore = (1 + Number(visibilityMatches) + Number(typeMatches) + Number(staticMatches)) / 4;
return {
refName: refAttr.name,
studentName: studentAttr.name,
visibilityMatches,
typeMatches,
staticMatches,
aspectScore,
};
};
const compareMethod = (refMethod: ClassMethod, studentMethod: ClassMethod): MethodMatch => {
const visibilityMatches = refMethod.visibility === studentMethod.visibility;
const parametersMatch = normalizeParams(refMethod.parameters) === normalizeParams(studentMethod.parameters);
const returnTypeMatches = normalizeType(refMethod.returnType) === normalizeType(studentMethod.returnType);
const staticMatches = Boolean(refMethod.isStatic) === Boolean(studentMethod.isStatic);
const abstractMatches = Boolean(refMethod.isAbstract) === Boolean(studentMethod.isAbstract);
// 6 aspects: presence (1), visibility, params, return, static, abstract
const aspectScore =
(1 +
Number(visibilityMatches) +
Number(parametersMatch) +
Number(returnTypeMatches) +
Number(staticMatches) +
Number(abstractMatches)) /
6;
return {
refName: refMethod.name,
studentName: studentMethod.name,
visibilityMatches,
parametersMatch,
returnTypeMatches,
staticMatches,
abstractMatches,
aspectScore,
};
};
type AttributeDiffOutcome = ClassMatch['attributes'];
type MethodDiffOutcome = ClassMatch['methods'];
const diffAttributes = (
refAttrs: ClassAttribute[],
studentAttrs: ClassAttribute[]
): AttributeDiffOutcome => {
const studentByName = new Map<string, ClassAttribute>();
for (const attr of studentAttrs) studentByName.set(normalizeName(attr.name), attr);
const matched: AttributeMatch[] = [];
const missing: string[] = [];
const usedStudent = new Set<string>();
for (const refAttr of refAttrs) {
const key = normalizeName(refAttr.name);
const studentAttr = studentByName.get(key);
if (studentAttr) {
matched.push(compareAttribute(refAttr, studentAttr));
usedStudent.add(key);
} else {
missing.push(refAttr.name);
}
}
const extra: string[] = [];
for (const studentAttr of studentAttrs) {
if (!usedStudent.has(normalizeName(studentAttr.name))) {
extra.push(studentAttr.name);
}
}
// Score: average aspect score weighted by (matched / refTotal)
const refTotal = refAttrs.length;
if (refTotal === 0) {
// No attributes expected — extras aren't penalised structurally
return { matched, missing, extra, score: 1 };
}
const avgAspect = matched.length === 0
? 0
: matched.reduce((acc, m) => acc + m.aspectScore, 0) / matched.length;
const coverage = matched.length / refTotal;
const score = coverage * avgAspect;
return { matched, missing, extra, score };
};
const diffMethods = (
refMethods: ClassMethod[],
studentMethods: ClassMethod[]
): MethodDiffOutcome => {
const studentByName = new Map<string, ClassMethod>();
for (const method of studentMethods) studentByName.set(normalizeName(method.name), method);
const matched: MethodMatch[] = [];
const missing: string[] = [];
const usedStudent = new Set<string>();
for (const refMethod of refMethods) {
const key = normalizeName(refMethod.name);
const studentMethod = studentByName.get(key);
if (studentMethod) {
matched.push(compareMethod(refMethod, studentMethod));
usedStudent.add(key);
} else {
missing.push(refMethod.name);
}
}
const extra: string[] = [];
for (const studentMethod of studentMethods) {
if (!usedStudent.has(normalizeName(studentMethod.name))) {
extra.push(studentMethod.name);
}
}
const refTotal = refMethods.length;
if (refTotal === 0) {
return { matched, missing, extra, score: 1 };
}
const avgAspect = matched.length === 0
? 0
: matched.reduce((acc, m) => acc + m.aspectScore, 0) / matched.length;
const coverage = matched.length / refTotal;
const score = coverage * avgAspect;
return { matched, missing, extra, score };
};
const buildNodeIndex = (nodes: ClassDiagramNode[]): Map<string, ClassDiagramNode> => {
const idx = new Map<string, ClassDiagramNode>();
for (const node of nodes) {
idx.set(normalizeName(node.data.name), node);
}
return idx;
};
const buildClassesById = (nodes: ClassDiagramNode[]): Map<string, ClassDiagramNode> => {
const idx = new Map<string, ClassDiagramNode>();
for (const node of nodes) idx.set(node.id, node);
return idx;
};
const refToEdgeRef = (
edge: ClassDiagramEdge,
byId: Map<string, ClassDiagramNode>
): EdgeRef | null => {
const source = byId.get(edge.source);
const target = byId.get(edge.target);
if (!source || !target) return null;
return {
source: source.data.name,
target: target.data.name,
relationship: edge.data.relationship,
};
};
export function diffClassDiagrams(
student: ClassDiagramState,
reference: ClassDiagramState
): ClassDiagramDiffResult {
const refByName = buildNodeIndex(reference.nodes);
const studentByName = buildNodeIndex(student.nodes);
const matchedClasses: ClassMatch[] = [];
const missingClasses: string[] = [];
const usedStudent = new Set<string>();
let attrMatchedCount = 0;
let attrTotalCount = 0;
let attrAggregateScore = 0;
let methodMatchedCount = 0;
let methodTotalCount = 0;
let methodAggregateScore = 0;
for (const [refKey, refNode] of refByName) {
const studentNode = studentByName.get(refKey);
if (!studentNode) {
missingClasses.push(refNode.data.name);
attrTotalCount += refNode.data.attributes.length;
methodTotalCount += refNode.data.methods.length;
continue;
}
usedStudent.add(refKey);
const refElementType = refNode.data.elementType ?? 'class';
const studentElementType = studentNode.data.elementType ?? 'class';
const elementTypeMatches = refElementType === studentElementType;
const attrOutcome = diffAttributes(refNode.data.attributes, studentNode.data.attributes);
const methodOutcome = diffMethods(refNode.data.methods, studentNode.data.methods);
matchedClasses.push({
refName: refNode.data.name,
studentName: studentNode.data.name,
refElementType,
studentElementType,
elementTypeMatches,
attributes: attrOutcome,
methods: methodOutcome,
});
attrMatchedCount += attrOutcome.matched.length;
attrTotalCount += refNode.data.attributes.length;
attrAggregateScore += attrOutcome.score * Math.max(refNode.data.attributes.length, 1);
methodMatchedCount += methodOutcome.matched.length;
methodTotalCount += refNode.data.methods.length;
methodAggregateScore += methodOutcome.score * Math.max(refNode.data.methods.length, 1);
}
const extraClasses: string[] = [];
for (const [studentKey, studentNode] of studentByName) {
if (!usedStudent.has(studentKey)) {
extraClasses.push(studentNode.data.name);
}
}
const refClassTotal = reference.nodes.length;
const classCoverage = safeRatio(matchedClasses.length, refClassTotal);
// Element-type mismatches discount the matched class to 0.7
const matchedClassQuality =
matchedClasses.length === 0
? 1
: matchedClasses.reduce(
(acc, m) => acc + (m.elementTypeMatches ? 1 : 0.7),
0
) / matchedClasses.length;
const classScore = classCoverage * matchedClassQuality;
const refClassesById = buildClassesById(reference.nodes);
const studentClassesById = buildClassesById(student.nodes);
const refEdges: EdgeRef[] = reference.edges
.map((e) => refToEdgeRef(e, refClassesById))
.filter((e): e is EdgeRef => e !== null);
const studentEdges: EdgeRef[] = student.edges
.map((e) => refToEdgeRef(e, studentClassesById))
.filter((e): e is EdgeRef => e !== null);
// Match edges: prefer exact (source, target, relationship); fall back to (source, target)
const matchedEdges: EdgeMatch[] = [];
const missingEdges: EdgeRef[] = [];
const usedStudentEdges = new Set<number>();
for (const refEdge of refEdges) {
const refKey = `${normalizeName(refEdge.source)}->${normalizeName(refEdge.target)}`;
let foundIdx = -1;
let exactMatch = false;
for (let i = 0; i < studentEdges.length; i += 1) {
if (usedStudentEdges.has(i)) continue;
const se = studentEdges[i];
const seKey = `${normalizeName(se.source)}->${normalizeName(se.target)}`;
if (seKey === refKey) {
if (se.relationship === refEdge.relationship) {
foundIdx = i;
exactMatch = true;
break;
}
if (foundIdx === -1) foundIdx = i; // tentative wrong-type match
}
}
if (foundIdx >= 0) {
const studentEdge = studentEdges[foundIdx];
matchedEdges.push({
ref: refEdge,
student: studentEdge,
relationshipMatches: exactMatch || studentEdge.relationship === refEdge.relationship,
});
usedStudentEdges.add(foundIdx);
} else {
missingEdges.push(refEdge);
}
}
const extraEdges: EdgeRef[] = studentEdges.filter((_, idx) => !usedStudentEdges.has(idx));
const refEdgeTotal = refEdges.length;
const edgeCoverage = safeRatio(matchedEdges.length, refEdgeTotal);
const edgeQuality =
matchedEdges.length === 0
? 1
: matchedEdges.reduce(
(acc, m) => acc + (m.relationshipMatches ? 1 : 0.5),
0
) / matchedEdges.length;
const edgeScore = edgeCoverage * edgeQuality;
const attrScore = attrTotalCount === 0 ? 1 : attrAggregateScore / Math.max(attrTotalCount, 1);
const methodScore =
methodTotalCount === 0 ? 1 : methodAggregateScore / Math.max(methodTotalCount, 1);
const totalScore =
classScore * CLASS_WEIGHT +
edgeScore * EDGE_WEIGHT +
attrScore * ATTRIBUTE_WEIGHT +
methodScore * METHOD_WEIGHT;
const summary = formatSummary({
classMatched: matchedClasses.length,
classMissing: missingClasses.length,
classExtra: extraClasses.length,
edgeMatched: matchedEdges.length,
edgeMissing: missingEdges.length,
edgeExtra: extraEdges.length,
attrMatched: attrMatchedCount,
attrTotal: attrTotalCount,
methodMatched: methodMatchedCount,
methodTotal: methodTotalCount,
score: totalScore,
});
return {
score: Math.max(0, Math.min(1, totalScore)),
classes: {
matched: matchedClasses,
missing: missingClasses,
extra: extraClasses,
score: classScore,
},
edges: {
matched: matchedEdges,
missing: missingEdges,
extra: extraEdges,
score: edgeScore,
},
summary,
};
}
const formatSummary = (input: {
classMatched: number;
classMissing: number;
classExtra: number;
edgeMatched: number;
edgeMissing: number;
edgeExtra: number;
attrMatched: number;
attrTotal: number;
methodMatched: number;
methodTotal: number;
score: number;
}): string => {
const pct = (input.score * 100).toFixed(1);
return [
`Structural score: ${pct}%.`,
`Classes: ${input.classMatched} matched, ${input.classMissing} missing, ${input.classExtra} extra.`,
`Relationships: ${input.edgeMatched} matched, ${input.edgeMissing} missing, ${input.edgeExtra} extra.`,
`Attributes: ${input.attrMatched}/${input.attrTotal} matched.`,
`Methods: ${input.methodMatched}/${input.methodTotal} matched.`,
].join(' ');
};
// =============================================================================
// Sequence diagrams
// =============================================================================
export type LifelineMatch = {
refName: string;
studentName: string;
refKind: LifelineKind;
studentKind: LifelineKind;
kindMatches: boolean;
};
export type SequenceMessageRef = {
source: string;
target: string;
messageType: SequenceMessageType;
label?: string;
/** 0-indexed position in the original ordering. Used to score order preservation. */
order: number;
/** Kind of the fragment this message is rendered inside, if any. */
parentKind: SequenceFragmentKind | null;
};
export type SequenceMessageMatch = {
ref: SequenceMessageRef;
student: SequenceMessageRef;
typeMatches: boolean;
labelMatches: boolean;
/** True when both messages share fragment context (both top-level, or both inside same-kind fragment). */
fragmentContextMatches: boolean;
/** 0..1 — partial credit across (presence, type, label, fragment context). */
aspectScore: number;
/** Matched on (source, target, label); false when matched by endpoints only. */
exactMatch: boolean;
};
export type SequenceDiagramDiffResult = {
/** Aggregate structural score, 0..1 */
score: number;
lifelines: {
matched: LifelineMatch[];
missing: string[];
extra: string[];
score: number;
};
messages: {
matched: SequenceMessageMatch[];
missing: SequenceMessageRef[];
extra: SequenceMessageRef[];
score: number;
};
/** Ordering preservation among matched messages, 0..1 (1 = identical order). */
orderScore: number;
summary: string;
};
const LIFELINE_WEIGHT = 0.3;
const MESSAGE_WEIGHT = 0.5;
const ORDER_WEIGHT = 0.2;
const buildLifelineByName = (
lifelines: SequenceLifeline[]
): Map<string, SequenceLifeline> => {
const idx = new Map<string, SequenceLifeline>();
for (const lifeline of lifelines) idx.set(normalizeName(lifeline.data.name), lifeline);
return idx;
};
const buildLifelineById = (
lifelines: SequenceLifeline[]
): Map<string, SequenceLifeline> => {
const idx = new Map<string, SequenceLifeline>();
for (const lifeline of lifelines) idx.set(lifeline.id, lifeline);
return idx;
};
const messageToRef = (
msg: SequenceMessage,
byId: Map<string, SequenceLifeline>,
fragmentsById: Map<string, SequenceFragment>,
index: number
): SequenceMessageRef | null => {
const source = byId.get(msg.source);
const target = byId.get(msg.target);
if (!source || !target) return null;
const parentId = msg.data.parentFragmentId;
const parentKind = parentId ? fragmentsById.get(parentId)?.kind ?? null : null;
return {
source: source.data.name,
target: target.data.name,
messageType: msg.data.messageType,
label: msg.data.label,
order: index,
parentKind,
};
};
const fragmentContextMatches = (
refKind: SequenceFragmentKind | null,
studentKind: SequenceFragmentKind | null
): boolean => {
if (refKind === null && studentKind === null) return true;
if (refKind !== null && studentKind !== null && refKind === studentKind) return true;
return false;
};
const messagePrimaryKey = (m: SequenceMessageRef): string =>
`${normalizeName(m.source)}|${normalizeName(m.target)}|${normalizeName(m.label ?? '')}`;
const messageEndpointsKey = (m: SequenceMessageRef): string =>
`${normalizeName(m.source)}|${normalizeName(m.target)}`;
/**
* Order score: count inversions in the student ordering of matched messages
* relative to the reference. 0 inversions = perfect order, max = fully reversed.
*/
const computeOrderScore = (matches: SequenceMessageMatch[]): number => {
if (matches.length < 2) return 1;
const sortedByRef = [...matches].sort((a, b) => a.ref.order - b.ref.order);
const studentOrders = sortedByRef.map((m) => m.student.order);
let inversions = 0;
for (let i = 0; i < studentOrders.length; i += 1) {
for (let j = i + 1; j < studentOrders.length; j += 1) {
if (studentOrders[i] > studentOrders[j]) inversions += 1;
}
}
const maxInversions = (studentOrders.length * (studentOrders.length - 1)) / 2;
return 1 - inversions / maxInversions;
};
export function diffSequenceDiagrams(
student: SequenceDiagramState,
reference: SequenceDiagramState
): SequenceDiagramDiffResult {
// 1. Match lifelines by case-insensitive name; track kind agreement separately.
const refByName = buildLifelineByName(reference.lifelines);
const studentByName = buildLifelineByName(student.lifelines);
const matchedLifelines: LifelineMatch[] = [];
const missingLifelines: string[] = [];
const usedStudent = new Set<string>();
for (const [key, refLine] of refByName) {
const studentLine = studentByName.get(key);
if (studentLine) {
matchedLifelines.push({
refName: refLine.data.name,
studentName: studentLine.data.name,
refKind: refLine.data.kind,
studentKind: studentLine.data.kind,
kindMatches: refLine.data.kind === studentLine.data.kind,
});
usedStudent.add(key);
} else {
missingLifelines.push(refLine.data.name);
}
}
const extraLifelines: string[] = [];
for (const [key, line] of studentByName) {
if (!usedStudent.has(key)) extraLifelines.push(line.data.name);
}
const refLifelineTotal = reference.lifelines.length;
const lifelineCoverage = safeRatio(matchedLifelines.length, refLifelineTotal);
const lifelineQuality =
matchedLifelines.length === 0
? 1
: matchedLifelines.reduce((acc, m) => acc + (m.kindMatches ? 1 : 0.7), 0) /
matchedLifelines.length;
const lifelineScore = lifelineCoverage * lifelineQuality;
// 2. Match messages — two-pass: exact (source, target, label) then endpoints fallback.
// Endpoints-only matches still count as matched but score the label aspect as a miss.
const refById = buildLifelineById(reference.lifelines);
const studentById = buildLifelineById(student.lifelines);
const refFragsById = new Map((reference.fragments ?? []).map((f) => [f.id, f]));
const studentFragsById = new Map((student.fragments ?? []).map((f) => [f.id, f]));
const refMessages = reference.messages
.map((msg, idx) => messageToRef(msg, refById, refFragsById, idx))
.filter((m): m is SequenceMessageRef => m !== null);
const studentMessages = student.messages
.map((msg, idx) => messageToRef(msg, studentById, studentFragsById, idx))
.filter((m): m is SequenceMessageRef => m !== null);
const matchedMessages: SequenceMessageMatch[] = [];
const usedStudentMessages = new Set<number>();
const matchedRefIdx = new Set<number>();
for (let r = 0; r < refMessages.length; r += 1) {
const refMsg = refMessages[r];
const refKey = messagePrimaryKey(refMsg);
for (let i = 0; i < studentMessages.length; i += 1) {
if (usedStudentMessages.has(i)) continue;
if (messagePrimaryKey(studentMessages[i]) === refKey) {
const sMsg = studentMessages[i];
matchedMessages.push({
ref: refMsg,
student: sMsg,
typeMatches: refMsg.messageType === sMsg.messageType,
labelMatches: true,
fragmentContextMatches: fragmentContextMatches(refMsg.parentKind, sMsg.parentKind),
aspectScore: 0,
exactMatch: true,
});
usedStudentMessages.add(i);
matchedRefIdx.add(r);
break;
}
}
}
for (let r = 0; r < refMessages.length; r += 1) {
if (matchedRefIdx.has(r)) continue;
const refMsg = refMessages[r];
const refKey = messageEndpointsKey(refMsg);
for (let i = 0; i < studentMessages.length; i += 1) {
if (usedStudentMessages.has(i)) continue;
if (messageEndpointsKey(studentMessages[i]) === refKey) {
const sMsg = studentMessages[i];
matchedMessages.push({
ref: refMsg,
student: sMsg,
typeMatches: refMsg.messageType === sMsg.messageType,
labelMatches: normalizeName(refMsg.label ?? '') === normalizeName(sMsg.label ?? ''),
fragmentContextMatches: fragmentContextMatches(refMsg.parentKind, sMsg.parentKind),
aspectScore: 0,
exactMatch: false,
});
usedStudentMessages.add(i);
matchedRefIdx.add(r);
break;
}
}
}
// Four aspects: presence (always 1), type, label, fragment context.
for (const m of matchedMessages) {
m.aspectScore =
(1 + Number(m.typeMatches) + Number(m.labelMatches) + Number(m.fragmentContextMatches)) / 4;
}
const missingMessages: SequenceMessageRef[] = refMessages.filter(
(_, idx) => !matchedRefIdx.has(idx)
);
const extraMessages: SequenceMessageRef[] = studentMessages.filter(
(_, idx) => !usedStudentMessages.has(idx)
);
const refMessageTotal = refMessages.length;
const messageCoverage = safeRatio(matchedMessages.length, refMessageTotal);
const messageQuality =
matchedMessages.length === 0
? 1
: matchedMessages.reduce((acc, m) => acc + m.aspectScore, 0) / matchedMessages.length;
const messageScore = messageCoverage * messageQuality;
const orderScore = computeOrderScore(matchedMessages);
const totalScore =
lifelineScore * LIFELINE_WEIGHT + messageScore * MESSAGE_WEIGHT + orderScore * ORDER_WEIGHT;
const summary = formatSequenceSummary({
lifelinesMatched: matchedLifelines.length,
lifelinesMissing: missingLifelines.length,
lifelinesExtra: extraLifelines.length,
messagesMatched: matchedMessages.length,
messagesMissing: missingMessages.length,
messagesExtra: extraMessages.length,
orderScore,
score: totalScore,
});
return {
score: Math.max(0, Math.min(1, totalScore)),
lifelines: {
matched: matchedLifelines,
missing: missingLifelines,
extra: extraLifelines,
score: lifelineScore,
},
messages: {
matched: matchedMessages,
missing: missingMessages,
extra: extraMessages,
score: messageScore,
},
orderScore,
summary,
};
}
const formatSequenceSummary = (input: {
lifelinesMatched: number;
lifelinesMissing: number;
lifelinesExtra: number;
messagesMatched: number;
messagesMissing: number;
messagesExtra: number;
orderScore: number;
score: number;
}): string => {
const pct = (input.score * 100).toFixed(1);
return [
`Structural score: ${pct}%.`,
`Lifelines: ${input.lifelinesMatched} matched, ${input.lifelinesMissing} missing, ${input.lifelinesExtra} extra.`,
`Messages: ${input.messagesMatched} matched, ${input.messagesMissing} missing, ${input.messagesExtra} extra.`,
`Message order: ${(input.orderScore * 100).toFixed(0)}% preserved.`,
].join(' ');
};
/**
* Render a sequence-diagram diff as a compact textual block for the LLM prompt.
*/
export function formatSequenceDiffForPrompt(diff: SequenceDiagramDiffResult): string {
const lines: string[] = [];
lines.push(`Structural score (deterministic): ${(diff.score * 100).toFixed(1)}%`);
lines.push(`Message order preserved: ${(diff.orderScore * 100).toFixed(0)}%`);
lines.push('');
lines.push('LIFELINES:');
if (diff.lifelines.matched.length > 0) {
lines.push(` Matched (${diff.lifelines.matched.length}):`);
for (const m of diff.lifelines.matched) {
const tag = m.kindMatches
? `[${m.refKind}]`
: `[expected ${m.refKind}, got ${m.studentKind}]`;
lines.push(` - ${m.refName} ${tag}`);
}
}
if (diff.lifelines.missing.length > 0) {
lines.push(
` Missing (${diff.lifelines.missing.length}): ${diff.lifelines.missing.join(', ')}`
);
}
if (diff.lifelines.extra.length > 0) {
lines.push(` Extra (${diff.lifelines.extra.length}): ${diff.lifelines.extra.join(', ')}`);
}
lines.push('');
lines.push('MESSAGES:');
if (diff.messages.matched.length > 0) {
lines.push(` Matched (${diff.messages.matched.length}):`);
for (const m of diff.messages.matched) {
const typeTag = m.typeMatches
? `[${m.ref.messageType}]`
: `[expected ${m.ref.messageType}, got ${m.student.messageType}]`;
const labelTag = m.labelMatches
? ''
: ` [label diff: "${m.ref.label ?? ''}" vs "${m.student.label ?? ''}"]`;
const fragmentTag = m.fragmentContextMatches
? ''
: ` [fragment: expected ${m.ref.parentKind ?? 'top-level'}, got ${m.student.parentKind ?? 'top-level'}]`;
lines.push(` - ${m.ref.source} → ${m.ref.target} ${typeTag}${labelTag}${fragmentTag}`);
}
}
if (diff.messages.missing.length > 0) {
lines.push(` Missing (${diff.messages.missing.length}):`);
for (const m of diff.messages.missing) {
const lbl = m.label ? ` : ${m.label}` : '';
lines.push(` - ${m.source} → ${m.target} [${m.messageType}]${lbl}`);
}
}
if (diff.messages.extra.length > 0) {
lines.push(` Extra (${diff.messages.extra.length}):`);
for (const m of diff.messages.extra) {
const lbl = m.label ? ` : ${m.label}` : '';
lines.push(` - ${m.source} → ${m.target} [${m.messageType}]${lbl}`);
}
}
return lines.join('\n');
}
/**
* Render the diff result as a compact textual block to embed in an LLM prompt.
* Stable formatting keeps the prompt deterministic and explainable.
*/
export function formatDiffForPrompt(diff: ClassDiagramDiffResult): string {
const lines: string[] = [];
lines.push(`Structural score (deterministic): ${(diff.score * 100).toFixed(1)}%`);
lines.push('');
lines.push('CLASSES:');
if (diff.classes.matched.length > 0) {
lines.push(` Matched (${diff.classes.matched.length}):`);
for (const m of diff.classes.matched) {
const elem = m.elementTypeMatches
? `[${m.refElementType}]`
: `[expected ${m.refElementType}, got ${m.studentElementType}]`;
lines.push(` - ${m.refName} ${elem}`);
if (m.attributes.missing.length > 0) {
lines.push(` missing attrs: ${m.attributes.missing.join(', ')}`);
}
if (m.attributes.extra.length > 0) {
lines.push(` extra attrs: ${m.attributes.extra.join(', ')}`);
}
if (m.methods.missing.length > 0) {
lines.push(` missing methods: ${m.methods.missing.join(', ')}`);
}
if (m.methods.extra.length > 0) {
lines.push(` extra methods: ${m.methods.extra.join(', ')}`);
}
}
}
if (diff.classes.missing.length > 0) {
lines.push(` Missing (${diff.classes.missing.length}): ${diff.classes.missing.join(', ')}`);
}
if (diff.classes.extra.length > 0) {
lines.push(` Extra (${diff.classes.extra.length}): ${diff.classes.extra.join(', ')}`);
}
lines.push('');
lines.push('RELATIONSHIPS:');
if (diff.edges.matched.length > 0) {
lines.push(` Matched (${diff.edges.matched.length}):`);
for (const m of diff.edges.matched) {
const tag = m.relationshipMatches
? `[${m.ref.relationship}]`
: `[expected ${m.ref.relationship}, got ${m.student.relationship}]`;
lines.push(` - ${m.ref.source} → ${m.ref.target} ${tag}`);
}
}
if (diff.edges.missing.length > 0) {
lines.push(` Missing (${diff.edges.missing.length}):`);
for (const e of diff.edges.missing) {
lines.push(` - ${e.source} → ${e.target} [${e.relationship}]`);
}
}
if (diff.edges.extra.length > 0) {
lines.push(` Extra (${diff.edges.extra.length}):`);
for (const e of diff.edges.extra) {
lines.push(` - ${e.source} → ${e.target} [${e.relationship}]`);
}
}
return lines.join('\n');
}