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 | 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 51x 27x 26x 26x 27x 27x 26x 27x 27x 26x 26x 26x 26x 231x 26x 4x 3x 26x 27x 26x 26x 26x 4x 4x 4x 4x 4x 624x 94x 88x 24x 2x 2x 46x 24x 24x 24x 24x 24x 24x 16x 16x 75x 14x 6x 2x 2x 17x 17x 17x 17x 16x 16x 16x 75x 1x 14x 3x 11x 1x 10x 2x 18x 18x 18x 18x 18x 18x 18x 2x 14x 14x 14x 10x 2x 8x 48x 8x 2x 6x 6x 6x 12x 12x 6x 6x 1x 6x 12x 18x 3x 3x 1x 2x 2x 1x 1x 2x 7x 7x 7x 7x 1x 6x 6x 1x 5x 7x 2x 3x 2x 5x 28x 2x 26x 1x 25x 15x 225x 14x 14x 210x 210x 2x 2x 208x 208x 14x 2x 2x 2x 1x 1x 2x 2x 2x 2x 3x 3x 32x 32x 26x 2x 24x 10x 14x 4x 4x 4x 4x 4x 2x 12x 6x 3x 1x 2x 3x 3x 4x 1x 2x 3x 1x 1x 2x 36x 36x 36x 36x 36x 36x 1x 35x 35x 1x 34x 36x 2x 32x 15x 13x 13x 23x | import { and, asc, desc, eq, gte, sql } from "drizzle-orm";
import { Hono } from "hono";
import { z } from "zod";
import type { Dal } from "../../../dal";
import {
ConfigAttributionRequiredError,
ConfigValueError,
RRM_CONFIG_DEFAULTS,
RRM_CONFIG_KEYS,
} from "../../../dal/rrm";
import type { RrmConfigKey, RrmConfigValue } from "../../../dal/rrm/config.dal";
import { getDb } from "../../../db";
import {
rrmConfig as CONFIG,
waConversations as CONVERSATIONS,
rrmProspectEvents as EVENTS,
rrmProspects as PROSPECTS,
rrmRampSteps as RAMP_STEPS,
} from "../../../db/schema";
import {
AppError,
UnauthorizedError,
ValidationError,
} from "../../../lib/errors";
import { generateId } from "../../../lib/ids";
import { handleError, success } from "../../../lib/response";
import { istDayStart, istParts } from "../../../lib/rrm/time";
import type { Services } from "../../../services";
/**
* The release gate and the kill switch — F-21 `/api/admin/rrm/*`.
*
* Releasing is the ONLY way prospects become eligible for sending, and the
* gate that guards it is evaluated here, server-side, on every read AND again
* on the write. The client is never trusted for the decision: it renders the
* conditions this endpoint returns, and `POST /ramp/release` re-derives them
* from the database before it moves a single row. A UI that has drifted, been
* left open for an hour, or been driven by curl cannot open a step that the
* engine would refuse.
*
* Auth: the parent admin router applies `contextMiddleware` and
* `requirePlatformAdmin`. Nothing is re-applied per route.
*/
type Env = {
Bindings: CloudflareBindings;
Variables: {
user: { id: string; name: string; email: string } | null;
session: unknown;
dal: Dal;
services: Services;
};
};
/** One gate condition, mirroring `RrmGateCondition` in the portal client. */
export type RrmGateCondition = {
key: string;
label: string;
pass: boolean;
value: string;
threshold: string;
fixHref?: string;
};
// ── Gate thresholds ─────────────────────────────────────────────────────────
const GATE_MAX_BLOCKS = 0;
const GATE_MIN_DELIVERY_RATE = 90;
const GATE_MIN_REPLIES = 3;
const GATE_MIN_REPLY_RATE = 10;
const GATE_MAX_BACKLOG_MINUTES = 12 * 60;
const GATE_MIN_RESERVE_PERCENT = 45;
/** How many recent sends the reply-rate condition looks back over. */
const REPLY_RATE_WINDOW = 100;
const ROLLING_WINDOW_MS = 86_400_000;
/**
* Meta counts business-initiated conversations as UNIQUE RECIPIENTS in a
* rolling 24 hours, and a fresh WABA starts on the 250 tier.
*
* Hard-coded rather than read from config because `RRM_CONFIG_KEYS` has no key
* for it — the tier is a property of the Meta account, not an operator
* setting. It is displayed as reassurance (at 30–150 sends/day it is nowhere
* near binding), never as admission control, so a stale value here cannot let
* a send through. Move it to config if the account is ever upgraded.
*/
const WABA_TIER_UNIQUE_RECIPIENTS_24H = 250;
/**
* The largest batch one release may move. The loop below writes a stage change
* plus its event per prospect, so an unbounded `count` would be an unbounded
* number of D1 round trips inside one request.
*/
const MAX_RELEASE_COUNT = 200;
/** The one screen that clears an inbox backlog. */
const INBOX_FIX_HREF = "/admin/rrm/inbox";
const HOURS_IN_DAY = 24;
// ── Facts the gate is computed from ─────────────────────────────────────────
type HourBucket = { hour: number; newOpeners: number; followUps: number };
type RampFacts = {
halted: boolean;
haltReason: string | null;
dailyCap: number;
hourlyRate: number;
blocksSinceRelease: number;
totalSent: number;
totalDelivered: number;
repliesSinceRelease: number;
uniqueRecipients24h: number;
replyCohort: number;
replyCohortReplied: number;
oldestWaitingMinutes: number | null;
contactable: number;
sendableRemaining: number;
maxStepIndex: number;
todayByHour: HourBucket[];
};
type Db = ReturnType<typeof getDb>;
/** Epoch seconds. Raw SQL binds numbers; only Drizzle operators map `Date`. */
function toEpochSeconds(date: Date): number {
return Math.floor(date.getTime() / 1000);
}
/**
* The most recent release, and the highest step index written so far.
*
* Read before everything else because two gate conditions are scoped to "since
* the last release" — a blocks or replies count over all time would keep
* answering for a step that closed a week ago.
*/
async function loadRampSteps(
db: Db,
): Promise<{ lastReleaseAt: Date | null; maxStepIndex: number }> {
const rows = await db
.select({
lastReleaseAt: sql<number | null>`max(${RAMP_STEPS.openedAt})`,
maxStepIndex: sql<number>`coalesce(max(${RAMP_STEPS.stepIndex}), 0)`,
})
.from(RAMP_STEPS);
const row = rows[0];
const seconds = row?.lastReleaseAt ?? null;
return {
lastReleaseAt: seconds === null ? null : new Date(Number(seconds) * 1000),
maxStepIndex: Number(row?.maxStepIndex ?? 0),
};
}
/**
* Everything the gate needs, in one pass.
*
* Every count comes from `rrm_prospect_events`, never from a derived column on
* the prospect — the stage column is current state, and a prospect who moved
* twice would be invisible to a state-based count.
*/
async function loadRampFacts(db: Db, dal: Dal, now: Date): Promise<RampFacts> {
const { lastReleaseAt, maxStepIndex } = await loadRampSteps(db);
const sinceRelease = lastReleaseAt ? toEpochSeconds(lastReleaseAt) : 0;
const since24h = toEpochSeconds(new Date(now.getTime() - ROLLING_WINDOW_MS));
const [
halted,
dailyCap,
hourlyRate,
haltRows,
poolRows,
eventRows,
cohortRows,
backlogRows,
hourRows,
] = await Promise.all([
dal.rrmConfig.isHalted(),
dal.rrmConfig.getNumber(
RRM_CONFIG_KEYS.dailySendCap,
RRM_CONFIG_DEFAULTS[RRM_CONFIG_KEYS.dailySendCap],
),
dal.rrmConfig.getNumber(
RRM_CONFIG_KEYS.hourlySendRate,
RRM_CONFIG_DEFAULTS[RRM_CONFIG_KEYS.hourlySendRate],
),
// The DAL exposes the halt VALUE but not the attribution stored beside
// it, and the banner is worthless without the reason.
db
.select({ reason: CONFIG.reason })
.from(CONFIG)
.where(eq(CONFIG.key, RRM_CONFIG_KEYS.halt))
.limit(1),
db
.select({
contactable: sql<number>`coalesce(sum(case when ${PROSPECTS.doNotContact} = 0 then 1 else 0 end), 0)`,
sendable: sql<number>`coalesce(sum(case when ${PROSPECTS.doNotContact} = 0 and ${PROSPECTS.stage} = 'sourced' then 1 else 0 end), 0)`,
})
.from(PROSPECTS),
db
.select({
sent: sql<number>`coalesce(sum(case when ${EVENTS.type} = 'message_sent' then 1 else 0 end), 0)`,
delivered: sql<number>`coalesce(sum(case when ${EVENTS.type} = 'message_delivered' then 1 else 0 end), 0)`,
blocks: sql<number>`coalesce(sum(case when ${EVENTS.type} = 'send_blocked' and ${EVENTS.occurredAt} >= ${sinceRelease} then 1 else 0 end), 0)`,
// Distinct prospects: one person sending four messages is one reply,
// otherwise a single chatty prospect clears a gate meant to prove
// that several different people answered.
replies: sql<number>`count(distinct case when ${EVENTS.type} = 'message_received' and ${EVENTS.occurredAt} >= ${sinceRelease} then ${EVENTS.prospectId} end)`,
uniqueRecipients24h: sql<number>`count(distinct case when ${EVENTS.type} = 'message_sent' and ${EVENTS.occurredAt} >= ${since24h} then ${EVENTS.prospectId} end)`,
})
.from(EVENTS),
// The last N sends, each flagged with whether that prospect ever replied.
// A correlated EXISTS rather than a join: D1 plans joins badly, and this
// one rides the (prospect_id, occurred_at) index.
db
.select({
prospectId: EVENTS.prospectId,
replied: sql<number>`case when exists (select 1 from rrm_prospect_events r where r.prospect_id = ${EVENTS.prospectId} and r.type = 'message_received') then 1 else 0 end`,
})
.from(EVENTS)
.where(eq(EVENTS.type, "message_sent"))
.orderBy(desc(EVENTS.occurredAt))
.limit(REPLY_RATE_WINDOW),
// Conversations waiting on us: their last inbound is newer than our last
// outbound.
//
// READ FROM `wa_conversations`, NOT from `rrm_prospect_events` — the same
// source `GET /inbox` uses, and that agreement is the whole point. This
// used to count `message_sent` events, which are only written when a
// reply goes out through an RRM code path AND the `wa_messages` row
// carries a `prospect_id`. A reply sent from the WhatsApp app, or from
// the platform's own WhatsApp screen, updates the conversation and
// writes no RRM event at all — so the gate saw an unanswered
// conversation that the inbox correctly showed as answered, blocked the
// campaign, and offered no row to click to clear it. Observed on
// production: an operator replied in four minutes and the gate still
// read a 22-hour backlog a day later, permanently.
//
// An opt-out still counts as answered — nobody replies to "STOP", so
// without that the condition would fail forever after the first opt-out.
db
.select({
lastInbound: sql<number>`${CONVERSATIONS.lastCustomerMessageAt}`,
})
.from(CONVERSATIONS)
.innerJoin(
PROSPECTS,
sql`${CONVERSATIONS.phoneNumber} IN (${PROSPECTS.phoneNorm}, '+' || ${PROSPECTS.phoneNorm})`,
)
.where(
and(
sql`${CONVERSATIONS.lastCustomerMessageAt} is not null`,
eq(PROSPECTS.doNotContact, false),
sql`(${CONVERSATIONS.lastMessageAt} is null or ${CONVERSATIONS.lastMessageAt} <= ${CONVERSATIONS.lastCustomerMessageAt})`,
),
),
// Today's sends, each carrying that prospect's first-ever send so the
// histogram can split openers from follow-ups. IST day, never UTC.
db
.select({
occurredAt: sql<number>`${EVENTS.occurredAt}`,
firstSentAt: sql<number>`(select min(f.occurred_at) from rrm_prospect_events f where f.prospect_id = ${EVENTS.prospectId} and f.type = 'message_sent')`,
})
.from(EVENTS)
.where(
and(
eq(EVENTS.type, "message_sent"),
gte(EVENTS.occurredAt, istDayStart(now)),
),
),
]);
const eventRow = eventRows[0];
const poolRow = poolRows[0];
const cohort = new Map<string, boolean>();
for (const row of cohortRows) {
cohort.set(row.prospectId, cohort.get(row.prospectId) || row.replied === 1);
}
// `HAVING` already excludes conversations with no inbound, but a null here
// would read as epoch 0 and report a backlog fifty years deep — the one
// wrong answer that would close the gate forever.
const waiting = backlogRows
.filter((row) => row.lastInbound !== null)
.map((row) => Number(row.lastInbound));
const oldestInbound = waiting.length > 0 ? Math.min(...waiting) : null;
return {
halted,
// Only while halted: the row keeps the last reason forever, and a resume
// reason attached to `halted: false` would read as an active halt.
haltReason: halted ? (haltRows[0]?.reason ?? null) : null,
dailyCap,
hourlyRate,
blocksSinceRelease: Number(eventRow?.blocks ?? 0),
totalSent: Number(eventRow?.sent ?? 0),
totalDelivered: Number(eventRow?.delivered ?? 0),
repliesSinceRelease: Number(eventRow?.replies ?? 0),
uniqueRecipients24h: Number(eventRow?.uniqueRecipients24h ?? 0),
replyCohort: cohort.size,
replyCohortReplied: [...cohort.values()].filter(Boolean).length,
oldestWaitingMinutes:
oldestInbound === null
? null
: Math.max(
0,
Math.floor((now.getTime() - oldestInbound * 1000) / 60_000),
),
contactable: Number(poolRow?.contactable ?? 0),
sendableRemaining: Number(poolRow?.sendable ?? 0),
maxStepIndex,
todayByHour: bucketByHour(hourRows),
};
}
/**
* Twenty-four buckets, always — a histogram with holes in it is a histogram
* that lies about the quiet hours.
*/
function bucketByHour(
rows: Array<{ occurredAt: number; firstSentAt: number | null }>,
): HourBucket[] {
const openers = new Map<number, number>();
const followUps = new Map<number, number>();
for (const row of rows) {
const at = Number(row.occurredAt);
// istParts, never the worker's local time: India is a fixed +05:30 and
// between 00:00 and 05:29 IST the UTC date is a day behind.
const { hour } = istParts(at * 1000);
// The prospect's earliest send IS this one → it opened the conversation.
const isOpener = row.firstSentAt !== null && Number(row.firstSentAt) === at;
const target = isOpener ? openers : followUps;
target.set(hour, (target.get(hour) ?? 0) + 1);
}
return Array.from({ length: HOURS_IN_DAY }, (_, hour) => ({
hour,
newOpeners: openers.get(hour) ?? 0,
followUps: followUps.get(hour) ?? 0,
}));
}
// ── The gate ────────────────────────────────────────────────────────────────
function percent(part: number, whole: number): number {
if (whole <= 0) return 0;
return Math.round((part / whole) * 100);
}
function formatWaiting(minutes: number | null): string {
if (minutes === null) return "nothing waiting";
const hours = Math.floor(minutes / 60);
return `${hours}h ${minutes % 60}m`;
}
/**
* How much of the contactable list is still untouched once `releaseCount`
* prospects are queued.
*
* Measured AFTER the prospective release on purpose. Evaluating the reserve as
* it stands today would happily open a step that breaches the floor the moment
* it completes — the number that matters is the one you are left holding.
*/
function reserveAfterRelease(facts: RampFacts, releaseCount: number): number {
return percent(
Math.max(0, facts.sendableRemaining - releaseCount),
facts.contactable,
);
}
/**
* The gate, evaluated server-side.
*
* `releaseCount` is the batch being judged, so the reserve condition answers
* for the release actually on the table rather than for a default.
*/
function evaluateGate(
facts: RampFacts,
releaseCount: number,
): RrmGateCondition[] {
// Before the campaign has sent anything there is no delivery receipt and no
// reply to count, so the send-derived conditions cannot be evaluated and
// would otherwise make the FIRST release impossible.
//
// Keyed on total sends ever, NOT on sends since the last release: the latter
// is zero for the minutes right after every release and would reopen the
// gate immediately each time.
const preLaunch = facts.totalSent === 0;
const deliveryRate = percent(facts.totalDelivered, facts.totalSent);
const replyRate = percent(facts.replyCohortReplied, facts.replyCohort);
const reserve = reserveAfterRelease(facts, releaseCount);
const backlog = facts.oldestWaitingMinutes;
return [
{
key: "blocks_since_release",
label: "Blocks since last release",
pass: facts.blocksSinceRelease <= GATE_MAX_BLOCKS,
value: String(facts.blocksSinceRelease),
threshold: String(GATE_MAX_BLOCKS),
},
{
key: "delivery_rate",
label: "Delivery rate",
pass: preLaunch || deliveryRate >= GATE_MIN_DELIVERY_RATE,
value: preLaunch ? "no sends yet" : `${deliveryRate}%`,
threshold: `>= ${GATE_MIN_DELIVERY_RATE}%`,
},
{
key: "replies_since_release",
label: "Replies since last release",
pass: preLaunch || facts.repliesSinceRelease >= GATE_MIN_REPLIES,
value: preLaunch ? "no sends yet" : String(facts.repliesSinceRelease),
threshold: `>= ${GATE_MIN_REPLIES}`,
},
{
key: "reply_rate",
label: `Reply rate (last ${REPLY_RATE_WINDOW} sends)`,
pass: preLaunch || replyRate >= GATE_MIN_REPLY_RATE,
value: preLaunch ? "no sends yet" : `${replyRate}%`,
threshold: `>= ${GATE_MIN_REPLY_RATE}%`,
},
{
key: "inbox_backlog",
label: "Inbox backlog",
pass: backlog === null || backlog < GATE_MAX_BACKLOG_MINUTES,
value: formatWaiting(backlog),
threshold: `< ${GATE_MAX_BACKLOG_MINUTES / 60}h`,
// One screen clears this, so hand the operator the door.
...(backlog !== null && backlog >= GATE_MAX_BACKLOG_MINUTES
? { fixHref: INBOX_FIX_HREF }
: {}),
},
{
key: "reserve_after_release",
label: "Reserve after release",
pass: reserve >= GATE_MIN_RESERVE_PERCENT,
// An EMPTY POOL is not a reserve problem, and saying "0%, needs 45%"
// sends an operator hunting for reserve when what they need is a list.
// With nothing at `sourced` the arithmetic is (0 - 0) / contactable =
// 0%, so the honest gate fails for an accurate reason and reports a
// misleading one. Name the real cause when there is nothing to move.
value:
facts.sendableRemaining === 0 ? "nothing to release" : `${reserve}%`,
threshold:
facts.sendableRemaining === 0
? "import prospects first"
: `>= ${GATE_MIN_RESERVE_PERCENT}%`,
},
];
}
/**
* How many prospects the next release would move.
*
* One day's worth of sending, bounded by what is actually left. The original
* five-tranche schedule is gone — the campaign runs at a flat configurable
* rate — so releasing more than a day's cap only parks prospects in `queued`
* where they age without being messaged.
*/
function nextReleaseCount(facts: RampFacts): number {
return Math.min(facts.dailyCap, facts.sendableRemaining);
}
function blockingReason(
facts: RampFacts,
conditions: RrmGateCondition[],
): string | null {
if (facts.halted) return facts.haltReason ?? "Sending is halted.";
const failing = conditions.find((condition) => !condition.pass);
if (!failing) return null;
return `${failing.label} is ${failing.value}, needs ${failing.threshold}.`;
}
// ── Routes ──────────────────────────────────────────────────────────────────
const ramp = new Hono<Env>();
// GET /api/admin/rrm/ramp
ramp.get("/ramp", async (c) => {
try {
const db = getDb(c.env.DB);
const now = new Date();
const facts = await loadRampFacts(db, c.get("dal"), now);
const count = nextReleaseCount(facts);
const conditions = evaluateGate(facts, count);
return success(c, {
conditions,
// A halt outranks the conditions: every one of them can pass while
// sending is stopped, and releasing into a halted campaign only builds
// a queue nobody asked for.
canRelease:
!facts.halted && conditions.every((condition) => condition.pass),
blockingReason: blockingReason(facts, conditions),
nextReleaseCount: count,
sendableRemaining: facts.sendableRemaining,
reservePercentAfterRelease: reserveAfterRelease(facts, count),
rollingWindow: {
used: facts.uniqueRecipients24h,
tier: WABA_TIER_UNIQUE_RECIPIENTS_24H,
},
todayByHour: facts.todayByHour,
dailyCap: facts.dailyCap,
hourlyRate: facts.hourlyRate,
halted: facts.halted,
haltReason: facts.haltReason,
});
} catch (err) {
return handleError(c, err);
}
});
function parseReleaseCount(input: unknown): number {
if (typeof input !== "number" || !Number.isInteger(input) || input < 1) {
throw new ValidationError("count must be a positive integer");
}
if (input > MAX_RELEASE_COUNT) {
throw new ValidationError(
`count must be ${MAX_RELEASE_COUNT} or fewer per release`,
);
}
return input;
}
// POST /api/admin/rrm/ramp/release
ramp.post("/ramp/release", async (c) => {
try {
const db = getDb(c.env.DB);
const dal = c.get("dal");
const user = c.get("user");
const body = await c.req.json<{
count?: unknown;
acknowledgedMetrics?: unknown;
override?: unknown;
}>();
// The gates below are OUR policy — delivery rate, backlog, template
// approval, the halt. An operator who has decided the campaign is worth
// the risk can force past them, but never anonymously and never without
// saying why: both land in `gateSnapshot`, which is the only record that
// a release happened against a failing gate.
const override = parseOverride(body.override, user?.id);
// The checkbox is the operator's signature on the release. Anything other
// than an explicit `true` is not one.
if (body.acknowledgedMetrics !== true) {
throw new ValidationError(
"acknowledgedMetrics must be true — releasing requires an explicit acknowledgement",
);
}
const count = parseReleaseCount(body.count);
const now = new Date();
const facts = await loadRampFacts(db, dal, now);
if (facts.halted && !override) {
throw new AppError(
409,
"RAMP_HALTED",
facts.haltReason
? `Sending is halted: ${facts.haltReason}`
: "Sending is halted.",
);
}
// Re-evaluated here, against the count actually requested. The client's
// word that the gate passed is not evidence that it does.
const conditions = evaluateGate(facts, count);
const failing = conditions.find((condition) => !condition.pass);
if (failing && !override) {
throw new AppError(
409,
"RAMP_GATE_NOT_MET",
`Release refused — ${failing.label} is ${failing.value}, needs ${failing.threshold}.`,
);
}
// Best prospects first, then grouped by micro-market: a batch that shares
// a locality gets one operator's local knowledge applied to all of it, and
// tier A ahead of D means the list is tested on its strongest names while
// there is still reserve behind them. `id` breaks ties so a rerun of the
// same query returns the same order.
const candidates = await db
.select({ id: PROSPECTS.id })
.from(PROSPECTS)
.where(
and(eq(PROSPECTS.stage, "sourced"), eq(PROSPECTS.doNotContact, false)),
)
.orderBy(
// SQLite sorts NULL first, which would put untiered prospects ahead
// of tier A.
sql`case when ${PROSPECTS.tier} is null then 1 else 0 end`,
asc(PROSPECTS.tier),
asc(PROSPECTS.microMarkets),
asc(PROSPECTS.id),
)
.limit(count);
// One `setStage` per prospect, sequentially. It is four D1 round trips
// each, which is the price of spec §0 rule 7 — the stage write and its
// event row go out in one batch, so the funnel can never be short an
// event. Bounded by MAX_RELEASE_COUNT above.
let released = 0;
for (const candidate of candidates) {
const result = await dal.rrmProspects.setStage(candidate.id, "queued", {
actorType: "operator",
actorId: user?.id ?? null,
reason: "ramp release",
});
if (result.changed) released += 1;
}
// Written last, and with the count that actually moved: an audit row is
// only worth keeping if it records what happened rather than what was
// asked for. `stepIndex` is derived from a prior read, which races under
// concurrent releases — acceptable for a single-operator console, and the
// unique index turns a collision into a loud failure rather than a silent
// overwrite.
await db.insert(RAMP_STEPS).values({
id: generateId(),
stepIndex: facts.maxStepIndex + 1,
plannedCount: count,
releasedCount: released,
state: "complete",
openedAt: now,
closedAt: now,
openedBy: user?.id ?? null,
gateSnapshot: {
evaluatedAt: now.toISOString(),
requestedCount: count,
releasedCount: released,
sendableRemaining: facts.sendableRemaining,
reservePercentAfterRelease: reserveAfterRelease(facts, count),
conditions,
// Absent on an ordinary release. Present means a human decided
// to go anyway, and names which conditions they went past.
...(override
? {
overriddenBy: user?.id ?? null,
overrideReason: override.reason,
overrodeHalt: facts.halted,
overrodeConditions: conditions
.filter((condition) => !condition.pass)
.map((condition) => condition.label),
}
: {}),
},
});
return success(c, { released });
} catch (err) {
return handleError(c, err);
}
});
/**
* An override is a decision with a name on it, or it is not an override.
*
* Returns undefined when the caller did not ask for one — the ordinary path.
* Throws when they asked for one they cannot have, rather than quietly
* releasing under the normal gates and reporting success.
*/
function parseOverride(
input: unknown,
actorId: string | undefined,
): { reason: string } | undefined {
if (input === undefined || input === null) return undefined;
Iif (typeof input !== "object") {
throw new ValidationError("override must be an object with a reason");
}
if (!actorId) {
throw new UnauthorizedError(
"An identified operator is required to override the ramp gate",
);
}
const reason = (input as { reason?: unknown }).reason;
if (typeof reason !== "string" || reason.trim().length < 20) {
throw new ValidationError(
"override.reason is required and must be at least 20 characters — it is the only record of why the gate was bypassed",
);
}
return { reason: reason.trim() };
}
// POST /api/admin/rrm/halt
ramp.post("/halt", async (c) => {
try {
const dal = c.get("dal");
const actorId = c.get("user")?.id;
if (!actorId) {
throw new UnauthorizedError(
"An identified operator is required to change the halt switch",
);
}
const body = await c.req.json<{ on?: unknown; reason?: unknown }>();
if (typeof body.on !== "boolean") {
throw new ValidationError("on must be a boolean");
}
const reason = typeof body.reason === "string" ? body.reason.trim() : "";
// Required in BOTH directions. An unattributed resume is the more
// dangerous of the two — it puts sends back on an account something
// stopped — and a kill switch nobody can attribute is one nobody trusts.
if (!reason) {
throw new ValidationError("reason is required to halt or resume sending");
}
await dal.rrmConfig.setHalt(body.on, reason, actorId);
return success(c, { halted: body.on });
} catch (err) {
return handleError(c, mapConfigError(err));
}
});
/** DAL config errors are caller mistakes, not server faults. */
function mapConfigError(err: unknown): unknown {
if (err instanceof ConfigAttributionRequiredError) {
return new ValidationError(err.message);
}
if (err instanceof ConfigValueError) {
return new ValidationError(err.message);
}
return err;
}
/**
* The config screen's contract: stored value where one exists, else the
* engine's own default. An unwritten key is not an absent setting — the
* scheduler falls back to the default and sends on it, so the screen (and the
* PATCH response below) has to show what will actually happen rather than an
* empty row. Shared by GET and the post-write PATCH response so the two can
* never show a different merge.
*/
async function loadEffectiveConfig(dal: Dal): Promise<Record<string, string>> {
const keys = Object.values(RRM_CONFIG_KEYS);
const stored = await Promise.all(keys.map((key) => dal.rrmConfig.get(key)));
const config: Record<string, string> = {};
keys.forEach((key, index) => {
const value = stored[index];
if (value !== null) {
config[key] = value;
return;
}
// Defaults are numbers, booleans and lists — stringify whatever is there
// rather than narrowing to one type. No default exists for `halt` or
// `holidays`, so those are simply absent until written.
const fallback = (RRM_CONFIG_DEFAULTS as Partial<Record<string, unknown>>)[
key
];
if (fallback !== undefined) config[key] = String(fallback);
});
return config;
}
// GET /api/admin/rrm/config
ramp.get("/config", async (c) => {
try {
const config = await loadEffectiveConfig(c.get("dal"));
return success(c, config);
} catch (err) {
return handleError(c, err);
}
});
// ── PATCH /api/admin/rrm/config ─────────────────────────────────────────────
/** Every writable key, as a zod enum so an unknown key is a schema failure. */
const configKeySchema = z.enum(
Object.values(RRM_CONFIG_KEYS) as [RrmConfigKey, ...RrmConfigKey[]],
);
/** Design doc §4: the pacing table's per-key ranges. */
const NUMERIC_CONFIG_RANGES: Partial<
Record<RrmConfigKey, { min: number; max: number }>
> = {
// The three pacing ceilings are one piece of arithmetic, not three round
// numbers. Read them together, from the bottom up.
//
// hourly_send_rate ≤ 60 — openers per IST clock hour. The default send
// window is 9 hours (10:00-19:00), so 60/h is the smallest ceiling that
// still clears 500 openers a day (500 ÷ 9 = 55.6/h) with a little
// headroom. It is NOT raised further: one hour must not be able to carry
// a fifth of the day.
//
// daily_opener_cap ≤ 540 — new N0s per IST day. 60/h × 9h is the most the
// hourly ceiling can physically deliver in a default window; a larger
// number here would be a cap the operator can type and never reach.
//
// daily_send_cap ≤ 1620 — EVERY template send per IST day. The ladder owes
// three templates per prospect (N0, then N2 at +3d, then N7 at +7d), so a
// steady campaign at the opener ceiling is sending 540 openers + 540 N2s
// + 540 N7s from day 8 onward = 3 × 540. Set this below that and the
// shortfall lands on the follow-ups, reported as `deferred` in the tick.
//
// Rule of thumb for the runbook: daily_send_cap ≈ 3 × daily_opener_cap.
// These are what an operator MAY set, not what is set — the defaults in
// `RRM_CONFIG_DEFAULTS` stay at ramp step 1, and the real ceiling is the
// WhatsApp messaging tier on the number (250 unique business-initiated
// recipients/24h until Meta raises it), which no code here can see.
[RRM_CONFIG_KEYS.dailySendCap]: { min: 1, max: 1620 },
[RRM_CONFIG_KEYS.dailyOpenerCap]: { min: 1, max: 540 },
[RRM_CONFIG_KEYS.hourlySendRate]: { min: 1, max: 60 },
[RRM_CONFIG_KEYS.sendWindowStartHour]: { min: 0, max: 23 },
[RRM_CONFIG_KEYS.sendWindowEndHour]: { min: 0, max: 23 },
[RRM_CONFIG_KEYS.snoozeDays]: { min: 1, max: 365 },
// Money. Paise, and whole ones — the integer check above is what keeps a
// fraction out of an INTEGER ledger column. A rate of 0 credits nothing, and
// a threshold of 0 lets a partner mint an empty payout that then occupies
// their one pending-payout slot (`RrmEarningsDal.requestPayout` compares
// `total < threshold`), so both floors are 1. The ceiling is ₹10,000 — an
// order of magnitude above today's ₹1,000 conversion, which is room for any
// real rate change and still catches the extra-zero typo.
[RRM_CONFIG_KEYS.validatedAmountPaise]: { min: 1, max: 1_000_000 },
[RRM_CONFIG_KEYS.convertedAmountPaise]: { min: 1, max: 1_000_000 },
[RRM_CONFIG_KEYS.payoutThresholdPaise]: { min: 1, max: 1_000_000 },
// 0 is legitimate: releasable the moment it is credited. The ceiling is a
// quarter of a year — a longer hold on a ₹100 referral is a typo.
[RRM_CONFIG_KEYS.holdDays]: { min: 0, max: 90 },
};
/** Behaviour switches — plain booleans, not tuning knobs. */
const BOOLEAN_CONFIG_KEYS: ReadonlySet<RrmConfigKey> = new Set([
RRM_CONFIG_KEYS.followupsFirst,
RRM_CONFIG_KEYS.autoReply,
RRM_CONFIG_KEYS.autoHaltReplyRateArmed,
]);
const HOLIDAY_DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
/** Rejects calendar nonsense (`2024-02-30`) that the regex alone lets through. */
function isValidCalendarDateISO(iso: string): boolean {
const parsed = new Date(`${iso}T00:00:00.000Z`);
return (
!Number.isNaN(parsed.getTime()) && parsed.toISOString().slice(0, 10) === iso
);
}
/**
* Per-key validation from the design doc's §4 table. `dal` is only touched for
* the send-window pair, where "start < end" cannot be judged from one key in
* isolation — the other side of the window is read as its current effective
* value (stored, or the engine default) so a lone PATCH to either edge is
* still checked against what will actually run.
*
* Returns the value in the shape `RrmConfigDal.set` accepts; throws
* `ValidationError` with a message an operator can act on.
*/
async function validateConfigPatchValue(
dal: Dal,
key: RrmConfigKey,
value: unknown,
): Promise<RrmConfigValue> {
const range = NUMERIC_CONFIG_RANGES[key];
if (range) {
if (typeof value !== "number" || !Number.isInteger(value)) {
throw new ValidationError(`${key} must be a whole number`);
}
if (value < range.min || value > range.max) {
throw new ValidationError(
`${key} must be between ${range.min} and ${range.max}`,
);
}
if (
key === RRM_CONFIG_KEYS.sendWindowStartHour ||
key === RRM_CONFIG_KEYS.sendWindowEndHour
) {
const otherKey =
key === RRM_CONFIG_KEYS.sendWindowStartHour
? RRM_CONFIG_KEYS.sendWindowEndHour
: RRM_CONFIG_KEYS.sendWindowStartHour;
const otherValue = await dal.rrmConfig.getNumber(
otherKey,
RRM_CONFIG_DEFAULTS[otherKey],
);
const start =
key === RRM_CONFIG_KEYS.sendWindowStartHour ? value : otherValue;
const end =
key === RRM_CONFIG_KEYS.sendWindowEndHour ? value : otherValue;
if (!(start < end)) {
throw new ValidationError(
`send_window_start_hour (${start}) must be before send_window_end_hour (${end})`,
);
}
}
return value;
}
if (BOOLEAN_CONFIG_KEYS.has(key)) {
if (typeof value !== "boolean") {
throw new ValidationError(`${key} must be true or false`);
}
return value;
}
Eif (key === RRM_CONFIG_KEYS.holidays) {
if (
!Array.isArray(value) ||
value.some((item) => typeof item !== "string")
) {
throw new ValidationError(
"holidays must be an array of YYYY-MM-DD date strings",
);
}
for (const item of value as string[]) {
if (!HOLIDAY_DATE_RE.test(item) || !isValidCalendarDateISO(item)) {
throw new ValidationError(
`holidays: "${item}" is not a valid YYYY-MM-DD date`,
);
}
}
return value as string[];
}
// Unreachable once `key` has passed `configKeySchema` and the `halt` guard
// below — every remaining key is covered by one of the branches above. Kept
// so this function is total rather than trusting the caller.
throw new ValidationError(`Unsupported config key: ${key}`);
}
// PATCH /api/admin/rrm/config
ramp.patch("/config", async (c) => {
try {
const dal = c.get("dal");
const actorId = c.get("user")?.id;
const body = await c.req.json<{
key?: unknown;
value?: unknown;
reason?: unknown;
}>();
const keyResult = configKeySchema.safeParse(body.key);
if (!keyResult.success) {
throw new ValidationError(
`key must be one of: ${Object.values(RRM_CONFIG_KEYS).join(", ")}`,
);
}
const key = keyResult.data;
// `halt` has its own endpoint with its own kill-switch semantics (manual
// resume only, both directions attributed) — this route must not grow a
// second way to flip it that could drift from that one.
if (key === RRM_CONFIG_KEYS.halt) {
throw new ValidationError(
"halt cannot be changed through /config — use /ramp/halt",
);
}
const reason = typeof body.reason === "string" ? body.reason.trim() : "";
// Attributed writes only. These values change what the campaign does to
// real people; "who widened the send window, and why" has to be
// answerable from the row itself.
if (reason.length < 3) {
throw new ValidationError(
"reason is required to change a config value (at least 3 characters)",
);
}
const value = await validateConfigPatchValue(dal, key, body.value);
await dal.rrmConfig.set(key, value, { reason, actorId });
// The full effective config, not just the one key — the screen renders
// off this response, and a send-window edit changes what BOTH hours show.
const config = await loadEffectiveConfig(dal);
return success(c, config);
} catch (err) {
return handleError(c, mapConfigError(err));
}
});
export default ramp;
|