-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlabels.service.ts
More file actions
2926 lines (2629 loc) · 88.8 KB
/
Copy pathlabels.service.ts
File metadata and controls
2926 lines (2629 loc) · 88.8 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
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Labels Service
*
* Handles label management operations including listing labels for a project,
* getting detailed label information with lines and characters, and
* authorization checks for label access.
*
* Also includes label file sync operations (consolidated from label-sync.service.ts
* and gitlab-file-sync.service.ts).
*/
import { getDb } from "../db/index.js";
import {
labels,
labelLines,
characters,
projects,
projectUsers,
routeConfigs,
projectFiles,
projectFileSyncState,
stats,
variables,
} from "../db/schema/index.js";
import { eq, and, asc, or, isNull, sql, desc, inArray, ne } from "drizzle-orm";
import type { Label, LabelLine } from "../db/schema/index.js";
import type { Transaction } from "../db/types.js";
import type { PublicLabel } from "@branchforge/shared";
import {
LabelStatus,
sanitizeLabelName,
RENPY_LABEL_REGEX,
type ComparisonOperator,
type StatCondition,
type VariableCondition,
} from "@branchforge/shared";
import type { IncomingJump } from "@branchforge/shared";
import { createAuditFields, updateAuditFields } from "../lib/audit.js";
import {
NotFoundError,
ForbiddenError,
ValidationError,
ConflictError,
} from "../middleware/error-handler.middleware.js";
import { logError, logWarn, LogEventType } from "../lib/logger.js";
import { requireProjectOwnership } from "../services/authz.service.js";
import {
addLabelToRPYContent,
removeLabelFromRPYContent,
parseRPYFileWithLabels,
convertToBranchForgeFormatFromLabels,
reconstructRPYFile,
type ParsedRPYFileWithLabels,
} from "./rpy-parser.service.js";
import { calculateContentHash, calculateLinesHash } from "../lib/hash.js";
import { mapEntryToDbType, type ContentType } from "./label-line-mapper.js";
import { resolveLabelNames } from "./label-name-resolver.service.js";
// Re-export PublicLabel from shared for route handlers
export type { PublicLabel };
// ============================================================================
// Types
// ============================================================================
/**
* Generic type for database query operations shared by both db connections
* and transactions. This allows the same function to work with either context.
*
* Only includes the query methods actually used by reconstructFileForLabel.
*/
type QueryContext =
| Pick<ReturnType<typeof getDb>, "select">
| Pick<Transaction, "select">;
// ============================================================================
// Constants
// ============================================================================
// Maximum attempts to find a unique label name before falling back to timestamp/UUID
const MAX_LABEL_ATTEMPTS = 1000;
// ============================================================================
// Sync Types
// ============================================================================
export interface SyncLabelsResult {
success: boolean;
labelsCreated: number;
labelsUpdated: number;
labelsDeleted: number;
linesProcessed: number;
errors: Array<{ label: string; error: string }>;
skipped: boolean; // True if sync was skipped due to idempotency
affectedLabelIds: string[]; // IDs of labels created, updated, or deleted
}
export interface SyncLabelsOptions {
skipCleanup?: boolean;
}
// ============================================================================
// Sync Validation Functions
// ============================================================================
/**
* Validate RPY content before sync
* @throws ValidationError if validation fails
*/
export function validateRPYContent(
content: string,
parsed: ParsedRPYFileWithLabels
): void {
if (!content || content.trim().length === 0) {
throw new ValidationError("RPY content is empty");
}
if (parsed.labels.length === 0) {
throw new ValidationError("No labels found in RPY content");
}
// Check for duplicate labels (case-insensitive)
const labelSet = new Set<string>();
const duplicateLabels: string[] = [];
for (const label of parsed.labels) {
const lowerLabel = label.label.toLowerCase();
if (labelSet.has(lowerLabel)) {
duplicateLabels.push(label.label);
}
labelSet.add(lowerLabel);
}
if (duplicateLabels.length > 0) {
throw new ValidationError(
`Duplicate labels found: ${duplicateLabels.join(", ")}`
);
}
}
/**
* Validate that file type is STORY (only STORY files should sync to labels)
* @throws ValidationError if validation fails
*/
export function validateFileType(fileType: string): void {
if (fileType !== "STORY") {
throw new ValidationError(
`Invalid file type for label sync: ${fileType}. Only STORY files can sync to labels.`
);
}
}
// ============================================================================
// Sync State Management (GitLab-specific)
// ============================================================================
/**
* Check if there's an in-progress sync for this file
* Uses completedAt = null with status 'modified_local' to indicate in-progress
*/
async function checkInProgressSync(projectFileId: string): Promise<boolean> {
const db = getDb();
const [inProgress] = await db
.select()
.from(projectFileSyncState)
.where(
and(
eq(projectFileSyncState.projectFileId, projectFileId),
eq(projectFileSyncState.status, "MODIFIED_LOCAL"),
isNull(projectFileSyncState.completedAt)
)
)
.limit(1);
return !!inProgress;
}
/**
* Check if content has already been synced (idempotency check)
*/
async function checkContentAlreadySynced(
projectFileId: string,
contentHash: string
): Promise<boolean> {
const db = getDb();
const [lastSynced] = await db
.select()
.from(projectFileSyncState)
.where(
and(
eq(projectFileSyncState.projectFileId, projectFileId),
eq(projectFileSyncState.status, "SYNCED"),
eq(projectFileSyncState.contentHash, contentHash)
)
)
.orderBy(desc(projectFileSyncState.completedAt))
.limit(1);
return !!lastSynced;
}
/**
* Create a new sync state record
*/
async function createSyncState(
projectFileId: string,
contentHash: string,
labelCount: number
): Promise<string> {
const db = getDb();
const [syncState] = await db
.insert(projectFileSyncState)
.values({
projectFileId,
contentHash,
status: "MODIFIED_LOCAL",
rpyLabelCount: labelCount,
dbLabelCount: 0,
})
.returning();
return syncState.id;
}
/**
* Update sync state on completion
*/
async function completeSyncState(
syncStateId: string,
success: boolean,
dbLabelCount?: number,
errorMessage?: string
): Promise<void> {
const db = getDb();
await db
.update(projectFileSyncState)
.set({
status: success ? "SYNCED" : "CONFLICT",
completedAt: new Date(),
dbLabelCount,
errorMessage,
})
.where(eq(projectFileSyncState.id, syncStateId));
}
// ============================================================================
// Derived Character Query
// ============================================================================
/**
* Get characters that appear in a label (derived from dialogue speakers)
*
* This function automatically derives character appearances from label_lines.speakerId,
* ensuring the data is always in sync with actual dialogue content.
*
* @param labelId - The label ID
* @returns Array of characters who speak in this label
*/
async function getDerivedCharactersForLabel(
labelId: string
): Promise<LabelCharacterWithInfo[]> {
const db = getDb();
// Query to get all characters who speak in this label
// Use selectDistinct to ensure unique rows at the database level
const result = await db
.selectDistinct({
id: characters.id,
name: characters.name,
displayName: characters.displayName,
renpyTag: characters.renpyTag,
})
.from(characters)
.innerJoin(labelLines, eq(labelLines.speakerId, characters.id))
.where(and(eq(labelLines.labelId, labelId), isNull(labelLines.deletedAt)));
// Result is already unique and correctly typed
return result as LabelCharacterWithInfo[];
}
// ============================================================================
// Helper Functions
// ============================================================================
/**
* Extract the basename from a file path
* @param filePath - Full file path (e.g., "labels/act_i.rpy" or "labels/chapter1/scene_01.rpy")
* @returns Basename of the file (e.g., "act_i.rpy" or "scene_01.rpy") or null if filePath is null
*/
function extractFileName(filePath: string): string {
const parts = filePath.split("/");
return parts[parts.length - 1] || filePath;
}
/**
* Resync label positions for all labels in a file
* Ensures positions are sequential starting from 0
*
* @param tx - Database transaction or connection
* @param projectFileId - The project file ID
*/
async function resyncLabelPositions(
tx: Transaction,
projectFileId: string
): Promise<void> {
const fileLabels = await tx
.select()
.from(labels)
.where(
and(eq(labels.projectFileId, projectFileId), isNull(labels.deletedAt))
)
.orderBy(asc(labels.labelPosition));
// Sort labels: those with same position maintain their relative order
// but when multiple labels have position 0 (newly inserted at beginning),
// the newest one (most recent createdAt) should come first
fileLabels.sort((a: Label, b: Label) => {
if (a.labelPosition !== b.labelPosition) {
return (a.labelPosition ?? 0) - (b.labelPosition ?? 0);
}
// Same position: newer labels come first
return new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime();
});
// Batch update all label positions in a single query using parameterized VALUES
// This avoids N round-trips to the database and prevents SQL injection
if (fileLabels.length > 0) {
// Create a parameterized VALUES list with explicit type casting
const valuesList = sql.join(
fileLabels.map(
(label: Label, i: number) => sql`(${label.id}::uuid, ${i}::integer)`
),
sql`, `
);
await tx.execute(
sql`UPDATE labels
SET "label_position" = new_positions.position
FROM (VALUES ${valuesList}) AS new_positions(id, position)
WHERE labels.id = new_positions.id`
);
}
}
// ============================================================================
// Sync Transaction Helpers
// ============================================================================
interface CharacterLookupMaps {
byTag: Map<string, string | null>;
byTagLower: Map<string, string | null>;
byDisplayName: Map<string, string | null>;
byDisplayNameLower: Map<string, string | null>;
}
function registerLookup(
map: Map<string, string | null>,
key: string,
value: string
): void {
if (!map.has(key)) {
map.set(key, value);
return;
}
const existing = map.get(key);
if (existing !== value) {
// Ambiguous key - force unresolved to avoid accidental mis-linking.
map.set(key, null);
}
}
/**
* Resolve parsed speaker text to character ID.
*
* Match order:
* 1) renpyTag exact
* 2) renpyTag case-insensitive
* 3) displayName exact (compatibility with legacy reconstructed content)
* 4) displayName case-insensitive
*/
function resolveSpeakerId(
speakerTag: string | undefined,
lookupMaps: CharacterLookupMaps
): string | null {
if (!speakerTag) {
return null;
}
const normalized = speakerTag.trim();
if (!normalized) {
return null;
}
const tagExact = lookupMaps.byTag.get(normalized);
if (tagExact !== undefined) {
return tagExact;
}
const tagLower = lookupMaps.byTagLower.get(normalized.toLowerCase());
if (tagLower !== undefined) {
return tagLower;
}
const nameExact = lookupMaps.byDisplayName.get(normalized);
if (nameExact !== undefined) {
return nameExact;
}
const nameLower = lookupMaps.byDisplayNameLower.get(normalized.toLowerCase());
if (nameLower !== undefined) {
return nameLower;
}
return null;
}
/**
* Build label line values for batch insert.
* Maps parsed entries to database records with hashes and metadata.
*/
function buildLineValues(
labelId: string,
entries: Array<{
type: ContentType;
speaker?: string;
target?: string;
text?: string;
lineNumber?: number;
indentLevel?: number;
menuOptions?: Array<{
label: string;
targetLabelId: string;
targetLabelName: string;
conditionFlags?: string[];
effects?: {
stats?: Record<string, number>;
};
}>;
}>,
sourceId: string,
lookupMaps: CharacterLookupMaps
): Array<{
labelId: string;
sequence: number;
contentType: "NARRATION" | "DIALOGUE" | "JUMP" | "MENU";
content: string;
speakerId: string | null;
visualType: "GENERATED";
projectFileId: string;
linePosition: number;
contentHash: string;
lastSyncedHash: string;
lastSyncedAt: Date;
rpyLineNumber: number | null;
rpyIndentLevel: number;
menuOptions?: Array<{
label: string;
targetLabelId: string;
targetLabelName: string;
conditionFlags?: string[];
effects?: {
stats?: Record<string, number>;
};
}> | null;
}> {
return entries.map((entry, index) => {
// Handle MENU entries with menuOptions
if (entry.type === "MENU") {
const contentHash = calculateContentHash(
JSON.stringify(entry.menuOptions ?? [])
);
return {
labelId,
sequence: index + 1,
contentType: "MENU" as const,
content: "",
speakerId: null,
visualType: "GENERATED" as const,
projectFileId: sourceId,
linePosition: index,
contentHash,
lastSyncedHash: contentHash,
lastSyncedAt: new Date(),
rpyLineNumber: entry.lineNumber ?? null,
rpyIndentLevel: entry.indentLevel ?? 0,
menuOptions: entry.menuOptions ?? null,
};
}
// Existing logic for non-MENU entries
const contentType = mapEntryToDbType(entry);
const content = entry.target ? `jump ${entry.target}` : entry.text || "";
const lineHash = calculateContentHash(content);
const speakerId =
contentType === "DIALOGUE"
? resolveSpeakerId(entry.speaker, lookupMaps)
: null;
return {
labelId,
sequence: index + 1,
contentType,
content,
speakerId,
visualType: "GENERATED" as const,
projectFileId: sourceId,
linePosition: index,
contentHash: lineHash,
lastSyncedHash: lineHash,
lastSyncedAt: new Date(),
rpyLineNumber: entry.lineNumber ?? null,
rpyIndentLevel: entry.indentLevel ?? 0,
};
});
}
// ============================================================================
// Multi-Signal Rename Detection
// ============================================================================
/**
* Minimum line-similarity threshold (Jaccard index) for a rename candidate.
* Below this, we don't consider the match valid even if the composite
* score is high (position alone should not trigger a rename).
*/
const RENAME_MIN_LINE_SIMILARITY = 0.25;
/**
* Compute a rename-likelihood score between an existing label and a parsed label.
*
* Uses two signals:
* - **Line Jaccard similarity** (80%): fraction of individual line hashes that
* overlap between the existing label's lines and the new parsed entries.
* This is robust to partial edits (changing some lines while keeping others).
* - **Position proximity** (20%): how close the two labels are in file order.
* Closer positions score higher; decays with distance.
*
* @param existingLineHashes - Set of contentHash values from the existing label's lines
* @param parsedEntryHashes - Set of hashes computed from the parsed label's entries
* @param existingPosition - labelPosition of the existing label in the file
* @param parsedPosition - index of the parsed label in the new file
* @returns Score between 0 and 1 (higher = more likely a rename)
*/
function computeRenameScore(
existingLineHashes: Set<string>,
parsedEntryHashes: Set<string>,
existingPosition: number,
parsedPosition: number
): { score: number; lineSimilarity: number } {
// Edge case: both empty → cannot distinguish, low score
if (existingLineHashes.size === 0 && parsedEntryHashes.size === 0) {
return { score: 0.1, lineSimilarity: 0 };
}
// Line Jaccard similarity: |intersection| / |union|
let intersection = 0;
for (const h of existingLineHashes) {
if (parsedEntryHashes.has(h)) intersection++;
}
const union = existingLineHashes.size + parsedEntryHashes.size - intersection;
const lineSimilarity = union === 0 ? 0 : intersection / union;
// Position proximity: 1.0 when adjacent, decays with distance
const posDistance = Math.abs(existingPosition - parsedPosition);
const posScore = 1 / (1 + posDistance);
// Weighted composite: content is the primary signal
return { score: lineSimilarity * 0.8 + posScore * 0.2, lineSimilarity };
}
/**
* Internal helper: Execute the label sync operations within a transaction.
* This function is called either within a new transaction or with an external one.
*
* @param tx - The transaction context (same API as Db, passed from db.transaction())
* @param projectId - The project ID
* @param parsed - The parsed RPY file
* @param rpyContent - The raw RPY content
* @param sourceId - The source file ID
* @param skipCleanup - Whether to skip orphan cleanup
* @returns Sync statistics
*/
async function syncLabelsInTransaction(
tx: Transaction,
projectId: string,
parsed: ParsedRPYFileWithLabels,
rpyContent: string,
sourceId: string,
skipCleanup: boolean
): Promise<{
labelsCreated: number;
labelsUpdated: number;
labelsDeleted: number;
linesProcessed: number;
errors: Array<{ label: string; error: string }>;
affectedLabelIds: string[];
}> {
// Fetch existing labels for this source file (including soft-deleted)
// We need soft-deleted labels to check for name conflicts when creating new labels
const existingLabels = await tx
.select()
.from(labels)
.where(eq(labels.projectFileId, sourceId));
// Build character lookup maps once for robust speaker linking during sync
const projectCharacters = await tx
.select({
id: characters.id,
renpyTag: characters.renpyTag,
displayName: characters.displayName,
})
.from(characters)
.where(eq(characters.projectId, projectId));
const lookupMaps: CharacterLookupMaps = {
byTag: new Map<string, string | null>(),
byTagLower: new Map<string, string | null>(),
byDisplayName: new Map<string, string | null>(),
byDisplayNameLower: new Map<string, string | null>(),
};
for (const char of projectCharacters) {
registerLookup(lookupMaps.byTag, char.renpyTag, char.id);
if (char.renpyTag) {
registerLookup(
lookupMaps.byTagLower,
char.renpyTag.toLowerCase(),
char.id
);
}
registerLookup(lookupMaps.byDisplayName, char.displayName, char.id);
if (char.displayName) {
registerLookup(
lookupMaps.byDisplayNameLower,
char.displayName.toLowerCase(),
char.id
);
}
}
const existingLabelsByName = new Map<string, (typeof existingLabels)[0]>();
for (const labelRow of existingLabels) {
if (labelRow.labelName) {
existingLabelsByName.set(labelRow.labelName, labelRow);
}
}
// Track results
let labelsCreated = 0;
let labelsUpdated = 0;
let linesProcessed = 0;
const errors: Array<{ label: string; error: string }> = [];
const affectedLabelIds: string[] = [];
// Build set of parsed label names (for rename detection)
const parsedLabelNames = new Set(parsed.labels.map((l) => l.label));
// Track which existing labels have been matched (by name or rename)
// to avoid double-matching an existing label when detecting renames
const matchedExistingIds = new Set<string>();
// Lazy-loaded map of label ID → Set of per-line content hashes.
// Populated on first use to avoid querying when all renames are detected
// by exact content hash match.
let lineHashesByLabelId: Map<string, Set<string>> | null = null;
async function getLineHashesForLabel(labelId: string): Promise<Set<string>> {
if (!lineHashesByLabelId) {
// Batch-fetch all line hashes for active labels in this file
const allLines = await tx
.select({
labelId: labelLines.labelId,
contentHash: labelLines.contentHash,
})
.from(labelLines)
.where(
and(
eq(labelLines.projectFileId, sourceId),
isNull(labelLines.deletedAt)
)
);
lineHashesByLabelId = new Map<string, Set<string>>();
for (const line of allLines) {
let hashSet = lineHashesByLabelId.get(line.labelId);
if (!hashSet) {
hashSet = new Set<string>();
lineHashesByLabelId.set(line.labelId, hashSet);
}
if (line.contentHash) {
hashSet.add(line.contentHash);
}
}
}
return lineHashesByLabelId.get(labelId) ?? new Set<string>();
}
// Process each label
for (let i = 0; i < parsed.labels.length; i++) {
const label = parsed.labels[i];
const labelData = convertToBranchForgeFormatFromLabels(
parsed,
label.label,
rpyContent
);
try {
const existingLabel = existingLabelsByName.get(label.label);
if (existingLabel) {
// If existing label is soft-deleted, create a new one instead of reviving
// This preserves the historical soft-deleted row for audit purposes
if (existingLabel.deletedAt !== null) {
// Create new scene
const labelLinesHash = calculateLinesHash(labelData.entries);
const [newScene] = await tx
.insert(labels)
.values({
projectId,
title: label.label,
projectFileId: sourceId,
labelName: label.label,
labelPosition: i,
sequenceOrder: i,
route: null,
labelNumber: i + 1,
status: "DRAFT",
conditions: {},
effects: {},
contentHash: labelLinesHash,
lastSyncedHash: labelLinesHash,
syncStatus: "SYNCED",
})
.returning();
affectedLabelIds.push(newScene.id);
// Insert lines in batch
if (labelData.entries.length > 0) {
const lineValues = buildLineValues(
newScene.id,
labelData.entries,
sourceId,
lookupMaps
);
await tx.insert(labelLines).values(lineValues);
linesProcessed += lineValues.length;
}
labelsCreated++;
continue;
}
// Update existing active label - Delete old lines
await tx
.delete(labelLines)
.where(eq(labelLines.labelId, existingLabel.id));
// Calculate label lines hash
const labelLinesHash = calculateLinesHash(labelData.entries);
// Insert new lines in batch
if (labelData.entries.length > 0) {
const lineValues = buildLineValues(
existingLabel.id,
labelData.entries,
sourceId,
lookupMaps
);
await tx.insert(labelLines).values(lineValues);
linesProcessed += lineValues.length;
}
// Update label sync metadata (clear deletedAt to revive if soft-deleted)
await tx
.update(labels)
.set({
contentHash: labelLinesHash,
lastSyncedHash: labelLinesHash,
syncStatus: "SYNCED",
updatedAt: new Date(),
deletedAt: null,
})
.where(eq(labels.id, existingLabel.id));
affectedLabelIds.push(existingLabel.id);
labelsUpdated++;
matchedExistingIds.add(existingLabel.id);
} else {
// No match by name — try to detect a rename.
// Pass 1: exact content-hash match (handles pure renames).
// Pass 2: multi-signal scoring (handles rename + partial edit).
const currentLabelLinesHash = calculateLinesHash(labelData.entries);
const unmatchedExisting = existingLabels.filter(
(s) =>
s.labelName &&
!matchedExistingIds.has(s.id) &&
!s.deletedAt &&
!parsedLabelNames.has(s.labelName)
);
// Pass 1: exact hash match
const exactHashCandidates = unmatchedExisting.filter(
(s) =>
s.contentHash === currentLabelLinesHash ||
s.lastSyncedHash === currentLabelLinesHash
);
// Sort by position proximity, then stable tiebreakers:
// 1) prefer lastSyncedHash match (more recent sync state)
// 2) prefer exact position match
// 3) fallback to createdAt for deterministic ordering
exactHashCandidates.sort((a, b) => {
const posDiff =
Math.abs((a.labelPosition ?? 0) - i) -
Math.abs((b.labelPosition ?? 0) - i);
if (posDiff !== 0) return posDiff;
// Prefer lastSyncedHash match over contentHash-only match
const aSynced = a.lastSyncedHash === currentLabelLinesHash ? 0 : 1;
const bSynced = b.lastSyncedHash === currentLabelLinesHash ? 0 : 1;
if (aSynced !== bSynced) return aSynced - bSynced;
// Prefer exact position match
const aExact = a.labelPosition === i ? 0 : 1;
const bExact = b.labelPosition === i ? 0 : 1;
if (aExact !== bExact) return aExact - bExact;
// Stable fallback by createdAt
return (
new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime()
);
});
let renameCandidate: (typeof existingLabels)[0] | null =
exactHashCandidates[0] || null;
// Pass 2: if no exact match, try multi-signal scoring
if (!renameCandidate && unmatchedExisting.length > 0) {
const parsedHashes = new Set<string>(
labelData.entries.map((entry) => {
if (entry.type === "MENU" && entry.menuOptions) {
return calculateContentHash(JSON.stringify(entry.menuOptions));
}
const content = entry.target
? `jump ${entry.target}`
: entry.text || "";
return calculateContentHash(content);
})
);
const scored: Array<{
labelId: string;
lineSimilarity: number;
score: number;
}> = [];
for (const existing of unmatchedExisting) {
const existingHashes = await getLineHashesForLabel(existing.id);
const { score, lineSimilarity } = computeRenameScore(
existingHashes,
parsedHashes,
existing.labelPosition ?? 0,
i
);
if (lineSimilarity >= RENAME_MIN_LINE_SIMILARITY) {
scored.push({ labelId: existing.id, lineSimilarity, score });
}
}
// Pick best-scoring candidate (only if there's a clear winner)
if (scored.length > 0) {
scored.sort((a, b) => b.score - a.score);
const best = scored[0];
const secondBest = scored[1];
const hasClearWinner =
!secondBest || best.score - secondBest.score > 0.1;
if (hasClearWinner) {
renameCandidate =
unmatchedExisting.find((s) => s.id === best.labelId) ?? null;
}
}
}
if (renameCandidate) {
matchedExistingIds.add(renameCandidate.id);
// Delete old lines
await tx
.delete(labelLines)
.where(eq(labelLines.labelId, renameCandidate.id));
const labelLinesHash = calculateLinesHash(labelData.entries);
// Insert new lines
if (labelData.entries.length > 0) {
const lineValues = buildLineValues(
renameCandidate.id,
labelData.entries,
sourceId,
lookupMaps
);
await tx.insert(labelLines).values(lineValues);
linesProcessed += lineValues.length;
}
// Rename existing label: update labelName, preserve custom title
// if the user has given it a different display name than the original
// label name. If the title still matches the old labelName it was
// auto-generated and should be updated to match the new name.
const preservedTitle =
renameCandidate.title === renameCandidate.labelName
? label.label
: renameCandidate.title;
await tx
.update(labels)
.set({
labelName: label.label,
labelPosition: i,
sequenceOrder: i,
title: preservedTitle,
contentHash: labelLinesHash,
lastSyncedHash: labelLinesHash,
syncStatus: "SYNCED",
updatedAt: new Date(),
deletedAt: null,
})
.where(eq(labels.id, renameCandidate.id));
affectedLabelIds.push(renameCandidate.id);
labelsUpdated++;
} else {
// Create new scene
const labelLinesHash = calculateLinesHash(labelData.entries);
const [newScene] = await tx
.insert(labels)
.values({
projectId,
title: label.label,
projectFileId: sourceId,
labelName: label.label,
labelPosition: i,
sequenceOrder: i,
route: null, // User will assign route later
labelNumber: i + 1,
status: "DRAFT",
conditions: {},
effects: {},
// Sync fields
contentHash: labelLinesHash,
lastSyncedHash: labelLinesHash,
syncStatus: "SYNCED",
})
.returning();
affectedLabelIds.push(newScene.id);
// Insert lines in batch
if (labelData.entries.length > 0) {
const lineValues = buildLineValues(
newScene.id,
labelData.entries,
sourceId,
lookupMaps
);
await tx.insert(labelLines).values(lineValues);
linesProcessed += lineValues.length;
}
labelsCreated++;
}
}
} catch (error) {
errors.push({
label: label.label,
error: error instanceof Error ? error.message : "Unknown error",
});
}
}
// Orphan cleanup (labels that no longer exist in RPY content)
let labelsDeleted = 0;
if (!skipCleanup) {
const currentLabelNames = new Set(parsed.labels.map((l) => l.label));
// Find orphaned labels (excluding already soft-deleted and labels
// that were handled during the main loop — matched by name or renamed)
const orphanedLabels = existingLabels.filter(