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 | 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 131x 131x 131x 131x 167x 61x 61x 2242x 4x 1058x 246x 244x 244x 601x 600x 600x 4x 3x 3x 2x 9x 9x 2x 2x 2x 2x 74x 74x 78x 78x 76x 76x 76x 76x 74x 74x 74x 74x 67x 700x 7x 74x 69x 69x 69x 3x 3x 69x 74x 66x 66x 3x 3x 11x 3x 2x 2x 2x 2x 2x 2x 2x 2x 74x 9x 9x 9x 9x 1x 9x 64x 64x 64x 2x 62x 62x 62x 62x 61x 61x 61x 61x 61x 61x 61x 61x 61x 61x 122x 61x 49x 49x 49x 64x 35x 35x 35x 393x 393x 393x 1572x 1572x 1x 1572x 393x 35x 35x 35x 62x 1x 61x 61x 61x 60x 60x 64x 64x 64x 1x 1x 63x 63x 63x 306x 63x 63x 62x 62x 62x 45x 45x 45x 613x 612x 613x 217x 216x 216x 217x 217x 45x 614x 614x 1x 1x 1x 613x 613x 1x 1x 1x 612x 612x 1x 1x 1x 611x 1x 1x 1x 610x 1x 1x 1x 609x 1x 608x 2x 2x 2x 2x 606x 1x 1x 1x 1x 1x 605x 6x 6x 599x 599x 1x 1x 1x 1x 598x 598x 598x 598x 45x 78x 78x 78x 78x 78x 3x 3x 78x 78x 3x 3x 78x 78x 1945x 1945x 1168x 1168x 1164x 1164x 1164x 78x 78x 78x 78x 78x 78x 78x 78x 78x 78x 1x 1x 1x 78x 78x 78x 78x 78x 3x 78x 64x 64x 63x 63x 1x 64x 64x 63x 63x 63x 63x 1x 78x 78x 78x 78x 78x 78x 1x 78x 10x 78x 13x 13x 13x 13x 8x 8x 8x 7x 7x 1x 8x 30x 18x 8x 17x 8x 5x 10x 5x 5x 8x 13x 11x 11x 11x 9x 9x 9x 2x 2x 1x 1x 1x 1x 8x 8x 1x 2x 2x 2x 2x 2x 2x 6x 2x 2x 2x | /**
* The RRM automated ladder — scheduler (`docs/operations/rrm-ladder-design.md`
* §6) and the branch triggers §8 wires on prospect events.
*
* `rrmSchedulerTick` runs on the every-5-minutes cron (wired in `index.ts`,
* which this module does not own). Five isolated parts, each in its own
* try/catch so one failure never stops the rest — the comment on each
* `runXxx` function below is the part it implements.
*
* DATA SOURCING: every pacing count (daily cap, hourly rate, the last-100
* failure rate, the 72h+ reply-rate cohort) is computed from
* `rrm_scheduled_steps` (`state` + `enqueued_at`, both written by THIS
* module and by `lib/rrm/send-consumer.ts`) and `rrm_prospects.replied_at` —
* never from `wa_messages` or from the gateway's own event payloads.
* `services/rrm/gateway.service.ts` (the only send path) owns `message_sent`
* / `send_blocked` / `last_contacted_at` / the `queued → contacted` stage
* move (see its own header comment); this file never writes any of them —
* the due-step loop's successful path only flips `rrm_scheduled_steps.state`
* and enqueues, it does not append a `message_sent` row itself.
*/
import { and, asc, desc, eq, gte, inArray, lte, sql } from "drizzle-orm";
import type { DrizzleD1Database } from "drizzle-orm/d1";
import {
RRM_CONFIG_DEFAULTS,
RRM_CONFIG_KEYS,
RrmConfigDal,
} from "../../dal/rrm/config.dal";
import { RrmEventsDal } from "../../dal/rrm/events.dal";
import { RrmProspectsDal } from "../../dal/rrm/prospects.dal";
import { getDb } from "../../db";
import * as schema from "../../db/schema";
import type { RrmProspect, RrmScheduledStep } from "../../db/schema/rrm";
import { generateId } from "../../lib/ids";
import { logger } from "../../lib/logger";
import {
IST_OFFSET_MS,
istParts,
isWithinSendWindow,
nextWindowStart,
} from "../../lib/rrm/ist";
import {
ensureDefaultSequence,
isTimerStep,
N1_ACK_TEXT,
parseSteps,
type StepDef,
signupAckText,
} from "../../lib/rrm/sequence";
import { expireStaleDrafts } from "../partners/referral.service";
import { releaseDueEarnings } from "./earnings-sweep";
import { sendToProspect } from "./gateway.service";
import { areLadderTemplatesApproved } from "./template-gate.service";
const PROSPECTS = schema.rrmProspects;
const RUNS = schema.rrmSequenceRuns;
const STEPS = schema.rrmScheduledSteps;
const EVENTS = schema.rrmProspectEvents;
const SEQUENCES = schema.rrmSequences;
const TASKS = schema.rrmTasks;
const HOUR_MS = 3_600_000;
const MINUTE_MS = 60_000;
const DAY_MS = 86_400_000;
/** Two templates to the same prospect must stay this far apart (design §4/§6). */
const MIN_TEMPLATE_GAP_MS = DAY_MS + 5 * MINUTE_MS;
/** A step stuck `enqueued` longer than this was lost by the queue (design §6.4). */
const STUCK_ENQUEUED_MS = 30 * MINUTE_MS;
/** The cron interval this tick runs on (`index.ts`), in minutes. Used to smooth the hourly rate. */
const TICK_MINUTES = 5;
/**
* Bound on the enrolment candidate pool per tick — the budget trims it further.
*
* It cannot itself throttle: under the route's range check the per-tick
* enrolment budget is bounded by `hourly_send_rate` (≤ 60), so 500 candidates
* is eight times the most a tick can ever spend. A direct D1 write could set a
* higher rate and reach this, which is exactly why the tick reports which
* budget bound it rather than leaving the operator to guess.
*/
const ENROL_CANDIDATE_LIMIT = 500;
/**
* Bound on due steps processed per tick (design §6.3).
*
* 200 is a ceiling the runtime imposes, not a floor to raise: a template row
* costs roughly four or five subrequests (prospect lookup, last-send lookup,
* the state update, the queue push), so a full 200-row tick already sits near
* the Workers 1000-subrequest limit for one invocation. It does not throttle a
* 500-opener day either — 200 × 12 ticks/hour is 2,400/hour against a ceiling
* of 1,620 template sends for the WHOLE day. When a backlog does exceed it (a
* halt lifted at noon), the daily cap binds long before this does, and the
* lever for draining faster is the cap and the window, never this number.
*/
const DUE_STEP_LIMIT = 200;
/**
* Why enrolment stopped short. Null when it enrolled every candidate it could
* see with budget left over — i.e. the pacing was not the limit.
*
* `no_candidates` means the queued pool ran dry, NOT that pacing bound: it is
* the difference between "nothing to send" and "not allowed to send", which is
* the question an operator asks first when a tick sends less than they expect.
*/
export type RrmEnrolLimit =
| "outside_window"
| "daily_total"
| "daily_openers"
| "hourly_rate"
| "no_candidates";
export type RrmSchedulerResult = {
/** False when any ladder template is not APPROVED — enrolment and sends are skipped. */
templatesReady: boolean;
halted: boolean;
enrolled: number;
/**
* Why enrolment stopped short, so "we sent fewer than I set" has an answer
* without reading the database. Null when pacing was not the limit; see
* {@link RrmEnrolLimit}.
*/
enrolLimit: RrmEnrolLimit | null;
enqueued: number;
skipped: number;
rescheduled: number;
/**
* Due template steps left pending because the day's TOTAL cap was already
* full. The counterpart to `enrolLimit` on the send side: non-zero means
* `daily_send_cap` is the thing to raise, not the opener cap.
*/
deferred: number;
swept: number;
/** Earnings moved past their hold to `released` this tick. */
earningsReleased: number;
/** Unforwarded partner referral drafts moved to `expired` this tick. */
draftsExpired: number;
};
type TickCtx = {
db: DrizzleD1Database<typeof schema>;
env: CloudflareBindings;
config: RrmConfigDal;
events: RrmEventsDal;
prospects: RrmProspectsDal;
now: Date;
};
// ─────────────────────────────────────────────────────────────────────────────
// Shared helpers
// ─────────────────────────────────────────────────────────────────────────────
/** The three config values `isWithinSendWindow`/`nextWindowStart` (`lib/rrm/ist.ts`) take. */
export type SendWindowConfig = {
startHour: number;
endHour: number;
holidays: readonly string[];
};
export async function loadWindowConfig(
config: RrmConfigDal,
): Promise<SendWindowConfig> {
const startHour = await config.getNumber(
RRM_CONFIG_KEYS.sendWindowStartHour,
RRM_CONFIG_DEFAULTS[RRM_CONFIG_KEYS.sendWindowStartHour],
);
const endHour = await config.getNumber(
RRM_CONFIG_KEYS.sendWindowEndHour,
RRM_CONFIG_DEFAULTS[RRM_CONFIG_KEYS.sendWindowEndHour],
);
const holidays =
(await config.getJson<string[]>(RRM_CONFIG_KEYS.holidays)) ?? [];
return { startHour, endHour, holidays };
}
/** Epoch ms of 00:00 IST on the IST calendar day containing `ms`. */
function istDayStartMs(ms: number): number {
return Math.floor((ms + IST_OFFSET_MS) / DAY_MS) * DAY_MS - IST_OFFSET_MS;
}
/** Epoch ms of the start of the IST clock hour containing `ms`. */
function istHourStartMs(ms: number): number {
const { hour } = istParts(ms);
return istDayStartMs(ms) + hour * HOUR_MS;
}
/** `date` is inside the configured send window and not a holiday. */
function isInWindow(date: Date, config: SendWindowConfig): boolean {
return isWithinSendWindow(
date.getTime(),
config.startHour,
config.endHour,
config.holidays,
);
}
/** The next sendable instant at/after `date`, per the configured window (no jitter — see `clampAgainstLastSend`). */
function nextWindowStartDate(date: Date, config: SendWindowConfig): Date {
return new Date(
nextWindowStart(
date.getTime(),
config.startHour,
config.endHour,
config.holidays,
0,
),
);
}
export function templateKeysOf(steps: readonly StepDef[]): string[] {
return steps.filter((s) => s.kind === "template").map((s) => s.key);
}
/**
* How many of `stepKeys` are in flight or already sent, counting `sent` and
* `enqueued` rows whose `enqueued_at` falls at or after `since`.
*
* `enqueued_at`, not `date_created`: a follow-up step's row is created at
* ENROLMENT (days before it is due), so `date_created` cannot bucket it by
* the day it actually went out. `enqueued_at` is stamped the instant this
* module (or the consumer's reschedule path) commits to sending it — the
* closest thing this schema has to a send timestamp — and is `null` again
* whenever a row returns to `pending`, so a step never contributes budget it
* isn't actually spending.
*/
export async function countInFlightOrSent(
db: DrizzleD1Database<typeof schema>,
stepKeys: readonly string[],
since: Date,
): Promise<number> {
if (stepKeys.length === 0) return 0;
const rows = await db
.select({ n: sql<number>`count(*)` })
.from(STEPS)
.where(
and(
inArray(STEPS.stepKey, stepKeys as string[]),
inArray(STEPS.state, ["enqueued", "sent"]),
gte(STEPS.enqueuedAt, since),
),
);
return rows[0]?.n ?? 0;
}
/** Most recent template send to this prospect, across any run. */
export async function lastTemplateSentAt(
db: DrizzleD1Database<typeof schema>,
prospectId: string,
templateKeys: readonly string[],
): Promise<Date | null> {
if (templateKeys.length === 0) return null;
const rows = await db
.select({ enqueuedAt: STEPS.enqueuedAt })
.from(STEPS)
.where(
and(
eq(STEPS.prospectId, prospectId),
inArray(STEPS.stepKey, templateKeys as string[]),
eq(STEPS.state, "sent"),
),
)
.orderBy(desc(STEPS.enqueuedAt))
.limit(1);
return rows[0]?.enqueuedAt ?? null;
}
/**
* Pushes a reschedule candidate out so it never lands under
* {@link MIN_TEMPLATE_GAP_MS} after this prospect's last template, then
* re-clamps into the send window (pushing the gap out can walk past
* `endHour`). Zero jitter here — jitter is for spreading fresh due-steps
* across the window, not for a gap that is already a deliberate, computed
* instant.
*/
export function clampAgainstLastSend(
candidate: Date,
lastSentAt: Date | null,
windowConfig: SendWindowConfig,
): Date {
if (!lastSentAt) return candidate;
const minAllowedMs = lastSentAt.getTime() + MIN_TEMPLATE_GAP_MS;
if (candidate.getTime() >= minAllowedMs) return candidate;
return nextWindowStartDate(new Date(minAllowedMs), windowConfig);
}
async function sendHaltAlertEmail(
env: CloudflareBindings,
trigger: string,
): Promise<void> {
const to = env.RRM_NOTIFY_EMAIL ?? env.FEEDBACK_NOTIFY_EMAIL;
if (!to) return;
// Loaded lazily: lib/email pulls @react-email/render (prettier, html-to-text,
// entities, react). Evaluating that at module scope costs startup CPU on every
// cold isolate, and this path only runs on an auto-halt.
const { createEmailService } = await import("../../lib/email");
const emailService = createEmailService(env);
await emailService.sendRawEmail(
to,
`RRM auto-halt: ${trigger}`,
`<p>The RRM scheduler halted marketing sends automatically.</p><p>Trigger: <strong>${trigger}</strong></p><p>Resume manually on Ramp & pacing after review — resume is never automatic (design §6.1).</p>`,
);
}
// ─────────────────────────────────────────────────────────────────────────────
// Part 1 — auto-halt (design §6.1)
// ─────────────────────────────────────────────────────────────────────────────
/**
* Attempts the failure-rate trigger needs before it may fire — and, because a
* floor above the scan's own LIMIT could never be reached, also the size of
* the window it samples.
*
* The number falls straight out of the 1% threshold: one failure in a sample
* of N reads as 1/N, so the smallest sample in which a single unlucky send is
* NOT a campaign-wide halt is 100 (1/100 = 1%, and the trigger is `> 1%`).
* Below that the trigger was arithmetic theatre — at 500 openers a day, send
* #1 failing meant 100%, and the whole ladder stopped on one bad number.
* Two failures in a full window still halts; that is the signal worth
* stopping a campaign for.
*
* Production's "2 failures in 30 lifetime messages" cannot seed this window:
* those are `wa_messages` rows, and this scan reads `rrm_scheduled_steps`,
* which is empty in production (checked against prod D1, 2026-09-09).
*/
const FAILURE_RATE_MIN_SAMPLE = 100;
/**
* When the `halt` row was last written — a halt and a resume both stamp it.
* `RrmConfigDal` exposes the halt VALUE but not the attribution beside it, so
* the row is read directly here, exactly as `routes/admin/rrm/ramp.routes.ts`
* reads it for the halt reason.
*/
async function lastHaltChangeAt(
db: DrizzleD1Database<typeof schema>,
): Promise<Date | null> {
const rows = await db
.select({ dateUpdated: schema.rrmConfig.dateUpdated })
.from(schema.rrmConfig)
.where(eq(schema.rrmConfig.key, RRM_CONFIG_KEYS.halt))
.limit(1);
return rows[0]?.dateUpdated ?? null;
}
async function runAutoHaltCheck(ctx: TickCtx): Promise<boolean> {
const { db, env, config, now } = ctx;
if (await config.isHalted()) return true;
const sequence = await ensureDefaultSequence(db);
const steps = parseSteps(sequence);
const templateKeys = templateKeysOf(steps);
if (templateKeys.length === 0) return false;
let trigger: string | null = null;
// (a) the last FAILURE_RATE_MIN_SAMPLE delivered template sends:
// failed/blocked > 1%.
//
// Bounded to attempts made since the halt switch last moved. Without that
// bound no minimum sample could satisfy "a resume must actually resume":
// this check runs BEFORE enrolment and sends, so the tick after an
// operator resumes would recompute the identical window, halt again, and
// no fresh send could ever age the bad attempts out — the campaign would
// be unresumable without hand-editing D1. Cost of the bound, stated
// plainly: for the next 100 attempts after a resume this trigger is
// under-sampled and silent. Trigger (b) shares the bound (same resume
// argument) but has no minimum sample, so it is never silent — that is the
// asymmetry below, and it is what guards the number in that stretch.
const haltChangedAt = await lastHaltChangeAt(db);
const attempts = await db
.select({ state: STEPS.state })
.from(STEPS)
.where(
and(
inArray(STEPS.stepKey, templateKeys),
inArray(STEPS.state, ["sent", "failed"]),
...(haltChangedAt ? [gte(STEPS.enqueuedAt, haltChangedAt)] : []),
),
)
.orderBy(desc(STEPS.enqueuedAt))
.limit(FAILURE_RATE_MIN_SAMPLE);
if (attempts.length < FAILURE_RATE_MIN_SAMPLE) {
// Not the same thing as "checked and fine", and the tick's result is
// discarded by the cron (index.ts) — the log is the only place an
// operator can tell the two apart, so say it on every tick.
logger.info(
`[RRM scheduler] failure-rate auto-halt under-sampled: ${attempts.length}/${FAILURE_RATE_MIN_SAMPLE} attempts${haltChangedAt ? " since the halt switch last moved" : ""} — not evaluated`,
);
} else {
const failed = attempts.filter((a) => a.state === "failed").length;
if (failed / attempts.length > 0.01) trigger = "failure_rate";
}
// (b) any 368 / 131031 account-restriction error in the last 24h. These
// arrive as `message_failed` events this module's consumer writes with
// the gateway's raw `detail` string in the payload (send-consumer.ts).
//
// DELIBERATELY no minimum sample, unlike (a). (a) is us second-guessing
// our own error counts, where one failure proves nothing; this is Meta
// telling us the number itself is in trouble, and one occurrence is the
// entire signal. A quality warning from the platform outranks any sample
// of ours — the more so because this number also carries every user's
// login OTP (design §L1).
//
// It DOES share (a)'s since-the-halt-switch-last-moved bound, for (a)'s
// reason and no other: without it, an operator who resumes after checking
// WhatsApp Manager is overruled by the next tick five minutes later, which
// re-reads the same 24h window, finds the same event, and re-halts — for up
// to 24h, with "Resume is always manual" printed in the runbook. That costs
// nothing in safety: a number still restricted rejects the very next send,
// and `send-consumer.ts` stamps that `message_failed` at wall-clock time,
// so a genuinely-still-restricted number halts again on the next tick. The
// bound only stops us re-litigating an event the operator has already ruled
// on. A NEW code still halts on its first occurrence.
if (!trigger) {
const since = new Date(now.getTime() - DAY_MS);
const recent = await db
.select({ payload: EVENTS.payload })
.from(EVENTS)
.where(
and(
eq(EVENTS.type, "message_failed"),
gte(EVENTS.occurredAt, since),
...(haltChangedAt ? [gte(EVENTS.occurredAt, haltChangedAt)] : []),
),
);
const restricted = recent.some((row) => {
const detail = (row.payload as { detail?: unknown } | null)?.detail;
return typeof detail === "string" && /368|131031/.test(detail);
});
if (restricted) trigger = "account_restriction";
}
// (c) reply rate < 10%, only over sends >= 72h old, only when armed.
if (!trigger) {
const armed = await config.getBoolean(
RRM_CONFIG_KEYS.autoHaltReplyRateArmed,
RRM_CONFIG_DEFAULTS[RRM_CONFIG_KEYS.autoHaltReplyRateArmed],
);
if (armed) {
const cutoff = new Date(now.getTime() - 72 * HOUR_MS);
const aged = await db
.select({ prospectId: STEPS.prospectId })
.from(STEPS)
.where(
and(
inArray(STEPS.stepKey, templateKeys),
eq(STEPS.state, "sent"),
lte(STEPS.enqueuedAt, cutoff),
),
);
const cohort = [...new Set(aged.map((a) => a.prospectId))];
if (cohort.length > 0) {
// Chunked for the same reason as the enrolment query above: D1
// caps bound parameters at 100 per statement, and this cohort
// grows unboundedly with send volume (it crosses 100 distinct
// prospects in a matter of days at the default daily cap).
// better-sqlite3 wouldn't catch an unchunked `inArray` here
// either — it only fails against real D1.
const COHORT_CHUNK = 90;
let repliedCount = 0;
for (let i = 0; i < cohort.length; i += COHORT_CHUNK) {
const slice = cohort.slice(i, i + COHORT_CHUNK);
const replied = await db
.select({ n: sql<number>`count(*)` })
.from(PROSPECTS)
.where(
and(
inArray(PROSPECTS.id, slice),
sql`${PROSPECTS.repliedAt} IS NOT NULL`,
),
);
repliedCount += replied[0]?.n ?? 0;
}
const rate = repliedCount / cohort.length;
if (rate < 0.1) trigger = "reply_rate";
}
}
}
if (!trigger) return false;
await config.setHalt(true, `auto:${trigger}`, "system");
logger.error(`[RRM scheduler] auto-halt triggered: ${trigger}`);
try {
await sendHaltAlertEmail(env, trigger);
} catch (err) {
logger.error("[RRM scheduler] auto-halt alert email failed:", err);
}
return true;
}
// ─────────────────────────────────────────────────────────────────────────────
// Part 2 — enrol (design §6.2)
// ─────────────────────────────────────────────────────────────────────────────
type EnrolResult = { enrolled: number; limit: RrmEnrolLimit | null };
async function runEnrolment(ctx: TickCtx): Promise<EnrolResult> {
const { db, config, events, now } = ctx;
const windowConfig = await loadWindowConfig(config);
// Enrolling outside the window would create an N0 whose `due_at` (= run
// start, delayMs 0) is immediately rescheduled — and every D+n follow-up
// is anchored to that same run start, so the whole ladder would drift by
// however long quiet hours has left to run. Simpler and correct: only
// start new runs while the window is open, which also keeps the hourly
// N0 counter meaningful (it would otherwise read 0 all night and let a
// tick over-enrol the instant the window opens).
if (!isInWindow(now, windowConfig))
return { enrolled: 0, limit: "outside_window" };
const sequence = await ensureDefaultSequence(db);
const steps = parseSteps(sequence);
const templateKeys = templateKeysOf(steps);
const dailyCap = await config.getNumber(
RRM_CONFIG_KEYS.dailySendCap,
RRM_CONFIG_DEFAULTS[RRM_CONFIG_KEYS.dailySendCap],
);
const openerCap = await config.getNumber(
RRM_CONFIG_KEYS.dailyOpenerCap,
RRM_CONFIG_DEFAULTS[RRM_CONFIG_KEYS.dailyOpenerCap],
);
const hourlyRate = await config.getNumber(
RRM_CONFIG_KEYS.hourlySendRate,
RRM_CONFIG_DEFAULTS[RRM_CONFIG_KEYS.hourlySendRate],
);
const dayStart = new Date(istDayStartMs(now.getTime()));
const hourStart = new Date(istHourStartMs(now.getTime()));
const templateToday = await countInFlightOrSent(db, templateKeys, dayStart);
const n0Today = await countInFlightOrSent(db, ["N0"], dayStart);
const n0ThisHour = await countInFlightOrSent(db, ["N0"], hourStart);
// The hourly rate, spread across the hour's ticks instead of handed out
// whole to whichever tick asks first.
//
// Unsmoothed, an hourly rate of 56 (what 500 openers over a 9-hour window
// needs) let the first tick of every hour enrol all 56 at once — and
// because enrolment and the due-step loop run in the SAME tick, and the
// send queue is `max_batch_size: 1` with auto-scaling consumers, all 56
// reach Meta within seconds, then nothing for 55 minutes. That is under
// the Cloud API's throughput ceiling so nothing is rejected, but it is not
// what "56 an hour" means to the operator who typed it, it is the wrong
// shape for a number Meta is still deciding whether to trust, and it
// concentrates any bad minute into the auto-halt's last-100 window.
//
// The allowance is CUMULATIVE against what the hour has already spent, not
// a flat per-tick quota: a tick that was blocked (quiet hours, a full daily
// cap, an empty pool) leaves its share on the table, and a later tick in
// the same hour can still take it. Do not "simplify" this to
// `hourlyRate / ticksPerHour` — that would silently cap an hour at less
// than its rate whenever any tick underspends.
const minutesIntoHour = (now.getTime() - hourStart.getTime()) / MINUTE_MS;
const pacedHourly = Math.min(
hourlyRate,
Math.ceil((hourlyRate * (minutesIntoHour + TICK_MINUTES)) / 60),
);
// Three budgets, deliberately counting three different things:
//
// daily_total — every template step today (N0 + N2 + N7). The hard
// ceiling that protects the number itself.
// daily_openers — N0s only. Paces NEW conversations on its own key, so
// the day's follow-ups cannot silently eat the opener
// allowance the way they did when this was one number.
// hourly_rate — N0s in this clock hour, smoothed above.
//
// PRECEDENCE, when the total cap binds: follow-ups win. The due-step loop
// fetches non-N0 steps first (`followups_first`, default on) and spends the
// day's remaining total on them before it looks at an opener. That is the
// right way round — a prospect who got an opener and never gets the nudge
// is a conversation we started and abandoned, and the opener is already
// spent; a prospect not yet enrolled has lost nothing but a day. It is also
// self-limiting: each cohort owes at most two more sends, while openers are
// unbounded.
//
// What that does NOT do is reserve capacity for follow-ups due LATER today
// — openers sent this morning can leave a thin total cap short by the
// afternoon. The fix is arithmetic, not code: set `daily_send_cap` to about
// three times `daily_opener_cap` (see the ranges in ramp.routes.ts). When it
// is set too low, the tick says so — `deferred` counts every due follow-up
// left pending by a full total cap.
const budgets: { limit: RrmEnrolLimit; left: number }[] = [
{ limit: "daily_total", left: Math.max(0, dailyCap - templateToday) },
{ limit: "daily_openers", left: Math.max(0, openerCap - n0Today) },
{ limit: "hourly_rate", left: Math.max(0, pacedHourly - n0ThisHour) },
];
// Ties report the first in that order; the tick's job is to name A reason
// the operator can act on, not to enumerate every simultaneous one.
const binding = budgets.reduce((a, b) => (b.left < a.left ? b : a));
if (binding.left <= 0) return { enrolled: 0, limit: binding.limit };
// Anyone with a prior run for this sequence — active OR completed — is
// excluded IN SQL. A completed run already spent 3 of the 4 lifetime
// templates (design §6.4); re-enrolling would create a run whose N0 dies at
// the gateway's cap and stalls forever.
//
// A correlated NOT EXISTS, in the same shape `ramp.routes.ts` uses for its
// reply-rate window, rather than reading every historical run into memory
// and filtering in JS. Two reasons, both about volume: that read grows
// without bound (a month at 500 openers a day is 15,000 rows, fetched on
// all 108 ticks of every day), and the enrolled-but-not-yet-sent prospects
// it filtered out stayed `queued`, so they sat at the head of this ORDER BY
// eating candidate slots and starving the real ones. It also binds exactly
// one parameter, well clear of D1's ~100-per-statement ceiling (see
// apps/api/CLAUDE.md, "PR #403") — which is why the JS filter existed.
const candidates = await db
.select()
.from(PROSPECTS)
.where(
and(
eq(PROSPECTS.stage, "queued"),
sql`not exists (select 1 from rrm_sequence_runs r where r.prospect_id = ${PROSPECTS.id} and r.sequence_id = ${sequence.id})`,
),
)
.orderBy(asc(PROSPECTS.dateCreated), asc(PROSPECTS.id))
.limit(ENROL_CANDIDATE_LIMIT);
const toEnrol = candidates.slice(0, binding.left);
// The pool ran dry rather than the pacing binding — a different problem
// with a different fix (source more prospects, not raise a cap).
const limit: RrmEnrolLimit =
candidates.length > toEnrol.length ? binding.limit : "no_candidates";
if (toEnrol.length === 0) return { enrolled: 0, limit };
const timerSteps = steps.filter(isTimerStep);
const statements: unknown[] = [];
for (const prospect of toEnrol) {
const runId = generateId();
statements.push(
db.insert(RUNS).values({
id: runId,
sequenceId: sequence.id,
prospectId: prospect.id,
state: "active",
startedAt: now,
}),
);
for (const step of timerSteps) {
let dueAt = new Date(now.getTime() + step.delayMs);
if (!isInWindow(dueAt, windowConfig))
dueAt = nextWindowStartDate(dueAt, windowConfig);
statements.push(
db.insert(STEPS).values({
id: generateId(),
runId,
prospectId: prospect.id,
stepKey: step.key,
dueAt,
state: "pending",
}),
);
}
statements.push(
events.buildEventStatement({
prospectId: prospect.id,
type: "queued",
actorType: "system",
payload: { sequenceKey: sequence.key, runId },
occurredAt: now,
}),
);
}
const [first, ...rest] = statements as [unknown, ...unknown[]];
// biome-ignore lint/suspicious/noExplicitAny: db.batch's tuple type does not infer across a heterogeneous statement array built in a loop
await db.batch([first, ...rest] as any);
return { enrolled: toEnrol.length, limit };
}
// ─────────────────────────────────────────────────────────────────────────────
// Part 3 — due steps (design §6.3)
// ─────────────────────────────────────────────────────────────────────────────
type DueStepsResult = {
enqueued: number;
skipped: number;
rescheduled: number;
deferred: number;
};
async function fetchDueSteps(
db: DrizzleD1Database<typeof schema>,
now: Date,
followupsFirst: boolean,
): Promise<RrmScheduledStep[]> {
if (!followupsFirst) {
return await db
.select()
.from(STEPS)
.where(and(eq(STEPS.state, "pending"), lte(STEPS.dueAt, now)))
.orderBy(asc(STEPS.dueAt))
.limit(DUE_STEP_LIMIT);
}
const followups = await db
.select()
.from(STEPS)
.where(
and(
eq(STEPS.state, "pending"),
lte(STEPS.dueAt, now),
sql`${STEPS.stepKey} != 'N0'`,
),
)
.orderBy(asc(STEPS.dueAt))
.limit(DUE_STEP_LIMIT);
const remaining = DUE_STEP_LIMIT - followups.length;
if (remaining <= 0) return followups;
const openers = await db
.select()
.from(STEPS)
.where(
and(
eq(STEPS.state, "pending"),
lte(STEPS.dueAt, now),
eq(STEPS.stepKey, "N0"),
),
)
.orderBy(asc(STEPS.dueAt))
.limit(remaining);
return [...followups, ...openers];
}
async function runDueSteps(ctx: TickCtx): Promise<DueStepsResult> {
const { db, env, config, events, prospects, now } = ctx;
const result: DueStepsResult = {
enqueued: 0,
skipped: 0,
rescheduled: 0,
deferred: 0,
};
if (!env.RRM_SEND_QUEUE) {
// Flipping a row to `enqueued` with nowhere to send it would strand it
// (the 30-min sweep would just put it back, forever). Leave everything
// `pending` and try again next tick.
logger.error(
"[RRM scheduler] RRM_SEND_QUEUE binding missing; skipping due steps",
);
return result;
}
const windowConfig = await loadWindowConfig(config);
const sequence = await ensureDefaultSequence(db);
const steps = parseSteps(sequence);
const stepsByKey = new Map(steps.map((s) => [s.key, s]));
const templateKeys = templateKeysOf(steps);
const followupsFirst = await config.getBoolean(
RRM_CONFIG_KEYS.followupsFirst,
RRM_CONFIG_DEFAULTS[RRM_CONFIG_KEYS.followupsFirst],
);
const dailyCap = await config.getNumber(
RRM_CONFIG_KEYS.dailySendCap,
RRM_CONFIG_DEFAULTS[RRM_CONFIG_KEYS.dailySendCap],
);
const due = await fetchDueSteps(db, now, followupsFirst);
if (due.length === 0) return result;
let templateSentToday = await countInFlightOrSent(
db,
templateKeys,
new Date(istDayStartMs(now.getTime())),
);
const prospectCache = new Map<string, RrmProspect | undefined>();
const n0SentCache = new Map<string, boolean>();
async function getProspect(id: string): Promise<RrmProspect | undefined> {
if (!prospectCache.has(id))
prospectCache.set(id, await prospects.findById(id));
return prospectCache.get(id);
}
async function isN0Sent(runId: string): Promise<boolean> {
if (n0SentCache.has(runId)) return n0SentCache.get(runId) as boolean;
const rows = await db
.select({ state: STEPS.state })
.from(STEPS)
.where(and(eq(STEPS.runId, runId), eq(STEPS.stepKey, "N0")))
.limit(1);
const sent = rows[0]?.state === "sent";
n0SentCache.set(runId, sent);
return sent;
}
for (const row of due) {
const def = stepsByKey.get(row.stepKey);
if (!def || def.kind === "freeform") {
// A freeform step (N1) is never scheduled — reaching this state is a
// data inconsistency, not a normal outcome. Get it off the due queue
// rather than re-evaluate it every 5 minutes forever.
await db
.update(STEPS)
.set({ state: "skipped", cancelReason: "invalid_step_definition" })
.where(eq(STEPS.id, row.id));
result.skipped++;
continue;
}
const prospect = await getProspect(row.prospectId);
if (!prospect) {
await db
.update(STEPS)
.set({ state: "skipped", cancelReason: "prospect_not_found" })
.where(eq(STEPS.id, row.id));
result.skipped++;
continue;
}
const hasReplied = prospect.repliedAt != null;
// Blanket safety net: DNC always cancels, whether or not this step
// declared `cancelOn: ["dnc"]` (the `task` kind never does).
if (prospect.doNotContact) {
await db
.update(STEPS)
.set({ state: "cancelled", cancelReason: "dnc" })
.where(eq(STEPS.id, row.id));
result.skipped++;
continue;
}
if (
def.kind === "template" &&
def.cancelOn?.includes("replied") &&
hasReplied
) {
await db
.update(STEPS)
.set({ state: "cancelled", cancelReason: "replied" })
.where(eq(STEPS.id, row.id));
result.skipped++;
continue;
}
if (def.requires?.noReply && hasReplied) {
// Declared `requires` without a matching `cancelOn` (N6): the
// precondition failed, but nothing "cancelled" it — it is `skipped`,
// not `cancelled`.
await db
.update(STEPS)
.set({ state: "skipped", cancelReason: "replied" })
.where(eq(STEPS.id, row.id));
result.skipped++;
continue;
}
// Every non-N0 step is anchored to run start, but run start is only
// "when N0 was created", not "when N0 actually went out". Under cap
// pressure N0 can sit pending for days; without this gate,
// `followups_first` would send N2 to someone who never got N0.
if (row.stepKey !== "N0" && !(await isN0Sent(row.runId))) {
continue;
}
if (def.kind === "task") {
const taskId = generateId();
await db.batch([
db.insert(TASKS).values({
id: taskId,
prospectId: row.prospectId,
type: def.taskType,
dueAt: now,
state: "open",
dateCreated: now,
}),
events.buildEventStatement({
prospectId: row.prospectId,
type: "task_created",
actorType: "system",
payload: { stepKey: row.stepKey, runId: row.runId, taskId },
occurredAt: now,
}),
db.update(STEPS).set({ state: "sent" }).where(eq(STEPS.id, row.id)),
]);
result.enqueued++;
continue;
}
// Template step from here.
if (!isInWindow(now, windowConfig)) {
const lastSent = await lastTemplateSentAt(
db,
row.prospectId,
templateKeys,
);
const candidate = clampAgainstLastSend(
nextWindowStartDate(now, windowConfig),
lastSent,
windowConfig,
);
await db
.update(STEPS)
.set({ dueAt: candidate })
.where(eq(STEPS.id, row.id));
result.rescheduled++;
continue;
}
if (templateSentToday >= dailyCap) {
// Leave the row pending and count it: this is the one outcome that
// used to be completely silent, so a day whose follow-ups had eaten
// the total cap looked identical to a quiet day with nothing due.
// `followups_first` means these are openers far more often than
// nudges — see the precedence note in `runEnrolment`.
result.deferred++;
continue;
}
const lastSent = await lastTemplateSentAt(db, row.prospectId, templateKeys);
if (lastSent && now.getTime() - lastSent.getTime() < MIN_TEMPLATE_GAP_MS) {
const candidate = clampAgainstLastSend(now, lastSent, windowConfig);
await db
.update(STEPS)
.set({ dueAt: candidate })
.where(eq(STEPS.id, row.id));
result.rescheduled++;
continue;
}
// Flip state BEFORE enqueuing — a row left `pending` while it sits on
// the queue would be picked up again on the next 5-minute tick and the
// prospect would receive the same message twice.
await db
.update(STEPS)
.set({ state: "enqueued", enqueuedAt: now })
.where(eq(STEPS.id, row.id));
await env.RRM_SEND_QUEUE.send({ runId: row.runId, stepKey: row.stepKey });
templateSentToday++;
result.enqueued++;
}
return result;
}
// ─────────────────────────────────────────────────────────────────────────────
// Part 4 — sweeps (design §6.4)
// ─────────────────────────────────────────────────────────────────────────────
async function runSweeps(ctx: TickCtx): Promise<number> {
const { db, events, prospects, now } = ctx;
let swept = 0;
// (a) stuck `enqueued` > 30 min — the queue lost it (or it's still in
// flight past a reasonable bound); give it back to the scheduler.
const stuckCutoff = new Date(now.getTime() - STUCK_ENQUEUED_MS);
const stuck = await db
.select()
.from(STEPS)
.where(
and(eq(STEPS.state, "enqueued"), lte(STEPS.enqueuedAt, stuckCutoff)),
);
for (const row of stuck) {
await db.batch([
db
.update(STEPS)
.set({ state: "pending", enqueuedAt: null })
.where(eq(STEPS.id, row.id)),
events.buildEventStatement({
prospectId: row.prospectId,
type: "requeued",
actorType: "system",
payload: {
stepKey: row.stepKey,
runId: row.runId,
reason: "stuck_enqueued",
},
occurredAt: now,
}),
]);
swept++;
}
// (b) snooze expiry — `not_now` + `snooze_until <= now` → back to
// `sourced`, no auto-send. NOT via `RrmProspectsDal.setStage`:
// `decideStage` treats `not_now → sourced` as backwards (sourced ranks
// below the terminal-exit floor of `replied`) and would silently no-op,
// leaving `snooze_until` in the past forever and re-selecting this row on
// every future tick. `buildEventStatement` exists precisely so another
// owner can batch the event alongside the row it describes (see its own
// doc comment in events.dal.ts).
const snoozeExpired = await db
.select()
.from(PROSPECTS)
.where(
and(eq(PROSPECTS.stage, "not_now"), lte(PROSPECTS.snoozeUntil, now)),
);
for (const prospect of snoozeExpired) {
await db.batch([
db
.update(PROSPECTS)
.set({
stage: "sourced",
stageChangedAt: now,
snoozeUntil: null,
dateUpdated: now,
})
.where(eq(PROSPECTS.id, prospect.id)),
events.buildEventStatement({
prospectId: prospect.id,
type: "stage_changed",
actorType: "system",
payload: { from: "not_now", to: "sourced", reason: "snooze_expired" },
occurredAt: now,
}),
]);
swept++;
}
// (c) unreachable — an active run with nothing left to fire and a
// prospect who never replied. This is also the general safety net that
// closes a run whose LAST step failed permanently rather than sending:
// the consumer only applies `onComplete` / closes the run on a
// *successful* final send (send-consumer.ts), so a run whose N7 failed
// would otherwise stay `active` forever with no steps left to process.
const activeRuns = await db
.select()
.from(RUNS)
.where(eq(RUNS.state, "active"));
for (const run of activeRuns) {
const remaining = await db
.select({ id: STEPS.id })
.from(STEPS)
.where(
and(
eq(STEPS.runId, run.id),
inArray(STEPS.state, ["pending", "enqueued"]),
),
)
.limit(1);
if (remaining.length > 0) continue;
const prospect = await prospects.findById(run.prospectId);
if (!prospect || prospect.repliedAt != null) continue;
await prospects.setStage(run.prospectId, "unreachable", {
actorType: "system",
reason: "ladder_exhausted_no_reply",
});
await db
.update(RUNS)
.set({ state: "completed", exitReason: "unreachable", endedAt: now })
.where(eq(RUNS.id, run.id));
swept++;
}
return swept;
}
// ─────────────────────────────────────────────────────────────────────────────
// Entry point
// ─────────────────────────────────────────────────────────────────────────────
export async function rrmSchedulerTick(
env: CloudflareBindings,
): Promise<RrmSchedulerResult> {
const db = getDb(env.DB);
const now = new Date();
const config = new RrmConfigDal(db);
const events = new RrmEventsDal(db);
const prospects = new RrmProspectsDal(db);
const ctx: TickCtx = { db, env, config, events, prospects, now };
const result: RrmSchedulerResult = {
templatesReady: true,
halted: false,
enrolled: 0,
// Not `"no_candidates"`: a halted or template-gated tick never reaches
// enrolment at all, and those two flags above already say why. Null is
// "enrolment did not run or was not limited", which is the truth here.
enrolLimit: null,
enqueued: 0,
skipped: 0,
rescheduled: 0,
deferred: 0,
swept: 0,
earningsReleased: 0,
draftsExpired: 0,
};
try {
result.halted = await runAutoHaltCheck(ctx);
} catch (err) {
logger.error("[RRM scheduler] auto-halt check failed:", err);
try {
result.halted = await config.isHalted();
} catch {
result.halted = false;
}
}
// Meta rejects a send on a template that is not APPROVED, and every such
// rejection is a mark against a number that also carries every user's login
// OTP. So an unapproved template is treated exactly like a halt: no
// enrolment, no template sends. Free-form replies inside an open window are
// unaffected — they are not templates and never reach this tick.
let templatesReady = true;
try {
templatesReady = await areLadderTemplatesApproved(db);
} catch (err) {
// Fail CLOSED: if the check itself breaks we do not know the status,
// and guessing "approved" is the guess that talks to Meta.
logger.error("[RRM scheduler] template approval check failed:", err);
templatesReady = false;
}
result.templatesReady = templatesReady;
if (!templatesReady) {
logger.info(
"[RRM scheduler] ladder templates are not all APPROVED — skipping enrolment and sends",
);
}
if (!result.halted && templatesReady) {
try {
const enrolment = await runEnrolment(ctx);
result.enrolled = enrolment.enrolled;
result.enrolLimit = enrolment.limit;
} catch (err) {
logger.error("[RRM scheduler] enrolment failed:", err);
}
try {
const due = await runDueSteps(ctx);
result.enqueued = due.enqueued;
result.skipped = due.skipped;
result.rescheduled = due.rescheduled;
result.deferred = due.deferred;
} catch (err) {
logger.error("[RRM scheduler] due-step processing failed:", err);
}
}
try {
result.swept = await runSweeps(ctx);
} catch (err) {
logger.error("[RRM scheduler] sweeps failed:", err);
}
// Release partner earnings whose hold has expired.
//
// Deliberately OUTSIDE the halt and template gates above: those stop
// SENDING, and this moves no messages — it moves money a partner has
// already earned from `accrued` to `released`. Withholding someone's
// earnings because the campaign is paused would be the wrong call, and a
// halted campaign is exactly when the hold windows keep expiring unattended.
//
// `releaseDueEarnings` swallows its own errors and returns 0, so this
// cannot take the tick down; the try/catch is belt.
try {
result.earningsReleased = await releaseDueEarnings(ctx.db, ctx.now);
} catch (err) {
logger.error("[RRM scheduler] earnings release failed:", err);
}
// Expire partner referral drafts nobody forwarded (FR-P-3.5).
//
// Outside the halt and template gates for the same reason as the earnings
// release: a halt stops SENDING, and this sends nothing. A draft that sits
// unexpired keeps its number locked as a permanent first referrer, and a
// halted campaign is exactly when nobody is watching for that.
//
// `expireStaleDrafts` swallows its own errors and returns 0; the try/catch
// is belt.
try {
result.draftsExpired = await expireStaleDrafts({ db: ctx.db }, ctx.now);
} catch (err) {
logger.error("[RRM scheduler] draft expiry failed:", err);
}
// The cron discards this result (`index.ts` fires the tick and keeps only
// the error), so a log line is the only place an operator can see WHY a
// tick did less than they set. Only the outcomes that mean a KNOB IS SET
// WRONG are logged. The other three are the designed normal and would bury
// it: an empty pool, a closed send window, and `hourly_rate` — which is the
// binding term on almost every in-window tick, because smoothing is exactly
// what makes it bind. All five stay on the result for callers that want
// them.
if (
result.deferred > 0 ||
result.enrolLimit === "daily_total" ||
result.enrolLimit === "daily_openers"
) {
logger.info(
`[RRM scheduler] paced: enrolled ${result.enrolled} (capped by ${result.enrolLimit ?? "nothing"}), enqueued ${result.enqueued}${result.deferred > 0 ? `, ${result.deferred} due step(s) deferred by the daily total cap` : ""}`,
);
}
return result;
}
// ─────────────────────────────────────────────────────────────────────────────
// Branch triggers (design §8) — exported for `inbound.service.ts` to call.
// That file is frozen for this build; wiring the call site is a follow-up.
// ─────────────────────────────────────────────────────────────────────────────
export type RrmBranchContext = {
db: DrizzleD1Database<typeof schema>;
env: CloudflareBindings;
now?: Date;
};
/**
* The prospect replied. Cancels every `pending` step whose `cancelOn`
* includes `replied`, closes the run, and — if `auto_reply` is on — sends ONE
* acknowledgement: N1 when a ladder run existed, otherwise (and only on the
* prospect's FIRST inbound) the sign-up acknowledgement carrying the partner
* app's address.
*
* The S0 branch exists because an organic sign-up — the go form, then a
* message on the partner number — never has a ladder run, so before this the
* early return below meant NOTHING answered them until an operator typed the
* address by hand.
*
* Both are sent as `actor: { type: "system" }`, not `"operator"`, and this
* function does not touch any operator-reply/SLA bookkeeping itself: the
* design requires the acknowledgement to never count as the operator having
* answered, and the simplest way to guarantee that is to not write anything
* that accounting reads, rather than writing something and hoping a
* downstream filter excludes it.
*/
export async function onProspectReplied(
ctx: RrmBranchContext,
prospectId: string,
opts: {
/**
* This is the prospect's first ever inbound message — the caller found
* no earlier `message_received` event before appending this one. NOT
* read off `replied_at`: the forward-only stage rule refuses
* `interested` → `replied`, so every go-form sign-up keeps a null stamp
* for life and the acknowledgement would repeat on every message.
*/
firstReply?: boolean;
} = {},
): Promise<void> {
const db = ctx.db;
const now = ctx.now ?? new Date();
const activeRuns = await db
.select()
.from(RUNS)
.where(and(eq(RUNS.prospectId, prospectId), eq(RUNS.state, "active")));
for (const run of activeRuns) {
const seqRows = await db
.select()
.from(SEQUENCES)
.where(eq(SEQUENCES.id, run.sequenceId))
.limit(1);
let steps: StepDef[] = [];
if (seqRows[0]) {
try {
steps = parseSteps(seqRows[0]);
} catch (err) {
logger.error(
"[RRM onProspectReplied] failed to parse sequence steps:",
err,
);
}
}
const cancelKeys = new Set(
steps
.filter((s) => s.kind === "template" && s.cancelOn?.includes("replied"))
.map((s) => s.key),
);
const pendingRows = await db
.select({ id: STEPS.id, stepKey: STEPS.stepKey })
.from(STEPS)
.where(and(eq(STEPS.runId, run.id), eq(STEPS.state, "pending")));
const cancelRows = pendingRows.filter((p) => cancelKeys.has(p.stepKey));
if (cancelRows.length > 0) {
const stmts = cancelRows.map((row) =>
db
.update(STEPS)
.set({ state: "cancelled", cancelReason: "replied" })
.where(eq(STEPS.id, row.id)),
);
const [first, ...rest] = stmts;
Eif (first) await db.batch([first, ...rest]);
}
await db
.update(RUNS)
.set({ state: "completed", exitReason: "replied", endedAt: now })
.where(eq(RUNS.id, run.id));
}
// No run and not a first message: a follow-up from someone whose ladder is
// already closed. Nothing to cancel and nothing to say — the operator owns
// that conversation.
if (activeRuns.length === 0 && !opts.firstReply) return;
const config = new RrmConfigDal(db);
const autoReply = await config.getBoolean(
RRM_CONFIG_KEYS.autoReply,
RRM_CONFIG_DEFAULTS[RRM_CONFIG_KEYS.autoReply],
);
if (!autoReply) return;
// A prospect with a run gets N1 and only N1 — it already carries a link and
// the same promise, so sending both would be two messages saying one thing.
let text = N1_ACK_TEXT;
let stepKey = "N1";
if (activeRuns.length === 0) {
const url = ctx.env.PARTNER_APP_URL;
if (!url) {
logger.error(
"[RRM onProspectReplied] PARTNER_APP_URL is not set — sign-up acknowledgement skipped",
);
return;
}
text = signupAckText(url);
stepKey = "S0";
}
try {
await sendToProspect(
{ db, env: ctx.env, now },
{
prospectId,
intent: "freeform_only",
text,
stepKey,
actor: { type: "system" },
},
);
} catch (err) {
logger.error(
`[RRM onProspectReplied] ${stepKey} acknowledgement send failed:`,
err,
);
}
}
/**
* The prospect opted out (or an operator marked them DNC/erased). Cancels
* every pending step on every active run and closes those runs
* `completed/dnc`. Does not itself flip `do_not_contact` — that is the
* caller's job (the opt-out detector, or the admin DNC route); this is only
* the ladder half of that transition.
*/
export async function onProspectOptedOut(
ctx: RrmBranchContext,
prospectId: string,
): Promise<void> {
const db = ctx.db;
const now = ctx.now ?? new Date();
const activeRuns = await db
.select()
.from(RUNS)
.where(and(eq(RUNS.prospectId, prospectId), eq(RUNS.state, "active")));
for (const run of activeRuns) {
const pending = await db
.select({ id: STEPS.id })
.from(STEPS)
.where(and(eq(STEPS.runId, run.id), eq(STEPS.state, "pending")));
const stmts: unknown[] = pending.map((row) =>
db
.update(STEPS)
.set({ state: "cancelled", cancelReason: "dnc" })
.where(eq(STEPS.id, row.id)),
);
stmts.push(
db
.update(RUNS)
.set({ state: "completed", exitReason: "dnc", endedAt: now })
.where(eq(RUNS.id, run.id)),
);
const [first, ...rest] = stmts as [unknown, ...unknown[]];
// biome-ignore lint/suspicious/noExplicitAny: heterogeneous update statements built dynamically
await db.batch([first, ...rest] as any);
}
}
|