All files / sync imap-sync.ts

85.06% Statements 393/462
71.91% Branches 192/267
85.96% Functions 49/57
90.12% Lines 365/405

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536                                                                                                                                                                        28x 28x 28x     28x     28x                               92x                 92x 92x           92x 92x 92x 92x       92x     92x 92x                     1x 1x               1x               43x 43x                 67x         81x 81x 81x 81x             81x 81x     81x             81x 81x 81x         21x 21x 21x 21x 21x   21x           51x 51x                         17x 17x 17x 17x             17x       17x 16x                                             45x   45x   43x     43x           43x 43x   45x 45x               45x     42x 42x     42x             42x   45x 45x   45x 59x   58x                 59x 58x 58x 58x 58x       58x 35x     58x                   42x                 45x 45x       45x   45x 1x     42x   43x 43x                 52x 49x   49x                   49x 49x   87x   87x 133x   86x 86x               86x       49x     49x   49x               49x       49x 49x   49x 87x 1x 1x       49x                                       58x                   58x           58x                         58x     58x 60x   1x             1x     57x 57x 57x                       57x               57x                         57x 41x           41x 41x   41x 41x   41x 35x                           57x 57x                 57x   57x 35x   35x     35x     35x 35x 35x                             35x 35x                                 35x 35x             35x 35x       35x 1x 1x         35x 3x 3x 3x                               35x 57x 57x 57x 57x     57x 57x                     57x 57x                     57x 4x 4x             4x 4x 3x 3x   4x 1x 1x                           57x                                           35x   35x       35x   35x               35x         35x 35x   35x 35x                         68x   68x 68x 68x                       68x   68x 68x                   68x 68x 68x 68x 68x           68x                                                       68x 1x 1x 1x 1x 1x 1x               1x       68x           68x 7x         68x                                       35x 35x                     35x                                 57x       57x   76x 38x 38x 76x     38x       38x       38x   38x     38x 38x 38x 38x   38x 38x               76x 76x 76x 76x 2x 2x                                       38x 38x 76x   38x                     38x               65x       65x           65x 65x 88x       65x               99x                                                 50x                                   50x                           50x     50x       50x   50x 50x 81x     50x     50x 42x     50x                 42x     42x   42x                           42x     42x   42x                                 42x                   42x                             3x       3x   2x       2x   2x 2x   2x 2x 4x     5x   2x                             6x   5x       5x           6x   6x 5x   5x 5x 5x   5x 5x 5x 11x     5x     5x   5x       5x                                 7x           7x       7x     6x   6x 9x   8x 8x 8x           8x 8x 8x   8x 8x 5x     5x 5x             8x 8x   8x 8x             5x       5x                   5x               5x 5x 8x 8x   8x             8x 8x 4x       4x                         4x 3x   3x   3x 3x           5x   5x 3x     5x                 86x     6x 6x 6x 5x 5x 4x 4x 1x 3x                     341x 282x         68x 68x 68x 425x       68x                             119x   119x         119x   119x 37x                   119x         119x 37x                         267x 285x 285x   27x 27x 18x       27x                   10x 10x 10x 7x   3x    
import type Database from "better-sqlite3-multiple-ciphers";
import { ImapFlow } from "imapflow";
import { type ParsedMail, simpleParser } from "mailparser";
import { upsertAttachmentBlob } from "../storage/attachment-storage.js";
import { compressText } from "../storage/compression.js";
import { htmlToText } from "../storage/html-to-text.js";
 
export interface ImapConfig {
	host: string;
	port: number;
	secure: boolean;
	auth: {
		user: string;
		pass: string;
	};
}
 
/** Classification of sync errors for retriability assessment */
export type SyncErrorType = "connection" | "folder" | "message" | "flags";
 
export interface SyncError {
	folderPath: string | null;
	uid: number | null;
	errorType: SyncErrorType;
	message: string;
	/** Whether this error is likely to succeed on retry */
	retriable: boolean;
}
 
export interface SyncResult {
	folder: string;
	newMessages: number;
	updatedFlags: number;
	deletedFolders: number;
	attachmentsSaved: number;
	/** Number of messages deleted from the IMAP server after syncing (connector mode) */
	deletedFromServer: number;
	errors: SyncError[];
}
 
export interface SyncAllResult {
	folders: SyncResult[];
	totalNew: number;
	totalErrors: number;
	/** True when the sync was cancelled via abort signal (e.g. shutdown) */
	aborted: boolean;
}
 
export interface RelabelResult {
	/** Number of IMAP folders whose UIDs were compared against local records */
	foldersScanned: number;
	/** Number of messages whose folder labels were updated */
	labelsUpdated: number;
	/** Number of cross-folder moves detected via Message-ID correlation */
	crossFolderMovesDetected: number;
}
 
export interface SyncProgress {
	/** Current phase of the sync operation */
	phase: "listing-folders" | "syncing-folder" | "applying-labels";
	/** Folder currently being synced (only set during syncing-folder phase) */
	currentFolder?: string;
	/** Number of folders fully synced so far */
	foldersCompleted: number;
	/** Total number of folders to sync (0 until folder list is fetched) */
	totalFolders: number;
	/** Total new messages synced so far */
	messagesNew: number;
	/** Total errors encountered so far */
	errors: number;
}
 
/** Special-use folder mapping from IMAP attributes */
export type SpecialUse =
	| "\\Inbox"
	| "\\Sent"
	| "\\Drafts"
	| "\\Trash"
	| "\\Junk"
	| "\\Archive"
	| "\\All"
	| "\\Flagged"
	| null;
 
const MAX_RETRIES = 3;
const RETRY_DELAY_MS = 1000;
const FETCH_BATCH_SIZE = 50;
/** Max UIDs per IMAP messageDelete call. Prevents overly-long UID-set strings on large initial syncs.
 *  Also used as the fetch batch size for interleaved fetch+delete in connector mode. */
const DELETE_BATCH_SIZE = 100;
/** Apply folder labels to messages after every this-many new messages within a folder.
 *  Keeps the UI responsive during large-folder syncs (e.g. Archive with 50k messages). */
const DEFAULT_SUB_BATCH_LABEL_SIZE = 500;
 
/**
 * Syncs messages from an IMAP server to local SQLite storage.
 *
 * Uses IMAP UIDs and UIDVALIDITY for efficient incremental sync.
 * Supports proper MIME parsing, attachment extraction, folder lifecycle,
 * flag sync, and error recovery with retry logic.
 */
export class ImapSync {
	private client: ImapFlow;
	private db: Database.Database;
	private inboundConnectorId: number;
	private config: ImapConfig;
	private subBatchLabelSize: number;
 
	private insertSyncError: Database.Statement | null = null;
	private activeOnError?: (error: SyncError) => void;
 
