All files / services/crawler-service-worker/src/activities index.js

77.77% Statements 1148/1476
36.25% Branches 58/160
86.66% Functions 26/30
77.77% Lines 1148/1476

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 14771x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 32x 32x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x 32x 32x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 6x 6x 6x 1x 6x 6x 6x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x     12x 12x 12x 12x 12x     12x 12x 12x 12x 12x 12x 12x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 1x 1x 3x 3x 3x 3x 3x 3x 3x 4x                 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x       4x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x       3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x     3x       3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x     3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x                 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x       3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x         3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x       3x 3x 3x 3x 3x 3x   3x 3x             3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 2x 2x 2x 2x 3x                                                                                                                                                                                                           3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x                                                     3x         3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 1x 1x 1x 1x 1x 1x 9x 9x 9x 9x 9x 9x 9x 9x 9x     9x 1x 2x 2x     2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 3x 3x 3x 3x     3x 3x 3x                       3x 3x 3x 3x 3x 3x 3x 3x 1x 1x 1x 1x 1x 2x 2x 2x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x                                                               3x 3x 3x 3x 3x       3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x         3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x             3x 3x 3x 3x 3x     3x 3x 3x 3x 1x 1x 1x 1x 1x 1x 1x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x                               6x 6x 6x 6x 6x 6x 6x 6x 6x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x       3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x       3x 3x 3x       3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 4x 4x 4x 4x 4x 4x 4x 4x             4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 3x 4x 3x 3x 4x 1x 1x 1x 1x 4x     4x 3x 3x 3x 3x     3x 3x 3x 1x 1x 1x 1x 1x 1x                           1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x       3x 3x 3x 3x 3x 3x 3x 3x 3x 3x       3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x             3x 3x 3x 3x 3x     3x 3x 3x 3x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x       3x     3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x       1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x       3x 3x 3x       3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x     3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x       3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x       1x  
/**
 * Crawler Activities
 * All activities for the crawling workflow
 * Uses workflow-service-api for extraction and LLM for evaluation
 */
 
const { activity, Context, ApplicationFailure } = require("@temporalio/activity");
const { S3Client, PutObjectCommand } = require("@aws-sdk/client-s3");
const { Readability } = require("@mozilla/readability");
const { JSDOM } = require("jsdom");
 
const logger = {
  info: (...args) => console.log("[Crawler]", ...args),
  warn: (...args) => console.warn("[Crawler]", ...args),
  error: (...args) => console.error("[Crawler]", ...args),
};
const axios = require("axios");
const Redis = require("ioredis");
const config = require("../config");
// Alias non masquable : plusieurs activités reçoivent un paramètre `config` (config du crawl)
// qui masque le module ci-dessus. On référence l'alias pour les réglages applicatifs.
const appConfig = config;
const { computeHash, buildKey, getFromCache, setToCache } = require("../../shared/cache");
const { addInternalKey } = require("../../shared/internalAuth");
const { chatCompletion: chatCompletionShared } = require("../../shared/llmChat");
const CONFIG_SERVICE_URL = process.env.CONFIG_SERVICE_URL || "http://config-service:8000";
const SERVICE_NAME = process.env.SERVICE_NAME || "crawler-service-worker";
 
// Redis client
let redisClient = null;
 
function getRedisClient() {
  if (!redisClient) {
    redisClient = new Redis({
      host: config.redis.host,
      port: config.redis.port,
      password: config.redis.password,
      db: config.redis.db,
      retryStrategy: (times) => Math.min(times * 50, 2000),
    });
 
    redisClient.on("error", (err) => {
      console.error("[Redis] Error:", err.message);
    });
 
    redisClient.on("connect", () => {
      console.log("[Redis] Connected");
    });
  }
  return redisClient;
}
 
const ACTIVITY_DATA_PREFIX = "activity-data:";
 
// Clés de dédup : permettent un rejeu sûr des activités `trigger…` (retry Temporal)
// sans créer un second job d'extraction/synthèse.
const EXTRACTION_DEDUP_PREFIX = "crawler:extract:job:";
const SYNTHESIS_DEDUP_PREFIX = "crawler:synthesis:job:";
const DEDUP_TTL = 86400; // 24h
 