	constructor(
		config: ImapConfig,
		db: Database.Database,
		inboundConnectorId: number,
		subBatchLabelSize = DEFAULT_SUB_BATCH_LABEL_SIZE,
	) {
		this.config = config;
		this.client = new ImapFlow({
			...config,
			logger: false,
		});
		// Attach error handler immediately to prevent unhandled 'error' events
		// between construction and first connect() call.
		this.client.on("error", () => {});
		this.db = db;
		this.inboundConnectorId = inboundConnectorId;
		this.subBatchLabelSize = subBatchLabelSize;
 
		// Prepare statement for persisting errors (table may not exist in tests
		// that use an older schema — check first)
		const hasTable = this.db
			.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='sync_errors'")
			.get();
		Eif (hasTable) {
			this.insertSyncError = this.db.prepare(`
				INSERT INTO sync_errors (inbound_connector_id, folder_path, uid, error_type, message, retriable)
				VALUES (?, ?, ?, ?, ?, ?)
			`);
		}
	}
 
	/**
	 * Records a sync error both in the result array and in the database.
	 */
	private recordError(result: SyncResult, error: SyncError): void {
		result.errors.push(error);
		this.insertSyncError?.run(
			this.inboundConnectorId,
			error.folderPath,
			error.uid,
			error.errorType,
			error.message,
			error.retriable ? 1 : 0,
		);
		this.activeOnError?.(error);
	}
 
	/**
	 * Marks all unresolved errors for this identity as resolved.
	 * Called at the start of each sync cycle so stale errors don't accumulate.
	 */
	private resolveStaleErrors(): void {
		Iif (!this.insertSyncError) return;
		this.db
			.prepare(
				`UPDATE sync_errors SET resolved = 1, resolved_at = datetime('now')
				 WHERE inbound_connector_id = ? AND resolved = 0`,
			)
			.run(this.inboundConnectorId);
	}
 
	async connect(): Promise<void> {
		await withRetry(async () => {
			// ImapFlow instances cannot be reconnected once closed — create a fresh
			// instance on each retry to avoid "Can not re-use ImapFlow instance".
			// Close the previous client first to release the underlying TCP socket
			// before creating a new one.
			suppressImapFlowErrors(this.client);
			const oldSocket = getImapSocket(this.client);
			try {
				this.client.close();
			} catch {
				// Ignore — client may not be connected yet on the first attempt
			}
			// Re-add error suppression: close() strips handlers before destroying
			// the socket (possibly via setImmediate), leaving a window where
			// ECONNRESET can fire unhandled.
			suppressSocketErrors(oldSocket);
			Iif (oldSocket && typeof oldSocket.destroy === "function") {
				oldSocket.destroy();
			}
			this.client = new ImapFlow({
				...this.config,
				logger: false,
			});
			// Attach error handler immediately to prevent unhandled 'error' events
			// (e.g. ETIMEOUT) from crashing the process. The sync loop's try/catch
			// handles the resulting failures gracefully.
			this.client.on("error", () => {});
			try {
				return await this.client.connect();
			} catch (err) {
				// Suppress errors on the just-failed client/socket immediately to
				// prevent ECONNRESET from surfacing as an unhandled exception in the
				// window between this rejection and the next retry (or forceClose).
				suppressImapFlowErrors(this.client);
				const failedSocket = getImapSocket(this.client);
				suppressSocketErrors(failedSocket);
				Eif (failedSocket && typeof failedSocket.destroy === "function") {
					failedSocket.destroy();
				}
				throw err;
			}
		}, "IMAP connect");
	}
 
	async disconnect(): Promise<void> {
		try {
			await this.client.logout();
		} catch {
			// Ignore errors during disconnect — connection may already be closed
		}
	}
 
	/**
	 * Forcefully closes the IMAP connection by destroying the underlying socket.
	 * Unlike disconnect(), this does not send a LOGOUT command and returns
	 * immediately. Any pending FETCH operations will throw, unblocking
	 * async iterators that are waiting for server data.
	 */
	forceClose(): void {
		suppressImapFlowErrors(this.client);
		const socket = getImapSocket(this.client);
		try {
			this.client.close();
		} catch {
			// Ignore errors — connection may already be closed
		}
		// Re-add error suppression: close() strips handlers before destroying
		// the socket (possibly via setImmediate), leaving a window where
		// ECONNRESET can fire unhandled.
		suppressSocketErrors(socket);
		// Destroy the socket synchronously to prevent ImapFlow's deferred
		// close from stripping our error handlers and leaving an orphaned
		// socket that can receive ECONNRESET with no listener.
		if (socket && typeof socket.destroy === "function") {
			socket.destroy();
		}
	}
 
	/**
	 * Full sync: sync folders, then sync each folder's messages.
	 * Also creates labels from IMAP folder names and applies them to messages.
	 *
	 * Accepts an optional AbortSignal for graceful cancellation — when aborted,
	 * the sync finishes the current message/batch and returns partial results.
	 *
	 * Accepts an optional onProgress callback that fires as sync proceeds,
	 * useful for showing real-time status in the UI.
	 *
	 * Accepts an optional onError callback that fires immediately when an
	 * error is recorded, so callers can log errors inline rather than
	 * waiting for the summary.
	 */
	async syncAll(
		signal?: AbortSignal,
		onProgress?: (progress: SyncProgress) => void,
		onError?: (error: SyncError) => void,
	): Promise<SyncAllResult> {
		const result: SyncAllResult = { folders: [], totalNew: 0, totalErrors: 0, aborted: false };
 
		if (signal?.aborted) return result;
 
		this.activeOnError = onError;
 
		// Mark previous errors as resolved — they'll be re-recorded if they recur
		this.resolveStaleErrors();
 
		// When the abort signal fires, force-close the IMAP connection to
		// immediately unblock any `for await` loops waiting on server data.
		// Without this, the loop only checks `signal.aborted` between messages,
		// so a slow FETCH (large mailbox) would hang until the next message arrives.
		const onAbort = () => this.forceClose();
		signal?.addEventListener("abort", onAbort, { once: true });
 
		try {
			onProgress?.({
				phase: "listing-folders",
				foldersCompleted: 0,
				totalFolders: 0,
				messagesNew: 0,
				errors: 0,
			});
 
			const folders = await this.syncFolders();
 
			// Ensure labels exist for all synced folders and for this identity
			this.ensureLabelsForFolders();
			this.ensureIdentityLabel();
 
			// Read connector mode setting from the inbound connector.
			const connectorRow = this.db
				.prepare(`
					SELECT sync_delete_from_server
					FROM inbound_connectors
					WHERE id = ?
				`)
				.get(this.inboundConnectorId) as { sync_delete_from_server: number } | undefined;
			const deleteFromServerAfterSync = connectorRow?.sync_delete_from_server === 1;
 
			const totalFolders = folders.length;
			let foldersCompleted = 0;
 
			for (const folderPath of folders) {
				if (signal?.aborted) break;
 
				onProgress?.({
					phase: "syncing-folder",
					currentFolder: folderPath,
					foldersCompleted,
					totalFolders,
					messagesNew: result.totalNew,
					errors: result.totalErrors,
				});
 
				const folderResult = await this.syncFolder(folderPath, signal, deleteFromServerAfterSync);
				result.folders.push(folderResult);
				result.totalNew += folderResult.newMessages;
				result.totalErrors += folderResult.errors.length;
				foldersCompleted++;
 
				// Apply labels immediately after each folder so messages are
				// visible in the UI during sync, not only after all folders finish
				if (folderResult.newMessages > 0) {
					this.applyFolderLabelsToMessages();
				}
 
				onProgress?.({
					phase: "syncing-folder",
					currentFolder: folderPath,
					foldersCompleted,
					totalFolders,
					messagesNew: result.totalNew,
					errors: result.totalErrors,
				});
			}
 
			onProgress?.({
				phase: "applying-labels",
				foldersCompleted,
				totalFolders,
				messagesNew: result.totalNew,
				errors: result.totalErrors,
			});
 
			// Final pass: catch any messages that may have been missed
			this.applyFolderLabelsToMessages();
			this.applyIdentityLabelToMessages();
 
			// Update cached label counts so API endpoints stay O(1)
			// regardless of database size. Runs once per sync cycle.
			this.refreshLabelCounts();
 
			if (signal?.aborted) {
				result.aborted = true;
			}
 
			return result;
		} finally {
			this.activeOnError = undefined;
			signal?.removeEventListener("abort", onAbort);
		}
	}
 
	/**
	 * Lists all mailbox folders from the IMAP server, syncs folder metadata,
	 * and detects deleted/renamed folders.
	 */
	async syncFolders(): Promise<string[]> {
		const mailboxes = await withRetry(() => this.client.list(), "list mailboxes");
		const remotePaths = new Set<string>();
 
		const upsertFolder = this.db.prepare(`
			INSERT INTO folders (inbound_connector_id, path, name, delimiter, flags, special_use)
			VALUES (?, ?, ?, ?, ?, ?)
			ON CONFLICT(inbound_connector_id, path) WHERE inbound_connector_id IS NOT NULL DO UPDATE SET
				name = excluded.name,
				delimiter = excluded.delimiter,
				flags = excluded.flags,
				special_use = excluded.special_use
		`);
 
		const insertMany = this.db.transaction(() => {
			for (const mailbox of mailboxes) {
				// Skip duplicate paths (some IMAP servers report the same folder twice)
				Iif (remotePaths.has(mailbox.path)) continue;
				// Skip non-selectable folders (namespace roots, \Noselect)
				const flags = mailbox.flags ? Array.from(mailbox.flags) : [];
				if (flags.some((f) => f.toLowerCase() === "\\noselect")) continue;
 
				const specialUse = resolveSpecialUse(mailbox);
				upsertFolder.run(
					this.inboundConnectorId,
					mailbox.path,
					mailbox.name,
					mailbox.delimiter,
					JSON.stringify(flags),
					specialUse,
				);
				remotePaths.add(mailbox.path);
			}
		});
 
		insertMany();
 
		// Detect deleted folders: remove local folders no longer on server
		this.pruneDeletedFolders(remotePaths);
 
		return Array.from(remotePaths);
	}
 
	/**
	 * Removes local folders that no longer exist on the IMAP server.
	 * Cascading deletes in the schema handle messages and attachments.
	 */
	private pruneDeletedFolders(remotePaths: Set<string>): number {
		const localFolders = this.db
			.prepare("SELECT id, path FROM folders WHERE inbound_connector_id = ?")
			.all(this.inboundConnectorId) as { id: number; path: string }[];
 
		let deleted = 0;
		const deleteFolder = this.db.prepare("DELETE FROM folders WHERE id = ?");
 
		for (const local of localFolders) {
			if (!remotePaths.has(local.path)) {
				deleteFolder.run(local.id);
				deleted++;
			}
		}
 
		return deleted;
	}
 