// Extensions considérées comme des fichiers (extraction fichier vs web).
const FILE_EXTENSIONS = [".pdf", ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", ".odt", ".ods"];
 
const { formatExtractionJobResult, formatSynthesisJobResult } = require("../workflows/job-polling");
 
function isFileUrl(url) {
  return FILE_EXTENSIONS.some((ext) => String(url).toLowerCase().endsWith(ext));
}
 
function buildDedupKey(prefix, jobId, url) {
  return `${prefix}${jobId || "nojob"}:${computeHash(url)}`;
}
 
/**
 * Démarre un heartbeat périodique pour l'activité courante et retourne une
 * fonction d'arrêt (à appeler dans un `finally`).
 *
 * Objectif : couvrir les appels bloquants longs (LLM, HTTP) sans boucle
 * applicative, afin que le `heartbeatTimeout` du workflow détecte une mort du
 * worker en secondes/minutes au lieu du `startToCloseTimeout`.
 *
 * Best-effort : hors contexte d'activité (tests unitaires), no-op.
 */
function startHeartbeat(details, intervalMs = 10000) {
  let timer = null;
  try {
    // Vérifie qu'on est bien dans un contexte d'activité (sinon no-op en tests).
    Context.current();
    const beat = () => {
      try {
        // AsyncLocalStorage propage le contexte d'activité aux callbacks de timer.
        Context.current().heartbeat(details);
      } catch (e) {
        // activité annulée/terminée : ignorer
      }
    };
    beat();
    timer = setInterval(beat, intervalMs);
    if (timer && typeof timer.unref === "function") timer.unref();
  } catch (e) {
    timer = null;
  }
  return () => {
    if (timer) {
      clearInterval(timer);
      timer = null;
    }
  };
}
 
// ============================================================================
// ACTIVITY: initCrawlQueue
// Initialize the Redis queue with starting URLs
// ============================================================================
async function initCrawlQueue({ jobId, startUrls, config }) {
  const redis = getRedisClient();
  const key = `crawler:${jobId}:queue`;
  const configKey = `crawler:${jobId}:config`;
 
  // Store config
  await redis.set(configKey, JSON.stringify(config), "EX", 86400);
 
  // Initialize queue with start URLs
  const pipeline = redis.pipeline();
 
  for (let i = 0; i < startUrls.length; i++) {
    const url = startUrls[i];
    // Priority: 100 for start URLs, sorted by index
    pipeline.zadd(
      key,
      10000 - i,
      JSON.stringify({
        url,
        depth: 0,
        parentScore: 100,
        linkScore: 100,
        heuristic: 10000,
        enqueuedAt: new Date().toISOString(),
      }),
    );
  }
 
  await pipeline.exec();
  // Auto-expire queue after 24h (avoids polluting Redis when crawler terminates without cleanup)
  await redis.expire(key, 86400);
 
  // Initialize visited set
  await redis.sadd(`crawler:${jobId}:visited`, "__placeholder__");
  await redis.expire(`crawler:${jobId}:visited`, 86400);
 
  logger.info(
    `[initCrawlQueue] Initialized queue for job ${jobId} with ${startUrls.length} URLs`,
  );
 
  return { queued: startUrls.length };
}
 
// ============================================================================
// ACTIVITY: getNextUrl
// Get the next URL from the priority queue (highest heuristic first), skipping visited
// ============================================================================
async function getNextUrl({ jobId }) {
  const redis = getRedisClient();
  const key = `crawler:${jobId}:queue`;
  const visitedKey = `crawler:${jobId}:visited`;
 
  // Keep trying until we find a non-visited URL or queue is empty
  let maxAttempts = 20;
  while (maxAttempts > 0) {
    // Get highest priority item
    const items = await redis.zrevrange(key, 0, 0);
 
    if (!items || items.length === 0) {
      return null;
    }
 
    const item = JSON.parse(items[0]);
 
    // Check if already visited (using normalized URL to ignore query/anchor)
    const normalizedUrl = normalizeUrl(item.url);
    const isVisited = await redis.sismember(visitedKey, normalizedUrl);
 
    if (isVisited) {
      // Remove from queue and try next
      await redis.zrem(key, items[0]);
      logger.info(
        `[getNextUrl] Skipping visited: ${normalizedUrl} (original: ${item.url})`,
      );
      maxAttempts--;
      continue;
    }
 
    // Not visited, proceed with this URL
    // Remove from queue
    await redis.zrem(key, items[0]);
 
    // Mark as in-progress
    await redis.hset(
      `crawler:${jobId}:in_progress`,
      item.url,
      JSON.stringify({
        ...item,
        startedAt: new Date().toISOString(),
      }),
    );
    await redis.expire(`crawler:${jobId}:in_progress`, 86400);
 
    logger.info(
      `[getNextUrl] Dequeued: ${item.url} (heuristic: ${item.heuristic})`,
    );
 
    return item;
  }

  logger.warn(`[getNextUrl] Too many visited URLs skipped for job ${jobId}`);
  return null;
}
 
// ============================================================================
// ACTIVITY: evaluatePage
// Score page and extract/score links using LLM
// Returns page score, relevance, and links with their heuristic scores
// ============================================================================
async function evaluatePage({
  content,
  contentKey,
  title,
  url,
  query,
  organizationId,
  pageThreshold = 60,
  linkThreshold = 40,
  links = [],
  llmModel,
  reasoning: reasoningEnabled = true,
  maxTokens,
}) {
  const startTime = Date.now();
  let apiKey = null;
  let failed = false;
  let errorReason = null;
  let llmCost = 0;
 
  // Fetch content from Redis if contentKey provided
  if (!content && contentKey) {
    const redis = getRedisClient();
    const data = await redis.get(contentKey);
    if (data) {
      content = data;
      logger.info(`[evaluatePage] Fetched ${content.length} chars from Redis key: ${contentKey}`);
      // NE PAS supprimer la cle : un rejeu de l'activite (apres perte de worker) doit
      // pouvoir relire le contenu. La cle a un TTL de 24 h (setex), le nettoyage est
      // donc assure sans casser l'idempotence.
    } else {
      logger.warn(`[evaluatePage] Content key not found in Redis: ${contentKey}`);
      return { failed: true, errorReason: "content_not_found", pageScore: 0, links: [], duration: Date.now() - startTime };
    }
  }
 
  // Clé LLM résolue À LA DEMANDE via le config-service interne (HMAC + organizationId).
  // Plus de session Redis `config:` ni de clé dans l'input workflow (D2).
  if (organizationId) {
    try {
      const res = await axios.get(
        `${CONFIG_SERVICE_URL}/internal/${organizationId}/config/openrouter`,
        { headers: addInternalKey({}, SERVICE_NAME), timeout: 5000 },
      );
      if (res.data?.success) {
        apiKey = res.data.data.value;
        logger.info(`[evaluatePage] OpenRouter key resolved for org ${organizationId}`);
      }
    } catch (e) {
      logger.warn(`[evaluatePage] Could not resolve OpenRouter key for org ${organizationId}: ${e.message}`);
    }
    if (!apiKey) {
      failed = true;
      errorReason = "config_key_absent";
    }
  }
 
  let pageScore = null;
  let reasoning = null;
  let scoredLinks = [];
 
  logger.info(`[evaluatePage] Starting evaluation for: ${url}`);
  logger.info(`[evaluatePage] LLM model: ${llmModel}`);
  logger.info(`[evaluatePage] Query: ${query}, API Key present: ${!!apiKey}`);
  logger.info(
    `[evaluatePage] Content length: ${content?.length || 0} chars, Title: ${title || "N/A"}`,
  );
 
  if (query && apiKey) {
    try {
      const baseDomain = new URL(url).hostname;
 
      logger.info(`[evaluatePage] Base domain: ${baseDomain}`);
      logger.info(
        `[evaluatePage] Content length: ${content?.length || 0} chars`,
);
      
      const MAX_EVAL_LINKS = 100;
      const evalLinks = links.slice(0, MAX_EVAL_LINKS);
      if (links.length > MAX_EVAL_LINKS) {
        logger.info(`[evaluatePage] Truncated links: ${links.length} → ${evalLinks.length} (page has too many links for LLM)`);
      }
 
      const linksJson = JSON.stringify(evalLinks, null, 2);
 
      const prompt = `You are analyzing a webpage for a crawling system. The user wants to find information related to this QUERY
---
QUERY: ${query}
---
Page URL: ${url}
Page Title: ${title || "No title"}
 
PAGE CONTENT:
${content}
 
---
Pre-extracted links from this page:
${linksJson}
---
Your task:
1. Rate the page relevance to the QUERY based on the page content (0-100)
2. Score ALL ${evalLinks.length} pre-extracted links for their likelihood to lead to more relevant content
 
CRITICAL INSTRUCTIONS:
- You MUST return EXACTLY ${evalLinks.length} links in the "links" array
- You MUST use the EXACT same URLs that were provided in the input
- Do NOT add, remove, or modify any URLs
- Do NOT create new URLs or invent URLs not in the original list
- For each link, provide a score from 0-100 based on how relevant it is to the QUERY
 
For link scoring, consider:
- Link text meaning (does it describe content related to QUERY?)
- Shorter paths often = more important pages
 
STRICT FORMAT RULES:
- Return ONLY a raw JSON object — NO markdown, NO code fences (\`\`\`), NO backticks
- ALL property names MUST be double-quoted ("pageScore", not pageScore)
- Do NOT wrap the JSON in any surrounding text, explanation, or formatting
- The response MUST start with { and end with }
 
Return ONLY this JSON (no other text, no markdown, no backticks):
{
  "pageScore": 90,
  "reasoning": "Brief explanation of page relevance to QUERY",
  "links": [
    {
      "url": "https://example.com/page",
      "score": 85,
      "reasoning": "Why this link is relevant to QUERY"
    }
  ]
}
`;
 
      // Cache Level 4: Check if this content+query was already evaluated
      const contentHash = computeHash(content);
      const queryHash = computeHash(query);
      const evalCacheKey = buildKey('evaluation', contentHash, queryHash);
      const evalCached = await getFromCache(evalCacheKey);
 
      if (evalCached) {
        try {
          const cached = JSON.parse(evalCached);
          logger.info(`[evaluatePage] ✅ CACHE HIT for ${url} (${cached.links?.length || 0} links)`);
          return { ...cached, duration: 0, cached: true };
        } catch (e) {
          logger.warn(`[evaluatePage] Cache parse error: ${e.message}`);
        }
      }
 
      logger.info(`[evaluatePage] ❌ CACHE MISS for ${url}, calling LLM...`);
 
      const LLM_TIMEOUT = 600000;
      let llmResponse;
      let lastLlmErr = null;
      for (let attempt = 1; attempt <= 3; attempt++) {
        // Heartbeat pendant l'appel LLM bloquant (heartbeatTimeout: 45s côté workflow).
        const stopHeartbeat = startHeartbeat(
          { activity: "evaluatePage", phase: "llm_call", attempt, url },
          15000,
        );
        try {
          logger.info(`[evaluatePage] Calling OpenRouter with model: ${llmModel} (attempt ${attempt}/3)`);
          llmResponse = await chatCompletionShared({
            url: "https://openrouter.ai/api/v1/chat/completions",
            apiKey,
            payload: { model: llmModel, messages: [{ role: 'user', content: prompt }], temperature: 0.1, provider: { sort: "latency" } },
            reasoning: reasoningEnabled,
            maxTokens,
            axiosInstance: axios,
            timeout: LLM_TIMEOUT,
            logger,
          });
          lastLlmErr = null;
          break;
        } catch (llmErr) {
          lastLlmErr = llmErr;
          logger.warn(`[evaluatePage] LLM attempt ${attempt}/3 failed: ${llmErr.message}`);
          if (attempt < 3) await new Promise(r => setTimeout(r, 2000));
        } finally {
          stopHeartbeat();
        }
      }
      if (lastLlmErr) throw lastLlmErr;
 
      const llmContent = llmResponse.data.choices?.[0]?.message?.content || "";
      llmCost = Math.round((llmResponse.data?.usage?.cost || 0) * 100);
 
      try {
        // Defensive cleaning: strip markdown code fences and extra whitespace
        let cleanedContent = llmContent.trim();
        cleanedContent = cleanedContent.replace(/^```(?:json)?\s*/i, '');
        cleanedContent = cleanedContent.replace(/\s*```$/i, '');
        cleanedContent = cleanedContent.trim();
 
        // If JSON.parse still fails, try to repair unquoted keys (JS object format)
        let parsed;
        try {
          parsed = JSON.parse(cleanedContent);
        } catch {
          parsed = JSON.parse(
            cleanedContent.replace(/([{,]\s*)(\w+)(\s*:)/g, '$1"$2"$3')
          );
        }
        logger.info(
          `[evaluatePage] Parsed JSON: pageScore=${parsed.pageScore}, links count=${parsed.links?.length || 0}`,
        );
 
        pageScore = Math.max(
          0,
          Math.min(100, parseInt(parsed.pageScore) || 50),
        );
        reasoning = parsed.reasoning || "LLM scored";
 
// Create a map of provided links by URL for quick lookup
        const providedLinksMap = new Map();
        for (const link of links) {
          providedLinksMap.set(link.url, link);
        }
        
        logger.info(`[evaluatePage] Provided ${providedLinksMap.size} links to LLM`);
        
        // Use LLM scored links, but keep original URLs from pre-extracted links
        const sourceLinks = parsed.links || [];
        logger.info(`[evaluatePage] LLM returned ${sourceLinks.length} links`);
        logger.info(`[evaluatePage] LLM links raw: ${JSON.stringify(sourceLinks.slice(0, 10))}`);
 
        // Count how many URLs from LLM are actually in our provided list
        const urlsInOriginalList = sourceLinks.filter(link => {
          const normalizedUrl = (link.url || '').replace(/\/+$/, '');
          return providedLinksMap.has(link.url) || providedLinksMap.has(normalizedUrl);
        }).length;
        logger.info(`[evaluatePage] URLs from LLM that are in original list: ${urlsInOriginalList}/${sourceLinks.length}`);
 
        scoredLinks = sourceLinks
          .filter((link) => {
            // Verify URL is valid
            try {
              new URL(link.url);
              return true;
            } catch {
              logger.warn(`[evaluatePage] Invalid URL from LLM: ${link.url}`);
              return false;
            }
          })
          .filter((link) => {
            // Only include URLs that were in our pre-extracted list (strict match, no normalization)
            if (providedLinksMap.has(link.url)) {
              return true;
            }
            // Try exact match after trailing slash removal but ONLY for checking, not accepting
            const normalizedUrl = (link.url || '').replace(/\/+$/, '');
            if (providedLinksMap.has(normalizedUrl) && link.url !== normalizedUrl) {
              // URL exists but with different trailing slash - accept but use original
              link.url = normalizedUrl;
              return true;
            }
            // URL is NOT in original list - reject it
            return false;
          })
          .map((link) => {
            const originalLink = providedLinksMap.get(link.url);
            const linkScore = link.score || 0;
            const heuristic = (pageScore * linkScore) / 100;
            return {
              url: link.url, // Use original URL from pre-extracted list
              text: originalLink?.linkText || "",
              heuristic,
              parentScore: pageScore,
              linkScore,
              reasoning: link.reasoning || "",
            };
          });
 
        logger.info(
          `[evaluatePage] After filtering: ${scoredLinks.length} links`,
        );
        if (scoredLinks.length > 0) {
          logger.info(
            `[evaluatePage] First 3 links: ${JSON.stringify(scoredLinks.slice(0, 3))}`,
          );
        }
      } catch (parseError) {
        logger.warn(
          `[evaluatePage] Failed to parse LLM response: ${parseError.message}`,
        );
        logger.warn(
          `[evaluatePage] Raw response (first 500): ${llmContent.substring(0, 500)}`,
        );

        // Fallback: ask LLM to reformat its own output into valid JSON
        try {
          logger.info(`[evaluatePage] Attempting reformat fallback...`);
          const stopReformatHeartbeat = startHeartbeat(
            { activity: "evaluatePage", phase: "reformat", url },
            15000,
          );
          let reformatResponse;
          try {
            reformatResponse = await axios.post(
              "https://openrouter.ai/api/v1/chat/completions",
              {
                model: llmModel,
                messages: [{
                  role: 'user',
                  content: `The following text was intended to be valid JSON but failed to parse (${parseError.message}). Fix it and return ONLY the corrected JSON. No markdown, no backticks, no explanation.

Invalid input:
${llmContent}

Return ONLY valid JSON matching this exact schema:
{"pageScore": 0-100, "reasoning": "...", "links": [{"url": "...", "score": 0-100, "reasoning": "..."}]}`
                }],
                temperature: 0,
                provider: { sort: "latency" },
              },
              {
                headers: {
                  Authorization: `Bearer ${apiKey}`,
                  "Content-Type": "application/json",
                },
              },
            );
          } finally {
            stopReformatHeartbeat();
          }

          const reformatContent = reformatResponse.data.choices?.[0]?.message?.content || "";
          logger.info(`[evaluatePage] Reformat response received, length: ${reformatContent.length}`);

          let cleanedReformat = reformatContent.trim();
          cleanedReformat = cleanedReformat.replace(/^```(?:json)?\s*/i, '');
          cleanedReformat = cleanedReformat.replace(/\s*```$/i, '');
          cleanedReformat = cleanedReformat.trim();

          const parsed = JSON.parse(cleanedReformat);
          logger.info(`[evaluatePage] Reformatted JSON: pageScore=${parsed.pageScore}, links count=${parsed.links?.length || 0}`);

          failed = false;
          errorReason = null;
          pageScore = Math.max(0, Math.min(100, parseInt(parsed.pageScore) || 50));
          reasoning = parsed.reasoning || "LLM scored (reformat)";

          const providedLinksMap = new Map();
          for (const link of links) {
            providedLinksMap.set(link.url, link);
          }

          const sourceLinks = parsed.links || [];
          scoredLinks = sourceLinks
            .filter((link) => {
              try { new URL(link.url); return true; } catch { return false; }
            })
            .filter((link) => {
              if (providedLinksMap.has(link.url)) return true;
              const normalizedUrl = (link.url || '').replace(/\/+$/, '');
              if (providedLinksMap.has(normalizedUrl) && link.url !== normalizedUrl) {
                link.url = normalizedUrl;
                return true;
              }
              return false;
            })
            .map((link) => {
              const originalLink = providedLinksMap.get(link.url);
              const linkScore = link.score || 0;
              const heuristic = (pageScore * linkScore) / 100;
              return {
                url: link.url,
                text: originalLink?.linkText || "",
                heuristic,
                parentScore: pageScore,
                linkScore,
                reasoning: link.reasoning || "",
              };
            });

          logger.info(`[evaluatePage] Reformat fallback succeeded: ${scoredLinks.length} links`);
        } catch (reformatError) {
          logger.warn(`[evaluatePage] Reformat fallback also failed: ${reformatError.message}`);
          failed = true;
          errorReason = "parse_error";
          reasoning = parseError.message;
        }
      }
 
      // Cache Level 4: Store evaluation result as-is (same format as LLM returns)
      if (!failed && pageScore !== null) {
        const contentHash = computeHash(content);
        const queryHash = computeHash(query);
        const evalCacheKey = buildKey('evaluation', contentHash, queryHash);
        await setToCache(evalCacheKey, JSON.stringify({
          pageScore,
          reasoning,
          links: scoredLinks,
          isRelevant: pageScore !== null && pageScore >= pageThreshold,
          queueSize: scoredLinks.length,
          failed: false,
          errorReason: null,
        }));
        logger.info(`[evaluatePage] Cache SET for ${url}`);
      }
    } catch (error) {
      let errorType = "unknown";
      if (error.code === 'ETIMEDOUT' || error.code === 'ECONNRESET') {
        errorType = "timeout";
      } else if (error.response?.status === 429) {
        errorType = "rate_limited";
      } else if (error.response?.status === 400) {
        errorType = "llm_bad_request";
      } else if (error.response?.status === 401) {
        errorType = "llm_unauthorized";
      } else if (error.response?.status === 402) {
        errorType = "insufficient_credits";
      } else if (error.response?.status === 500 || error.response?.status === 502 || error.response?.status === 503) {
        errorType = "llm_server_error";
      } else if (!error.response && error.code) {
        errorType = "connection_error";
      }
      
      logger.warn(`[evaluatePage] LLM scoring failed: ${error.message} (${errorType})`);
      if (error.response) {
        logger.warn(`[evaluatePage] LLM response status: ${error.response.status}`);
        logger.warn(`[evaluatePage] LLM response data: ${JSON.stringify(error.response.data)}`);
      }
      failed = true;
      errorReason = errorType;
      reasoning = error.message;
    }
  } else if (!apiKey) {
    failed = true;
    errorReason = "no_api_key";
    reasoning = "No API key available";
  }
 
  const duration = Date.now() - startTime;
  const status = failed ? "❌ FAILED" : "✅ SUCCESS";
  logger.info(
    `[evaluatePage] ${status} ${url}: score=${pageScore ?? 'null'}, links=${scoredLinks.length}, duration=${duration}ms, error=${errorReason || 'none'}`,
  );
 
  return {
    pageScore,
    reasoning,
    links: scoredLinks,
    isRelevant: pageScore !== null && pageScore >= pageThreshold,
    queueSize: scoredLinks.length,
    failed,
    errorReason,
    llmCost,
    duration,
  };
}
 
// ============================================================================
// ACTIVITY: queueLinks
// Add links to the Redis queue with their heuristic scores
// Skips URLs that have already been visited (normalized - no query/anchor)
// ============================================================================
function normalizeUrl(url) {
  try {
    const parsed = new URL(url);
    // Remove query params and anchor, keep only protocol + hostname + pathname
    return `${parsed.protocol}//${parsed.hostname}${parsed.pathname}`.replace(
      /\/$/,
      "",
    );
  } catch {
    return url.replace(/[?#].*$/, "").replace(/\/$/, "");
  }
}
 
async function queueLinks({ jobId, links, parentScore, depth = 0, minLinkScore = 30, allowedDomains }) {
  if (!links || links.length === 0) {
    return { queued: 0 };
  }
 
  const redis = getRedisClient();
  const key = `crawler:${jobId}:queue`;
  const visitedKey = `crawler:${jobId}:visited`;
 
  const pipeline = redis.pipeline();
  let queuedCount = 0;
 
  logger.info(`[queueLinks] job=${jobId} links=${links.length} minScore=${minLinkScore} first.heuristic=${links[0]?.heuristic||0}`);
  for (const link of links) {
    const linkHeuristic = link.heuristic || 0;
 
    // Skip low-scoring links (not relevant to the crawl context)
    if (linkHeuristic < minLinkScore) {
      continue;
    }
 
    // Skip links outside allowed domains (safety net)
    if (allowedDomains && allowedDomains.length > 0) {
      try {
        const hostname = new URL(link.url).hostname;
        if (!allowedDomains.some(d => hostname === d || hostname.endsWith('.' + d))) {
          logger.info(`[queueLinks] Skipping (domain ${hostname} not in allowed domains): ${link.url}`);
          continue;
        }
      } catch {
        logger.warn(`[queueLinks] Failed to parse URL: ${link.url}`);
        continue;
      }
    }
 
    // Normalize URL to check against visited (remove query params and anchor)
    const normalizedUrl = normalizeUrl(link.url);
 
    // Check if this normalized URL was already visited
    const isVisited = await redis.sismember(visitedKey, normalizedUrl);
 
    if (isVisited) {
      logger.info(
        `[queueLinks] Skipping already visited: ${normalizedUrl} (original: ${link.url})`,
      );
      continue;
    }
 
    const item = {
      url: link.url,
      depth: (link.depth !== undefined ? link.depth : depth) + 1,
      parentScore: link.parentScore || parentScore,
      linkScore: link.linkScore || 50,
      heuristic: link.heuristic || 0,
      enqueuedAt: new Date().toISOString(),
    };
 
    // ZADD with score = heuristic
    pipeline.zadd(key, item.heuristic, JSON.stringify(item));
    queuedCount++;
  }
 
  if (queuedCount > 0) {
    await pipeline.exec();
    await redis.expire(key, 86400);
    await redis.expire(visitedKey, 86400);
    logger.info(
      `[queueLinks] Queued ${queuedCount} new links for job ${jobId}`,
    );
  } else {
    logger.info(`[queueLinks] No new links to queue for job ${jobId}`);
  }
 
  return { queued: queuedCount };
}
 
// ============================================================================
// ACTIVITY: markUrlDone
// Mark a URL as visited in Redis (stores both original and normalized URL)
// ============================================================================
async function markUrlDone({ jobId, url }) {
  const redis = getRedisClient();
 
  // Normalize URL (remove query params and anchor)
  const normalizedUrl = normalizeUrl(url);
 
  // Add both original and normalized URL to visited set
  await redis.sadd(`crawler:${jobId}:visited`, url);
  await redis.sadd(`crawler:${jobId}:visited`, normalizedUrl);
  await redis.expire(`crawler:${jobId}:visited`, 86400);
 
  // Remove from in-progress
  await redis.hdel(`crawler:${jobId}:in_progress`, url);
 
  // Increment counter
  await redis.hincrby(`crawler:${jobId}:stats`, "crawled", 1);
  await redis.expire(`crawler:${jobId}:stats`, 86400);
 
  // logger.debug(`markUrlDone ${url}`);
 
  return { url, normalizedUrl, marked: true };
}
 
// ============================================================================
// ACTIVITY: triggerExtraction (courte)
// Démarre une extraction via workflow-service-api et retourne IMMÉDIATEMENT
// le jobId. AUCUNE attente : la boucle d'attente est faite par le WORKFLOW
// (durable — reprise au dernier poll après un redémarrage).
// Idempotent au retry grâce à une clé de dédup Redis (le jobId créé est réutilisé).
// ============================================================================
async function triggerExtraction({ jobId, url, config, organizationId }) {
  const workflowApiUrl = config.workflowApiUrl || appConfig.workflowApiUrl || "http://workflow-service-api:8000";
  const isFile = isFileUrl(url);
  const redis = getRedisClient();
 
  logger.info(
    `[triggerExtraction] ${url} (org: ${organizationId}, file: ${isFile})`,
  );
 
  // Cache Level 1: Check cache for file URLs only
  if (isFile) {
    const prompt = config.prompt || "";
    const outputFormat = config.outputFormat || "html";
    const cacheKey = buildKey(
      "crawler",
      computeHash(url),
      computeHash(prompt),
      computeHash(outputFormat),
    );
    const cached = await getFromCache(cacheKey);

    if (cached) {
      try {
        const cachedData = JSON.parse(cached);
        logger.info(`[triggerExtraction][Cache HIT] File extraction cache hit for ${url}`);
        return {
          success: true,
          cached: true,
          url,
          isFileUrl: true,
          contentUrl: cachedData.contentUrl,
          title: cachedData.title || "",
          metadata: cachedData.metadata || {},
          cacheKeys: [],
        };
      } catch (e) {
        logger.warn(`[triggerExtraction][Cache] Failed to parse cached data for ${url}: ${e.message}`);
      }
    } else {
      logger.info(`[triggerExtraction][Cache MISS] File extraction cache miss for ${url}`);
    }
  }
 
  // Dédup au retry : réutiliser un job déjà créé pour (jobId, url).
  const dedupKey = buildDedupKey(EXTRACTION_DEDUP_PREFIX, jobId, url);
  const existingJobId = await redis.get(dedupKey);
  if (existingJobId) {
    logger.info(`[triggerExtraction][Dedup] Reusing extraction job ${existingJobId} for ${url}`);
    return { success: true, cached: false, deduped: true, jobId: existingJobId, isFileUrl: isFile, url };
  }
 
  // Appel machine → workflow-service-api : HMAC (x-internal-token), org dans l'URL.
  const headers = addInternalKey({ "Content-Type": "application/json" }, SERVICE_NAME);
 
  // Trigger extraction workflow (async). Un échec technique lève : Temporal rejoue
  // l'activité (maximumAttempts: 2) ; la clé de dédup évite un double job.
  const response = await axios.post(
    `${workflowApiUrl}/${organizationId}/workflow/extract`,
    {
      idempotencyKey: computeHash(`${jobId}:${url}`),
      extractor: isFile
        ? {
            type: "file",
            fileUrl: url,
            config: { outputFormat: config.outputFormat },
          }
        : {
            type: "web",
            url: url,
            config: {
              useReadability: config.useReadability,
              outputFormat: config.outputFormat,
            },
          },
    },
    { headers, timeout: 120000 },
  );
 
  const workflowJobId = response.data?.data?.jobId;
  if (!workflowJobId) {
    throw new ApplicationFailure(
      "No jobId returned by extraction API",
      "ExtractionTriggerError",
      true,
    );
  }
 
  // Clé de dédup écrite immédiatement après la création du job.
  try {
    await redis.set(dedupKey, workflowJobId, "EX", DEDUP_TTL);
  } catch (e) {
    logger.warn(`[triggerExtraction][Dedup] Could not store dedup key for ${url}: ${e.message}`);
  }
 
  logger.info(`[triggerExtraction] Started extraction job ${workflowJobId} for ${url}`);
  return { success: true, cached: false, jobId: workflowJobId, isFileUrl: isFile, url };
}
 
// ============================================================================
// ACTIVITY: waitForExtractionJob (courte, idempotente, heartbeat)
// UN SEUL poll de l'état/résultats du job via le job-manager.
// Retourne { status, success, url, outputs, contentUrl?, title?, metadata?, error? }.
// C'est le WORKFLOW qui boucle (pollUntilTerminal) et applique la politique.
// ============================================================================
async function waitForExtractionJob({ jobId, url, config, minioUrl }) {
  const jobManagerUrl = config.jobManagerUrl || appConfig.jobManagerUrl || "http://job-manager-service:8000";
  const effectiveMinio = minioUrl || config.minioUrl || appConfig.minioUrl || "http://minio:9000";
  const stopHeartbeat = startHeartbeat({ activity: "waitForExtractionJob", jobId, url }, 10000);
 
  try {
    const res = await axios.get(`${jobManagerUrl}/jobs/${jobId}/results`, {
      timeout: 30000,
      // 404 (job pas encore visible) non bloquant ; 5xx -> throw -> retry Temporal.
      validateStatus: (status) => status < 500,
    });
 
    const raw = res.data?.data || res.data || {};
    const formatted = formatExtractionJobResult(raw, { url, minioUrl: effectiveMinio });
 
    // Cache Level 1 : mémoriser le résultat fichier (clé déterministe, idempotent).
    if (formatted.status === "completed" && formatted.contentUrl && isFileUrl(url)) {
      const prompt = config.prompt || "";
      const outputFormat = config.outputFormat || "html";
      const cacheKey = buildKey(
        "crawler",
        computeHash(url),
        computeHash(prompt),
        computeHash(outputFormat),
      );
      const cacheValue = JSON.stringify({
        contentUrl: formatted.contentUrl,
        title: formatted.title || "",
        metadata: formatted.metadata || {},
      });
      await setToCache(cacheKey, cacheValue);
      formatted.cacheKeys = [cacheKey];
    } else {
      formatted.cacheKeys = [];
    }
 
    return formatted;
  } finally {
    stopHeartbeat();
  }
}
 
 
// ============================================================================
// ACTIVITY: stripHtmlForLLM
// Strip useless HTML tags for LLM processing
// Removes script, style, meta, noscript, iframe, comments but keeps readable text
// ============================================================================
async function stripHtmlForLLM({ html, contentUrl }) {
  // Download from MinIO if URL provided instead of direct content
  if (!html && contentUrl) {
    try {
      const response = await axios.get(contentUrl, { timeout: 60000 });
      html = response.data;
    } catch (error) {
      logger.error(`[stripHtmlForLLM] Failed to download from ${contentUrl}: ${error.message}`);
      return { contentKey: null, originalLength: 0 };
    }
  }
 
  if (!html) return { contentKey: null, originalLength: 0 };
 
  let cleaned = html;
 
  // Remove script tags and content
  cleaned = cleaned.replace(
    /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,
    "",
  );
  // Remove style tags and content
  cleaned = cleaned.replace(
    /<style\b[^<]*(?:(?!<\/style>)<[^<]*)*<\/style>/gi,
    "",
  );
  // Remove noscript tags and content
  cleaned = cleaned.replace(
    /<noscript\b[^<]*(?:(?!<\/noscript>)<[^<]*)*<\/noscript>/gi,
    "",
  );
  // Remove iframe tags and content
  cleaned = cleaned.replace(
    /<iframe\b[^<]*(?:(?!<\/iframe>)<[^<]*)*<\/iframe>/gi,
    "",
  );
  // Remove HTML comments
  cleaned = cleaned.replace(/<!--[\s\S]*?-->/g, "");
  // Remove on* attributes (event handlers)
  cleaned = cleaned.replace(
    /\s(onclick|onload|onerror|onmouse\w+)=["'][^"']*["']/gi,
    "",
  );
  // Strip all HTML attributes except a whitelist of content-bearing ones
  // Keeps: value, href, src, alt, title (form values, links, images, tooltips)
  cleaned = cleaned.replace(/\s(?!value=|href=|src=|alt=|title=|>)[\w-]+=["'][^"']*["']/gi, '');
  cleaned = cleaned.replace(/\s(value|href|src|alt|title)=["']["']/gi, '');
 
  const savings = html.length - cleaned.length;
  const percent = savings > 0 ? Math.round((savings / html.length) * 100) : 0;
  logger.info(`[stripHtmlForLLM] ${html.length} -> ${cleaned.length} chars (${percent}% stripped)`);
 
  // Store cleaned content in Redis and return key
  const contentKey = `${ACTIVITY_DATA_PREFIX}stripped:${computeHash(contentUrl || html)}`;
  const redis = getRedisClient();
  await redis.setex(contentKey, 86400, cleaned);
  logger.info(`[stripHtmlForLLM] Stored cleaned content in Redis: ${contentKey}`);
 
  return { contentKey, originalLength: html.length };
}
 
// ============================================================================
// ACTIVITY: extractLinksFromHtml
// Extract all links from HTML using JSDOM (deterministic, no LLM)
// Returns real URLs found in the page
// ============================================================================
async function extractLinksFromHtml({ content, contentUrl, url, allowedDomains }) {
  const links = [];
 
  // Download from MinIO if URL provided instead of direct content
  if (!content && contentUrl) {
    try {
      const response = await axios.get(contentUrl, { timeout: 60000 });
      content = response.data;
    } catch (error) {
      logger.error(`[extractLinksFromHtml] Failed to download from ${contentUrl}: ${error.message}`);
      return { url, links: [] };
    }
  }
 
  if (!content || !url) {
    logger.warn(`[extractLinksFromHtml] Missing content or url`);
    return { url, links: [] };
  }
 
  try {
    const baseUrl = new URL(url);
    const dom = new JSDOM(content);
    const doc = dom.window.document;
    const anchorElements = doc.querySelectorAll("a[href]");
 
    logger.info(`[extractLinksFromHtml] Found ${anchorElements.length} anchor elements in DOM`);
 
    // Normalize function: remove # anchors and trailing slashes for deduplication
    const normalizeUrl = (u) => u.replace(/[?#].*$/, "").replace(/\/+$/, "");
 
    for (const a of anchorElements) {
      try {
        const rawHref = a.getAttribute('href');
        const linkUrl = new URL(rawHref, baseUrl);
        const href = linkUrl.href;
        const linkText = a.textContent?.trim() || "";
        
        // Skip links outside allowed domains
        if (allowedDomains && allowedDomains.length > 0) {
          const hostname = linkUrl.hostname;
          if (!allowedDomains.some(d => hostname === d || hostname.endsWith('.' + d))) {
            logger.info(`[extractLinksFromHtml] SKIP (domain ${hostname} not in allowed domains): ${href}`);
            continue;
          }
        }
        
        // Normalize for deduplication check
        const normalizedHref = normalizeUrl(href);
        
        logger.info(`[extractLinksFromHtml] Link: raw="${rawHref}" resolved="${href}" normalized="${normalizedHref}" text="${linkText.substring(0, 50)}"`);
        
        if (
          normalizedHref && // Skip empty URLs
          !links.some((l) => normalizeUrl(l.url) === normalizedHref) &&
          !href.includes("#") &&
          !href.includes("javascript:") &&
          !href.includes("mailto:")
        ) {
          links.push({ url: href, linkText });
          logger.info(`[extractLinksFromHtml] ADDED link: ${href}`);
        } else {
          if (href.includes("#")) logger.info(`[extractLinksFromHtml] SKIP (anchor): ${href}`);
          if (href.includes("javascript:")) logger.info(`[extractLinksFromHtml] SKIP (javascript): ${href}`);
          if (href.includes("mailto:")) logger.info(`[extractLinksFromHtml] SKIP (mailto): ${href}`);
        }
      } catch (e) {
        logger.warn(`[extractLinksFromHtml] Failed to parse href "${a.getAttribute('href')}": ${e.message}`);
      }
    }
 
    logger.info(`[extractLinksFromHtml] FINAL: Extracted ${links.length} links from ${url}`);
    logger.info(`[extractLinksFromHtml] Links list: ${JSON.stringify(links.map(l => ({ url: l.url, text: l.linkText.substring(0, 30) })))}`);
  } catch (error) {
    logger.error(`[extractLinksFromHtml] Error: ${error.message}`);
  }
 
  return { url, links };
}
 
// ============================================================================
// ACTIVITY: fetchContent
// Fetch content from URL (MinIO or external)
// Used by crawler workflow to load content on demand
// ============================================================================
async function fetchContent({ url }) {
  logger.info(`[fetchContent] Fetching from: ${url}`);

  try {
    const response = await axios.get(url, { timeout: 60000 });
    const content = response.data;
    logger.info(`[fetchContent] Fetched ${content.length} chars`);
    return { success: true, content };
  } catch (error) {
    logger.error(`[fetchContent] Error: ${error.message}`);
    return { success: false, error: error.message };
  }
}
 
// ============================================================================
// ACTIVITY: triggerSynthesis (courte)
// Démarre la synthèse + dispatch via HTTP et retourne IMMÉDIATEMENT le jobId.
// Le contenu est lu depuis Redis (contentKey) puis la clé est supprimée.
// Idempotent au retry via une clé de dédup Redis (jobId réutilisé).
// ============================================================================
async function triggerSynthesis({
  jobId,
  organizationId,
  content,
  contentKey,
  title,
  url,
  config,
  destinations = [],
}) {
  const workflowApiUrl = config.workflowApiUrl || appConfig.workflowApiUrl || "http://workflow-service-api:8000";
  const redis = getRedisClient();
 
  // Fetch content from Redis if contentKey provided (avoids passing heavy content via Temporal history)
  if (!content && contentKey) {
    const data = await redis.get(contentKey);
    if (data) {
      content = data;
      logger.info(`[triggerSynthesis] Fetched ${content.length} chars from Redis key: ${contentKey}`);
      // NE PAS supprimer la cle (TTL 24 h) : le rejeu de l'activite (maximumAttempts 2)
      // doit pouvoir relire le contenu.
    } else {
      logger.warn(`[triggerSynthesis] Content key not found in Redis: ${contentKey}`);
      return { success: false, error: "content_not_found", url };
    }
  }
 
  logger.info(
    `[triggerSynthesis] ${url} (${content.length} chars), destinations: ${JSON.stringify(destinations)}, org: ${organizationId}`,
  );
 
  // Dédup au retry : réutiliser un job déjà créé pour (jobId, url).
  const dedupKey = buildDedupKey(SYNTHESIS_DEDUP_PREFIX, jobId, url);
  const existingJobId = await redis.get(dedupKey);
  if (existingJobId) {
    logger.info(`[triggerSynthesis][Dedup] Reusing synthesis job ${existingJobId} for ${url}`);
    return { success: true, deduped: true, jobId: existingJobId, url };
  }
 
  // Appel machine → workflow-service-api : HMAC (x-internal-token), org dans l'URL.
  const headers = addInternalKey({ "Content-Type": "application/json" }, SERVICE_NAME);
 
  // Le raffinage (mode + spec + modèle LLM) est porté par chaque destination de la
  // config : rien à envoyer ici.
  const requestBody = {
    input: {
      content: content,
      source: url,
    },
  };
 
  // Add destinations if specified (raw destinations resolved by workflow-service-api)
  if (destinations && destinations.length > 0) {
    requestBody.destination = destinations;
  }
 
  const response = await axios.post(
    `${workflowApiUrl}/${organizationId}/workflow/extract`,
    requestBody,
    { headers, timeout: 240000 },
  );
 
  const workflowJobId = response.data?.data?.jobId;
  if (!workflowJobId) {
    throw new ApplicationFailure(
      "No jobId returned by synthesis API",
      "SynthesisTriggerError",
      true,
    );
  }
 
  // Clé de dédup écrite immédiatement après la création du job.
  try {
    await redis.set(dedupKey, workflowJobId, "EX", DEDUP_TTL);
  } catch (e) {
    logger.warn(`[triggerSynthesis][Dedup] Could not store dedup key for ${url}: ${e.message}`);
  }
 
  logger.info(`[triggerSynthesis] Started synthesis job ${workflowJobId} for ${url}`);
  return { success: true, jobId: workflowJobId, url };
}
 
// ============================================================================
// ACTIVITY: waitForSynthesisJob (courte, idempotente, heartbeat)
// UN SEUL poll de l'état/résultats de la synthèse via le job-manager, puis
// récupération des assertions depuis MinIO si le job est terminé.
// C'est le WORKFLOW qui boucle (pollUntilTerminal) et applique la politique.
// ============================================================================
async function waitForSynthesisJob({ jobId, config, url }) {
  const jobManagerUrl = config.jobManagerUrl || appConfig.jobManagerUrl || "http://job-manager-service:8000";
  const stopHeartbeat = startHeartbeat({ activity: "waitForSynthesisJob", jobId, url }, 10000);
 
  try {
    const res = await axios.get(`${jobManagerUrl}/jobs/${jobId}/results`, {
      timeout: 30000,
      // 404 (job pas encore visible) non bloquant ; 5xx -> throw -> retry Temporal.
      validateStatus: (status) => status < 500,
    });
 
    const raw = res.data?.data || res.data || {};
    const formatted = formatSynthesisJobResult(raw, { url, jobId });
 
    if (formatted.status === "completed") {
      const assertionsOutput = (raw.outputs || []).find(
        (o) => o.type === "assertions" || o.type === "facts",
      );
      if (assertionsOutput?.url) {
        try {
          const minioUrl = config.minioUrl || appConfig.minioUrl || "http://minio:9000";
          const assertionsUrl = assertionsOutput.url.replace("http://localhost:9090", minioUrl);
          const assertionsRes = await axios.get(assertionsUrl, { timeout: 30000 });
          formatted.assertionsData = Array.isArray(assertionsRes.data)
            ? assertionsRes.data
            : assertionsRes.data.assertions || assertionsRes.data.facts || [];
        } catch (e) {
          logger.warn(`[waitForSynthesisJob] Could not fetch assertions data: ${e.message}`);
          formatted.assertionsData = [];
        }
      } else {
        formatted.assertionsData = [];
      }
      logger.info(
        `[waitForSynthesisJob] job=${jobId} assertions=${formatted.assertionsCount} dispatched=${JSON.stringify(formatted.dispatchedTo)}`,
      );
    }
 
    return formatted;
  } finally {
    stopHeartbeat();
  }
}
 
 
// ============================================================================
// ACTIVITY: getQueueStats
// Get current queue statistics
// ============================================================================
async function getQueueStats({ jobId }) {
  const redis = getRedisClient();
 
  const [queueSize, visitedCount, inProgress] = await Promise.all([
    redis.zcard(`crawler:${jobId}:queue`),
    redis.scard(`crawler:${jobId}:visited`),
    redis.hgetall(`crawler:${jobId}:in_progress`),
  ]);
 
  const stats = await redis.hgetall(`crawler:${jobId}:stats`);
 
  return {
    queueSize,
    visitedCount: visitedCount - 1, // Subtract placeholder
    inProgress: Object.keys(inProgress).length,
    crawled: parseInt(stats?.crawled || "0"),
    queued: parseInt(stats?.queued || "0"),
  };
}
 
// ============================================================================
// ACTIVITY: savePageData
// Save page data to Redis for real-time access
// ============================================================================
async function savePageData({ jobId, pageData }) {
  const redis = getRedisClient();
  const key = `crawler:${jobId}:pages`;
 
  const existingData = await redis.get(key);
  let pages = existingData ? JSON.parse(existingData) : [];
 
  pageData.savedAt = new Date().toISOString();
  pages.push(pageData);
 
  // Keep only last 50 pages
  pages = pages.slice(-50);
 
  await redis.setex(key, 3600, JSON.stringify(pages));
 
  return { saved: true, pageCount: pages.length };
}
 
// ============================================================================
// ACTIVITY: uploadCrawlResults
// Upload crawl results (assertions, stats) to MinIO
// ============================================================================
async function uploadCrawlResults({ jobId, assertions, stats }) {
  const minioEndpoint = process.env.MINIO_URL || process.env.MINIO_ENDPOINT || "http://minio:9000";
  const minioAccessKey = process.env.MINIO_ACCESS_KEY || "minioadmin";
  const minioSecretKey = process.env.MINIO_SECRET_KEY || "minioadmin";
 
  logger.info(`[uploadCrawlResults] Uploading results for job ${jobId}`);
 
  try {
    const s3Client = new S3Client({
      endpoint: minioEndpoint,
      region: "us-east-1",
      credentials: {
        accessKeyId: minioAccessKey,
        secretAccessKey: minioSecretKey,
      },
      forcePathStyle: true,
    });
 
    const bucket = "workflow";
    const key = `${jobId}/assertions.json`;
 
    const dataToUpload = {
      jobId,
      type: "crawl",
      assertions: assertions || [],
      stats: stats || {},
      timestamp: new Date().toISOString(),
    };
 
    await s3Client.send(
      new PutObjectCommand({
        Bucket: bucket,
        Key: key,
        Body: JSON.stringify(dataToUpload),
        ContentType: "application/json",
      }),
    );
 
    logger.info(
      `[uploadCrawlResults] Successfully uploaded to ${bucket}/${key}`,
    );
 
    return {
      success: true,
      outputPath: key,
      bucket,
      url: `${minioEndpoint}/${bucket}/${key}`,
    };
  } catch (error) {
    logger.error(`[uploadCrawlResults] Error:`, error.message);
    throw error;
  }
}
 
// ============================================================================
// ACTIVITY: cleanHtml
// Clean HTML content using Readability (removes nav, ads, sidebar)
// Returns cleaned HTML (not markdown)
// This must be an activity because JSDOM/Readability use Node.js modules
// ============================================================================
async function cleanHtml({ html, contentUrl, url }) {
  // Download from MinIO if URL provided instead of direct content
  if (!html && contentUrl) {
    try {
      const response = await axios.get(contentUrl, { timeout: 60000 });
      html = response.data;
    } catch (error) {
      logger.error(`[cleanHtml] Failed to download from ${contentUrl}: ${error.message}`);
      throw error;
    }
  }
 
  if (!html) {
    logger.warn(`[cleanHtml] No html content provided`);
    return { contentKey: null };
  }
 
  try {
    const dom = new JSDOM(html, { url });
    const doc = dom.window.document;
 
    // Remove elements with data-nosnippet attribute (standard semantic signal:
    // explicitly marks content as NOT being the main content — used by cookie
    // banners, subscription prompts, etc.)
    doc.querySelectorAll('[data-nosnippet]').forEach(el => el.remove());
 
    const reader = new Readability(doc);
    const article = reader.parse();
 
    let cleaned;
    if (!article || !article.content) {
      logger.warn(`[cleanHtml] Readability returned empty content, using raw HTML`);
      cleaned = html;
    } else {
      cleaned = article.content;
    }
 
    logger.info(`[cleanHtml] Cleaned ${html.length} -> ${cleaned.length} chars`);
 
    // Store in Redis and return key
    const contentKey = `${ACTIVITY_DATA_PREFIX}readability:${computeHash(contentUrl || url)}`;
    const redis = getRedisClient();
    await redis.setex(contentKey, 86400, cleaned);
    logger.info(`[cleanHtml] Stored in Redis: ${contentKey}`);
 
    return { contentKey };
  } catch (error) {
    logger.error(`[cleanHtml] Error: ${error.message}`);
    throw error;
  }
}
 
module.exports = {
  initCrawlQueue,
  getNextUrl,
  triggerExtraction,
  waitForExtractionJob,
  fetchContent,
  extractLinksFromHtml,
  evaluatePage,
  queueLinks,
  markUrlDone,
  triggerSynthesis,
  waitForSynthesisJob,
  getQueueStats,
  savePageData,
  stripHtmlForLLM,
  cleanHtml,
  uploadCrawlResults,
  trackUsage: require('./track-usage').trackUsage,
  checkLlmBudget: require('./track-usage').checkLlmBudget,
  cleanupCrawlData,
};
 
// ============================================================================
// ACTIVITY: cleanupCrawlData
// Delete all crawler runtime keys from Redis for a completed/stopped job
// Prevents Redis pollution when crawler finishes without explicit cleanup
// ============================================================================
async function cleanupCrawlData({ jobId }) {
  const redis = getRedisClient();
  const pattern = `crawler:${jobId}:*`;
  logger.info(`[cleanupCrawlData] Cleaning up keys matching: ${pattern}`);
 
  try {
    // SCAN for all keys matching the pattern
    let cursor = "0";
    let deleted = 0;
    do {
      // ioredis attend la forme RESP (et non les options objet de node-redis v4) :
      // `{ match, count }` etait serialise en [object Object] => 'ERR syntax error'.
      const result = await redis.scan(cursor, 'MATCH', pattern, 'COUNT', 100);
      cursor = result[0];
      const keys = result[1];
      if (keys.length > 0) {
        await redis.del(keys);
        deleted += keys.length;
      }
    } while (cursor !== "0");
 
    logger.info(`[cleanupCrawlData] Deleted ${deleted} keys for job ${jobId}`);
    return { deleted };
  } catch (error) {
    logger.error(`[cleanupCrawlData] Error: ${error.message}`);
    return { deleted: 0, error: error.message };
  }
}