	/**
	 * Syncs messages from a specific folder using an interleaved fetch+delete design.
	 *
	 * Phase 0: Acquire lock → get mailbox status, check UIDVALIDITY, update metadata
	 *          → search for new UIDs → release lock.
	 * Phase 1 (per-batch): For each batch of DELETE_BATCH_SIZE UIDs:
	 *   a. acquire lock → fetchUidBatch() → release lock
	 *   b. if connector mode: deleteFromServer() for this batch (acquires its own lock)
	 * Phase 2: Acquire lock → sync flags → release lock.
	 * Phase 3 (crash recovery): Delete any pending_archive=1, deleted_from_server=0
	 *          messages not handled in Phase 1 (from previous incomplete cycles).
	 */
	async syncFolder(
		folderPath: string,
		signal?: AbortSignal,
		deleteFromServerAfterSync = false,
	): Promise<SyncResult> {
		const result: SyncResult = {
			folder: folderPath,
			newMessages: 0,
			updatedFlags: 0,
			deletedFolders: 0,
			attachmentsSaved: 0,
			deletedFromServer: 0,
			errors: [],
		};
 
		const folder = this.db
			.prepare("SELECT id, uid_validity FROM folders WHERE inbound_connector_id = ? AND path = ?")
			.get(this.inboundConnectorId, folderPath) as
			| { id: number; uid_validity: number | null }
			| undefined;
 
		Iif (!folder) {
			this.recordError(result, {
				folderPath,
				uid: null,
				errorType: "folder",
				message: `Folder not found in database: ${folderPath}`,
				retriable: true,
			});
			return result;
		}
 
		// Phase 0: acquire lock → get mailbox status, check UIDVALIDITY, update
		// metadata → search for new UIDs → release lock.
		let newUids: number[] = [];
		{
			let lock: { release: () => void };
			try {
				lock = await withRetry(() => this.client.getMailboxLock(folderPath), `lock ${folderPath}`);
			} catch (err) {
				this.recordError(result, {
					folderPath,
					uid: null,
					errorType: "folder",
					message: `Could not lock mailbox ${folderPath}: ${formatImapError(err)} [STORK-E001]`,
					retriable: true,
				});
				return result;
			}
 
			try {
				const mailboxStatus = this.client.mailbox;
				Iif (!mailboxStatus) {
					this.recordError(result, {
						folderPath,
						uid: null,
						errorType: "folder",
						message: `Could not open mailbox: ${folderPath}`,
						retriable: true,
					});
					return result;
				}
 
				// Check UIDVALIDITY — if it changed, the folder was recreated; full resync needed
				Iif (folder.uid_validity && BigInt(folder.uid_validity) !== mailboxStatus.uidValidity) {
					this.db.prepare("DELETE FROM messages WHERE folder_id = ?").run(folder.id);
					this.db
						.prepare("DELETE FROM sync_state WHERE inbound_connector_id = ? AND folder_id = ?")
						.run(this.inboundConnectorId, folder.id);
				}
 
				// Update folder metadata
				this.db
					.prepare(`
					UPDATE folders SET
						uid_validity = ?,
						uid_next = ?,
						message_count = ?,
						last_synced_at = datetime('now')
					WHERE id = ?
				`)
					.run(mailboxStatus.uidValidity, mailboxStatus.uidNext, mailboxStatus.exists, folder.id);
 
				// Search for new UIDs (skip empty folders — IMAP SEARCH/FETCH on
				// an empty mailbox returns "Invalid messageset")
				if (mailboxStatus.exists > 0) {
					const syncState = this.db
						.prepare(
							"SELECT last_uid FROM sync_state WHERE inbound_connector_id = ? AND folder_id = ?",
						)
						.get(this.inboundConnectorId, folder.id) as { last_uid: number } | undefined;
 
					const lastUid = syncState?.last_uid ?? 0;
					const range = lastUid > 0 ? `${lastUid + 1}:*` : "1:*";
 
					try {
						const searchResult = await this.client.search({ uid: range }, { uid: true });
						// ImapFlow returns false when search finds nothing or fails
						if (searchResult && Array.isArray(searchResult) && searchResult.length > 0) {
							newUids = searchResult as number[];
						}
					} catch (err) {
						if (signal?.aborted) throw err;
						this.recordError(result, {
							folderPath,
							uid: null,
							errorType: "folder",
							message: `Search failed for ${folderPath}: ${formatImapError(err)} [STORK-E002]`,
							retriable: true,
						});
					}
				}
			} finally {
				try {
					lock.release();
				} catch {
					// Lock release may fail if connection was force-closed during shutdown
				}
			}
		}
 
		// Phase 1 (per-batch loop): fetch+delete interleaved in batches of DELETE_BATCH_SIZE.
		// Track a running label-application counter across all batches.
		let runningLabelCount = 0;
 
		for (let i = 0; i < newUids.length; i += DELETE_BATCH_SIZE) {
			Iif (signal?.aborted) break;
 
			const batchUids = newUids.slice(i, i + DELETE_BATCH_SIZE);
 
			// Phase 1a: acquire lock → fetch this batch → release lock
			let batchCount = 0;
			{
				let lock: { release: () => void };
				try {
					lock = await withRetry(
						() => this.client.getMailboxLock(folderPath),
						`lock ${folderPath}`,
					);
				} catch (err) {
					if (signal?.aborted) break;
					this.recordError(result, {
						folderPath,
						uid: null,
						errorType: "folder",
						message: `Could not lock mailbox ${folderPath} for fetch: ${formatImapError(err)} [STORK-E001]`,
						retriable: true,
					});
					break;
				}
 
				try {
					batchCount = await this.fetchUidBatch(
						folder.id,
						batchUids,
						result,
						signal,
						deleteFromServerAfterSync,
					);
				} catch (err) {
					if (signal?.aborted) throw err;
					this.recordError(result, {
						folderPath,
						uid: null,
						errorType: "folder",
						message: `Fetch failed for ${folderPath}: ${formatImapError(err)} [STORK-E002]`,
						retriable: true,
					});
				} finally {
					try {
						lock.release();
					} catch {
						// Lock release may fail if connection was force-closed during shutdown
					}
				}
			}
 
			result.newMessages += batchCount;
			runningLabelCount += batchCount;
 
			// Apply labels periodically across batches so messages become queryable
			// by label before the entire folder finishes syncing
			if (runningLabelCount >= this.subBatchLabelSize) {
				this.applyFolderLabelsToMessages();
				runningLabelCount = 0;
			}
 
			// Phase 1b: if connector mode, delete this batch from the server.
			// deleteFromServer() acquires its own lock per batch internally.
			if (deleteFromServerAfterSync && !signal?.aborted) {
				try {
					const deleted = await this.deleteFromServer(folderPath, batchUids);
					result.deletedFromServer += deleted;
				} catch (err) {
					if (signal?.aborted) throw err;
					this.recordError(result, {
						folderPath,
						uid: null,
						errorType: "folder",
						message: `Failed to delete synced messages from server: ${formatImapError(err)} [STORK-E005]`,
						retriable: true,
					});
				}
			}
		}
 
		// Phase 2: sync flags on existing messages (skip if aborted).
		// Acquires and releases its own lock internally.
		if (!signal?.aborted) {
			let lock: { release: () => void } | null = null;
			try {
				lock = await withRetry(
					() => this.client.getMailboxLock(folderPath),
					`lock ${folderPath} for flags`,
				);
				const flagCount = await this.syncFlags(folder.id, result, signal);
				result.updatedFlags = flagCount;
			} catch (err) {
				if (signal?.aborted) throw err;
				this.recordError(result, {
					folderPath,
					uid: null,
					errorType: "flags",
					message: `Could not acquire lock for flag sync on ${folderPath}: ${formatImapError(err)} [STORK-E003]`,
					retriable: true,
				});
			} finally {
				try {
					lock?.release();
				} catch {
					// Lock release may fail if connection was force-closed during shutdown
				}
			}
		}
 
		// Phase 3 (crash recovery): delete any pending_archive=1, deleted_from_server=0
		// messages not already handled in Phase 1. These are from previous incomplete
		// cycles where the process was killed after fetch but before delete.
		// Only runs in connector mode and when not aborted.
		if (deleteFromServerAfterSync && !signal?.aborted) {
			try {
				const pendingRows = this.db
					.prepare(
						"SELECT uid FROM messages WHERE folder_id = ? AND pending_archive = 1 AND deleted_from_server = 0",
					)
					.all(folder.id) as { uid: number }[];
 
				// Filter out UIDs already processed in Phase 1 (avoid double-delete)
				const phase1UidSet = new Set(newUids);
				const crashRecoveryUids = pendingRows
					.map((r) => r.uid)
					.filter((uid) => !phase1UidSet.has(uid));
 
				if (crashRecoveryUids.length > 0) {
					const deleted = await this.deleteFromServer(folderPath, crashRecoveryUids);
					result.deletedFromServer += deleted;
				}
			} catch (err) {
				if (signal?.aborted) throw err;
				this.recordError(result, {
					folderPath,
					uid: null,
					errorType: "folder",
					message: `Failed to delete crash-recovery messages from server: ${formatImapError(err)} [STORK-E005]`,
					retriable: true,
				});
			}
		}
 
		return result;
	}
 
	/**
	 * Fetches a specific list of UIDs, parses MIME, stores messages, and extracts attachments.
	 *
	 * Takes an explicit list of UIDs to fetch (used by the interleaved fetch+delete loop
	 * in syncFolder). Updates last_uid in sync_state after processing the batch.
	 *
	 * In connector mode, marks each newly-stored message as pending_archive=1 so that
	 * a crash between fetch and delete is recoverable — the next sync cycle picks
	 * up pending_archive=1 records and retries the deletion (Phase 3 crash recovery).
	 *
	 * Returns the count of new messages stored.
	 */
	private async fetchUidBatch(
		folderId: number,
		uids: number[],
		result: SyncResult,
		signal?: AbortSignal,
		vaultMode = false,
	): Promise<number> {
		Iif (uids.length === 0) return 0;
 
		const syncState = this.db
			.prepare("SELECT last_uid FROM sync_state WHERE inbound_connector_id = ? AND folder_id = ?")
			.get(this.inboundConnectorId, folderId) as { last_uid: number } | undefined;
 
		const lastUid = syncState?.last_uid ?? 0;
 
		const insertMessage = this.db.prepare(`
			INSERT OR IGNORE INTO messages (
				inbound_connector_id, folder_id, uid, message_id, in_reply_to, "references",
				subject, from_address, from_name, to_addresses, cc_addresses, bcc_addresses,
				date, text_body, html_text_body, html_body, flags, size, has_attachments, raw_headers
			) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
		`);
 
		const insertAttachment = this.db.prepare(`
			INSERT INTO attachments (message_id, filename, content_type, size, content_id, content_hash)
			VALUES (?, ?, ?, ?, ?, ?)
		`);
 
		let maxUid = lastUid;
		let count = 0;
 
		try {
			for await (const message of this.client.fetch(
				uids,
				{
					uid: true,
					envelope: true,
					bodyStructure: true,
					flags: true,
					size: true,
					source: true,
				},
				{ uid: true },
			)) {
				// Check abort signal between messages for graceful cancellation
				Iif (signal?.aborted) break;
 
				try {
					const source = message.source;
					Iif (!source) {
						this.recordError(result, {
							folderPath: result.folder,
							uid: message.uid,
							errorType: "message",
							message: `UID ${message.uid}: no source available`,
							retriable: true,
						});
						continue;
					}
 
					// Parse MIME with mailparser
					const parsed = await simpleParser(source);
 
					const envelope = message.envelope;
					Iif (!envelope) {
						this.recordError(result, {
							folderPath: result.folder,
							uid: message.uid,
							errorType: "message",
							message: `UID ${message.uid}: no envelope available`,
							retriable: true,
						});
						continue;
					}
					const fromAddr = envelope.from?.[0];
					const toAddrs = envelope.to?.map((a) => a.address).filter(Boolean);
					const ccAddrs = envelope.cc?.map((a) => a.address).filter(Boolean);
					const bccAddrs = envelope.bcc?.map((a) => a.address).filter(Boolean);
					const refs = parsed.references
						? Array.isArray(parsed.references)
							? parsed.references
							: [parsed.references]
						: null;
 
					const dbResult = insertMessage.run(
						this.inboundConnectorId,
						folderId,
						message.uid,
						toStringOrNull(envelope.messageId),
						toStringOrNull(envelope.inReplyTo),
						refs ? JSON.stringify(refs) : null,
						toStringOrNull(envelope.subject),
						toStringOrNull(fromAddr?.address),
						toStringOrNull(fromAddr?.name),
						toAddrs ? JSON.stringify(toAddrs) : null,
						ccAddrs ? JSON.stringify(ccAddrs) : null,
						bccAddrs ? JSON.stringify(bccAddrs) : null,
						envelope.date instanceof Date && !Number.isNaN(envelope.date.getTime())
							? envelope.date.toISOString()
							: typeof envelope.date === "string"
								? envelope.date
								: null,
						typeof parsed.text === "string" ? parsed.text : null,
						htmlToText(typeof parsed.html === "string" ? parsed.html : null),
						typeof parsed.html === "string" ? compressText(parsed.html) : null,
						Array.from(message.flags ?? new Set()).join(","),
						typeof message.size === "number" ? message.size : null,
						parsed.attachments.length > 0 ? 1 : 0,
						compressText(formatHeaders(parsed)),
					);
 
					// Extract and store attachments
					if (dbResult.changes > 0 && parsed.attachments.length > 0) {
						const messageId = dbResult.lastInsertRowid;
						for (const att of parsed.attachments) {
							const content = att.content ?? null;
							Iif (!content) continue; // Can't store without hashable data
							const contentHash = upsertAttachmentBlob(this.db, content);
							insertAttachment.run(
								messageId,
								att.filename ?? null,
								toStringOrNull(att.contentType) ?? "application/octet-stream",
								typeof att.size === "number" ? att.size : content.length,
								att.contentId ?? null,
								contentHash,
							);
							result.attachmentsSaved++;
						}
					}
 
					Eif (message.uid > maxUid) maxUid = message.uid;
 
					// Mark message as pending server deletion for crash-safe connector mode.
					// This must be set BEFORE Phase 1b (deleteFromServer) runs so that a
					// crash between fetch and delete is recoverable — the next sync cycle's
					// Phase 3 will find pending_archive=1 and retry the deletion.
					if (vaultMode && dbResult.changes > 0) {
						this.db
							.prepare("UPDATE messages SET pending_archive = 1 WHERE folder_id = ? AND uid = ?")
							.run(folderId, message.uid);
					}
 
					count++;
				} catch (err) {
					this.recordError(result, {
						folderPath: result.folder,
						uid: message.uid,
						errorType: "message",
						message: `Failed to process UID ${message.uid}: ${err instanceof Error ? err.message : err} [STORK-E004]`,
						retriable: false,
					});
				}
			}
		} catch (err) {
			// When the connection is force-closed during shutdown, the async
			// iterator throws a connection error. Treat this as a normal abort.
			if (!signal?.aborted) {
				throw err;
			}
		}
 
		// Update sync state to the max UID seen in this batch
		Eif (maxUid > lastUid) {
			this.db
				.prepare(`
				INSERT INTO sync_state (inbound_connector_id, folder_id, last_uid, last_synced_at)
				VALUES (?, ?, ?, datetime('now'))
				ON CONFLICT(inbound_connector_id, folder_id) DO UPDATE SET
					last_uid = excluded.last_uid,
					last_synced_at = excluded.last_synced_at
			`)
				.run(this.inboundConnectorId, folderId, maxUid);
		}
 
		return count;
	}
 
	/**
	 * Syncs flags (read/unread, starred, etc.) for messages already in the database.
	 * Fetches flags for all known UIDs and updates any that changed.
	 *
	 * Also detects expunged messages — UIDs that no longer exist on the server.
	 * These are deleted from the local DB (with CASCADE removing their labels),
	 * which keeps the inbox view accurate when messages are moved or deleted
	 * server-side.
	 */
	private async syncFlags(
		folderId: number,
		result: SyncResult,
		signal?: AbortSignal,
	): Promise<number> {
		const localMessages = this.db
			.prepare("SELECT uid, flags FROM messages WHERE folder_id = ? AND deleted_from_server = 0")
			.all(folderId) as { uid: number; flags: string }[];
 
		if (localMessages.length === 0) return 0;
 
		const uidSet = localMessages.map((m) => m.uid);
		const localFlagMap = new Map<number, string>();
		for (const m of localMessages) {
			localFlagMap.set(m.uid, m.flags);
		}
 
		const updateFlags = this.db.prepare(
			"UPDATE messages SET flags = ? WHERE folder_id = ? AND uid = ?",
		);
 
		let updated = 0;
 
		// Track which UIDs the server confirmed still exist. UIDs missing
		// from the response have been expunged (moved or deleted server-side).
		const serverSeenUids = new Set<number>();
		// Track batches that failed so we don't false-positive expunge them
		const failedBatchUids = new Set<number>();
 
		// Fetch flags in batches to avoid oversized IMAP commands
		for (let i = 0; i < uidSet.length; i += FETCH_BATCH_SIZE) {
			Iif (signal?.aborted) break;
			const batch = uidSet.slice(i, i + FETCH_BATCH_SIZE);
			const rangeStr = batch.join(",");
 
			try {
				for await (const msg of this.client.fetch(
					rangeStr,
					{
						uid: true,
						flags: true,
					},
					{ uid: true },
				)) {
					serverSeenUids.add(msg.uid);
					const newFlags = Array.from(msg.flags ?? new Set()).join(",");
					const oldFlags = localFlagMap.get(msg.uid);
					if (oldFlags !== newFlags) {
						updateFlags.run(newFlags, folderId, msg.uid);
						updated++;
					}
				}
			} catch (err) {
				// Connection force-closed during shutdown — treat as normal abort
				if (signal?.aborted) break;
				// Mark this batch as failed — don't treat its UIDs as expunged
				for (const uid of batch) failedBatchUids.add(uid);
				this.recordError(result, {
					folderPath: result.folder,
					uid: null,
					errorType: "flags",
					message: `Flag sync failed for "${result.folder}" (UIDs ${batch[0]}–${batch[batch.length - 1]}): ${formatImapError(err)} [STORK-E003]`,
					retriable: true,
				});
			}
		}
 
		// Detect expunged messages: UIDs we asked for but the server didn't
		// return, excluding any batches that failed (to avoid false positives).
		Eif (!signal?.aborted) {
			const expungedUids = uidSet.filter(
				(uid) => !serverSeenUids.has(uid) && !failedBatchUids.has(uid),
			);
			Iif (expungedUids.length > 0) {
				const deleteMsg = this.db.prepare("DELETE FROM messages WHERE folder_id = ? AND uid = ?");
				const deleteExpunged = this.db.transaction((uids: number[]) => {
					for (const uid of uids) {
						deleteMsg.run(folderId, uid);
					}
				});
				deleteExpunged(expungedUids);
			}
		}
 
		return updated;
	}
 
	/**
	 * Creates labels for all synced IMAP folders that don't already have one.
	 * Uses the folder's full IMAP path as the label name, with source='imap'.
	 */
	ensureLabelsForFolders(): void {
		const folders = this.db
			.prepare("SELECT id, path FROM folders WHERE inbound_connector_id = ?")
			.all(this.inboundConnectorId) as { id: number; path: string }[];
 
		const upsertLabel = this.db.prepare(`
			INSERT INTO labels (name, source)
			VALUES (?, 'imap')
			ON CONFLICT(name) DO NOTHING
		`);
 
		const insertMany = this.db.transaction(() => {
			for (const folder of folders) {
				upsertLabel.run(folder.path);
			}
		});
 
		insertMany();
	}
 
	/**
	 * Applies folder-derived labels to messages that don't have them yet.
	 * Each message gets a label matching its IMAP folder path.
	 */
	applyFolderLabelsToMessages(): void {
		this.db
			.prepare(`
			INSERT OR IGNORE INTO message_labels (message_id, label_id, date)
			SELECT m.id, l.id, m.date
			FROM messages m
			JOIN folders f ON f.id = m.folder_id
			JOIN labels l ON l.name = f.path
			LEFT JOIN message_labels ml ON ml.message_id = m.id AND ml.label_id = l.id
			LEFT JOIN label_overrides lo ON lo.message_id = m.id AND lo.label_id = l.id
			WHERE m.inbound_connector_id = ? AND ml.message_id IS NULL AND lo.message_id IS NULL
		`)
			.run(this.inboundConnectorId);
	}
 
	/**
	 * Recomputes and caches message_count and unread_count on the labels table.
	 * Called at the end of each sync cycle. This keeps the GET /labels API
	 * endpoint O(labels) — a simple column read — instead of forcing it to
	 * re-join all of message_labels × messages on every request.
	 *
	 * Uses a single GROUP BY scan instead of N correlated subqueries, so the
	 * full message_labels × messages join happens once (not once per label).
	 */
	refreshLabelCounts(): void {
		// One pass: count total and unread per label across all identities (labels are now global)
		const counts = this.db
			.prepare(`
				SELECT ml.label_id,
					COUNT(*) AS message_count,
					SUM(CASE WHEN m.flags IS NULL OR m.flags NOT LIKE '%\\Seen%' THEN 1 ELSE 0 END) AS unread_count
				FROM message_labels ml
				JOIN messages m ON m.id = ml.message_id
				GROUP BY ml.label_id
			`)
			.all() as Array<{
			label_id: number;
			message_count: number;
			unread_count: number;
		}>;
 
		// Per-connector message and unread counts — used by the cross-connector
		// all-messages/count and unread-messages/count endpoints so they return in
		// O(connectors) instead of doing a full messages table scan with a LIKE filter.
		const connectorCounts = this.db
			.prepare(`
				SELECT inbound_connector_id,
					COUNT(*) AS message_count,
					SUM(CASE WHEN flags IS NULL OR flags NOT LIKE '%\\Seen%' THEN 1 ELSE 0 END) AS unread_count
				FROM messages
				GROUP BY inbound_connector_id
			`)
			.all() as Array<{
			inbound_connector_id: number;
			message_count: number;
			unread_count: number;
		}>;
 
		const updateLabel = this.db.prepare(
			"UPDATE labels SET message_count = ?, unread_count = ? WHERE id = ?",
		);
		const updateConnector = this.db.prepare(
			"UPDATE inbound_connectors SET cached_message_count = ?, cached_unread_count = ? WHERE id = ?",
		);
 
		const applyUpdate = this.db.transaction(() => {
			// Reset all labels to 0; labels with no messages won't appear in counts above
			this.db.prepare("UPDATE labels SET message_count = 0, unread_count = 0").run();
			for (const row of counts) {
				updateLabel.run(row.message_count, row.unread_count, row.label_id);
			}
			// Reset connector caches; connectors with no messages won't appear above
			this.db
				.prepare("UPDATE inbound_connectors SET cached_message_count = 0, cached_unread_count = 0")
				.run();
			for (const row of connectorCounts) {
				updateConnector.run(row.message_count, row.unread_count, row.inbound_connector_id);
			}
		});
		applyUpdate();
	}
 
	/**
	 * Ensures a label exists for this inbound connector (source='connector'), named after
	 * the connector's display name. These auto-labels enable label-based connector filtering
	 * that composes with other label filters.
	 */
	ensureIdentityLabel(): void {
		const connector = this.db
			.prepare("SELECT name FROM inbound_connectors WHERE id = ?")
			.get(this.inboundConnectorId) as { name: string } | undefined;
		Iif (!connector) return;
 
		this.db
			.prepare(`
				INSERT INTO labels (name, source, color)
				VALUES (?, 'connector', ?)
				ON CONFLICT(name) DO UPDATE SET source = 'connector'
			`)
			.run(connector.name, this.connectorLabelColor());
	}
 
	/**
	 * Applies the connector label to all messages from this connector that don't have it yet.
	 * Runs after each sync cycle alongside applyFolderLabelsToMessages().
	 */
	applyIdentityLabelToMessages(): void {
		const connector = this.db
			.prepare("SELECT name FROM inbound_connectors WHERE id = ?")
			.get(this.inboundConnectorId) as { name: string } | undefined;
		Iif (!connector) return;
 
		this.db
			.prepare(`
				INSERT OR IGNORE INTO message_labels (message_id, label_id, date)
				SELECT m.id, l.id, m.date
				FROM messages m
				JOIN labels l ON l.name = ? AND l.source = 'connector'
				LEFT JOIN message_labels ml ON ml.message_id = m.id AND ml.label_id = l.id
				WHERE m.inbound_connector_id = ? AND ml.message_id IS NULL
			`)
			.run(connector.name, this.inboundConnectorId);
	}
 
	/**
	 * Returns a color for the connector label based on connector ID position.
	 * Uses a curated palette of distinct, accessible colors.
	 */
	private connectorLabelColor(): string {
		const palette = [
			"#3b82f6", // blue
			"#10b981", // emerald
			"#f59e0b", // amber
			"#8b5cf6", // violet
			"#ef4444", // red
			"#06b6d4", // cyan
			"#ec4899", // pink
			"#84cc16", // lime
		];
		return palette[(this.inboundConnectorId - 1) % palette.length] ?? palette[0];
	}
 
	/**
	 * Recomputes and caches total message count and unread count on the identities table.
	 * Called at the end of each sync cycle alongside refreshLabelCounts(). This keeps
	 * the GET /all-messages/count and GET /unread-messages/count endpoints O(1) —
	 * a single row read — instead of a full messages table scan on every request.
	 */
 
	/**
	 * Detects messages deleted from the server since last sync.
	 * Returns UIDs of messages that exist locally but not on the server.
	 */
	async detectServerDeletions(folderPath: string): Promise<number[]> {
		const folder = this.db
			.prepare("SELECT id FROM folders WHERE inbound_connector_id = ? AND path = ?")
			.get(this.inboundConnectorId, folderPath) as { id: number } | undefined;
 
		if (!folder) return [];
 
		const localUids = this.db
			.prepare("SELECT uid FROM messages WHERE folder_id = ? AND deleted_from_server = 0")
			.all(folder.id) as { uid: number }[];
 
		Iif (localUids.length === 0) return [];
 
		const lock = await this.client.getMailboxLock(folderPath);
		try {
			// Ask the server which UIDs still exist
			const serverUids = new Set<number>();
			for await (const msg of this.client.fetch("1:*", { uid: true })) {
				serverUids.add(msg.uid);
			}
 
			return localUids.filter((m) => !serverUids.has(m.uid)).map((m) => m.uid);
		} finally {
			lock.release();
		}
	}
 
	/**
	 * Deletes messages from the server that have been synced locally.
	 * Only operates on messages explicitly marked for server deletion.
	 *
	 * Deletes in batches of DELETE_BATCH_SIZE to avoid overly-long IMAP UID-set
	 * strings on large initial syncs (e.g. a mailbox with thousands of messages).
	 * Each batch is fully deleted and marked in the DB before the next batch starts,
	 * so a crash mid-batch only loses progress on the current batch — pending_archive
	 * records for unprocessed batches remain and are picked up on the next sync cycle.
	 */
	async deleteFromServer(folderPath: string, uids: number[]): Promise<number> {
		if (uids.length === 0) return 0;
 
		const folder = this.db
			.prepare("SELECT id FROM folders WHERE inbound_connector_id = ? AND path = ?")
			.get(this.inboundConnectorId, folderPath) as { id: number } | undefined;
 
		const markDeleted = folder
			? this.db.prepare(
					"UPDATE messages SET deleted_from_server = 1, pending_archive = 0 WHERE folder_id = ? AND uid = ?",
				)
			: null;
 
		let totalDeleted = 0;
 
		for (let i = 0; i < uids.length; i += DELETE_BATCH_SIZE) {
			const batch = uids.slice(i, i + DELETE_BATCH_SIZE);
 
			const lock = await this.client.getMailboxLock(folderPath);
			try {
				await this.client.messageDelete(batch, { uid: true });
 
				Eif (folder && markDeleted) {
					const markMany = this.db.transaction(() => {
						for (const uid of batch) {
							markDeleted.run(folder.id, uid);
						}
					});
					markMany();
				}
 
				totalDeleted += batch.length;
			} finally {
				lock.release();
			}
		}
 
		return totalDeleted;
	}
 
	/**
	 * Reconciles folder labels against current IMAP server state.
	 *
	 * For each locally-tracked folder, fetches the current UID list from the
	 * server (IMAP SEARCH ALL) and compares it against locally-stored UIDs.
	 * Messages whose UIDs no longer appear in their stored folder are treated
	 * as potential cross-folder moves: if the same RFC 5322 Message-ID appears
	 * locally in a different folder, the stale label is removed and the new
	 * folder's label is confirmed on the destination row.
	 *
	 * This is a bounded, on-demand pass — new UIDs not yet in the local DB are
	 * left for the next incremental sync cycle.
	 */
	async relabelFromServer(signal?: AbortSignal): Promise<RelabelResult> {
		const result: RelabelResult = {
			foldersScanned: 0,
			labelsUpdated: 0,
			crossFolderMovesDetected: 0,
		};
 
		const folders = this.db
			.prepare("SELECT id, path, name FROM folders WHERE inbound_connector_id = ?")
			.all(this.inboundConnectorId) as { id: number; path: string; name: string }[];
 
		if (folders.length === 0) return result;
 
		// Phase 1: collect current server UIDs for each folder
		const serverUidsByFolderId = new Map<number, Set<number>>();
 
		for (const folder of folders) {
			if (signal?.aborted) return result;
 
			let lock: { release: () => void } | null = null;
			try {
				lock = await this.client.getMailboxLock(folder.path);
			} catch {
				// Folder inaccessible on server — skip
				continue;
			}
 
			try {
				const mailboxStatus = this.client.mailbox;
				Iif (!mailboxStatus) continue;
 
				let uids = new Set<number>();
				if (mailboxStatus.exists > 0) {
					const searchResult = await this.client
						.search({ all: true }, { uid: true })
						.catch(() => false as false);
					if (searchResult && Array.isArray(searchResult)) {
						uids = new Set(searchResult as number[]);
					} else E{
						// Search failed — skip this folder to avoid false positives
						continue;
					}
				}
				// exists === 0: empty folder, uids stays as empty Set
				serverUidsByFolderId.set(folder.id, uids);
				result.foldersScanned++;
			} finally {
				try {
					lock.release();
				} catch {
					// Ignore lock release errors
				}
			}
		}
 
		Iif (signal?.aborted) return result;
 
		// Phase 2: find messages missing from their server folder and update labels
		// via Message-ID cross-folder matching
		const removeLabelStmt = this.db.prepare(`
			DELETE FROM message_labels
			WHERE message_id = ?
			  AND label_id = (
			    SELECT l.id FROM labels l
			    JOIN folders f ON f.name = l.name
			    WHERE f.id = ? LIMIT 1
			  )
		`);
 
		const addLabelStmt = this.db.prepare(`
			INSERT OR IGNORE INTO message_labels (message_id, label_id, date)
			SELECT ?, l.id, (SELECT m.date FROM messages m WHERE m.id = ?)
			FROM labels l
			JOIN folders f ON f.name = l.name
			WHERE f.id = ? LIMIT 1
		`);
 
		const applyRelabels = this.db.transaction(() => {
			for (const folder of folders) {
				const serverUids = serverUidsByFolderId.get(folder.id);
				Iif (serverUids === undefined) continue; // Folder was skipped
 
				const localMessages = this.db
					.prepare(
						`SELECT id, uid, message_id FROM messages
						 WHERE folder_id = ? AND deleted_from_server = 0`,
					)
					.all(folder.id) as { id: number; uid: number; message_id: string | null }[];
 
				for (const msg of localMessages) {
					if (serverUids.has(msg.uid)) continue;
					Iif (!msg.message_id) continue;
 
					// UID missing from server — look for the same message_id in
					// another locally-tracked folder (cross-folder move already synced)
					const movedTo = this.db
						.prepare(
							`SELECT id, folder_id FROM messages
							 WHERE message_id = ?
							   AND folder_id != ?
							   AND inbound_connector_id = ?
							   AND deleted_from_server = 0
							 LIMIT 1`,
						)
						.get(msg.message_id, folder.id, this.inboundConnectorId) as
						| { id: number; folder_id: number }
						| undefined;
 
					if (movedTo) {
						result.crossFolderMovesDetected++;
						// Remove stale old-folder label from the original row
						removeLabelStmt.run(msg.id, folder.id);
						// Ensure new-folder label is on the destination row
						addLabelStmt.run(movedTo.id, movedTo.id, movedTo.folder_id);
						result.labelsUpdated++;
					}
				}
			}
		});
 
		applyRelabels();
 
		if (result.labelsUpdated > 0) {
			this.refreshLabelCounts();
		}
 
		return result;
	}
}
 
/**
 * Resolves the special-use attribute for a mailbox.
 * Handles both the standardized RFC 6154 attributes and common folder names.
 */
function resolveSpecialUse(mailbox: { specialUse?: string; path: string }): SpecialUse {
	if (mailbox.specialUse) return mailbox.specialUse as SpecialUse;
 
	// Fallback: detect by common folder names
	const lower = mailbox.path.toLowerCase();
	Iif (lower === "inbox") return "\\Inbox";
	if (lower === "sent" || lower === "sent mail" || lower === "sent items") return "\\Sent";
	Iif (lower === "drafts" || lower === "draft") return "\\Drafts";
	if (lower === "trash" || lower === "deleted" || lower === "deleted items") return "\\Trash";
	Iif (lower === "junk" || lower === "spam") return "\\Junk";
	if (lower === "archive" || lower === "all mail" || lower === "[gmail]/all mail")
		return "\\Archive";
	return null;
}
 
/**
 * Formats parsed email headers into a compact string for storage.
 */
/**
 * Coerces a value to a string or null for safe SQLite binding.
 * Malformed emails can produce unexpected types in envelope fields.
 */
function toStringOrNull(value: unknown): string | null {
	if (value == null) return null;
	Eif (typeof value === "string") return value;
	return String(value);
}
 
function formatHeaders(parsed: ParsedMail): string | null {
	Iif (!parsed.headers) return null;
	const lines: string[] = [];
	for (const [key, value] of parsed.headers) {
		lines.push(
			`${key}: ${typeof value === "object" && value !== null && "text" in value ? (value as { text: string }).text : value}`,
		);
	}
	return lines.join("\r\n");
}
 
/**
 * Suppress async errors from an ImapFlow client before closing it.
 *
 * ImapFlow's close() removes socket error handlers before destroying the socket,
 * creating a race where ECONNRESET fires with no listener (uncaught exception).
 * Additionally, close() may be deferred via setImmediate (closeAfter), producing
 * unhandled rejections when pending operations are rejected asynchronously.
 *
 * Adding noop handlers to both the socket and the ImapFlow EventEmitter prevents
 * these expected teardown errors from surfacing as test/process failures.
 */
function suppressImapFlowErrors(client: ImapFlow): void {
	const noop = () => {};
	// Suppress errors emitted on the ImapFlow EventEmitter (e.g. from emitError)
	Iif (!client.listenerCount("error")) {
		client.on("error", noop);
	}
	// Suppress socket-level errors (ECONNRESET) after handler removal
	const socket = (
		client as unknown as { socket?: { on?: (event: string, fn: () => void) => void } }
	).socket;
	if (socket && typeof socket.on === "function") {
		socket.on("error", noop);
	}
}
 
type ImapSocket =
	| { on?: (event: string, fn: () => void) => void; destroy?: () => void }
	| undefined;
 
/** Extract the internal socket from an ImapFlow client (private field). */
function getImapSocket(client: ImapFlow): ImapSocket {
	return (client as unknown as { socket?: ImapSocket }).socket;
}
 
/** Add a noop error handler to a raw socket if it exists. */
function suppressSocketErrors(socket: ImapSocket): void {
	if (socket && typeof socket.on === "function") {
		socket.on("error", () => {});
	}
}
 
/**
 * Generic retry wrapper with exponential backoff.
 */
async function withRetry<T>(
	fn: () => Promise<T>,
	label: string,
	retries = MAX_RETRIES,
): Promise<T> {
	let lastError: unknown;
	for (let attempt = 1; attempt <= retries; attempt++) {
		try {
			return await fn();
		} catch (err) {
			lastError = err;
			if (attempt < retries) {
				await new Promise((resolve) => setTimeout(resolve, RETRY_DELAY_MS * attempt));
			}
		}
	}
	throw new Error(`${label} failed after ${retries} attempts: ${formatImapError(lastError)}`);
}
 
/**
 * Extracts a useful error message from ImapFlow errors.
 * ImapFlow sets error.message to "Command failed" but puts the actual
 * IMAP server response in error.responseText and the status (NO/BAD)
 * in error.responseStatus. This function combines them.
 */
function formatImapError(err: unknown): string {
	Iif (!(err instanceof Error)) return String(err);
	const imapErr = err as Error & { responseText?: string; responseStatus?: string };
	if (imapErr.responseText) {
		return `${imapErr.responseStatus ?? "ERROR"}: ${imapErr.responseText}`;
	}
	return imapErr.message;
}